

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# Amazon Managed Workflows for Apache Airflow 的最佳實務
<a name="best-practices"></a>

本指南說明使用 Amazon Managed Workflows for Apache Airflow 時建議的最佳實務。

**Topics**
+ [Amazon MWAA 上 Apache Airflow 的效能調校](best-practices-tuning.md)
+ [在 requirements.txt 中管理 Python 相依性](best-practices-dependencies.md)

# Amazon MWAA 上 Apache Airflow 的效能調校
<a name="best-practices-tuning"></a>

本主題說明如何使用 調整 Amazon Managed Workflows for Apache Airflow 環境的效能[在 Amazon MWAA 上使用 Apache Airflow 組態選項](configuring-env-variables.md)。

**Contents**
+ [新增 Apache Airflow 組態選項](#best-practices-tuning-console-add)
+ [Apache Airflow 排程器](#best-practices-tuning-scheduler)
  + [Parameters](#best-practices-tuning-scheduler-params)
  + [限制](#best-practices-tuning-scheduler-limits)
+ [DAG 資料夾](#best-practices-tuning-dag-folders)
  + [Parameters](#best-practices-tuning-dag-folders-params)
+ [DAG 檔案](#best-practices-tuning-dag-files)
  + [Parameters](#best-practices-tuning-dag-files-params)
+ [任務​](#best-practices-tuning-tasks)
  + [Parameters](#best-practices-tuning-tasks-params)

## 新增 Apache Airflow 組態選項
<a name="best-practices-tuning-console-add"></a>

使用下列程序將 Airflow 組態選項新增至您的環境。

1. 在 Amazon MWAA 主控台上開啟[環境](https://console.aws.amazon.com/mwaa/home#/environments)頁面。

1. 選擇環境。

1. 選擇**編輯**。

1. 選擇**下一步**。

1. 在 Airflow **組態選項窗格中選擇新增自訂**組態。 ****

1. 從下拉式清單中選擇組態並輸入值，或輸入自訂組態並輸入值。

1. 針對您要新增的每個組態，選擇**新增自訂**組態。

1. 選擇**儲存**。

若要進一步了解，請參閱 [在 Amazon MWAA 上使用 Apache Airflow 組態選項](configuring-env-variables.md)。

## Apache Airflow 排程器
<a name="best-practices-tuning-scheduler"></a>

Apache Airflow 排程器是 Apache Airflow 的核心元件。排程器的問題可防止剖析 DAGs 和排程任務。如需 Apache Airflow 排程器調校的詳細資訊，請參閱 Apache Airflow 文件網站上的[微調排程器效能](https://airflow.apache.org/docs/apache-airflow/2.2.2/concepts/scheduler.html#fine-tuning-your-scheduler-performance)。

### Parameters
<a name="best-practices-tuning-scheduler-params"></a>

本節說明 Apache Airflow 排程器 (Apache Airflow v2 和更新版本） 可用的組態選項及其使用案例。

------
#### [ Apache Airflow v3 ]


| Configuration | 使用案例 | 
| --- | --- | 
|  **[celery.sync\$1parallelism](https://airflow.apache.org/docs/apache-airflow/3.0.6/configurations-ref.html#parallelism)** Celery Executor 用來同步任務狀態的程序數目。 **預設值**：1  |  您可以使用此選項來限制 Celery Executor 使用的程序，以防止佇列衝突。根據預設， 值會設定為 `1` ，以防止將任務日誌交付至 CloudWatch Logs 時發生錯誤。將值設定為 `0`表示使用最大數量的程序，但在交付任務日誌時可能會導致錯誤。  | 
|  **[scheduler.scheduler\$1idle\$1sleep\$1time](https://airflow.apache.org/docs/apache-airflow/3.0.6/configurations-ref.html#scheduler-idle-sleep-time)** 排程器「迴圈」中連續 DAG 檔案處理之間的等待秒數。 **預設值**：1  |  您可以使用此選項來釋放排程器上的 CPU 用量，方法是**增加**排程器在完成擷取 DAG 剖析結果後休眠的時間、尋找和佇列任務，以及在*執行器*中執行排入佇列的任務。增加此值會耗用 `dag_processor.parsing_processes` Apache Airflow v2 和 Apache Airflow v3 在 環境中執行的排程器執行緒數目。這可以減少排程器剖析 DAGs 的容量，並增加 DAGs 在 Web 伺服器中填入所需的時間。  | 
|  **[scheduler.max\$1dagruns\$1to\$1create\$1per\$1loop](https://airflow.apache.org/docs/apache-airflow/3.0.6/configurations-ref.html#max-dagruns-to-create-per-loop)** 為每個排程器「迴圈」建立 *DagRuns* 的 DAGs 數目上限。 **預設值**：10  |  您可以使用此選項，藉由**減少**排程器「迴圈」的 *DagRuns* 數目上限，釋放用於排程任務的資源。  | 
|  **[dag\$1processor.parsing\$1processes](https://airflow.apache.org/docs/apache-airflow/3.0.6/configurations-ref.html#parsing-processes)** 排程器可以平行執行以排程 DAGs執行緒數目。 **預設：**使用 `(2 * number of vCPUs) - 1`  |  您可以使用此選項，藉由**減少**排程器平行執行以剖析 DAGs 的程序數目來釋放資源。如果 DAG 剖析影響任務排程，建議您將此數字保持較低。**您必須**指定小於您環境中 vCPU 計數的值。若要進一步了解，請參閱 [限制](#best-practices-tuning-scheduler-limits)。  | 

------
#### [ Apache Airflow v2 ]


| Configuration | 使用案例 | 
| --- | --- | 
|  **[celery.sync\$1parallelism](https://airflow.apache.org/docs/apache-airflow/2.10.3/configurations-ref.html#parallelism)** Celery Executor 用來同步任務狀態的程序數目。 **預設值**：1  |  您可以使用此選項來限制 Celery Executor 使用的程序，以防止佇列衝突。根據預設， 值會設定為 `1` ，以防止將任務日誌交付至 CloudWatch Logs 時發生錯誤。將值設定為 `0`表示使用最大數量的程序，但在交付任務日誌時可能會導致錯誤。  | 
|  **[scheduler.idle\$1sleep\$1time](https://airflow.apache.org/docs/apache-airflow/2.10.3/configurations-ref.html#scheduler-idle-sleep-time)** 排程器「迴圈」中連續 DAG 檔案處理之間的等待秒數。 **預設值**：1  |  您可以使用此選項來釋放排程器上的 CPU 用量，方法是**增加**排程器在完成擷取 DAG 剖析結果後休眠的時間、尋找和佇列任務，以及在*執行器*中執行排入佇列的任務。增加此值會耗用 `scheduler.parsing_processes` Apache Airflow v2 和 Apache Airflow v3 在 環境中執行的排程器執行緒數目。這可以減少排程器剖析 DAGs 的容量，並增加 DAGs 在 Web 伺服器中填入所需的時間。  | 
|  **[scheduler.max\$1dagruns\$1to\$1create\$1per\$1loop](https://airflow.apache.org/docs/apache-airflow/2.10.3/configurations-ref.html#max-dagruns-to-create-per-loop)** 為每個排程器「迴圈」建立 *DagRuns* 的 DAGs 數目上限。 **預設值**：10  |  您可以使用此選項，藉由**減少**排程器「迴圈」的 *DagRuns* 數目上限，釋放用於排程任務的資源。  | 
|  **[scheduler.parsing\$1processes](https://airflow.apache.org/docs/apache-airflow/2.10.3/configurations-ref.html#parsing-processes)** 排程器可以平行執行以排程 DAGs執行緒數目。 **預設：**使用 `(2 * number of vCPUs) - 1`  |  您可以使用此選項，藉由**減少**排程器平行執行以剖析 DAGs 的程序數目來釋放資源。如果 DAG 剖析影響任務排程，建議您將此數字保持較低。**您必須**指定小於您環境中 vCPU 計數的值。若要進一步了解，請參閱 [限制](#best-practices-tuning-scheduler-limits)。  | 

------

### 限制
<a name="best-practices-tuning-scheduler-limits"></a>

本節說明調整排程器的預設參數時應考慮的限制。<a name="scheduler-considerations"></a>

**scheduler.parsing\$1processes、scheduler.max\$1threads （僅限 v2)**  
環境類別的每個 vCPU 允許兩個執行緒。環境類別的排程器必須至少保留一個執行緒。如果您注意到任務排程延遲，您可能需要增加[環境類別](environment-class.md)。例如，大型環境的排程器具有 4 個 vCPU Fargate 容器執行個體。這表示執行緒`7`總數上限為 ，可用於其他程序。也就是說，兩個執行緒會乘以四個 vCPUs，減去排程器本身的一個 vCPU。您在 `scheduler.max_threads`（僅限 v2) 中指定的值，且`scheduler.parsing_processes`不得超過 環境類別可用的執行緒數目，如下所示：  
+ **mw1.small** – 不得超過其他程序的`1`執行緒。剩餘的執行緒會保留給排程器。
+ **mw1.medium** – 不得超過其他程序的`3`執行緒。剩餘的執行緒會保留給排程器。
+ **mw1.large** – 不得超過其他程序的`7`執行緒。剩餘的執行緒會保留給排程器。

## DAG 資料夾
<a name="best-practices-tuning-dag-folders"></a>

Apache Airflow 排程器會持續掃描您環境中DAGs 資料夾。任何包含`plugins.zip`的檔案，或包含「airflow」匯入陳述式的 Python (`.py`) 檔案。然後，任何產生的 Python DAG 物件都會放入 *DagBag* 中，以供排程器處理該檔案，以決定需要排程哪些任務。無論檔案是否包含任何可行的 DAG 物件，都會進行大型檔案剖析。

### Parameters
<a name="best-practices-tuning-dag-folders-params"></a>

本節說明 DAGs (Apache Airflow v2 及更新版本） 可用的組態選項及其使用案例。

------
#### [ Apache Airflow v3 ]


| Configuration | 使用案例 | 
| --- | --- | 
|  **[dag\$1processor.refresh\$1interval](https://airflow.apache.org/docs/apache-airflow/3.0.6/configurations-ref.html#config-dag-processor-refresh-interval)** 必須掃描 DAGs是否有新檔案的秒數。 **預設：**300 秒  |  您可以使用此選項，透過**增加**剖析 DAGs秒數來釋放資源。如果您在 中遇到長時間的剖析時間`total_parse_time metrics`，建議您增加此值，這可能是因為 DAGs資料夾中有大量檔案所致。  | 
|  **[dag\$1processor.min\$1file\$1process\$1interval](https://airflow.apache.org/docs/apache-airflow/3.0.6/configurations-ref.html#min-file-process-interval)** 排程器剖析 DAG 並反映 DAG 更新的秒數。 **預設：**30 秒  |  您可以使用此選項，透過**增加**排程器在剖析 DAG 之前等待的秒數來釋放資源。例如，如果您指定 的值`30`，則會每 30 秒剖析一次 DAG 檔案。我們建議您將此數字保持高，以減少環境中的 CPU 用量。  | 

------
#### [ Apache Airflow v2 ]


| Configuration | 使用案例 | 
| --- | --- | 
|  **[scheduler.dag\$1dir\$1list\$1interval](https://airflow.apache.org/docs/apache-airflow/2.10.3/configurations-ref.html#dag-dir-list-interval)** 必須掃描 DAGs是否有新檔案的秒數。 **預設：**300 秒  |  您可以使用此選項，透過**增加**剖析 DAGs秒數來釋放資源。如果您在 中遇到長時間的剖析時間`total_parse_time metrics`，建議您增加此值，這可能是因為 DAGs資料夾中有大量檔案所致。  | 
|  **[scheduler.min\$1file\$1process\$1interval](https://airflow.apache.org/docs/apache-airflow/2.10.3/configurations-ref.html#min-file-process-interval)** 排程器剖析 DAG 並反映 DAG 更新的秒數。 **預設：**30 秒  |  您可以使用此選項，透過**增加**排程器在剖析 DAG 之前等待的秒數來釋放資源。例如，如果您指定 的值`30`，則會每 30 秒剖析一次 DAG 檔案。我們建議您將此數字保持高，以減少環境中的 CPU 用量。  | 

------

## DAG 檔案
<a name="best-practices-tuning-dag-files"></a>

做為 Apache Airflow 排程器迴圈的一部分，會剖析個別 DAG 檔案以擷取 DAG Python 物件。在 Apache Airflow v2 和更新版本中，排程器會同時剖析最多 個[剖析程序](https://airflow.apache.org/docs/apache-airflow/2.10.3/configurations-ref.html#parsing-processes)。`scheduler.min_file_process_interval` (v2) 或 `dag_processor.min_file_process_interval`(v3) 中指定的秒數必須先通過，才能再次剖析相同的檔案。

### Parameters
<a name="best-practices-tuning-dag-files-params"></a>

本節說明 Apache Airflow DAG 檔案 (Apache Airflow v2 及更新版本） 可用的組態選項及其使用案例。

------
#### [ Apache Airflow v3 ]


| Configuration | 使用案例 | 
| --- | --- | 
|  **[dag\$1processor.dag\$1file\$1processor\$1timeout](https://airflow.apache.org/docs/apache-airflow/3.0.6/configurations-ref.html#dag-file-processor-timeout)** *DagFileProcessor* 逾時處理 DAG 檔案之前的秒數。 **預設：**50 秒  |  您可以使用此選項，透過**增加** *DagFileProcessor* 逾時之前所需的時間來釋放資源。如果您在 DAG 處理日誌中遇到逾時，導致沒有載入可行DAGs，建議您增加此值。  | 
|  **[core.dagbag\$1import\$1timeout](https://airflow.apache.org/docs/apache-airflow/3.0.6/configurations-ref.html#dagbag-import-timeout)** 匯入 Python 檔案逾時之前的秒數。 **預設：**30 秒  |  您可以使用此選項，藉由**在**匯入 Python 檔案以擷取 DAG 物件時，增加排程器逾時之前所花費的時間來釋放資源。此選項會做為排程器「迴圈」的一部分處理，且必須包含小於 中指定值的值`dag_processor.dag_file_processor_timeout`。  | 
|  **[core.min\$1serialized\$1dag\$1update\$1interval](https://airflow.apache.org/docs/apache-airflow/3.0.6/configurations-ref.html#min-serialized-dag-update-interval)** 更新資料庫中序列化 DAGs的最小秒數。 **預設：**30  |  您可以使用此選項，透過**增加**資料庫中序列化 DAGs更新後的秒數來釋放資源。如果您有大量 DAGs 或複雜的 DAGs，建議您增加此值。隨著 DAGs 序列化，增加此值可減少排程器和資料庫的負載。  | 
|  **[core.min\$1serialized\$1dag\$1fetch\$1interval](https://airflow.apache.org/docs/apache-airflow/3.0.6/configurations-ref.html#min-serialized-dag-fetch-interval)** 當已載入 DagBag 時，從資料庫重新擷取序列化 DAG 的秒數。 **預設值**：10  |  您可以使用此選項，透過**增加**重新擷取序列化 DAG 的秒數來釋放資源。值必須大於 中指定的值`core.min_serialized_dag_update_interval`，以降低資料庫「寫入」速率。隨著 DAGs序列化，增加此值可減少 Web 伺服器和資料庫的負載。  | 

------
#### [ Apache Airflow v2 ]


| Configuration | 使用案例 | 
| --- | --- | 
|  **[core.dag\$1file\$1processor\$1timeout](https://airflow.apache.org/docs/apache-airflow/2.10.3/configurations-ref.html#dag-file-processor-timeout)** *DagFileProcessor* 逾時處理 DAG 檔案之前的秒數。 **預設：**50 秒  |  您可以使用此選項，透過**增加** *DagFileProcessor* 逾時之前所需的時間來釋放資源。如果您在 DAG 處理日誌中遇到逾時，導致沒有載入可行DAGs，建議您增加此值。  | 
|  **[core.dagbag\$1import\$1timeout](https://airflow.apache.org/docs/apache-airflow/2.10.3/configurations-ref.html#dagbag-import-timeout)** 匯入 Python 檔案逾時之前的秒數。 **預設：**30 秒  |  您可以使用此選項，藉由**在**匯入 Python 檔案以擷取 DAG 物件時，增加排程器逾時之前所花費的時間來釋放資源。此選項會做為排程器「迴圈」的一部分處理，且必須包含小於 中指定值的值`core.dag_file_processor_timeout`。  | 
|  **[core.min\$1serialized\$1dag\$1update\$1interval](https://airflow.apache.org/docs/apache-airflow/2.10.3/configurations-ref.html#min-serialized-dag-update-interval)** 更新資料庫中序列化 DAGs的最小秒數。 **預設：**30  |  您可以使用此選項，透過**增加**資料庫中序列化 DAGs更新後的秒數來釋放資源。如果您有大量 DAGs 或複雜的 DAGs，建議您增加此值。隨著 DAGs 序列化，增加此值可減少排程器和資料庫的負載。  | 
|  **[core.min\$1serialized\$1dag\$1fetch\$1interval](https://airflow.apache.org/docs/apache-airflow/2.10.3/configurations-ref.html#min-serialized-dag-fetch-interval)** 當已載入 DagBag 時，從資料庫重新擷取序列化 DAG 的秒數。 **預設值**：10  |  您可以使用此選項，透過**增加**重新擷取序列化 DAG 的秒數來釋放資源。值必須大於 中指定的值`core.min_serialized_dag_update_interval`，以降低資料庫「寫入」速率。隨著 DAGs序列化，增加此值可減少 Web 伺服器和資料庫的負載。  | 

------

## 任務​
<a name="best-practices-tuning-tasks"></a>

Apache Airflow 排程器和工作者都參與佇列和取消佇列任務。排程器會將準備從**無**狀態排程的剖析任務轉換為**已排程**狀態。執行器也會在 Fargate 的排程器容器上執行，將這些任務排入佇列，並將其狀態設定為**已排**入佇列。當工作者有容量時，會從佇列中取得任務，並將狀態設定為**執行**中，然後****根據任務是否成功，將其狀態變更為**成功**或失敗。

### Parameters
<a name="best-practices-tuning-tasks-params"></a>

本節說明 Apache Airflow 任務可用的組態選項及其使用案例。

Amazon MWAA 覆寫的預設組態選項會以*紅色*標示。

------
#### [ Apache Airflow v3 ]


| Configuration | 使用案例 | 
| --- | --- | 
|  **[core.parallelism](https://airflow.apache.org/docs/apache-airflow/3.0.6/configurations-ref.html#parallelism)** 可具有 `Running` 狀態的任務執行個體數目上限。 **預設：**根據 動態設定`(maxWorkers * maxCeleryWorkers) / schedulers * 1.5`。  |  您可以使用此選項，透過**增加**可同時執行的任務執行個體數量來釋放資源。指定的值必須是可用工作者的數量乘以工作者的任務密度。我們建議您只有在遇到大量任務卡在「執行中」或「佇列」狀態時，才變更此值。  | 
|  **[core.execute\$1tasks\$1new\$1python\$1interpreter](https://airflow.apache.org/docs/apache-airflow/3.0.6/configurations-ref.html#execute-tasks-new-python-interpreter)** 決定 Apache Airflow 是否透過強制執行父程序或建立新的 Python 程序來執行任務。 **預設**：`True`  |  設定為 時`True`，Apache Airflow 會將您對外掛程式所做的變更辨識為新的 Python 程序，以便建立以執行任務。  | 
|  **[celery.worker\$1concurrency](https://airflow.apache.org/docs/apache-airflow-providers-celery/stable/configurations-ref.html#worker-concurrency)** Amazon MWAA 會覆寫此選項的 Airflow 基本安裝，以擴展工作者作為其自動擴展元件的一部分。 **預設：**不適用  |  *此選項指定的任何值都會遭到忽略。*  | 
|  **[celery.worker\$1autoscale](https://airflow.apache.org/docs/apache-airflow-providers-celery/stable/configurations-ref.html#worker-autoscale)** 工作者的任務並行。 **預設值：** [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/mwaa/latest/userguide/best-practices-tuning.html)  |  您可以使用此選項，透過**減少**工作者的任務`minimum`並行`maximum`來釋放資源。工作者最多接受設定的`maximum`並行任務，無論是否有足夠資源可以這樣做。如果任務排程時沒有足夠的資源，任務會立即失敗。我們建議將此值變更為資源密集型任務，方法是將值減少為小於預設值，以允許每個任務更多的容量。  | 

------
#### [ Apache Airflow v2 ]


| Configuration | 使用案例 | 
| --- | --- | 
|  **[core.parallelism](https://airflow.apache.org/docs/apache-airflow/2.10.3/configurations-ref.html#parallelism)** 可具有 `Running` 狀態的任務執行個體數目上限。 **預設：**根據 動態設定`(maxWorkers * maxCeleryWorkers) / schedulers * 1.5`。  |  您可以使用此選項，透過**增加**可同時執行的任務執行個體數量來釋放資源。指定的值必須是可用工作者的數量乘以工作者的任務密度。我們建議您只有在遇到大量任務卡在「執行中」或「佇列」狀態時，才變更此值。  | 
|  **[core.dag\$1concurrency](https://airflow.apache.org/docs/apache-airflow/2.10.3/configurations-ref.html#dag-concurrency)** 允許為每個 DAG 同時執行的任務執行個體數目。 **預設：**10000  |  您可以使用此選項，透過**增加**允許同時執行的任務執行個體數量來釋放資源。例如，如果您有 100 個具有 10 個平行任務DAGs，而且您希望所有 DAGs 同時執行，則可以計算最大平行處理，將可用工作者數量乘以 中的工作者任務密度`celery.worker_concurrency`，再除以 DAGs 數量。  | 
|  **[core.execute\$1tasks\$1new\$1python\$1interpreter](https://airflow.apache.org/docs/apache-airflow/2.10.3/configurations-ref.html#execute-tasks-new-python-interpreter)** 決定 Apache Airflow 是否透過強制執行父程序或建立新的 Python 程序來執行任務。 **預設**：`True`  |  設定為 時`True`，Apache Airflow 會將您對外掛程式所做的變更辨識為新的 Python 程序，以便建立以執行任務。  | 
|  **[celery.worker\$1concurrency](https://airflow.apache.org/docs/apache-airflow-providers-celery/stable/configurations-ref.html#worker-concurrency)** Amazon MWAA 會覆寫此選項的 Airflow 基本安裝，以擴展工作者作為其自動擴展元件的一部分。 **預設：**不適用  |  *此選項指定的任何值都會遭到忽略。*  | 
|  **[celery.worker\$1autoscale](https://airflow.apache.org/docs/apache-airflow-providers-celery/stable/configurations-ref.html#worker-autoscale)** 工作者的任務並行。 **預設值：** [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/mwaa/latest/userguide/best-practices-tuning.html)  |  您可以使用此選項，透過**減少**工作者的任務`minimum`並行`maximum`來釋放資源。工作者最多接受設定的`maximum`並行任務，無論是否有足夠資源可以這樣做。如果任務排程時沒有足夠的資源，任務會立即失敗。我們建議將此值變更為資源密集型任務，方法是將值減少為小於預設值，以允許每個任務更多的容量。  | 

------

# 在 requirements.txt 中管理 Python 相依性
<a name="best-practices-dependencies"></a>

本主題說明如何在 Amazon Managed Workflows for Apache Airflow 環境的 `requirements.txt` 檔案中安裝和管理 Python 相依性。

**Contents**
+ [使用 Amazon MWAA CLI 公用程式測試 DAGs](#best-practices-dependencies-cli-utility)
+ [使用 PyPi.org 要求檔案格式安裝 Python 相依性](#best-practices-dependencies-different-ways)
  + [選項一：Python 套件索引中的 Python 相依性](#best-practices-dependencies-pip-extras)
  + [選項二：Python wheel (.whl)](#best-practices-dependencies-python-wheels)
    + [在 Amazon S3 儲存貯體上使用 `plugins.zip` 檔案](#best-practices-dependencies-python-wheels-s3)
    + [使用 URL 上託管的 WHL 檔案](#best-practices-dependencies-python-wheels-url)
    + [從 DAG 建立 WHL 檔案](#best-practices-dependencies-python-wheels-dag)
  + [選項三：託管在私有 PyPi/PEP-503 相容儲存庫上的 Python 相依性](#best-practices-dependencies-custom-auth-url)
+ [在 Amazon MWAA 主控台上啟用日誌](#best-practices-dependencies-troubleshooting-enable)
+ [在 CloudWatch Logs 主控台上存取日誌](#best-practices-dependencies-troubleshooting-view)
+ [在 Apache Airflow UI 中存取錯誤](#best-practices-dependencies-troubleshooting-aa)
  + [登入 Apache Airflow](#airflow-access-and-login)
+ [範例`requirements.txt`案例](#best-practices-dependencies-ex-mix-match)

## 使用 Amazon MWAA CLI 公用程式測試 DAGs
<a name="best-practices-dependencies-cli-utility"></a>
+ 命令列界面 (CLI) 公用程式會在本機複寫 Amazon Managed Workflows for Apache Airflow 環境。
+ CLI 會在本機建置類似於 Amazon MWAA 生產映像的 Docker 容器映像。您可以使用它來執行本機 Apache Airflow 環境，以在部署到 Amazon MWAA 之前開發和測試 DAGs、自訂外掛程式和相依性。
+ 若要執行 CLI，請參閱 GitHub 上的 [aws-mwaa-docker-images](https://github.com/aws/amazon-mwaa-docker-images)。

## 使用 PyPi.org 要求檔案格式安裝 Python 相依性
<a name="best-practices-dependencies-different-ways"></a>

下一節說明根據 PyPi.org [需求檔案格式](https://pip.pypa.io/en/stable/reference/pip_install/#requirements-file-format)安裝 Python 相依性的不同方式。

### 選項一：Python 套件索引中的 Python 相依性
<a name="best-practices-dependencies-pip-extras"></a>

下一節說明如何從 `requirements.txt` 檔案中的 Python [套件索引指定 Python](https://pypi.org/) 相依性。

------
#### [ Apache Airflow v3 ]

1. 在**本機測試**。在建立`requirements.txt`檔案之前，反覆新增其他程式庫，以尋找套件及其版本的正確組合。若要執行 Amazon MWAA CLI 公用程式，請參閱 GitHub 上的 [aws-mwaa-docker-images](https://github.com/aws/amazon-mwaa-docker-images)。

1. **檢閱 Apache Airflow 套件額外項目**。若要存取 Amazon MWAA 上為 Apache Airflow v3 安裝的套件清單，請參閱 GitHub 網站上的 [aws-mwaa-docker-images`requirements.txt`](https://github.com/aws/amazon-mwaa-docker-images/blob/main/requirements.txt)。

1. **新增限制條件陳述式**。在檔案頂端新增 Apache Airflow v3 環境的限制條件`requirements.txt`檔案。Apache Airflow 限制條件檔案會指定 Apache Airflow 發行時可用的提供者版本。

    在下列範例中，將 *\$1environment-version\$1* 取代為您環境的版本編號，並將 *\$1Python-version\$1* 取代為您環境相容的 Python 版本。

    如需有關與 Apache Airflow 環境相容的 Python 版本的資訊，請參閱 [Apache Airflow 版本](airflow-versions.md#airflow-versions-official)。

   ```
   --constraint "https://raw.githubusercontent.com/apache/airflow/constraints-{Airflow-version}/constraints-{Python-version}.txt"
   ```

    如果限制條件檔案判斷`xyz==1.0`套件與您環境中的其他套件不相容， `pip3 install` 無法防止不相容的程式庫安裝到您的環境。如果任何套件的安裝失敗，您可以在 CloudWatch Logs 的對應日誌串流中存取每個 Apache Airflow 元件 （排程器、工作者和 Web 伺服器） 的錯誤日誌。如需日誌類型的詳細資訊，請參閱 [在 Amazon CloudWatch 中存取 Airflow 日誌](monitoring-airflow.md)。

1. **Apache Airflow 套件**。新增[套件額外項目](http://airflow.apache.org/docs/apache-airflow/2.5.1/extra-packages-ref.html)和版本 (`==`)。這有助於防止相同名稱但不同版本的套件安裝在您的環境中。

   ```
   apache-airflow[package-extra]==2.5.1
   ```

1. **Python 程式庫**。在 `requirements.txt` 檔案中新增套件名稱和版本 (`==`)。這有助於防止 [PyPi.org](https://pypi.org) 未來的重大更新自動套用。

   ```
   library == version
   ```  
**Example Boto3 和 psycopg2-binary**  

   此範例僅供示範之用。boto 和 psycopg2-binary 程式庫包含在 Apache Airflow v3 的基本安裝中，不需要在`requirements.txt`檔案中指定。

   ```
   boto3==1.17.54
   boto==2.49.0
   botocore==1.20.54
   psycopg2-binary==2.8.6
   ```

   如果指定的套件沒有版本，Amazon MWAA 會從 [PyPi.org](https://pypi.org) 安裝最新版本的套件。此版本可能會與您 中的其他套件衝突`requirements.txt`。

------
#### [ Apache Airflow v2 ]

1. 在**本機測試**。在建立`requirements.txt`檔案之前，反覆新增其他程式庫，以尋找套件及其版本的正確組合。若要執行 Amazon MWAA CLI 公用程式，請參閱 GitHub 上的 [aws-mwaa-docker-images](https://github.com/aws/amazon-mwaa-docker-images)。

1. **檢閱 Apache Airflow 套件額外項目**。若要存取 Amazon MWAA 上為 Apache Airflow v2 安裝的套件清單，請存取 GitHub 網站上的 [aws-mwaa-docker-images`requirements.txt`](https://github.com/aws/amazon-mwaa-docker-images/blob/main/requirements.txt)。

1. **新增限制條件陳述式**。在檔案頂端新增 Apache Airflow v2 環境的限制條件`requirements.txt`檔案。Apache Airflow 限制條件檔案會指定 Apache Airflow 發行時可用的提供者版本。

    從 Apache Airflow 2.7.2 版開始，您的需求檔案必須包含 `--constraint`陳述式。如果您未提供限制條件，Amazon MWAA 會為您指定一個限制條件，以確保您的需求中列出的套件與您正在使用的 Apache Airflow 版本相容。

   在下列範例中，將 *\$1environment-version\$1* 取代為您環境的版本編號，並將 *\$1Python-version\$1* 取代為您環境相容的 Python 版本。

   如需有關與 Apache Airflow 環境相容的 Python 版本的資訊，請參閱 [Apache Airflow 版本](airflow-versions.md#airflow-versions-official)。

   ```
   --constraint "https://raw.githubusercontent.com/apache/airflow/constraints-{Airflow-version}/constraints-{Python-version}.txt"
   ```

   如果限制條件檔案判斷`xyz==1.0`套件與您環境中的其他套件不相容， `pip3 install` 無法防止不相容的程式庫安裝到您的環境。如果任何套件的安裝失敗，您可以在 CloudWatch Logs 的對應日誌串流中存取每個 Apache Airflow 元件 （排程器、工作者和 Web 伺服器） 的錯誤日誌。如需日誌類型的詳細資訊，請參閱 [在 Amazon CloudWatch 中存取 Airflow 日誌](monitoring-airflow.md)。

1. **Apache Airflow 套件**。新增[套件額外項目](http://airflow.apache.org/docs/apache-airflow/2.5.1/extra-packages-ref.html)和版本 (`==`)。這有助於防止相同名稱但不同版本的套件安裝在您的環境中。

   ```
   apache-airflow[package-extra]==2.5.1
   ```

1. **Python 程式庫**。在 `requirements.txt` 檔案中新增套件名稱和版本 (`==`)。這有助於防止 [PyPi.org](https://pypi.org) 未來的重大更新自動套用。

   ```
   library == version
   ```  
**Example Boto3 和 psycopg2-binary**  

   此範例僅供示範之用。boto 和 psycopg2-binary 程式庫包含在 Apache Airflow v2 基本安裝中，不需要在`requirements.txt`檔案中指定。

   ```
   boto3==1.17.54
   boto==2.49.0
   botocore==1.20.54
   psycopg2-binary==2.8.6
   ```

   如果指定的套件沒有版本，Amazon MWAA 會從 [PyPi.org](https://pypi.org) 安裝最新版本的套件。此版本可能會與您 中的其他套件衝突`requirements.txt`。

------

### 選項二：Python wheel (.whl)
<a name="best-practices-dependencies-python-wheels"></a>

Python wheel 是一種套件格式，旨在使用編譯的成品來運送程式庫。輪子套件做為在 Amazon MWAA 中安裝相依性的方法，有幾個好處：
+ **更快速的安裝** – WHL 檔案會以單一 ZIP 的形式複製到容器，然後在本機安裝，無需下載每個檔案。
+ **較少衝突** – 您可以事先判斷套件的版本相容性。因此， 不需要`pip`遞迴處理相容的版本。
+ **更高的彈性** – 使用外部託管程式庫時，下游需求可能會變更，導致 Amazon MWAA 環境中容器之間的版本不相容。透過不依賴相依性的外部來源， 上的每個容器都有相同的程式庫，無論每個容器何時執行個體化。

我們建議您使用下列方法來從 中的 Python wheel 封存檔 (`.whl`) 安裝 Python 相依性`requirements.txt`。

**Topics**
+ [在 Amazon S3 儲存貯體上使用 `plugins.zip` 檔案](#best-practices-dependencies-python-wheels-s3)
+ [使用 URL 上託管的 WHL 檔案](#best-practices-dependencies-python-wheels-url)
+ [從 DAG 建立 WHL 檔案](#best-practices-dependencies-python-wheels-dag)

#### 在 Amazon S3 儲存貯體上使用 `plugins.zip` 檔案
<a name="best-practices-dependencies-python-wheels-s3"></a>

Apache Airflow 排程器、工作者和 webserver （適用於 Apache Airflow 2.2.2 版及更新版本） 會在 中為您的環境在 AWS受管 Fargate 容器上啟動期間搜尋自訂外掛程式。 `/usr/local/airflow/plugins/*`此程序會在 Python 相依性和 Apache Airflow 服務啟動`pip3 install -r requirements.txt`的 Amazon MWAA 之前開始。`plugins.zip` 檔案可用於您不想要在環境執行期間持續變更的任何檔案，或者您不想將存取權授予寫入 DAGs的使用者。例如，Python 程式庫 wheel 檔案、憑證 PEM 檔案和組態 YAML 檔案。

下一節說明如何在 Amazon S3 儲存貯體的 `plugins.zip` 檔案中安裝輪子。

1. **下載必要的 WHL 檔案** 您可以[https://pip.pypa.io/en/stable/cli/pip_download/](https://pip.pypa.io/en/stable/cli/pip_download/)與 Amazon MWAA [aws-mwaa-docker-images](https://github.com/aws/amazon-mwaa-docker-images) 或其他 [Amazon Linux 2](https://aws.amazon.com/amazon-linux-2) 容器`requirements.txt`上的現有 搭配使用，以解析和下載必要的 Python wheel 檔案。

   ```
   pip3 download -r "$AIRFLOW_HOME/dags/requirements.txt" -d "$AIRFLOW_HOME/plugins"
   cd "$AIRFLOW_HOME/plugins"
   zip "$AIRFLOW_HOME/plugins.zip" *
   ```

1. **在 中指定路徑`requirements.txt`**。使用 指定您 requirements.txt 頂端的外掛程式目錄，[https://pip.pypa.io/en/stable/cli/pip_install/#install-find-links](https://pip.pypa.io/en/stable/cli/pip_install/#install-find-links)並指示`pip`不要使用 從其他來源安裝 [https://pip.pypa.io/en/stable/cli/pip_install/#install-no-index](https://pip.pypa.io/en/stable/cli/pip_install/#install-no-index)，如下列程式碼所列：

   ```
   --find-links /usr/local/airflow/plugins
   --no-index
   ```  
**Example requirements.txt 中的 wheel**  

   下列範例假設您已在 Amazon S3 儲存貯體根目錄中的`plugins.zip`檔案中上傳輪子。例如：

   ```
   --find-links /usr/local/airflow/plugins
   --no-index
   
   numpy
   ```

   Amazon MWAA 會從 `plugins` 資料夾擷取`numpy-1.20.1-cp37-cp37m-manylinux1_x86_64.whl`輪子，並將其安裝在您的環境中。

#### 使用 URL 上託管的 WHL 檔案
<a name="best-practices-dependencies-python-wheels-url"></a>

下一節說明如何安裝託管在 URL 上的滾輪。URL 必須可公開存取，或從您為 Amazon MWAA 環境指定的自訂 Amazon VPC 中存取。
+ **提供 URL**。將 URL 提供給 中的滾輪`requirements.txt`。  
**Example 公有 URL 上的車輪封存**  

  下列範例會從公有網站下載輪子。

  ```
  --find-links https://files.pythonhosted.org/packages/
  --no-index
  ```

  Amazon MWAA 會從您指定的 URL 擷取輪子，並將其安裝在您的環境中。
**注意**  
URLs。

#### 從 DAG 建立 WHL 檔案
<a name="best-practices-dependencies-python-wheels-dag"></a>

如果您有使用 Apache Airflow 2.2.2 版或更新版本的私有 Web 伺服器，而且由於您的環境無法存取外部儲存庫，因此無法安裝需求，您可以使用下列 DAG 來接受現有的 Amazon MWAA 需求，並將其封裝在 Amazon S3 上：

```
from airflow import DAG
 from airflow.operators.bash_operator import BashOperator
 from airflow.utils.dates import days_ago
					
 S3_BUCKET = 'my-s3-bucket'
 S3_KEY = 'backup/plugins_whl.zip' 
					
 with DAG(dag_id="create_whl_file", schedule_interval=None, catchup=False, start_date=days_ago(1)) as dag:
 cli_command = BashOperator(
 task_id="bash_command",
 bash_command=f"mkdir /tmp/whls;pip3 download -r /usr/local/airflow/requirements/requirements.txt -d /tmp/whls;zip -j /tmp/plugins.zip /tmp/whls/*;aws s3 cp /tmp/plugins.zip s3://amzn-s3-demo-bucket/{S3_KEY}"
)
```

執行 DAG 之後，請`plugins.zip`選擇性地使用此新檔案做為您的 Amazon MWAA，並與其他外掛程式一起封裝。然後，以 `--find-links /usr/local/airflow/plugins` 和 更新您的`requirements.txt`前綴，`--no-index`而不新增 `--constraint`。

此方法可讓您離線使用相同的程式庫。

### 選項三：託管在私有 PyPi/PEP-503 相容儲存庫上的 Python 相依性
<a name="best-practices-dependencies-custom-auth-url"></a>

下一節說明如何安裝在具有身分驗證的私有 URL 上託管的 Apache Airflow 額外項目。

1. 將您的使用者名稱和密碼新增為 [Apache Airflow 組態選項](configuring-env-variables.md)。例如：
   + `foo.user` : `YOUR_USER_NAME`
   + `foo.pass` : `YOUR_PASSWORD`

1. 建立您的 `requirements.txt` 檔案。將下列範例中的預留位置替換為您的私有 URL，以及您新增為 [Apache Airflow 組態選項](configuring-env-variables.md)的使用者名稱和密碼。例如：

   ```
   --index-url https://${AIRFLOW__FOO__USER}:${AIRFLOW__FOO__PASS}@my.privatepypi.com
   ```

1. 將任何其他程式庫新增至您的 `requirements.txt` 檔案。例如：

   ```
   --index-url https://${AIRFLOW__FOO__USER}:${AIRFLOW__FOO__PASS}@my.privatepypi.com
   my-private-package==1.2.3
   ```

## 在 Amazon MWAA 主控台上啟用日誌
<a name="best-practices-dependencies-troubleshooting-enable"></a>

Amazon MWAA 環境的[執行角色](mwaa-create-role.md)需要許可，才能將日誌傳送至 CloudWatch Logs。若要更新執行角色的許可，請參閱 [Amazon MWAA 執行角色](mwaa-create-role.md)。

您可以在 `INFO`、`ERROR`、 或 `CRITICAL`層級啟用 Apache Airflow `WARNING`日誌。當您選擇日誌層級時，Amazon MWAA 會傳送該層級和所有較高嚴重性層級的日誌。例如，如果您在 `INFO`層級啟用日誌，Amazon MWAA 會將`INFO`日誌和 `ERROR`、 `WARNING`和 `CRITICAL`日誌層級傳送至 CloudWatch Logs。我們建議在排程器的 `INFO`層級啟用 Apache Airflow 日誌，以存取 收到的日誌`requirements.txt`。

![\[此影像說明如何在 INFO 層級啟用日誌。\]](http://docs.aws.amazon.com/zh_tw/mwaa/latest/userguide/images/mwaa-console-logs-info.png)


## 在 CloudWatch Logs 主控台上存取日誌
<a name="best-practices-dependencies-troubleshooting-view"></a>

您可以存取排程器的 Apache Airflow 日誌來排程工作流程和剖析`dags`資料夾。下列步驟說明如何在 Amazon MWAA 主控台上開啟排程器的日誌群組，以及在 CloudWatch Logs 主控台上存取 Apache Airflow 日誌。

**存取 的日誌 `requirements.txt`**

1. 在 Amazon MWAA 主控台上開啟[環境](https://console.aws.amazon.com/mwaa/home#/environments)頁面。

1. 選擇環境。

1. 在**監控**窗格中選擇 **Airflow 排程器日誌群組**。

1. 在`requirements_install_ip`日誌**串流中選擇日誌**。

1. 請參閱 環境上安裝的套件清單`/usr/local/airflow/.local/bin`。例如：

   ```
   Collecting appdirs==1.4.4 (from -r /usr/local/airflow/.local/bin (line 1))
   Downloading https://files.pythonhosted.org/packages/3b/00/2344469e2084fb28kjdsfiuyweb47389789vxbmnbjhsdgf5463acd6cf5e3db69324/appdirs-1.4.4-py2.py3-none-any.whl  
   Collecting astroid==2.4.2 (from -r /usr/local/airflow/.local/bin (line 2))
   ```

1. 檢閱套件清單，以及是否有任何套件在安裝期間發生錯誤。如果發生錯誤，您可能會收到類似以下的錯誤：

   ```
   2021-03-05T14:34:42.731-07:00
   No matching distribution found for LibraryName==1.0.0 (from -r /usr/local/airflow/.local/bin (line 4))
   No matching distribution found for LibraryName==1.0.0 (from -r /usr/local/airflow/.local/bin (line 4))
   ```

## 在 Apache Airflow UI 中存取錯誤
<a name="best-practices-dependencies-troubleshooting-aa"></a>

您也可以檢查 Apache Airflow UI，以識別錯誤是否與另一個問題相關。使用 Amazon MWAA 上的 Apache Airflow 時最常遇到的錯誤是：

```
Broken DAG: No module named x
```

如果您在 Apache Airflow UI 中發現此錯誤，則檔案中可能會缺少必要的相依性`requirements.txt`。

### 登入 Apache Airflow
<a name="airflow-access-and-login"></a>

您需要 AWS 帳戶 in AWS Identity and Access Management (IAM) 存取 Apache Airflow UI 的[Apache Airflow UI 存取政策：AmazonMWAAWebServerAccess](access-policies.md#web-ui-access)許可。

**存取您的 Apache Airflow UI**

1. 在 Amazon MWAA 主控台上開啟[環境](https://console.aws.amazon.com/mwaa/home#/environments)頁面。

1. 選擇環境。

1. 選擇**開啟氣流使用者介面**。

## 範例`requirements.txt`案例
<a name="best-practices-dependencies-ex-mix-match"></a>

您可以在 中混合和比對不同的格式`requirements.txt`。下列範例使用不同方式的組合來安裝額外項目。

**Example PyPi.org 上的額外項目和公有 URL**  
從 PyPi.org 指定套件時，除了公有 URL 上的套件，例如自訂 PEP 503 相容儲存庫 URLs，您還需要使用 `--index-url`選項。 PyPi.org,   

```
aws-batch == 0.6
				phoenix-letter >= 0.3
				
				--index-url http://dist.repoze.org/zope2/2.10/simple
				zopelib
```