View a markdown version of this page

在 Amazon MWAA 环境中清理 Aurora PostgreSQL 数据库 - Amazon Managed Workflows for Apache Airflow

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

在 Amazon MWAA 环境中清理 Aurora PostgreSQL 数据库

Amazon Managed Workflows for Apache Airflow 使用 Aurora PostgreSQL 数据库作为 DAG 运行并存储任务实例的 Apache Airflow 元数据库。以下示例代码会定期为 Amazon MWAA 环境清除专用 Aurora PostgreSQL 数据库中的条目。

重要

Apache Airflow v3 限制了任务代码对元数据数据库的直接访问。工作人员不再连接到元数据数据库,而且 DAG 或任务代码无法直接导入或使用 Apache Airflow 数据库会话或模型。此更改提高了安全性和可扩展性。但是,适用于 Apache Airflow v2 的 DAG-based 数据库清理方法不适用于 Apache Airflow v3 环境。

取而代之的是,通过亚马逊 MWAA airflow db clean CLI 终端节点使用 CLI 命令来执行元数据数据库清理。

注意

随着时间的推移,元数据数据库会积累旧记录、xCom 数据和过时的任务数据。这种增长使用了数据库连接,减慢了您的环境并延迟了任务。定期进行元数据清理以防止出现这些问题。

版本

此页面上的代码示例特定于亚马逊 MWAA 支持的 Apache Airflow v2 和 v3。请参阅支持的 Apache Airflow 版本

先决条件

要使用本页上的示例代码,您需要以下内容:

依赖项

要在 Apache Airflow v2 中使用此代码示例,无需附加依赖项。使用 aws-mwaa-docker-images 安装 Apache Airflow。

代码示例

以下示例显示如何清理您的 Amazon MWAA 环境中的元数据数据库。

Apache Airflow v3.0.6 to 3.2.1
重要注意事项
  • 必须指定--clean-before-timestamp以控制清理可以追溯到多长时间。使用 ISO 8601 格式的时间戳(例如)。2025-01-01T00:00:00+00:00

  • 我们建议您指定--tables将清理范围限制在特定的表中。如果省略,该命令将清理所有支持的表。

  • 从较小的范围开始 — 使用较旧的--clean-before-timestamp值(更接近您的环境创建日期),然后先使用单个表。这仅限于清理最旧的记录。由于该命令会删除指定时间戳之前的所有内容,因此使用更新的时间戳会导致更大的删除范围。当你对这个过程充满信心时,逐渐向前移动时间戳。

  • Large-scale 清理会影响数据库性能。删除大量记录会给 Aurora PostgreSQL 数据库带来压力,并可能影响环境的响应能力。使用--batch-size参数控制事务大小,并考虑在低流量时段运行清理程序。在生产环境上运行时要小心。

依赖表行为

当您使用指定表时--tables,该命令会自动包括与指定表具有外键关系的所有依赖(子)表。为了满足外键约束,首先删除子表记录,然后删除父表记录。例如,指定--tables dag_run还会清除task_instance、、task_instance_historyxcom、和task_state_storedeadline因为这些表dag_run通过外键引用。

下表汇总了依赖链。

已指定表 已清理其他表格(受抚养人)
dag_run task_instance, task_instance_history, xcom, task_state_store, deadline
dag dag_version, deadline
task_instance task_instance_history, xcom
trigger task_instance, task_instance_history, xcom
dag_version task_instance, task_instance_history, xcom, dag_run

没有依赖项(例如log、、jobimport_errorsla_miss)的表在指定时将单独清除。

--dry-run在提交清理之前,使用它可以确切查看哪些表和有多少行会受到影响。

的可用参数 airflow db clean

下表描述了的可用参数airflow db clean

参数 说明 默认
--clean-before-timestamp (必填)清除数据的日期或时间戳。如果未提供时区,则假定为 Apache Airflow 的默认时区。示例:2025-01-01T00:00:00+00:00
--tables-t 要执行维护的表名(以逗号分隔)。选项包括:dag_runtask_instancetask_instance_historylogjobxcomimport_errortask_rescheduletriggerdagdag_versionsla_misscallback_requestcelery_taskmetacelery_tasksetmetaasset_eventdeadlinerevoked_tokentask_state_storeconnection_test_request_xcom_archive
--batch-size 单个事务中要删除或存档的最大行数。较低的值会减少长时间运行的锁定,但会增加批次数。
--dry-run 在不实际删除数据的情况下进行试运行。建议用于初始测试。 False
--skip-archive 不要将已清除的记录保存在存档表中。默认情况下,将清除的记录db clean移至存档表(例如按_<table>_archive惯例命名_dag_run_archive),而不是将其永久删除。这提供了一个安全网——您可以检查存档的数据,将其导出airflow db export-archived,也可以稍后删除airflow db drop-archived。设置后--skip-archive,无需此中间步骤即可永久删除记录。 False
--dag-ids 仅清理与给定 DAG ID 相关的数据。
--exclude-dag-ids 避免清理与给定 DAG ID 相关的数据。
-y, --yes 跳过确认提示。通过亚马逊 MWAA 执行非交互式 CLI 时是必需的。 False
-v, --verbose 使日志输出更加详细。 False

有关可用参数的更多信息,请参阅 Apache Airflow 网站上的 CLI 和环境变量参考

代码示例

以下示例显示如何airflow db clean通过亚马逊 MWAA CLI 终端节点进行调用。有关创建 CLI 令牌的更多信息,请参阅创建 Apache Airflow CLI 令牌

使用 Python 脚本:

import boto3 import base64 import requests # Replace with your environment name and AWS Region mwaa_env_name = "YOUR_ENVIRONMENT_NAME" region = "YOUR_REGION" # Configure cleanup scope clean_before_timestamp = "2025-06-01T00:00:00+00:00" tables = "dag_run,task_instance,log,job,xcom" # Build the Airflow CLI command # -y flag is required to skip interactive confirmation prompt airflow_cmd = f"db clean --clean-before-timestamp {clean_before_timestamp} --tables {tables} -y" # Create a CLI token client = boto3.client("mwaa", region_name=region) cli_token_response = client.create_cli_token(Name=mwaa_env_name) cli_token = cli_token_response["CliToken"] web_server_hostname = cli_token_response["WebServerHostname"] # Invoke the Airflow CLI through the MWAA endpoint url = f"https://{web_server_hostname}/aws_mwaa/cli" response = requests.post( url, headers={ "Authorization": f"Bearer {cli_token}", "Content-Type": "text/plain", }, data=airflow_cmd, ) # Parse and display the results stdout_message = base64.b64decode(response.json()["stdout"]).decode("utf-8") stderr_message = base64.b64decode(response.json()["stderr"]).decode("utf-8") print(f"Status code: {response.status_code}") print(f"stdout:\n{stdout_message}") print(f"stderr:\n{stderr_message}")
试运行示例(建议的第一步)

在执行实际清理之前,运行以下--dry-run命令以查看会删除的内容:

AIRFLOW_CMD="db clean --clean-before-timestamp 2025-06-01T00:00:00+00:00 --tables dag_run,task_instance --dry-run -y"
Apache Airflow v2.7.2 to 2.11.2
from airflow import DAG from airflow.models.param import Param from airflow.operators.bash_operator import BashOperator from airflow.utils.dates import days_ago from datetime import datetime, timedelta # Note: Database commands might time out if running longer than 5 minutes. If this occurs, please increase the MAX_AGE_IN_DAYS (or change # timestamp parameter to an earlier date) for initial runs, then reduce on subsequent runs until the desired retention is met. MAX_AGE_IN_DAYS = 30 # To clean specific tables, please provide a comma-separated list per # https://airflow.apache.org/docs/apache-airflow/stable/cli-and-env-variables-ref.html#clean # A value of None will clean all tables TABLES_TO_CLEAN = None with DAG( dag_id="clean_db_dag", schedule_interval=None, catchup=False, start_date=days_ago(1), params={ "timestamp": Param( default=(datetime.now()-timedelta(days=MAX_AGE_IN_DAYS)).strftime("%Y-%m-%d %H:%M:%S"), type="string", minLength=1, maxLength=255, ), } ) as dag: if TABLES_TO_CLEAN: bash_command="airflow db clean --clean-before-timestamp '{{ params.timestamp }}' --tables '"+TABLES_TO_CLEAN+"' --skip-archive --yes" else: bash_command="airflow db clean --clean-before-timestamp '{{ params.timestamp }}' --skip-archive --yes" cli_command = BashOperator( task_id="bash_command", bash_command=bash_command )