dag_dataops_pipeline_data_scheduler.py 54 KB

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