使用GCP Cloud Scheduler加上Pub/Sub和Cloud Functions API来触发Composer DAG
首先,创建一个Pub/Sub主题以将消息发送到Cloud Functions API。你可以在终端窗口中输入以下命令来创建一个主题,其中MY_TOPIC_NAME应替换为您所需的主题名称:
gcloud pubsub topics create MY_TOPIC_NAME
接下来,我们需要编写一个 Cloud Function,使用 Composer API 来触发 DAG。此处给出了简单的 Python 函数:
from google.cloud import composer_v1 as composer
def trigger_dag(request):
client = composer.EnvironmentsClient(
client_options={"api_endpoint": f"{request['location']}-composer.googleapis.com"}
)
dag_name = request['dag_name']
response = client.create_dag_run(
request={
"name": f"projects/{request['project_id']}/locations/{request['location']}/environments/{request['composer_environment']}/dagRuns",
"dag_run": {
"dag_id": dag_name
}
}
)
return "DAG triggered!"
最后,我们使用 Cloud Scheduler 将消息发送到 Pub/Sub 主题,以触发 Cloud Functions。你可以使用以下命令在终端窗口中创建 Cloud Scheduler 作业:
gcloud scheduler jobs create pubsub JOB_NAME --schedule="SCHEDULE_INTERVAL" --topic=MY_TOPIC_NAME --message-body="{\"project_id\":\"MY_PROJECT_ID\", \"location\":\"LOCATION\", \"composer_environment\":\"MY_ENV\", \"dag_name\":\"MY_DAG\"}"
在这里,你需要将 JOB_NAME 替换为作业的名称,SCHEDULE_INTERVAL 替换为您所需的时间表(例如,每天中午12点),MY_PROJECT_ID 替换为您的项目 ID,LOCATION 替换为 Composer 环境的位置,MY_ENV 替换为 Composer 环境的名称,MY_DAG 替换为您要触发的 DAG 的名称。
这样就可以使用 Cloud Scheduler 加上 Pub/Sub 和 Cloud Functions API 来触发 Composer DAG 了!