0x00 前言

最近手头上需要定时自动化维护一些数据,一开始还在想怎么可以减少重复劳动的工作量,后来有前辈跟我提了一嘴Airflow,然后试了试,真香……

然后就开始了下面的踩坑之旅……

0x01 Docker 自动化部署

虽然说可以手动pip安装,但是感觉这样不够轻量,然后就去Github上看看有没有docker镜像~官方那个all in one有点臃肿,然后就看到了docker-airflow,他提供了3种不同的executor,我这里LocalExecutorCeleryExecutor都试过,感觉单节点的话,用LocalExecutor基本上就可以了,如果后续需要添加worker节点,可以考虑CeleryExecutor,但是下面的坑,其实都是通用的。

但是要注意的一个点就是,建议在docker-compose_xx.yml里先自行填上FERNET_KEY,免得启动容器了再在里面加。

0x02 初始化数据库

默认启动的时候数据库是没有进行初始化的。。所以脚本是跑不通的。。因为会报各种表不存在

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: task_instance

这时候就用airflow initdb初始化一下数据库,但是这里会发现他初始化的是sqlite,这就导致后面表不统一(明明开了PostgreSQL

所以还是要把airflow.cfg的数据库配置改成sql_alchemy_conn = postgresql://airflow:airflow@postgres/airflow才会对应用postgresql数据库

0x03 Web登陆认证配置

修改配置

airflow.cfg[webserver]下面添加如下配置

authenticate = True
auth_backend = airflow.contrib.auth.backends.password_auth

然后安装一个pip包

pip install flask_bcrypt

增加用户

然后这里就是坑点。。。网上有的大哥说可以直接用命令建

airflow create_user --username admin --lastname admin --firstname admin --email test@test.com --role Admin --password admin

// 但是也会报表不存在
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: ab_permission_view_role

我后面是直接在Web页面建了用户,然后手动在数据库update的密码……
后来又发现在原来的基础上需要把sql engine也给配了,才不会用默认的sqlite

import airflow
from airflow import models, settings
from airflow.contrib.auth.backends.password_auth import PasswordUser
from sqlalchemy import create_engine
user = PasswordUser(models.User())
user.username = ''
user.email = ''
user.password = ''
# Make the value true if you want the user to be a administrator
user.superuser = True
engine = create_engine("postgresql://airflow:airflow@postgres:5432/airflow")
session = settings.Session(bind=engine)
session.add(user)
session.commit()
session.close()
exit()

0x04 任务定时执行窗口

Note that if you run a DAG on a schedule_interval of one day, the run stamped 2016-01-01 will be trigger soon after 2016-01-01T23:59. In other words, the job instance is started once the period it covers has ended.

其实就是要注意下,下一个执行周期到来的时候当前任务才会执行。即假设是每日任务,今天的任务,会在明天才执行。

0x05 测试任务

按照模版写好dag,然后就可以开始测试脚本了

# 列出所有可执行的tasks
airflow list_tasks dag_name
# 测试执行tasks
airflow test dag_name task_name date