自定义 `Extractor` 支持公司内部 REST API 的血缘上报

解读

在国内中大型公司,数据资产目录与血缘图谱往往由数据治理平台统一收口,平台对外暴露 REST 风格的元数据网关(通常基于 Spring Cloud 或自研框架)。Airflow 原生通过 LineageBackend 将任务级血缘推送到 Apache Atlas,但 Atlas 并不是国内主流,更多公司要求把血缘字段(库、表、列、转换逻辑、责任人、安全等级)实时上报到内部网关,再由网关写入图数据库(Neo4j/JanusGraph)或元数据仓库(Hive Meta、自研 MetaStore)。
因此,面试官想考察:

  1. 你是否理解 Airflow 的血缘扩展点与调用链;
  2. 能否在不改动 Airflow 源码的前提下,用插件机制优雅地对接公司 REST 规范;
  3. 对鉴权、重试、并发、性能、数据质量等国内生产痛点是否有闭环方案。

知识点

  • LineageBackend 接口:Airflow 2.0+ 官方插件入口,含 send_lineage 回调,参数为 operator、inlets、outlets、context。
  • Extractor 与 Operator 的对应关系:Airflow 1.10 时代使用 extractors 包,2.x 后合并进 airflow.lineage,但自定义仍需实现 extractor.get_inlets/outlets。
  • 公司 REST 网关规范:通常要求字段 appId、appSecret、env、dc、lineageBody,body 内包含 upstreamAssetList、downstreamAssetList、taskName、dagName、owner、timestamp、sign。
  • 插件加载顺序:$AIRFLOW_HOME/plugins 目录 > PYTHONPATH > 内置包;需避免与官方 extractors 命名冲突。
  • 并发与性能:国内 DAG 规模常达数千任务/分钟,需批量聚合上报、异步发送、可配置降级。
  • 安全合规:必须通过公司统一 AK/SK 网关鉴权,支持国密 SM2 签名;敏感字段脱敏;HTTPS 双向证书。
  • 监控告警:上报失败要进入夜鹰/自研告警通道,支持重试指数退避,避免拖垮调度线程。

答案

  1. 项目结构

    airflow_plugins/
    ├── __init__.py
    ├── lineage_backend
    │   └── company_rest_backend.py
    └── extractors
        └── company_python_extractor.py
    
  2. 实现 CompanyRESTBackend

from airflow.lineage.backend import LineageBackend
from airflow.utils.log.logging_mixin import LoggingMixin
import requests, json, time, hmac, hashlib, os

class CompanyRESTBackend(LineageBackend, LoggingMixin):
    def __init__(self):
        self.gateway = os.getenv("COMPANY_LINEAGE_GATEWAY")
        self.ak = os.getenv("COMPANY_AK")
        self.sk = os.getenv("COMPANY_SK")
        self.session = requests.Session()
        adapter = requests.adapters.HTTPAdapter(pool_connections=20, pool_maxsize=50)
        self.session.mount("https://", adapter)

    def _sign(self, payload: str) -> str:
        return hmac.new(self.sk.encode(), payload.encode(), hashlib.sha256).hexdigest()

    def send_lineage(self, operator, inlets, outlets, context):
        body = {
            "dagId": context["dag"].dag_id,
            "taskId": operator.task_id,
            "executionDate": context["execution_date"].isoformat(),
            "owner": context["dag"].owner,
            "upstream":  [{"asset": i.asset_name, "type": i.asset_type} for i in inlets],
            "downstream":[{"asset": o.asset_name, "type": o.asset_type} for o in outlets],
        }
        payload = json.dumps(body, sort_keys=True, separators=(',', ':'))
        headers = {
            "Content-Type": "application/json",
            "X-AK": self.ak,
            "X-Sign": self._sign(payload),
            "X-Timestamp": str(int(time.time()))
        }
        # 指数退避重试
        for attempt in range(1, 4):
            try:
                resp = self.session.post(self.gateway, data=payload, headers=headers, timeout=3)
                if resp.status_code == 200:
                    self.log.info("Lineage reported for %s.%s", body["dagId"], body["taskId"])
                    return
            except Exception as e:
                self.log.warning("Attempt %s failed: %s", attempt, e)
                time.sleep(2 ** attempt)
        # 失败写入本地队列,由 sidecar 补偿
        self._write_to_local_queue(body)

    def _write_to_local_queue(self, body):
        with open("/data/airflow/lineage_failed/%s_%s.json" % (body["dagId"], body["taskId"]), "w") as f:
            f.write(json.dumps(body))
  1. 注册 backend
    在 airflow.cfg 增加
[lineage]
backend = airflow_plugins.lineage_backend.company_rest_backend.CompanyRESTBackend
  1. 自定义 Extractor(以 PythonOperator 为例)
from airflow.lineage.extractors import BaseExtractor
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults

class CompanyPythonExtractor(BaseExtractor):
    @apply_defaults
    def __init__(self, operator):
        super().__init__(operator)

    def get_inlets(self):
        # 从 operator 的 doc_md 或 templated_field 中解析公司注释标记
        inlets = []
        if hasattr(self.operator, "inlet_tables"):
            for t in self.operator.inlet_tables.split(","):
                inlets.append(self.create_asset(asset_name=t.strip(), asset_type="hive_table"))
        return inlets

    def get_outlets(self):
        outlets = []
        if hasattr(self.operator, "outlet_tables"):
            for t in self.operator.outlet_tables.split(","):
                outlets.append(self.create_asset(asset_name=t.strip(), asset_type="hive_table"))
        return outlets
  1. 绑定 Extractor
    在插件 __init__.py 中
from airflow.plugins_manager import AirflowPlugin
from airflow.lineage import extractors
from extractors.company_python_extractor import CompanyPythonExtractor

class CompanyLineagePlugin(AirflowPlugin):
    name = "company_lineage"
    extractors = [CompanyPythonExtractor]
  1. 使用示例
from airflow.operators.python import PythonOperator

def etl_logic():
    pass

task = PythonOperator(
    task_id="etl",
    python_callable=etl_logic,
    inlet_tables="dwd.user_info",
    outlet_tables="dws.user_daily_summary",
    dag=dag
)
  1. 生产加固
  • 开启 COMPANY_LINEAGE_GATEWAY 的灰度开关,支持按 DAG 维度降级。
  • 使用 Kafka 做异步缓冲,网关消费后写图库,避免直连打爆。
  • 对失败文件用 Flume 或 Logstash 侧车进程二次上传,实现至少一次语义。
  • 通过 Prometheus + Grafana 暴露 airflow_lineage_send_total、airflow_lineage_failed_total 指标,接入公司夜鹰告警。

拓展思考

  1. 如果公司网关要求批量聚合(每 500 条一次性推送),你如何在 send_lineage 里实现内存队列 + 定时刷盘?请考虑 Airflow 的多进程调度模型,避免不同 worker 间重复聚合。
  2. 当任务使用 KubernetesPodOperator 时,Pod 内产生的临时表血缘无法通过 Python 端提取,你会如何利用sidecar 日志规范或Pod annotation 把血缘带出并在 Extractor 侧补齐?
  3. 国内金融公司要求字段级血缘(column lineage),但 SQL 解析器往往无法识别视图嵌套与 UDF,你会如何结合 Apache Calcite 或自研 SQL 解析服务在 Extractor 中落地?
  4. 如果未来公司把元数据网关升级为 gRPC + Protobuf,你如何在不改业务 DAG 代码的前提下,仅通过插件热更新完成协议切换?请给出版本兼容性与回滚方案。