Airflow 簡介及原理
Airflow 一個用于編排複雜計算工作流和資料處理流水線的開源工具,通常可以解決一些複雜超長 Cron 腳本任務或者大資料的批量處理任務。
其工作流的設計是基于有向無環圖 (Directed Acyclical Graphs, DAG) ,用于設定任務依賴關系和時間排程。
簡單來說,在編寫工作流時,盡量考慮如何将一個大型的任務拆分為多個可獨立執行的原子任務,再将這些任務合并為一個邏輯整體。
這裡簡單介紹一些常見的基本概念及其使用方法。
常見名詞解釋
DAG
代表一個工作流,一個 DAG 中包含多個 Task,多個 Task 組成一個有向無環圖。DAG 可以配置排程時間。如下圖是一個 DAG,其中有 6 個 Task 按順序執行。
DAG 通過 Python 定義,如下
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from builtins import range
from datetime import timedelta
import airflow
from airflow.models import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.dummy_operator import DummyOperator
args = {
'owner': 'Airflow',
'start_date': airflow.utils.dates.days_ago(2),
}
dag = DAG(
dag_id='example_bash_operator',
default_args=args,
schedule_interval='0 0 * * *',
dagrun_timeout=timedelta(minutes=60),
)
run_this_last = DummyOperator(
task_id='run_this_last',
dag=dag,
)
# [START howto_operator_bash]
run_this = BashOperator(
task_id='run_after_loop',
bash_command='echo 1',
dag=dag,
)
# [END howto_operator_bash]
run_this >> run_this_last
for i in range(3):
task = BashOperator(
task_id='runme_' + str(i),
bash_command='echo "{{ task_instance_key_str }}" && sleep 1',
dag=dag,
)
task >> run_this
# [START howto_operator_bash_template]
also_run_this = BashOperator(
task_id='also_run_this',
bash_command='echo "run_id={{ run_id }} | dag_run={{ dag_run }}"',
dag=dag,
)
# [END howto_operator_bash_template]
also_run_this >> run_this_last
if __name__ == "__main__":
dag.cli()
Task
Airflow 任務中的最小執行單元,Operator 的執行個體。,Airflow 中有很多 Operator 供選擇,常用的有 BashOperator,用來執行 bash 指令的 Operator。如下表示一個 Task
run_this = BashOperator(
task_id='run_after_loop',
bash_command='echo 1',
dag=dag,
)
Schedule
排程時間,類似于 crontab。用法跟 crontab 一樣
Execution_date
執行日期,指目前排程的排程日期。
Airflow 核心元件
Airflow 核心元件有 Web Server,Scheduler,Metadata Database, Executor, Worker。
- webserver : 提供圖形界面,可以監控 dag 運作狀态,也可以對 dag 操作。需要注意的一點是,airflow 的 webserver 使用的是 Gunicorn 架構,是以 webserver 隻能運作在 Linux/Unix 核心的作業系統中。
- Scheduler:排程器,你的 dag 是否該執行由排程器管理。
- metadata database:中繼資料庫,預設為 SQLite,可以支援 MySQL,PostgreSQL。需要注意的是,如果使用 SQLite,并發數隻能為 1,是以一般情況下都不會選用SQLite。
- Executor:定義任務的執行。
- Worker:用來執行 Executor 接收的任務。