

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# Amazon MMWAA 的最佳实践
<a name="best-practices"></a>

本指南介绍了在使用 Amazon MWAA 时我们推荐的最佳实践。

**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 MWAA 上使用 Apache Airflow 配置选项](configuring-env-variables.md) 调整 Amazon MWAA 环境的性能。

**Contents**
+ [添加 Apache Airflow 配置选项。](#best-practices-tuning-console-add)
+ [Apache Airflow 计划程序](#best-practices-tuning-scheduler)
  + [参数](#best-practices-tuning-scheduler-params)
  + [限制](#best-practices-tuning-scheduler-limits)
+ [DAG 文件夹](#best-practices-tuning-dag-folders)
  + [参数](#best-practices-tuning-dag-folders-params)
+ [DAG 文件](#best-practices-tuning-dag-files)
  + [参数](#best-practices-tuning-dag-files-params)
+ [任务](#best-practices-tuning-tasks)
  + [参数](#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)。

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

本节介绍可用于 Apache Airflow 计划程序（Apache Airflow v2 和更高版本）的配置选项及其使用案例。

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


| 配置 | 使用案例 | 
| --- | --- | 
|  **[celery.sync\$1parallelism](https://airflow.apache.org/docs/apache-airflow/3.0.6/configurations-ref.html#parallelism)** Celery 执行程序用于同步任务状态的进程数。 **默认值**：1  |  您可以使用此选项通过限制 Celery 执行程序使用的进程来防止队列冲突。默认情况下，将值设置为，`1`以防止在将任务日志传送到 CloudWatch 日志时出错。将该值设为 `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  |  在计划程序检索 DAG 解析结果、查找任务和对任务进行排队以及在*执行程序*中执行排队任务后，您可以使用此选项通过**延长**计划程序的休眠时间来释放计划程序上的 CPU 使用率。增加此值会消耗在 Apache Airflow v2 和 Apache Airflow v3 的 `dag_processor.parsing_processes` 的环境中运行的计划程序线程数。这可能会降低调度程序的解析能力 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 ]


| 配置 | 使用案例 | 
| --- | --- | 
|  **[celery.sync\$1parallelism](https://airflow.apache.org/docs/apache-airflow/2.10.3/configurations-ref.html#parallelism)** Celery 执行程序用于同步任务状态的进程数。 **默认值**：1  |  您可以使用此选项通过限制 Celery 执行程序使用的进程来防止队列冲突。默认情况下，将值设置为，`1`以防止在将任务日志传送到 CloudWatch 日志时出错。将该值设为 `0` 意味着使用最大进程数，但在传送任务日志时可能会导致错误。  | 
|  **[scheduler.idle\$1sleep\$1time](https://airflow.apache.org/docs/apache-airflow/2.10.3/configurations-ref.html#scheduler-idle-sleep-time)** 在计划程序“循环”中连续处理 DAG 文件之间等待的秒数。 **默认值**：1  |  在计划程序检索 DAG 解析结果、查找任务和对任务进行排队以及在*执行程序*中执行排队任务后，您可以使用此选项通过**延长**计划程序的休眠时间来释放计划程序上的 CPU 使用率。增加此值会消耗在 Apache Airflow v2 和 Apache Airflow v3 的 `scheduler.parsing_processes` 的环境中运行的计划程序线程数。这可能会降低调度程序的解析能力 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，调度器本身减一。您在 `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 对象，都会进行 DAG 文件解析。

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

本节介绍该 DAGs 文件夹（Apache Airflow v2 及更高版本）可用的配置选项及其用例。

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


| 配置 | 使用案例 | 
| --- | --- | 
|  **[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 ]


| 配置 | 使用案例 | 
| --- | --- | 
|  **[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) 中指定的秒数必须流逝后，才能再次解析同一个文件。

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

本节介绍可用于 Apache Airflow DAG 文件的配置选项（Apache Airflow v2 和更高版本）及其使用案例。

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


| 配置 | 使用案例 | 
| --- | --- | 
|  **[dag\$1processor.dag\$1file\$1processor\$1timeout](https://airflow.apache.org/docs/apache-airflow/3.0.6/configurations-ref.html#dag-file-processor-timeout)** 处理 DAG 文件超*DagFileProcessor*时之前的秒数。 **默认值：**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)** 序列化的 DAG 已加载到数据库中时从数据库中重新提取的秒数。 DagBag **默认值**：10  |  通过**增加**序列化的 DAG 重新提取的秒数，您可以使用此选项来释放资源。该值必须大于 `core.min_serialized_dag_update_interval` 中指定的值才能降低数据库的“写入”速率。增加此值可减少序列化后的 Web 服务器和数据库 DAGs 的负载。  | 

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


| 配置 | 使用案例 | 
| --- | --- | 
|  **[core.dag\$1file\$1processor\$1timeout](https://airflow.apache.org/docs/apache-airflow/2.10.3/configurations-ref.html#dag-file-processor-timeout)** 处理 DAG 文件超*DagFileProcessor*时之前的秒数。 **默认值：**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)** 序列化的 DAG 已加载到数据库中时从数据库中重新提取的秒数。 DagBag **默认值**：10  |  通过**增加**序列化的 DAG 重新提取的秒数，您可以使用此选项来释放资源。该值必须大于 `core.min_serialized_dag_update_interval` 中指定的值才能降低数据库的“写入”速率。增加此值可减少序列化后的 Web 服务器和数据库 DAGs 的负载。  | 

------

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

Apache Airflow 计划程序和工作线程都参与排队和出队任务。计划程序将已解析的准备调度的任务从**无**状态变为**已计划**状态。也在 Fargate 的计划程序容器上运行的执行程序，对这些任务进行排队并将其状态设置为**已排队**。当工作线程有容量时，它会从队列中提取任务并将状态设置为**正在运行**，然后根据任务成功还是失败将其状态更改为**成功**或**失败**。

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

本节介绍可用于 Apache Airflow 任务的配置选项及其用例。

标记 Amazon MWAA 覆盖的默认配置选项。*red*

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


| 配置 | 使用案例 | 
| --- | --- | 
|  **[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 基础版安装，以作为自动扩缩组件的一部分扩缩工作线程。 **默认值：**不适用  |  *Any value specified for this option is ignored.*  | 
|  **[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_cn/mwaa/latest/userguide/best-practices-tuning.html)  |  通过**降低**工作线程的 `minimum`、`maximum` 任务并发度，您可以使用此选项来释放资源。无论是否有足够的资源，工作人员最多可以接受配置的`maximum`并发任务。如果在没有足够资源的情况下调度任务，则任务会立即失败。我们建议为资源密集型任务更改此值，方法是将该值减少到小于默认值，以允许每个任务有更多容量。  | 

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


| 配置 | 使用案例 | 
| --- | --- | 
|  **[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  |  通过**增加**可以并发运行的任务实例数，您可以使用此选项来释放资源。例如，如果您有一百个包含十 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 基础版安装，以作为自动扩缩组件的一部分扩缩工作线程。 **默认值：**不适用  |  *Any value specified for this option is ignored.*  | 
|  **[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_cn/mwaa/latest/userguide/best-practices-tuning.html)  |  通过**降低**工作线程的 `minimum`、`maximum` 任务并发度，您可以使用此选项来释放资源。无论是否有足够的资源，工作人员最多可以接受配置的`maximum`并发任务。如果在没有足够资源的情况下调度任务，则任务会立即失败。我们建议为资源密集型任务更改此值，方法是将该值减少到小于默认值，以允许每个任务有更多容量。  | 

------

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

本主题介绍了在 `requirements.txt` 文件中如何为 Amazon MWAA 环境安装和管理 Python 依赖项。

**Contents**
+ [DAGs 使用 Amazon MWAA CLI 实用工具进行测试](#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 日志](#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)

## DAGs 使用 Amazon MWAA CLI 实用工具进行测试
<a name="best-practices-dependencies-cli-utility"></a>
+ 命令行界面 (CLI) 实用工具可在本地复制 Amazon MWAA 环境。
+ CLI 在本地构建 Docker 容器镜像，类似于 Amazon MWAA 生产镜像。在部署到 Amazon MWAA 之前，您可以使用它来运行本地 Apache Airflow 环境来开发和 DAGs测试自定义插件和依赖项。
+ 要运行 CLI，请参阅[aws-mwaa-docker-images](https://github.com/aws/amazon-mwaa-docker-images)上的 GitHub。

## 使用 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 程序包索引](https://pypi.org/)中的 Python 依赖项。

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

1. **本地测试**。在创建 `requirements.txt` 文件之前，以迭代方式添加其他库以找到程序包及其版本的正确组合。要运行 Amazon MWAA CLI 实用程序，请参阅上的。[aws-mwaa-docker-images](https://github.com/aws/amazon-mwaa-docker-images) GitHub

1. **查看 Apache Airflow 程序包的 Extras**。要访问亚马逊 MWAA 上为 Apache Airflow v3 安装的软件包列表，请参阅网站。[aws-mwaa-docker-images `requirements.txt`](https://github.com/aws/amazon-mwaa-docker-images/blob/main/requirements.txt) GitHub 

1. **添加约束语句**。在文件顶部添加 Apache Airflow v3 环境的约束文件。`requirements.txt`Apache Airflow 约束文件指定了 Apache Airflow 发布时可用的提供程序版本。

    在以下示例中，用环境的版本号替换 *\$1environment-version\$1* 以及用与环境兼容的 Python 版本替换 *\$1Python-version\$1*。

    有关与 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` 将无法阻止不兼容的库安装到环境中。如果任何软件包的安装失败，则可以在日志的相应日志流中访问每个 Apache Airflow 组件（调度程序、工作程序和 Web 服务器）的错误日志。 CloudWatch 有关日志类型的更多信息，请参阅 [访问 Amazon 中的 Airflow 日志 CloudWatch](monitoring-airflow.md)。

1. **Apache Airflow 程序包**。添加[程序包 Extras](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) 的 future 更新。

   ```
   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 会安装.org 中最新版本的PyPi软件包。](https://pypi.org)此版本可能与您 `requirements.txt` 中的其他程序包冲突。

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

1. **本地测试**。在创建 `requirements.txt` 文件之前，以迭代方式添加其他库以找到程序包及其版本的正确组合。要运行 Amazon MWAA CLI 实用程序，请参阅上的。[aws-mwaa-docker-images](https://github.com/aws/amazon-mwaa-docker-images) GitHub

1. **查看 Apache Airflow 程序包的 Extras**。要访问亚马逊 MWAA 上为 Apache Airflow v2 安装的软件包列表，请访问网站。[aws-mwaa-docker-images `requirements.txt`](https://github.com/aws/amazon-mwaa-docker-images/blob/main/requirements.txt) GitHub 

1. **添加约束语句**。在 `requirements.txt` 文件顶部添加 Apache Airflow v2 环境的约束文件。Apache Airflow 约束文件指定了 Apache Airflow 发布时可用的提供程序版本。

    从 Apache Airflow v2.7.2 开始，要求文件必须包含一条 `--constraint` 语句。如果您未提供约束条件，Amazon MWAA 将为您指定一个约束条件，以确保您的要求中列出的程序包与您正在使用的 Apache Airflow 版本兼容。

   在以下示例中，用环境的版本号替换 *\$1environment-version\$1* 以及用与环境兼容的 Python 版本替换 *\$1Python-version\$1*。

   有关与 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` 将无法阻止不兼容的库安装到环境中。如果任何软件包的安装失败，则可以在日志的相应日志流中访问每个 Apache Airflow 组件（调度程序、工作程序和 Web 服务器）的错误日志。CloudWatch 有关日志类型的更多信息，请参阅 [访问 Amazon 中的 Airflow 日志 CloudWatch](monitoring-airflow.md)。

1. **Apache Airflow 程序包**。添加[程序包 Extras](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) 的 future 更新。

   ```
   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 会安装.org 中最新版本的PyPi软件包。](https://pypi.org)此版本可能与您 `requirements.txt` 中的其他程序包冲突。

------

### 选项二：Python Wheel（.whl）
<a name="best-practices-dependencies-python-wheels"></a>

Python Wheel 是一种程序包格式，旨在发布包含已编译构件的库。将 Wheel 程序包作为在 Amazon MWAA 中安装依赖项的方法有几个好处：
+ **安装速度更快** — WHL 文件作为单个 ZIP 文件复制到容器中，然后安装到本地，无需下载每个文件。
+ **减少冲突**-您可以提前确定程序包的版本兼容性。因此，无需 `pip` 以递归方式计算出兼容版本。
+ **更高的弹性** — 对于外部托管的库，下游要求可能会发生变化，从而导致 Amazon MWAA 环境中容器之间的版本不兼容。由于不依赖外部来源来获取依赖项，因此无论每个容器何时实例化，其上每个容器都有相同的库。

我们建议使用以下方法来安装 `requirements.txt` 中来自 Python Wheel 档案 (`.whl`) 的 Python 依赖项。

**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 调度程序、工作程序和网络服务器（适用于 Apache Airflow v2.2.2 及更高版本）在启动期间在您的环境的托管的 Fargate 容器上搜索自定义插件，网址为。 AWS`/usr/local/airflow/plugins/*`此过程在 Python 依赖项的 Amazon MWAA 的 `pip3 install -r requirements.txt` 和 Apache Airflow 服务启动之前开始。`plugins.zip`文件可用于任何您不想在环境执行期间持续更改的文件，或者您不想向写入用户授予访问权限的任何文件 DAGs。例如，Python 库 Wheel 文件、证书 PEM 文件和配置 YAML 文件。

下一节介绍如何在 Amazon S3 存储桶上安装 `plugins.zip` 文件中的 Wheel。

1. **下载必要的 WHL 文件**您可以使用[https://pip.pypa.io/en/stable/cli/pip_download/](https://pip.pypa.io/en/stable/cli/pip_download/)亚马逊 MWAA [aws-mwaa-docker-images](https://github.com/aws/amazon-mwaa-docker-images)或其他[亚马逊 Linux 2](https://aws.amazon.com/amazon-linux-2) 容器`requirements.txt`上的现有文件来解析和下载必要的 Python 轮子文件。

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

1. **在 `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) 指定位于 requirements.txt 顶部的插件目录，并指示 `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**  

   以下示例假设您已将 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` Wheel 并将其安装到环境中。

#### 使用托管在 URL 上的 WHL 文件
<a name="best-practices-dependencies-python-wheels-url"></a>

下一节将介绍如何安装托管在 URL 上的 Wheel。此 URL 必须是可公开访问的，或者可以从您为 Amazon MWAA 环境指定的自定义 Amazon VPC 中访问。
+ **提供 URL**。向 `requirements.txt` 中的 Wheel 提供 URL。  
**Example 公有 URL 上的 Wheel 档案**  

  以下示例从公有站点下载 Wheel。

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

  Amazon MWAA 从您指定的 URL 中获取 Wheel 并将其安装到环境中。
**注意**  
URLs 无法通过私有 Web 服务器访问 Amazon MWAA v2.2 及更高版本中的安装要求。

#### 从 DAG 创建 WHL 文件
<a name="best-practices-dependencies-python-wheels-dag"></a>

如果私有 Web 服务器使用 Apache Airflow v2.2.2 或更高版本，并且由于环境无法访问外部存储库而无法安装要求，则可以使用以下 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 后，使用这个新文件作为 Amazon MWAA `plugins.zip`，也可以选择与其他插件一起打包。然后通过在前面添加 `--find-links /usr/local/airflow/plugins` 和 `--no-index`，但不添加 `--constraint` 来更新 `requirements.txt`。

此方法允许您离线使用相同的库。

### 选项三：托管在兼容 PyPi /PEP-503 的私有存储库上的 Python 依赖关系
<a name="best-practices-dependencies-custom-auth-url"></a>

下一节介绍如何安装托管在私有 URL 上且经过身份验证的 Apache Airflow Extra。

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 要更新执行角色的权限，请参阅 [Amazon MWAA 执行角色](mwaa-create-role.md)。

您可以启用 `INFO`、`WARNING`、`ERROR` 或 `CRITICAL` 级别的 Apache Airflow 日志。当您选择日志级别时，Amazon MWAA 会发送该级别和所有更高级别的严重性级别的日志。例如，如果您在`INFO`级别启用日志，Amazon MWAA 会向`INFO`日志发送日志`WARNING`、`ERROR`、和`CRITICAL`日志级别。 CloudWatch 我们建议启用 `INFO` 级别的 Apache Airflow 日志，以便计划程序访问为 `requirements.txt` 收到的日志。

![\[此图说明了如何启用 INFO 级别的日志。\]](http://docs.aws.amazon.com/zh_cn/mwaa/latest/userguide/images/mwaa-console-logs-info.png)


## 在日志控制台上访问 CloudWatch 日志
<a name="best-practices-dependencies-troubleshooting-view"></a>

您可以访问调度工作流程并解析 `dags` 文件夹的计划程序的 Apache Airflow 日志。以下步骤介绍如何在 Amazon MWAA 控制台上打开计划程序的日志组，以及如何在日志控制台上访问 Apache Airflow 日志。 CloudWatch 

**访问 `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 账户 内部 AWS Identity and Access Management (IAM) [Apache Airflow 用户界面访问策略：亚马逊 MWAAWeb ServerAccess](access-policies.md#web-ui-access) 权限才能访问你的 Apache Airflow 用户界面。

**要访问 Apache Airflow UI，请执行以下操作**

1. 在 Amazon MWAA 控制台上打开[环境页面](https://console.aws.amazon.com/mwaa/home#/environments)。

1. 选择环境。

1. 选择**打开 Airflow UI**。

## 示例 `requirements.txt` 应用场景
<a name="best-practices-dependencies-ex-mix-match"></a>

您可以在 `requirements.txt` 中混合搭配不同的格式。以下示例使用不同方式的组合来安装 Extras。

**Example PyPi.org 上的额外内容和公共网址**  
除了在公共 URL 上指定软件包（例如 PyPi兼容 PEP 503 的自定义 repo）之外，您还需要使用该`--index-url`选项。 URLs  

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