dag_dataops_pipeline_data_scheduler.py 56 KB

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