DEPosit / Scripts /pipeline_parsers /airflow_parser.py
taher-ghaleb's picture
DEPosit Dataset
031cf82
Raw
History Blame Contribute Delete
13.6 kB
"""
airflow_parser.py
~~~~~~~~~~~~~~~~~
Extracts structural and quality features from Airflow DAG files.
Strategy: AST-walk the file. We collect every Call node whose function
resolves to a known DAG constructor or task operator, plus every binary
operation (>>, <<) and explicit set_downstream / set_upstream call.
We intentionally avoid executing the file: dynamic DAG generation patterns
(DagFactory, loop-based DAGs) are flagged via heuristics rather than
skipped entirely.
"""
import ast
import json
import re
from typing import Any
# Operators we track individually because they carry specific semantic meaning
# for SE research (coupling, reliability, observability).
_SENSOR_OPERATORS = {
"ExternalTaskSensor", "ExternalTaskMarker",
"HttpSensor", "S3KeySensor", "SqlSensor",
"BaseSensorOperator",
}
_BRANCH_OPERATORS = {
"BranchPythonOperator", "BranchSQLOperator",
"BranchDayOfWeekOperator", "BranchDateTimeOperator",
"BaseBranchOperator",
}
_PYTHON_OPERATORS = {"PythonOperator", "PythonVirtualenvOperator", "ExternalPythonOperator"}
_BASH_OPERATORS = {"BashOperator"}
_SCHEDULE_PRESETS = {
"@once", "@hourly", "@daily", "@weekly", "@monthly", "@yearly", "None",
}
_CRON_RE = re.compile(
r"^(\*|[0-9,\-\*/]+)\s+" # minute
r"(\*|[0-9,\-\*/]+)\s+" # hour
r"(\*|[0-9,\-\*/]+)\s+" # day-of-month
r"(\*|[0-9,\-\*/]+)\s+" # month
r"(\*|[0-9,\-\*/]+)$" # day-of-week
)
def _schedule_type(raw: str | None) -> str:
if raw is None or raw in ("None", ""):
return "none"
if raw in _SCHEDULE_PRESETS:
return "preset"
if _CRON_RE.match(raw.strip()):
return "cron"
if "timedelta" in raw or "datetime.timedelta" in raw:
return "timedelta"
if "schedule" in raw.lower() or "timetable" in raw.lower():
return "dynamic"
return "other"
class _DAGVisitor(ast.NodeVisitor):
"""Walks a DAG file AST and accumulates all features we care about."""
def __init__(self) -> None:
self.dags: list[dict] = []
self._current_dag: dict | None = None
self._operator_names: set[str] = set()
self._edge_count: int = 0
self._uses_xcom: bool = False
self._uses_pools: bool = False
self._uses_connections: bool = False
# ── DAG detection ─────────────────────────────────────────────────────
def visit_With(self, node: ast.With) -> None:
"""Handles: with DAG(...) as dag:"""
for item in node.items:
if isinstance(item.context_expr, ast.Call):
name = self._call_name(item.context_expr)
if name in ("DAG", "airflow.DAG"):
dag = self._parse_dag_call(item.context_expr)
self._current_dag = dag
self.generic_visit(node)
self._finalise_dag()
return
self.generic_visit(node)
def visit_Assign(self, node: ast.Assign) -> None:
"""Handles: dag = DAG(...)"""
if isinstance(node.value, ast.Call):
name = self._call_name(node.value)
if name in ("DAG", "airflow.DAG"):
dag = self._parse_dag_call(node.value)
self._current_dag = dag
self.generic_visit(node)
self._finalise_dag()
return
self.generic_visit(node)
# ── @dag decorator ────────────────────────────────────────────────────
def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
for dec in node.decorator_list:
call = dec if isinstance(dec, ast.Call) else None
bare = dec if isinstance(dec, ast.Name) else None
name = (self._call_name(call) if call else
(bare.id if bare else None))
if name == "dag":
dag = self._parse_dag_call(call) if call else {}
dag.setdefault("dag_id", node.name)
self._current_dag = dag
self.generic_visit(node)
self._finalise_dag()
return
self.generic_visit(node)
visit_AsyncFunctionDef = visit_FunctionDef
def _finalise_dag(self) -> None:
if self._current_dag is None:
return
d = self._current_dag
d["task_count"] = d.get("task_count", 0)
d["edge_count"] = self._edge_count
d["operator_types"] = json.dumps(sorted(self._operator_names))
d["unique_operator_count"] = len(self._operator_names)
d["has_python_operator"] = int(bool(self._operator_names & _PYTHON_OPERATORS))
d["has_bash_operator"] = int(bool(self._operator_names & _BASH_OPERATORS))
d["has_external_task_sensor"] = int(bool(self._operator_names & _SENSOR_OPERATORS))
d["has_branch_operator"] = int(bool(self._operator_names & _BRANCH_OPERATORS))
d["uses_xcom"] = int(self._uses_xcom)
d["uses_pools"] = int(self._uses_pools)
d["uses_connections"] = int(self._uses_connections)
# Derive anti-patterns
catchup = d.get("catchup")
max_active = d.get("max_active_runs")
retries = d.get("default_retries")
on_fail = d.get("has_on_failure_callback", 0)
sched_type = d.get("schedule_type", "none")
d["antipattern_catchup_no_maxruns"] = int(
catchup is True and max_active is None
)
d["antipattern_no_retries"] = int(retries is None or retries == 0)
d["antipattern_no_failure_cb"] = int(not on_fail)
d["antipattern_no_schedule"] = int(sched_type == "none")
d["antipattern_bare_xcom"] = int(self._uses_xcom) # heuristic; refine if needed
self.dags.append(d)
self._current_dag = None
self._operator_names = set()
self._edge_count = 0
self._uses_xcom = False
self._uses_pools = False
self._uses_connections = False
# ── Task operator detection ───────────────────────────────────────────
def visit_Call(self, node: ast.Call) -> None:
name = self._call_name(node)
# Count task operators
if name and ("Operator" in name or "Sensor" in name or "Hook" in name):
short = name.split(".")[-1]
self._operator_names.add(short)
if self._current_dag is not None:
self._current_dag["task_count"] = (
self._current_dag.get("task_count", 0) + 1
)
# xcom usage
if name in ("xcom_push", "xcom_pull") or (
isinstance(node.func, ast.Attribute)
and node.func.attr in ("xcom_push", "xcom_pull")
):
self._uses_xcom = True
# pool usage
for kw in node.keywords:
if kw.arg == "pool":
self._uses_pools = True
if kw.arg in ("conn_id", "gcp_conn_id", "aws_conn_id",
"azure_conn_id", "http_conn_id"):
self._uses_connections = True
self.generic_visit(node)
# ── Dependency edges ──────────────────────────────────────────────────
def visit_BinOp(self, node: ast.BinOp) -> None:
if isinstance(node.op, (ast.RShift, ast.LShift)):
self._edge_count += 1
self.generic_visit(node)
def visit_Expr(self, node: ast.Expr) -> None:
if isinstance(node.value, ast.Call):
name = self._call_name(node.value)
if name in ("set_downstream", "set_upstream") or (
isinstance(node.value.func, ast.Attribute)
and node.value.func.attr in ("set_downstream", "set_upstream")
):
self._edge_count += 1
self.generic_visit(node)
# ── DAG constructor argument parsing ─────────────────────────────────
def _parse_dag_call(self, node: ast.Call) -> dict:
d: dict[str, Any] = {}
# Positional: DAG(dag_id, schedule_interval=...)
if node.args:
d["dag_id"] = self._const_str(node.args[0])
for kw in node.keywords:
arg = kw.arg
val = kw.value
if arg == "dag_id":
d["dag_id"] = self._const_str(val)
elif arg in ("schedule_interval", "schedule"):
raw = self._const_str(val)
d["schedule_interval"] = raw
d["schedule_type"] = _schedule_type(raw)
elif arg == "catchup":
d["catchup"] = self._const_bool(val)
elif arg == "max_active_runs":
d["max_active_runs"] = self._const_int(val)
elif arg == "default_args":
self._parse_default_args(val, d)
elif arg == "tags":
d["dag_tags"] = self._const_list_str(val)
elif arg == "sla_miss_callback":
d["has_sla"] = 1
elif arg == "on_failure_callback":
d["has_on_failure_callback"] = 1
elif arg == "on_success_callback":
d["has_on_success_callback"] = 1
return d
def _parse_default_args(self, node: ast.expr, d: dict) -> None:
"""Extract retries / sla / callbacks from default_args dict literal."""
if not isinstance(node, ast.Dict):
return
for key, val in zip(node.keys, node.values):
k = self._const_str(key)
if k == "retries":
d["default_retries"] = self._const_int(val)
elif k == "retry_delay":
# timedelta(minutes=...) etc. — just flag presence
d["default_retry_delay_seconds"] = -1 # present but not trivially parsed
elif k == "sla":
d["has_sla"] = 1
elif k == "on_failure_callback":
d["has_on_failure_callback"] = 1
elif k == "on_success_callback":
d["has_on_success_callback"] = 1
# ── AST helper utilities ──────────────────────────────────────────────
@staticmethod
def _call_name(node: ast.Call | None) -> str | None:
if node is None:
return None
f = node.func
if isinstance(f, ast.Name):
return f.id
if isinstance(f, ast.Attribute):
parts = []
cur: ast.expr = f
while isinstance(cur, ast.Attribute):
parts.append(cur.attr)
cur = cur.value
if isinstance(cur, ast.Name):
parts.append(cur.id)
return ".".join(reversed(parts))
return None
@staticmethod
def _const_str(node: ast.expr | None) -> str | None:
if node is None:
return None
if isinstance(node, ast.Constant) and isinstance(node.value, str):
return node.value
if isinstance(node, ast.Constant) and node.value is None:
return "None"
if isinstance(node, ast.Name) and node.id == "None":
return "None"
return repr(node) # non-literal: store textual representation
@staticmethod
def _const_int(node: ast.expr | None) -> int | None:
if isinstance(node, ast.Constant) and isinstance(node.value, int):
return node.value
return None
@staticmethod
def _const_bool(node: ast.expr | None) -> bool | None:
if isinstance(node, ast.Constant) and isinstance(node.value, bool):
return node.value
if isinstance(node, ast.Name):
if node.id == "True":
return True
if node.id == "False":
return False
return None
@staticmethod
def _const_list_str(node: ast.expr | None) -> str:
if not isinstance(node, (ast.List, ast.Tuple)):
return "[]"
items = []
for elt in node.elts:
if isinstance(elt, ast.Constant) and isinstance(elt.value, str):
items.append(elt.value)
return json.dumps(items)
def extract(content: str, file_path: str) -> list[dict]:
"""
Parse one Airflow DAG file and return a list of feature dicts,
one per DAG definition found in the file.
Returns [{"parse_error": ..., "file_lines": ...}] on parse failure.
"""
lines = content.splitlines()
file_lines = len(lines)
try:
tree = ast.parse(content, filename=file_path)
except SyntaxError as exc:
return [{"parse_error": str(exc), "file_lines": file_lines}]
visitor = _DAGVisitor()
try:
visitor.visit(tree)
except Exception as exc: # noqa: BLE001
return [{"parse_error": f"visitor: {exc}", "file_lines": file_lines}]
if not visitor.dags:
# No DAG found — could be a helper module in the dags/ folder.
return [{"parse_error": "no_dag_found", "file_lines": file_lines}]
for d in visitor.dags:
d["file_lines"] = file_lines
d.setdefault("parse_error", None)
return visitor.dags