dag_dataops_pipeline_data_scheduler.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  1. """
  2. 统一数据运维调度器 DAG
  3. 功能:
  4. 1. 将数据处理与统计汇总整合到一个DAG中
  5. 2. 保留原有的每个处理脚本单独运行的特性,方便通过Web UI查看
  6. 3. 支持执行计划文件的动态解析和执行
  7. 4. 执行完成后自动生成汇总报告
  8. """
  9. from airflow import DAG
  10. from airflow.operators.python import PythonOperator, ShortCircuitOperator
  11. from airflow.operators.empty import EmptyOperator
  12. from airflow.utils.task_group import TaskGroup
  13. from datetime import datetime, timedelta, date
  14. import logging
  15. import networkx as nx
  16. import json
  17. import os
  18. from decimal import Decimal
  19. from common import (
  20. get_pg_conn,
  21. get_neo4j_driver,
  22. get_today_date
  23. )
  24. from config import TASK_RETRY_CONFIG, SCRIPTS_BASE_PATH, PG_CONFIG, NEO4J_CONFIG
  25. import pytz
  26. # 创建日志记录器
  27. logger = logging.getLogger(__name__)
  28. # 开启详细诊断日志记录
  29. ENABLE_DEBUG_LOGGING = True
  30. def log_debug(message):
  31. """记录调试日志,但只在启用调试模式时"""
  32. if ENABLE_DEBUG_LOGGING:
  33. logger.info(f"[DEBUG] {message}")
  34. # 在DAG启动时输出诊断信息
  35. log_debug("======== 诊断信息 ========")
  36. log_debug(f"当前工作目录: {os.getcwd()}")
  37. log_debug(f"SCRIPTS_BASE_PATH: {SCRIPTS_BASE_PATH}")
  38. log_debug(f"导入的common模块路径: {get_pg_conn.__module__}")
  39. # 检查数据库连接
  40. def validate_database_connection():
  41. """验证数据库连接是否正常"""
  42. try:
  43. conn = get_pg_conn()
  44. cursor = conn.cursor()
  45. cursor.execute("SELECT version()")
  46. version = cursor.fetchone()
  47. log_debug(f"数据库连接正常,PostgreSQL版本: {version[0]}")
  48. # 检查airflow_exec_plans表是否存在
  49. cursor.execute("""
  50. SELECT EXISTS (
  51. SELECT FROM information_schema.tables
  52. WHERE table_name = 'airflow_exec_plans'
  53. )
  54. """)
  55. table_exists = cursor.fetchone()[0]
  56. if table_exists:
  57. # 检查表结构
  58. cursor.execute("""
  59. SELECT column_name, data_type
  60. FROM information_schema.columns
  61. WHERE table_name = 'airflow_exec_plans'
  62. """)
  63. columns = cursor.fetchall()
  64. log_debug(f"airflow_exec_plans表存在,列信息:")
  65. for col in columns:
  66. log_debug(f" - {col[0]}: {col[1]}")
  67. # 查询最新记录数量
  68. cursor.execute("SELECT COUNT(*) FROM airflow_exec_plans")
  69. count = cursor.fetchone()[0]
  70. log_debug(f"airflow_exec_plans表中有 {count} 条记录")
  71. # 检查最近的执行记录
  72. cursor.execute("""
  73. SELECT ds, COUNT(*) as record_count
  74. FROM airflow_exec_plans
  75. GROUP BY ds
  76. ORDER BY ds DESC
  77. LIMIT 3
  78. """)
  79. recent_dates = cursor.fetchall()
  80. log_debug(f"最近的执行日期及记录数:")
  81. for date_info in recent_dates:
  82. log_debug(f" - {date_info[0]}: {date_info[1]} 条记录")
  83. else:
  84. log_debug("airflow_exec_plans表不存在!")
  85. cursor.close()
  86. conn.close()
  87. return True
  88. except Exception as e:
  89. log_debug(f"数据库连接验证失败: {str(e)}")
  90. import traceback
  91. log_debug(f"错误堆栈: {traceback.format_exc()}")
  92. return False
  93. # 执行数据库连接验证
  94. try:
  95. validate_database_connection()
  96. except Exception as e:
  97. log_debug(f"验证数据库连接时出错: {str(e)}")
  98. log_debug("======== 诊断信息结束 ========")
  99. #############################################
  100. # 通用工具函数
  101. #############################################
  102. def json_serial(obj):
  103. """将日期对象序列化为ISO格式字符串的JSON序列化器"""
  104. if isinstance(obj, (datetime, date)):
  105. return obj.isoformat()
  106. raise TypeError(f"类型 {type(obj)} 不能被序列化为JSON")
  107. # 添加自定义JSON编码器解决Decimal序列化问题
  108. class DecimalEncoder(json.JSONEncoder):
  109. def default(self, obj):
  110. if isinstance(obj, Decimal):
  111. return float(obj)
  112. # 处理日期类型
  113. elif isinstance(obj, (datetime, date)):
  114. return obj.isoformat()
  115. # 让父类处理其他类型
  116. return super(DecimalEncoder, self).default(obj)
  117. #############################################
  118. # 新的工具函数
  119. #############################################
  120. def execute_python_script(target_table, script_name, script_exec_mode, exec_date, **kwargs):
  121. """
  122. 执行Python脚本并返回执行结果
  123. 参数:
  124. target_table: 目标表名
  125. script_name: 脚本名称
  126. script_exec_mode: 脚本执行模式
  127. exec_date: 执行日期
  128. 返回:
  129. bool: 脚本执行结果
  130. """
  131. # 添加详细日志
  132. logger.info(f"===== 开始执行脚本 =====")
  133. logger.info(f"target_table: {target_table}, 类型: {type(target_table)}")
  134. logger.info(f"script_name: {script_name}, 类型: {type(script_name)}")
  135. logger.info(f"script_exec_mode: {script_exec_mode}, 类型: {type(script_exec_mode)}")
  136. logger.info(f"exec_date: {exec_date}, 类型: {type(exec_date)}")
  137. # 检查script_name是否为空
  138. if not script_name:
  139. logger.error(f"表 {target_table} 的script_name为空,无法执行")
  140. return False
  141. # 记录执行开始时间
  142. start_time = datetime.now()
  143. try:
  144. # 导入和执行脚本模块
  145. import importlib.util
  146. import sys
  147. script_path = os.path.join(SCRIPTS_BASE_PATH, script_name)
  148. if not os.path.exists(script_path):
  149. logger.error(f"脚本文件不存在: {script_path}")
  150. return False
  151. # 动态导入模块
  152. spec = importlib.util.spec_from_file_location("dynamic_module", script_path)
  153. module = importlib.util.module_from_spec(spec)
  154. spec.loader.exec_module(module)
  155. # 检查并调用标准入口函数run
  156. if hasattr(module, "run"):
  157. logger.info(f"调用脚本 {script_name} 的标准入口函数 run()")
  158. result = module.run(table_name=target_table, execution_mode=script_exec_mode)
  159. logger.info(f"脚本执行完成,原始返回值: {result}, 类型: {type(result)}")
  160. # 确保result是布尔值
  161. if result is None:
  162. logger.warning(f"脚本返回值为None,转换为False")
  163. result = False
  164. elif not isinstance(result, bool):
  165. original_result = result
  166. result = bool(result)
  167. logger.warning(f"脚本返回非布尔值 {original_result},转换为布尔值: {result}")
  168. # 记录结束时间和结果
  169. end_time = datetime.now()
  170. duration = (end_time - start_time).total_seconds()
  171. logger.info(f"脚本 {script_name} 执行完成,结果: {result}, 耗时: {duration:.2f}秒")
  172. return result
  173. else:
  174. logger.error(f"脚本 {script_name} 中未定义标准入口函数 run(),无法执行")
  175. return False
  176. except Exception as e:
  177. # 处理异常
  178. logger.error(f"执行任务出错: {str(e)}")
  179. end_time = datetime.now()
  180. duration = (end_time - start_time).total_seconds()
  181. logger.error(f"脚本 {script_name} 执行失败,耗时: {duration:.2f}秒")
  182. logger.info(f"===== 脚本执行异常结束 =====")
  183. import traceback
  184. logger.error(traceback.format_exc())
  185. # 确保不会阻塞DAG
  186. return False
  187. #############################################
  188. # 第一阶段: 准备阶段(Prepare Phase)的函数
  189. #############################################
  190. def get_enabled_tables():
  191. """获取所有启用的表"""
  192. conn = get_pg_conn()
  193. cursor = conn.cursor()
  194. try:
  195. cursor.execute("""
  196. SELECT owner_id, table_name
  197. FROM schedule_status
  198. WHERE schedule_is_enabled = TRUE
  199. """)
  200. result = cursor.fetchall()
  201. return [row[1] for row in result] # 只返回表名
  202. except Exception as e:
  203. logger.error(f"获取启用表失败: {str(e)}")
  204. return []
  205. finally:
  206. cursor.close()
  207. conn.close()
  208. def check_table_directly_subscribed(table_name):
  209. """检查表是否在schedule_status表中直接订阅"""
  210. conn = get_pg_conn()
  211. cursor = conn.cursor()
  212. try:
  213. cursor.execute("""
  214. SELECT schedule_is_enabled
  215. FROM schedule_status
  216. WHERE table_name = %s
  217. """, (table_name,))
  218. result = cursor.fetchone()
  219. return result and result[0] is True
  220. except Exception as e:
  221. logger.error(f"检查表订阅状态失败: {str(e)}")
  222. return False
  223. finally:
  224. cursor.close()
  225. conn.close()
  226. def get_table_info_from_neo4j(table_name):
  227. """从Neo4j获取表的详细信息"""
  228. driver = get_neo4j_driver()
  229. # 检查表是否直接订阅
  230. is_directly_schedule = check_table_directly_subscribed(table_name)
  231. table_info = {
  232. 'target_table': table_name,
  233. 'is_directly_schedule': is_directly_schedule, # 初始值设为True,从schedule_status表获取
  234. }
  235. try:
  236. with driver.session() as session:
  237. # 查询表标签和状态
  238. query_table = """
  239. MATCH (t {en_name: $table_name})
  240. RETURN labels(t) AS labels, t.status AS status, t.frequency AS frequency
  241. """
  242. result = session.run(query_table, table_name=table_name)
  243. record = result.single()
  244. if record:
  245. labels = record.get("labels", [])
  246. table_info['target_table_label'] = [label for label in labels if label in ["DataResource", "DataModel", "DataSource"]][0] if labels else None
  247. table_info['target_table_status'] = record.get("status", True) # 默认为True
  248. table_info['default_update_frequency'] = record.get("frequency")
  249. # 根据标签类型查询关系和脚本信息
  250. if "DataResource" in labels:
  251. query_rel = """
  252. MATCH (target {en_name: $table_name})-[rel:ORIGINATES_FROM]->(source)
  253. RETURN source.en_name AS source_table, rel.script_name AS script_name,
  254. rel.script_type AS script_type, rel.script_exec_mode AS script_exec_mode
  255. """
  256. elif "DataModel" in labels:
  257. query_rel = """
  258. MATCH (target {en_name: $table_name})-[rel:DERIVED_FROM]->(source)
  259. RETURN source.en_name AS source_table, rel.script_name AS script_name,
  260. rel.script_type AS script_type, rel.script_exec_mode AS script_exec_mode
  261. """
  262. else:
  263. logger.warning(f"表 {table_name} 不是DataResource或DataModel类型")
  264. return table_info
  265. result = session.run(query_rel, table_name=table_name)
  266. record = result.single()
  267. if record:
  268. table_info['source_table'] = record.get("source_table")
  269. # 检查script_name是否为空
  270. script_name = record.get("script_name")
  271. if not script_name:
  272. logger.warning(f"表 {table_name} 的关系中没有script_name属性,可能导致后续处理出错")
  273. table_info['script_name'] = script_name
  274. # 设置默认值,确保即使属性为空也有默认值
  275. table_info['script_type'] = record.get("script_type", "python") # 默认为python
  276. table_info['script_exec_mode'] = record.get("script_exec_mode", "append") # 默认为append
  277. else:
  278. logger.warning(f"未找到表 {table_name} 的关系信息")
  279. else:
  280. logger.warning(f"在Neo4j中找不到表 {table_name} 的信息")
  281. except Exception as e:
  282. logger.error(f"获取表 {table_name} 的信息时出错: {str(e)}")
  283. finally:
  284. driver.close()
  285. return table_info
  286. def process_dependencies(tables_info):
  287. """处理表间依赖关系,添加被动调度的表"""
  288. # 存储所有表信息的字典
  289. all_tables = {t['target_table']: t for t in tables_info}
  290. driver = get_neo4j_driver()
  291. try:
  292. with driver.session() as session:
  293. for table_name, table_info in list(all_tables.items()):
  294. if table_info.get('target_table_label') == 'DataModel':
  295. # 查询其依赖表
  296. query = """
  297. MATCH (dm {en_name: $table_name})-[:DERIVED_FROM]->(dep)
  298. RETURN dep.en_name AS dep_name, labels(dep) AS dep_labels,
  299. dep.status AS dep_status, dep.frequency AS dep_frequency
  300. """
  301. result = session.run(query, table_name=table_name)
  302. for record in result:
  303. dep_name = record.get("dep_name")
  304. dep_labels = record.get("dep_labels", [])
  305. dep_status = record.get("dep_status", True)
  306. dep_frequency = record.get("dep_frequency")
  307. # 处理未被直接调度的依赖表
  308. if dep_name and dep_name not in all_tables:
  309. logger.info(f"发现被动依赖表: {dep_name}, 标签: {dep_labels}")
  310. # 获取依赖表详细信息
  311. dep_info = get_table_info_from_neo4j(dep_name)
  312. dep_info['is_directly_schedule'] = False
  313. # 处理调度频率继承
  314. if not dep_info.get('default_update_frequency'):
  315. dep_info['default_update_frequency'] = table_info.get('default_update_frequency')
  316. all_tables[dep_name] = dep_info
  317. except Exception as e:
  318. logger.error(f"处理依赖关系时出错: {str(e)}")
  319. finally:
  320. driver.close()
  321. return list(all_tables.values())
  322. def filter_invalid_tables(tables_info):
  323. """过滤无效表及其依赖,使用NetworkX构建依赖图"""
  324. # 构建表名到索引的映射
  325. table_dict = {t['target_table']: i for i, t in enumerate(tables_info)}
  326. # 找出无效表
  327. invalid_tables = set()
  328. for table in tables_info:
  329. if table.get('target_table_status') is False:
  330. invalid_tables.add(table['target_table'])
  331. logger.info(f"表 {table['target_table']} 的状态为无效")
  332. # 构建依赖图
  333. G = nx.DiGraph()
  334. # 添加所有节点
  335. for table in tables_info:
  336. G.add_node(table['target_table'])
  337. # 查询并添加依赖边
  338. driver = get_neo4j_driver()
  339. try:
  340. with driver.session() as session:
  341. for table in tables_info:
  342. if table.get('target_table_label') == 'DataModel':
  343. query = """
  344. MATCH (source {en_name: $table_name})-[:DERIVED_FROM]->(target)
  345. RETURN target.en_name AS target_name
  346. """
  347. result = session.run(query, table_name=table['target_table'])
  348. for record in result:
  349. target_name = record.get("target_name")
  350. if target_name and target_name in table_dict:
  351. # 添加从目标到源的边,表示目标依赖于源
  352. G.add_edge(table['target_table'], target_name)
  353. logger.debug(f"添加依赖边: {table['target_table']} -> {target_name}")
  354. except Exception as e:
  355. logger.error(f"构建依赖图时出错: {str(e)}")
  356. finally:
  357. driver.close()
  358. # 找出依赖于无效表的所有表
  359. downstream_invalid = set()
  360. for invalid_table in invalid_tables:
  361. # 获取可从无效表到达的所有节点
  362. try:
  363. descendants = nx.descendants(G, invalid_table)
  364. downstream_invalid.update(descendants)
  365. logger.info(f"表 {invalid_table} 的下游无效表: {descendants}")
  366. except Exception as e:
  367. logger.error(f"处理表 {invalid_table} 的下游依赖时出错: {str(e)}")
  368. # 合并所有无效表
  369. all_invalid = invalid_tables.union(downstream_invalid)
  370. logger.info(f"总共 {len(all_invalid)} 个表被标记为无效: {all_invalid}")
  371. # 过滤出有效表
  372. valid_tables = [t for t in tables_info if t['target_table'] not in all_invalid]
  373. logger.info(f"过滤后保留 {len(valid_tables)} 个有效表")
  374. return valid_tables
  375. def prepare_dag_schedule(**kwargs):
  376. """准备DAG调度任务的主函数"""
  377. exec_date = kwargs.get('ds') or get_today_date()
  378. execution_date = kwargs.get('execution_date')
  379. # 记录重要的时间参数
  380. logger.info(f"【时间参数】prepare_dag_schedule: ds={exec_date}, execution_date={execution_date}")
  381. logger.info(f"开始准备执行日期 {exec_date} 的统一调度任务")
  382. # 1. 获取启用的表
  383. enabled_tables = get_enabled_tables()
  384. logger.info(f"从schedule_status表获取到 {len(enabled_tables)} 个启用的表")
  385. if not enabled_tables:
  386. logger.warning("没有找到启用的表,准备工作结束")
  387. return 0
  388. # 2. 获取表的详细信息
  389. tables_info = []
  390. for table_name in enabled_tables:
  391. table_info = get_table_info_from_neo4j(table_name)
  392. if table_info:
  393. tables_info.append(table_info)
  394. logger.info(f"成功获取 {len(tables_info)} 个表的详细信息")
  395. # 3. 处理依赖关系,添加被动调度的表
  396. enriched_tables = process_dependencies(tables_info)
  397. logger.info(f"处理依赖后,总共有 {len(enriched_tables)} 个表")
  398. # 4. 过滤无效表及其依赖
  399. valid_tables = filter_invalid_tables(enriched_tables)
  400. logger.info(f"过滤无效表后,最终有 {len(valid_tables)} 个有效表")
  401. # 已删除对 airflow_dag_schedule 表的写入操作
  402. # 只记录准备了多少个表
  403. logger.info(f"处理了 {len(valid_tables)} 个有效表")
  404. # 7. 生成执行计划数据
  405. resource_tasks = []
  406. model_tasks = []
  407. for table in valid_tables:
  408. if table.get('target_table_label') == 'DataResource':
  409. resource_tasks.append({
  410. "source_table": table.get('source_table'),
  411. "target_table": table['target_table'],
  412. "target_table_label": "DataResource",
  413. "script_name": table.get('script_name'),
  414. "script_exec_mode": table.get('script_exec_mode', 'append')
  415. })
  416. elif table.get('target_table_label') == 'DataModel':
  417. model_tasks.append({
  418. "source_table": table.get('source_table'),
  419. "target_table": table['target_table'],
  420. "target_table_label": "DataModel",
  421. "script_name": table.get('script_name'),
  422. "script_exec_mode": table.get('script_exec_mode', 'append')
  423. })
  424. # 获取依赖关系
  425. model_table_names = [t['target_table'] for t in model_tasks]
  426. dependencies = {}
  427. driver = get_neo4j_driver()
  428. try:
  429. with driver.session() as session:
  430. for table_name in model_table_names:
  431. query = """
  432. MATCH (source:DataModel {en_name: $table_name})-[:DERIVED_FROM]->(target)
  433. RETURN source.en_name AS source, target.en_name AS target, labels(target) AS target_labels
  434. """
  435. result = session.run(query, table_name=table_name)
  436. deps = []
  437. for record in result:
  438. target = record.get("target")
  439. target_labels = record.get("target_labels", [])
  440. if target:
  441. table_type = next((label for label in target_labels if label in ["DataModel", "DataResource"]), None)
  442. deps.append({
  443. "table_name": target,
  444. "table_type": table_type
  445. })
  446. dependencies[table_name] = deps
  447. finally:
  448. driver.close()
  449. # 创建执行计划
  450. execution_plan = {
  451. "exec_date": exec_date,
  452. "resource_tasks": resource_tasks,
  453. "model_tasks": model_tasks,
  454. "dependencies": dependencies
  455. }
  456. # 将执行计划保存到XCom
  457. kwargs['ti'].xcom_push(key='execution_plan', value=execution_plan)
  458. logger.info(f"准备了执行计划,包含 {len(resource_tasks)} 个资源表任务和 {len(model_tasks)} 个模型表任务")
  459. return len(valid_tables)
  460. def check_execution_plan(**kwargs):
  461. """
  462. 检查执行计划是否存在且有效
  463. 返回False将阻止所有下游任务执行
  464. """
  465. execution_date = kwargs.get('execution_date')
  466. exec_date = kwargs.get('ds') or get_today_date()
  467. # 记录重要的时间参数
  468. logger.info(f"【时间参数】check_execution_plan: ds={exec_date}, execution_date={execution_date}")
  469. logger.info("检查数据库中的执行计划是否存在且有效")
  470. # 从数据库获取执行计划
  471. execution_plan = get_execution_plan_from_db(exec_date)
  472. # 检查是否成功获取到执行计划
  473. if not execution_plan:
  474. logger.error(f"未找到执行日期 {exec_date} 的执行计划")
  475. return False
  476. # 检查执行计划是否包含必要字段
  477. if "exec_date" not in execution_plan:
  478. logger.error("执行计划缺少exec_date字段")
  479. return False
  480. if not isinstance(execution_plan.get("resource_tasks", []), list):
  481. logger.error("执行计划的resource_tasks字段无效")
  482. return False
  483. if not isinstance(execution_plan.get("model_tasks", []), list):
  484. logger.error("执行计划的model_tasks字段无效")
  485. return False
  486. # 检查是否有任务数据
  487. resource_tasks = execution_plan.get("resource_tasks", [])
  488. model_tasks = execution_plan.get("model_tasks", [])
  489. if not resource_tasks and not model_tasks:
  490. logger.warning("执行计划不包含任何任务")
  491. # 如果没有任务,则阻止下游任务执行
  492. return False
  493. logger.info(f"执行计划验证成功: 包含 {len(resource_tasks)} 个资源任务和 {len(model_tasks)} 个模型任务")
  494. return True
  495. #############################################
  496. # 第二阶段: 数据处理阶段(Data Processing Phase)的函数
  497. #############################################
  498. def get_all_tasks(exec_date):
  499. """
  500. 获取所有需要执行的任务(DataResource和DataModel)
  501. 直接从执行计划获取任务信息,不再查询数据库
  502. """
  503. # 从数据库获取执行计划
  504. execution_plan = get_execution_plan_from_db(exec_date)
  505. if not execution_plan:
  506. logger.warning(f"未找到执行日期 {exec_date} 的执行计划")
  507. return [], []
  508. # 提取资源任务和模型任务
  509. resource_tasks = execution_plan.get("resource_tasks", [])
  510. model_tasks = execution_plan.get("model_tasks", [])
  511. logger.info(f"获取到 {len(resource_tasks)} 个资源任务和 {len(model_tasks)} 个模型任务")
  512. return resource_tasks, model_tasks
  513. def get_table_dependencies(table_names):
  514. """获取表之间的依赖关系"""
  515. driver = get_neo4j_driver()
  516. dependency_dict = {name: [] for name in table_names}
  517. try:
  518. with driver.session() as session:
  519. # 获取所有模型表之间的依赖关系
  520. query = """
  521. MATCH (source:DataModel)-[:DERIVED_FROM]->(target)
  522. WHERE source.en_name IN $table_names
  523. RETURN source.en_name AS source, target.en_name AS target, labels(target) AS target_labels
  524. """
  525. result = session.run(query, table_names=table_names)
  526. for record in result:
  527. source = record.get("source")
  528. target = record.get("target")
  529. target_labels = record.get("target_labels", [])
  530. if source and target:
  531. # 将目标表添加到源表的依赖列表中
  532. dependency_dict[source].append({
  533. "table_name": target,
  534. "table_type": next((label for label in target_labels if label in ["DataModel", "DataResource"]), None)
  535. })
  536. logger.debug(f"依赖关系: {source} 依赖于 {target}")
  537. except Exception as e:
  538. logger.error(f"从Neo4j获取依赖关系时出错: {str(e)}")
  539. finally:
  540. driver.close()
  541. return dependency_dict
  542. def create_execution_plan(**kwargs):
  543. """准备执行计划的函数,使用从准备阶段传递的数据"""
  544. try:
  545. execution_date = kwargs.get('execution_date')
  546. exec_date = kwargs.get('ds') or get_today_date()
  547. # 记录重要的时间参数
  548. logger.info(f"【时间参数】create_execution_plan: ds={exec_date}, execution_date={execution_date}")
  549. # 从XCom获取执行计划
  550. execution_plan = kwargs['ti'].xcom_pull(task_ids='prepare_phase.prepare_dag_schedule', key='execution_plan')
  551. # 如果找不到执行计划,则从数据库获取
  552. if not execution_plan:
  553. # 获取执行日期
  554. logger.info(f"未找到执行计划,从数据库获取。使用执行日期: {exec_date}")
  555. # 获取所有任务
  556. resource_tasks, model_tasks = get_all_tasks(exec_date)
  557. if not resource_tasks and not model_tasks:
  558. logger.warning(f"执行日期 {exec_date} 没有找到任务")
  559. return 0
  560. # 为所有模型表获取依赖关系
  561. model_table_names = [task["target_table"] for task in model_tasks]
  562. dependencies = get_table_dependencies(model_table_names)
  563. # 创建执行计划
  564. new_execution_plan = {
  565. "exec_date": exec_date,
  566. "resource_tasks": resource_tasks,
  567. "model_tasks": model_tasks,
  568. "dependencies": dependencies
  569. }
  570. # 保存执行计划到XCom
  571. kwargs['ti'].xcom_push(key='execution_plan', value=new_execution_plan)
  572. logger.info(f"创建新的执行计划,包含 {len(resource_tasks)} 个资源表任务和 {len(model_tasks)} 个模型表任务")
  573. return new_execution_plan
  574. logger.info(f"成功获取执行计划")
  575. return execution_plan
  576. except Exception as e:
  577. logger.error(f"创建执行计划时出错: {str(e)}")
  578. # 返回空执行计划
  579. empty_plan = {
  580. "exec_date": get_today_date(),
  581. "resource_tasks": [],
  582. "model_tasks": [],
  583. "dependencies": {}
  584. }
  585. return empty_plan
  586. def process_resource(target_table, script_name, script_exec_mode, exec_date):
  587. """处理单个资源表"""
  588. task_id = f"resource_{target_table}"
  589. logger.info(f"===== 开始执行 {task_id} =====")
  590. logger.info(f"执行资源表 {target_table} 的脚本 {script_name}")
  591. # 确保exec_date是字符串
  592. if not isinstance(exec_date, str):
  593. exec_date = str(exec_date)
  594. logger.info(f"将exec_date转换为字符串: {exec_date}")
  595. try:
  596. # 使用新的函数执行脚本,不依赖数据库
  597. logger.info(f"调用execute_python_script: target_table={target_table}, script_name={script_name}")
  598. result = execute_python_script(
  599. target_table=target_table,
  600. script_name=script_name,
  601. script_exec_mode=script_exec_mode,
  602. exec_date=exec_date
  603. )
  604. logger.info(f"资源表 {target_table} 处理完成,结果: {result}")
  605. return result
  606. except Exception as e:
  607. logger.error(f"处理资源表 {target_table} 时出错: {str(e)}")
  608. import traceback
  609. logger.error(traceback.format_exc())
  610. logger.info(f"===== 结束执行 {task_id} (失败) =====")
  611. return False
  612. finally:
  613. logger.info(f"===== 结束执行 {task_id} =====")
  614. def process_model(target_table, script_name, script_exec_mode, exec_date):
  615. """处理单个模型表"""
  616. task_id = f"model_{target_table}"
  617. logger.info(f"===== 开始执行 {task_id} =====")
  618. logger.info(f"执行模型表 {target_table} 的脚本 {script_name}")
  619. # 确保exec_date是字符串
  620. if not isinstance(exec_date, str):
  621. exec_date = str(exec_date)
  622. logger.info(f"将exec_date转换为字符串: {exec_date}")
  623. try:
  624. # 使用新的函数执行脚本,不依赖数据库
  625. logger.info(f"调用execute_python_script: target_table={target_table}, script_name={script_name}")
  626. result = execute_python_script(
  627. target_table=target_table,
  628. script_name=script_name,
  629. script_exec_mode=script_exec_mode,
  630. exec_date=exec_date
  631. )
  632. logger.info(f"模型表 {target_table} 处理完成,结果: {result}")
  633. return result
  634. except Exception as e:
  635. logger.error(f"处理模型表 {target_table} 时出错: {str(e)}")
  636. import traceback
  637. logger.error(traceback.format_exc())
  638. logger.info(f"===== 结束执行 {task_id} (失败) =====")
  639. return False
  640. finally:
  641. logger.info(f"===== 结束执行 {task_id} =====")
  642. #############################################
  643. # 第三阶段: 汇总阶段(Summary Phase)的函数
  644. #############################################
  645. def get_execution_stats(exec_date):
  646. """
  647. 获取执行统计信息,使用Airflow的API获取执行状态
  648. 不再依赖airflow_dag_schedule表
  649. """
  650. from airflow.models import DagRun, TaskInstance
  651. from airflow.utils.state import State
  652. from sqlalchemy import desc
  653. from airflow import settings
  654. # 记录原始输入参数,仅供参考
  655. logger.debug(f"【执行日期】get_execution_stats接收到 exec_date: {exec_date}, 类型: {type(exec_date)}")
  656. logger.debug(f"获取执行日期 {exec_date} 的执行统计信息")
  657. # 当前DAG ID
  658. dag_id = "dag_dataops_pipeline_data_scheduler"
  659. try:
  660. # 直接查询最近的DAG运行,不依赖于精确的执行日期
  661. logger.debug("忽略精确的执行日期,直接查询最近的DAG运行")
  662. session = settings.Session()
  663. # 查询最近的DAG运行,按updated_at降序排序
  664. dag_runs = session.query(DagRun).filter(
  665. DagRun.dag_id == dag_id
  666. ).order_by(desc(DagRun.updated_at)).limit(1).all()
  667. if not dag_runs:
  668. logger.warning(f"未找到DAG {dag_id} 的任何运行记录")
  669. session.close()
  670. return {
  671. "exec_date": exec_date,
  672. "total_tasks": 0,
  673. "type_counts": {},
  674. "success_count": 0,
  675. "fail_count": 0,
  676. "pending_count": 0,
  677. "success_rate": 0,
  678. "avg_duration": None,
  679. "min_duration": None,
  680. "max_duration": None,
  681. "failed_tasks": []
  682. }
  683. dag_run = dag_runs[0]
  684. logger.debug(f"找到最近的DAG运行: execution_date={dag_run.execution_date}, updated_at={dag_run.updated_at}, state={dag_run.state}")
  685. # 直接查询最近更新的任务实例,不再通过execution_date过滤
  686. # 只通过dag_id过滤,按更新时间降序排序
  687. task_instances = session.query(TaskInstance).filter(
  688. TaskInstance.dag_id == dag_id
  689. ).order_by(desc(TaskInstance.updated_at)).limit(100).all() # 获取最近100条记录
  690. # 日志记录找到的任务实例数量
  691. logger.debug(f"找到 {len(task_instances)} 个最近的任务实例")
  692. # 关闭会话
  693. session.close()
  694. # 统计任务状态
  695. total_tasks = len(task_instances)
  696. success_count = len([ti for ti in task_instances if ti.state == State.SUCCESS])
  697. fail_count = len([ti for ti in task_instances if ti.state in (State.FAILED, State.UPSTREAM_FAILED)])
  698. pending_count = total_tasks - success_count - fail_count
  699. # 计算成功率
  700. success_rate = (success_count / total_tasks * 100) if total_tasks > 0 else 0
  701. # 计算执行时间
  702. durations = []
  703. for ti in task_instances:
  704. if ti.start_date and ti.end_date:
  705. duration = (ti.end_date - ti.start_date).total_seconds()
  706. durations.append(duration)
  707. avg_duration = sum(durations) / len(durations) if durations else None
  708. min_duration = min(durations) if durations else None
  709. max_duration = max(durations) if durations else None
  710. # 分类统计信息
  711. type_counts = {
  712. "resource": len([ti for ti in task_instances if ti.task_id.startswith("resource_")]),
  713. "model": len([ti for ti in task_instances if ti.task_id.startswith("model_")])
  714. }
  715. # 获取失败任务详情
  716. failed_tasks = []
  717. for ti in task_instances:
  718. if ti.state in (State.FAILED, State.UPSTREAM_FAILED):
  719. task_dict = {
  720. "task_id": ti.task_id,
  721. "state": ti.state,
  722. }
  723. if ti.start_date and ti.end_date:
  724. task_dict["exec_duration"] = (ti.end_date - ti.start_date).total_seconds()
  725. failed_tasks.append(task_dict)
  726. # 汇总统计信息
  727. stats = {
  728. "exec_date": exec_date,
  729. "dag_run_execution_date": dag_run.execution_date,
  730. "dag_run_updated_at": dag_run.updated_at,
  731. "total_tasks": total_tasks,
  732. "type_counts": type_counts,
  733. "success_count": success_count,
  734. "fail_count": fail_count,
  735. "pending_count": pending_count,
  736. "success_rate": success_rate,
  737. "avg_duration": avg_duration,
  738. "min_duration": min_duration,
  739. "max_duration": max_duration,
  740. "failed_tasks": failed_tasks
  741. }
  742. return stats
  743. except Exception as e:
  744. logger.error(f"获取执行统计信息时出错: {str(e)}")
  745. import traceback
  746. logger.error(traceback.format_exc())
  747. # 在出错时显式抛出异常,确保任务失败
  748. raise
  749. def generate_execution_report(exec_date, stats):
  750. """生成简化的执行报告,只包含基本信息"""
  751. # 构建简化报告
  752. report = []
  753. report.append(f"========== 数据运维系统执行报告 ==========")
  754. report.append(f"执行日期: {exec_date}")
  755. report.append(f"总任务数: {stats['total_tasks']}")
  756. # 将报告转换为字符串
  757. report_str = "\n".join(report)
  758. # 记录到日志
  759. logger.info("\n" + report_str)
  760. return report_str
  761. def summarize_execution(**kwargs):
  762. """简化的汇总执行情况函数,只判断整个作业是否成功"""
  763. exec_date = kwargs.get('ds') or get_today_date()
  764. execution_date = kwargs.get('execution_date')
  765. # 记录重要的时间参数,仅供参考
  766. logger.debug(f"【时间参数】summarize_execution: ds={exec_date}, execution_date={execution_date}")
  767. logger.debug(f"开始汇总执行日期 {exec_date} 的执行情况")
  768. # 获取任务实例对象
  769. task_instance = kwargs.get('ti')
  770. dag_id = task_instance.dag_id
  771. # 获取DAG运行状态信息 - 直接查询最近的运行
  772. from airflow.models import DagRun
  773. from airflow.utils.state import State
  774. from sqlalchemy import desc
  775. from airflow import settings
  776. logger.debug("直接查询最近更新的DAG运行记录,不依赖执行日期")
  777. session = settings.Session()
  778. # 查询最近的DAG运行,按updated_at降序排序
  779. dag_runs = session.query(DagRun).filter(
  780. DagRun.dag_id == dag_id
  781. ).order_by(desc(DagRun.updated_at)).limit(1).all()
  782. session.close()
  783. if not dag_runs or len(dag_runs) == 0:
  784. logger.warning(f"未找到DAG {dag_id} 的任何运行记录")
  785. state = "UNKNOWN"
  786. success = False
  787. else:
  788. # 获取状态
  789. dag_run = dag_runs[0] # 取最近更新的DAG运行
  790. state = dag_run.state
  791. logger.debug(f"找到最近的DAG运行: execution_date={dag_run.execution_date}, updated_at={dag_run.updated_at}, state={state}")
  792. logger.debug(f"DAG {dag_id} 的状态为: {state}")
  793. # 判断是否成功
  794. success = (state == State.SUCCESS)
  795. # 获取更详细的执行统计信息 - 直接调用get_execution_stats而不关心具体日期
  796. stats = get_execution_stats(exec_date)
  797. # 创建简单的报告
  798. if success:
  799. report = f"DAG {dag_id} 在 {exec_date} 的执行成功完成。"
  800. if stats:
  801. report += f" 总共有 {stats.get('total_tasks', 0)} 个任务," \
  802. f"其中成功 {stats.get('success_count', 0)} 个," \
  803. f"失败 {stats.get('fail_count', 0)} 个。"
  804. else:
  805. report = f"DAG {dag_id} 在 {exec_date} 的执行未成功完成,状态为: {state}。"
  806. if stats and stats.get('failed_tasks'):
  807. report += f" 有 {len(stats.get('failed_tasks', []))} 个任务失败。"
  808. # 记录执行结果
  809. logger.info(report)
  810. # 如果 stats 为空或缺少total_tasks字段,创建一个完整的状态信息
  811. if not stats or 'total_tasks' not in stats:
  812. stats = {
  813. "exec_date": exec_date,
  814. "total_tasks": 0,
  815. "type_counts": {},
  816. "success_count": 0,
  817. "fail_count": 0,
  818. "pending_count": 0,
  819. "success_rate": 0,
  820. "avg_duration": None,
  821. "min_duration": None,
  822. "max_duration": None,
  823. "failed_tasks": [],
  824. "success": success,
  825. "dag_id": dag_id,
  826. "dag_run_state": state
  827. }
  828. else:
  829. # 添加success状态到stats
  830. stats["success"] = success
  831. # 将结果推送到XCom
  832. task_instance.xcom_push(key='execution_stats', value=stats)
  833. task_instance.xcom_push(key='execution_report', value=report)
  834. task_instance.xcom_push(key='execution_success', value=success)
  835. # 生成简化的执行报告
  836. simple_report = generate_execution_report(exec_date, stats)
  837. return simple_report
  838. # 添加新函数,用于从数据库获取执行计划
  839. def get_execution_plan_from_db(ds):
  840. """
  841. 从数据库airflow_exec_plans表中获取执行计划
  842. 参数:
  843. ds (str): 执行日期,格式为'YYYY-MM-DD'
  844. 返回:
  845. dict: 执行计划字典,如果找不到则返回None
  846. """
  847. # 记录输入参数详细信息
  848. if isinstance(ds, datetime):
  849. if ds.tzinfo:
  850. logger.debug(f"【执行日期】get_execution_plan_from_db接收到datetime对象: {ds}, 带时区: {ds.tzinfo}")
  851. else:
  852. logger.debug(f"【执行日期】get_execution_plan_from_db接收到datetime对象: {ds}, 无时区")
  853. else:
  854. logger.debug(f"【执行日期】get_execution_plan_from_db接收到: {ds}, 类型: {type(ds)}")
  855. logger.info(f"尝试从数据库获取执行日期 {ds} 的执行计划")
  856. conn = get_pg_conn()
  857. cursor = conn.cursor()
  858. execution_plan = None
  859. try:
  860. # 查询条件a: 当前日期=表的ds,如果有多条记录,取insert_time最大的一条
  861. cursor.execute("""
  862. SELECT plan, run_id, insert_time
  863. FROM airflow_exec_plans
  864. WHERE dag_id = 'dag_dataops_pipeline_prepare_scheduler' AND ds = %s
  865. ORDER BY insert_time DESC
  866. LIMIT 1
  867. """, (ds,))
  868. result = cursor.fetchone()
  869. if result:
  870. # 获取计划、run_id和insert_time
  871. plan_json, run_id, insert_time = result
  872. logger.info(f"找到当前日期 ds={ds} 的执行计划记录,run_id: {run_id}, insert_time: {insert_time}")
  873. # 处理plan_json可能已经是dict的情况
  874. if isinstance(plan_json, dict):
  875. execution_plan = plan_json
  876. else:
  877. execution_plan = json.loads(plan_json)
  878. return execution_plan
  879. # 查询条件b: 找不到当前日期的记录,查找ds<当前ds的最新记录
  880. logger.info(f"未找到当前日期 ds={ds} 的执行计划记录,尝试查找历史记录")
  881. cursor.execute("""
  882. SELECT plan, run_id, insert_time, ds
  883. FROM airflow_exec_plans
  884. WHERE dag_id = 'dag_dataops_pipeline_prepare_scheduler' AND ds < %s
  885. ORDER BY ds DESC, insert_time DESC
  886. LIMIT 1
  887. """, (ds,))
  888. result = cursor.fetchone()
  889. if result:
  890. # 获取计划、run_id、insert_time和ds
  891. plan_json, run_id, insert_time, plan_ds = result
  892. logger.info(f"找到历史执行计划记录,ds: {plan_ds}, run_id: {run_id}, insert_time: {insert_time}")
  893. # 处理plan_json可能已经是dict的情况
  894. if isinstance(plan_json, dict):
  895. execution_plan = plan_json
  896. else:
  897. execution_plan = json.loads(plan_json)
  898. return execution_plan
  899. # 找不到任何执行计划记录
  900. logger.error(f"在数据库中未找到任何执行计划记录,当前DAG ds={ds}")
  901. return None
  902. except Exception as e:
  903. logger.error(f"从数据库获取执行计划时出错: {str(e)}")
  904. import traceback
  905. logger.error(traceback.format_exc())
  906. return None
  907. finally:
  908. cursor.close()
  909. conn.close()
  910. # 创建DAG
  911. with DAG(
  912. "dag_dataops_pipeline_data_scheduler",
  913. start_date=datetime(2024, 1, 1),
  914. schedule_interval="@daily",
  915. catchup=False,
  916. default_args={
  917. 'owner': 'airflow',
  918. 'depends_on_past': False,
  919. 'email_on_failure': False,
  920. 'email_on_retry': False,
  921. 'retries': 1,
  922. 'retry_delay': timedelta(minutes=5)
  923. },
  924. # 添加DAG级别参数,确保任务运行时有正确的环境
  925. params={
  926. "scripts_path": SCRIPTS_BASE_PATH,
  927. "airflow_base_path": os.path.dirname(os.path.dirname(__file__))
  928. }
  929. ) as dag:
  930. # 记录DAG实例化时的重要信息
  931. now = datetime.now()
  932. now_with_tz = now.replace(tzinfo=pytz.timezone('Asia/Shanghai'))
  933. default_exec_date = get_today_date()
  934. logger.info(f"【DAG初始化】当前时间: {now} / {now_with_tz}, 默认执行日期: {default_exec_date}")
  935. #############################################
  936. # 阶段1: 准备阶段(Prepare Phase)
  937. #############################################
  938. with TaskGroup("prepare_phase") as prepare_group:
  939. # 任务开始标记
  940. start_preparation = EmptyOperator(
  941. task_id="start_preparation"
  942. )
  943. # 准备调度任务
  944. prepare_task = PythonOperator(
  945. task_id="prepare_dag_schedule",
  946. python_callable=prepare_dag_schedule,
  947. provide_context=True
  948. )
  949. # 验证执行计划有效性
  950. check_plan = ShortCircuitOperator(
  951. task_id="check_execution_plan",
  952. python_callable=check_execution_plan,
  953. provide_context=True
  954. )
  955. # 创建执行计划
  956. create_plan = PythonOperator(
  957. task_id="create_execution_plan",
  958. python_callable=create_execution_plan,
  959. provide_context=True
  960. )
  961. # 准备完成标记
  962. preparation_completed = EmptyOperator(
  963. task_id="preparation_completed"
  964. )
  965. # 设置任务依赖
  966. start_preparation >> prepare_task >> check_plan >> create_plan >> preparation_completed
  967. #############################################
  968. # 阶段2: 数据处理阶段(Data Processing Phase)
  969. #############################################
  970. with TaskGroup("data_processing_phase") as data_group:
  971. # 数据处理开始任务
  972. start_processing = EmptyOperator(
  973. task_id="start_processing"
  974. )
  975. # 数据处理完成标记
  976. processing_completed = EmptyOperator(
  977. task_id="processing_completed",
  978. trigger_rule="none_failed_min_one_success" # 只要有一个任务成功且没有失败的任务就标记为完成
  979. )
  980. # 设置依赖
  981. start_processing >> processing_completed
  982. #############################################
  983. # 阶段3: 汇总阶段(Summary Phase)
  984. #############################################
  985. with TaskGroup("summary_phase") as summary_group:
  986. # 汇总执行情况
  987. summarize_task = PythonOperator(
  988. task_id="summarize_execution",
  989. python_callable=summarize_execution,
  990. provide_context=True
  991. )
  992. # 总结完成标记
  993. summary_completed = EmptyOperator(
  994. task_id="summary_completed"
  995. )
  996. # 设置任务依赖
  997. summarize_task >> summary_completed
  998. # 设置三个阶段之间的依赖关系
  999. prepare_group >> data_group >> summary_group
  1000. # 尝试从数据库获取执行计划
  1001. try:
  1002. # 获取当前DAG的执行日期
  1003. exec_date = get_today_date() # 使用当天日期作为默认值
  1004. logger.info(f"当前DAG执行日期 ds={exec_date},尝试从数据库获取执行计划")
  1005. # 记录实际使用的执行日期的时区信息和原始格式
  1006. if isinstance(exec_date, datetime):
  1007. logger.info(f"【执行日期详情】类型: datetime, 时区: {exec_date.tzinfo}, 值: {exec_date}")
  1008. else:
  1009. logger.info(f"【执行日期详情】类型: {type(exec_date)}, 值: {exec_date}")
  1010. # 从数据库获取执行计划
  1011. execution_plan = get_execution_plan_from_db(exec_date)
  1012. # 检查是否成功获取到执行计划
  1013. if execution_plan is None:
  1014. error_msg = f"无法从数据库获取有效的执行计划,当前DAG ds={exec_date}"
  1015. logger.error(error_msg)
  1016. # 使用全局变量而不是异常来强制DAG失败
  1017. raise ValueError(error_msg)
  1018. # 如果获取到了执行计划,处理它
  1019. logger.info(f"成功从数据库获取执行计划")
  1020. # 提取信息
  1021. exec_date = execution_plan.get("exec_date", exec_date)
  1022. resource_tasks = execution_plan.get("resource_tasks", [])
  1023. model_tasks = execution_plan.get("model_tasks", [])
  1024. dependencies = execution_plan.get("dependencies", {})
  1025. logger.info(f"执行计划: exec_date={exec_date}, resource_tasks数量={len(resource_tasks)}, model_tasks数量={len(model_tasks)}")
  1026. # 如果执行计划为空(没有任务),也应该失败
  1027. if not resource_tasks and not model_tasks:
  1028. error_msg = f"执行计划中没有任何任务,当前DAG ds={exec_date}"
  1029. logger.error(error_msg)
  1030. raise ValueError(error_msg)
  1031. # 动态创建处理任务
  1032. task_dict = {}
  1033. # 1. 创建资源表任务
  1034. for task_info in resource_tasks:
  1035. table_name = task_info["target_table"]
  1036. script_name = task_info["script_name"]
  1037. exec_mode = task_info.get("script_exec_mode", "append")
  1038. # 创建安全的任务ID
  1039. safe_table_name = table_name.replace(".", "_").replace("-", "_")
  1040. # 确保所有任务都是data_processing_phase的一部分
  1041. with data_group:
  1042. resource_task = PythonOperator(
  1043. task_id=f"resource_{safe_table_name}",
  1044. python_callable=process_resource,
  1045. op_kwargs={
  1046. "target_table": table_name,
  1047. "script_name": script_name,
  1048. "script_exec_mode": exec_mode,
  1049. # 确保使用字符串而不是可能是默认(非字符串)格式的执行日期
  1050. "exec_date": str(exec_date)
  1051. },
  1052. retries=TASK_RETRY_CONFIG["retries"],
  1053. retry_delay=timedelta(minutes=TASK_RETRY_CONFIG["retry_delay_minutes"])
  1054. )
  1055. # 将任务添加到字典
  1056. task_dict[table_name] = resource_task
  1057. # 设置与start_processing的依赖
  1058. start_processing >> resource_task
  1059. # 创建有向图,用于检测模型表之间的依赖关系
  1060. G = nx.DiGraph()
  1061. # 将所有模型表添加为节点
  1062. for task_info in model_tasks:
  1063. table_name = task_info["target_table"]
  1064. G.add_node(table_name)
  1065. # 添加模型表之间的依赖边
  1066. for source, deps in dependencies.items():
  1067. for dep in deps:
  1068. if dep.get("table_type") == "DataModel" and dep.get("table_name") in G.nodes():
  1069. G.add_edge(dep.get("table_name"), source) # 依赖方向:依赖项 -> 目标
  1070. # 检测循环依赖并处理
  1071. try:
  1072. cycles = list(nx.simple_cycles(G))
  1073. if cycles:
  1074. logger.warning(f"检测到循环依赖: {cycles}")
  1075. for cycle in cycles:
  1076. G.remove_edge(cycle[-1], cycle[0])
  1077. logger.info(f"打破循环依赖: 移除 {cycle[-1]} -> {cycle[0]} 的依赖")
  1078. except Exception as e:
  1079. logger.error(f"检测循环依赖时出错: {str(e)}")
  1080. # 生成拓扑排序,确定执行顺序
  1081. execution_order = []
  1082. try:
  1083. execution_order = list(nx.topological_sort(G))
  1084. except Exception as e:
  1085. logger.error(f"生成拓扑排序失败: {str(e)}")
  1086. execution_order = [task_info["target_table"] for task_info in model_tasks]
  1087. # 2. 按拓扑排序顺序创建模型表任务
  1088. for table_name in execution_order:
  1089. task_info = next((t for t in model_tasks if t["target_table"] == table_name), None)
  1090. if not task_info:
  1091. continue
  1092. script_name = task_info["script_name"]
  1093. exec_mode = task_info.get("script_exec_mode", "append")
  1094. # 创建安全的任务ID
  1095. safe_table_name = table_name.replace(".", "_").replace("-", "_")
  1096. # 确保所有任务都是data_processing_phase的一部分
  1097. with data_group:
  1098. model_task = PythonOperator(
  1099. task_id=f"model_{safe_table_name}",
  1100. python_callable=process_model,
  1101. op_kwargs={
  1102. "target_table": table_name,
  1103. "script_name": script_name,
  1104. "script_exec_mode": exec_mode,
  1105. # 确保使用字符串而不是可能是默认(非字符串)格式的执行日期
  1106. "exec_date": str(exec_date)
  1107. },
  1108. retries=TASK_RETRY_CONFIG["retries"],
  1109. retry_delay=timedelta(minutes=TASK_RETRY_CONFIG["retry_delay_minutes"])
  1110. )
  1111. # 将任务添加到字典
  1112. task_dict[table_name] = model_task
  1113. # 设置依赖关系
  1114. deps = dependencies.get(table_name, [])
  1115. has_dependency = False
  1116. # 处理模型表之间的依赖
  1117. for dep in deps:
  1118. dep_table = dep.get("table_name")
  1119. dep_type = dep.get("table_type")
  1120. if dep_table in task_dict:
  1121. task_dict[dep_table] >> model_task
  1122. has_dependency = True
  1123. logger.info(f"设置依赖: {dep_table} >> {table_name}")
  1124. # 如果没有依赖,则依赖于start_processing和资源表任务
  1125. if not has_dependency:
  1126. # 从start_processing任务直接连接
  1127. start_processing >> model_task
  1128. # 同时从所有资源表任务连接
  1129. resource_count = 0
  1130. for resource_table in resource_tasks:
  1131. if resource_count >= 5: # 最多设置5个依赖
  1132. break
  1133. resource_name = resource_table["target_table"]
  1134. if resource_name in task_dict:
  1135. task_dict[resource_name] >> model_task
  1136. resource_count += 1
  1137. # 找出所有终端任务(没有下游依赖的任务)
  1138. terminal_tasks = []
  1139. # 检查所有模型表任务
  1140. for table_name in execution_order:
  1141. # 检查是否有下游任务
  1142. has_downstream = False
  1143. for source, deps in dependencies.items():
  1144. if source == table_name: # 跳过自身
  1145. continue
  1146. for dep in deps:
  1147. if dep.get("table_name") == table_name:
  1148. has_downstream = True
  1149. break
  1150. if has_downstream:
  1151. break
  1152. # 如果没有下游任务,添加到终端任务列表
  1153. if not has_downstream and table_name in task_dict:
  1154. terminal_tasks.append(table_name)
  1155. # 如果没有模型表任务,将所有资源表任务视为终端任务
  1156. if not model_tasks and resource_tasks:
  1157. terminal_tasks = [task["target_table"] for task in resource_tasks]
  1158. logger.info(f"没有模型表任务,将所有资源表任务视为终端任务: {terminal_tasks}")
  1159. # 如果既没有模型表任务也没有资源表任务,已有默认依赖链
  1160. if not terminal_tasks:
  1161. logger.warning("未找到任何任务,使用默认依赖链")
  1162. else:
  1163. # 将所有终端任务连接到完成标记
  1164. for table_name in terminal_tasks:
  1165. if table_name in task_dict:
  1166. task_dict[table_name] >> processing_completed
  1167. logger.info(f"设置终端任务: {table_name} >> processing_completed")
  1168. except Exception as e:
  1169. logger.error(f"加载执行计划时出错: {str(e)}")
  1170. import traceback
  1171. logger.error(traceback.format_exc())
  1172. logger.info(f"DAG dag_dataops_pipeline_data_scheduler 定义完成")