dag_dataops_unified_scheduler.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  1. # dag_dataops_unified_scheduler.py
  2. # 合并了prepare, data和summary三个DAG的功能
  3. from airflow import DAG
  4. from airflow.operators.python import PythonOperator
  5. from airflow.operators.empty import EmptyOperator
  6. from airflow.utils.task_group import TaskGroup
  7. from datetime import datetime, timedelta, date
  8. import logging
  9. import networkx as nx
  10. import json
  11. from decimal import Decimal
  12. from common import (
  13. get_pg_conn,
  14. get_neo4j_driver,
  15. execute_with_monitoring,
  16. get_today_date
  17. )
  18. from config import TASK_RETRY_CONFIG, PG_CONFIG, NEO4J_CONFIG
  19. # 创建日志记录器
  20. logger = logging.getLogger(__name__)
  21. # 添加日期序列化器
  22. def json_serial(obj):
  23. """将日期对象序列化为ISO格式字符串的JSON序列化器"""
  24. if isinstance(obj, (datetime, date)):
  25. return obj.isoformat()
  26. raise TypeError(f"类型 {type(obj)} 不能被序列化为JSON")
  27. # 添加自定义JSON编码器解决Decimal序列化问题
  28. class DecimalEncoder(json.JSONEncoder):
  29. def default(self, obj):
  30. if isinstance(obj, Decimal):
  31. return float(obj)
  32. # 处理日期类型
  33. elif isinstance(obj, (datetime, date)):
  34. return obj.isoformat()
  35. # 让父类处理其他类型
  36. return super(DecimalEncoder, self).default(obj)
  37. #############################################
  38. # 第一阶段: 准备阶段(Prepare Phase)的函数
  39. #############################################
  40. def get_enabled_tables():
  41. """获取所有启用的表"""
  42. conn = get_pg_conn()
  43. cursor = conn.cursor()
  44. try:
  45. cursor.execute("""
  46. SELECT owner_id, table_name
  47. FROM schedule_status
  48. WHERE schedule_is_enabled = TRUE
  49. """)
  50. result = cursor.fetchall()
  51. return [row[1] for row in result] # 只返回表名
  52. except Exception as e:
  53. logger.error(f"获取启用表失败: {str(e)}")
  54. return []
  55. finally:
  56. cursor.close()
  57. conn.close()
  58. def check_table_directly_subscribed(table_name):
  59. """检查表是否在schedule_status表中直接订阅"""
  60. conn = get_pg_conn()
  61. cursor = conn.cursor()
  62. try:
  63. cursor.execute("""
  64. SELECT schedule_is_enabled
  65. FROM schedule_status
  66. WHERE table_name = %s
  67. """, (table_name,))
  68. result = cursor.fetchone()
  69. return result and result[0] is True
  70. except Exception as e:
  71. logger.error(f"检查表订阅状态失败: {str(e)}")
  72. return False
  73. finally:
  74. cursor.close()
  75. conn.close()
  76. def get_table_info_from_neo4j(table_name):
  77. """从Neo4j获取表的详细信息"""
  78. driver = get_neo4j_driver()
  79. # 检查表是否直接订阅
  80. is_directly_schedule = check_table_directly_subscribed(table_name)
  81. table_info = {
  82. 'target_table': table_name,
  83. 'is_directly_schedule': is_directly_schedule, # 初始值设为True,从schedule_status表获取
  84. }
  85. try:
  86. with driver.session() as session:
  87. # 查询表标签和状态
  88. query_table = """
  89. MATCH (t {en_name: $table_name})
  90. RETURN labels(t) AS labels, t.status AS status, t.frequency AS frequency
  91. """
  92. result = session.run(query_table, table_name=table_name)
  93. record = result.single()
  94. if record:
  95. labels = record.get("labels", [])
  96. table_info['target_table_label'] = [label for label in labels if label in ["DataResource", "DataModel", "DataSource"]][0] if labels else None
  97. table_info['target_table_status'] = record.get("status", True) # 默认为True
  98. table_info['default_update_frequency'] = record.get("frequency")
  99. # 根据标签类型查询关系和脚本信息
  100. if "DataResource" in labels:
  101. query_rel = """
  102. MATCH (target {en_name: $table_name})-[rel:ORIGINATES_FROM]->(source)
  103. RETURN source.en_name AS source_table, rel.script_name AS script_name,
  104. rel.script_type AS script_type, rel.script_exec_mode AS script_exec_mode
  105. """
  106. elif "DataModel" in labels:
  107. query_rel = """
  108. MATCH (target {en_name: $table_name})-[rel:DERIVED_FROM]->(source)
  109. RETURN source.en_name AS source_table, rel.script_name AS script_name,
  110. rel.script_type AS script_type, rel.script_exec_mode AS script_exec_mode
  111. """
  112. else:
  113. logger.warning(f"表 {table_name} 不是DataResource或DataModel类型")
  114. return table_info
  115. result = session.run(query_rel, table_name=table_name)
  116. record = result.single()
  117. if record:
  118. table_info['source_table'] = record.get("source_table")
  119. # 检查script_name是否为空
  120. script_name = record.get("script_name")
  121. if not script_name:
  122. logger.warning(f"表 {table_name} 的关系中没有script_name属性,可能导致后续处理出错")
  123. table_info['script_name'] = script_name
  124. # 设置默认值,确保即使属性为空也有默认值
  125. table_info['script_type'] = record.get("script_type", "python") # 默认为python
  126. table_info['script_exec_mode'] = record.get("script_exec_mode", "append") # 默认为append
  127. else:
  128. logger.warning(f"未找到表 {table_name} 的关系信息")
  129. else:
  130. logger.warning(f"在Neo4j中找不到表 {table_name} 的信息")
  131. except Exception as e:
  132. logger.error(f"获取表 {table_name} 的信息时出错: {str(e)}")
  133. finally:
  134. driver.close()
  135. return table_info
  136. def process_dependencies(tables_info):
  137. """处理表间依赖关系,添加被动调度的表"""
  138. # 存储所有表信息的字典
  139. all_tables = {t['target_table']: t for t in tables_info}
  140. driver = get_neo4j_driver()
  141. try:
  142. with driver.session() as session:
  143. for table_name, table_info in list(all_tables.items()):
  144. if table_info.get('target_table_label') == 'DataModel':
  145. # 查询其依赖表
  146. query = """
  147. MATCH (dm {en_name: $table_name})-[:DERIVED_FROM]->(dep)
  148. RETURN dep.en_name AS dep_name, labels(dep) AS dep_labels,
  149. dep.status AS dep_status, dep.frequency AS dep_frequency
  150. """
  151. result = session.run(query, table_name=table_name)
  152. for record in result:
  153. dep_name = record.get("dep_name")
  154. dep_labels = record.get("dep_labels", [])
  155. dep_status = record.get("dep_status", True)
  156. dep_frequency = record.get("dep_frequency")
  157. # 处理未被直接调度的依赖表
  158. if dep_name and dep_name not in all_tables:
  159. logger.info(f"发现被动依赖表: {dep_name}, 标签: {dep_labels}")
  160. # 获取依赖表详细信息
  161. dep_info = get_table_info_from_neo4j(dep_name)
  162. dep_info['is_directly_schedule'] = False
  163. # 处理调度频率继承
  164. if not dep_info.get('default_update_frequency'):
  165. dep_info['default_update_frequency'] = table_info.get('default_update_frequency')
  166. all_tables[dep_name] = dep_info
  167. except Exception as e:
  168. logger.error(f"处理依赖关系时出错: {str(e)}")
  169. finally:
  170. driver.close()
  171. return list(all_tables.values())
  172. def filter_invalid_tables(tables_info):
  173. """过滤无效表及其依赖,使用NetworkX构建依赖图"""
  174. # 构建表名到索引的映射
  175. table_dict = {t['target_table']: i for i, t in enumerate(tables_info)}
  176. # 找出无效表
  177. invalid_tables = set()
  178. for table in tables_info:
  179. if table.get('target_table_status') is False:
  180. invalid_tables.add(table['target_table'])
  181. logger.info(f"表 {table['target_table']} 的状态为无效")
  182. # 构建依赖图
  183. G = nx.DiGraph()
  184. # 添加所有节点
  185. for table in tables_info:
  186. G.add_node(table['target_table'])
  187. # 查询并添加依赖边
  188. driver = get_neo4j_driver()
  189. try:
  190. with driver.session() as session:
  191. for table in tables_info:
  192. if table.get('target_table_label') == 'DataModel':
  193. query = """
  194. MATCH (source {en_name: $table_name})-[:DERIVED_FROM]->(target)
  195. RETURN target.en_name AS target_name
  196. """
  197. result = session.run(query, table_name=table['target_table'])
  198. for record in result:
  199. target_name = record.get("target_name")
  200. if target_name and target_name in table_dict:
  201. # 添加从目标到源的边,表示目标依赖于源
  202. G.add_edge(table['target_table'], target_name)
  203. logger.debug(f"添加依赖边: {table['target_table']} -> {target_name}")
  204. except Exception as e:
  205. logger.error(f"构建依赖图时出错: {str(e)}")
  206. finally:
  207. driver.close()
  208. # 找出依赖于无效表的所有表
  209. downstream_invalid = set()
  210. for invalid_table in invalid_tables:
  211. # 获取可从无效表到达的所有节点
  212. try:
  213. descendants = nx.descendants(G, invalid_table)
  214. downstream_invalid.update(descendants)
  215. logger.info(f"表 {invalid_table} 的下游无效表: {descendants}")
  216. except Exception as e:
  217. logger.error(f"处理表 {invalid_table} 的下游依赖时出错: {str(e)}")
  218. # 合并所有无效表
  219. all_invalid = invalid_tables.union(downstream_invalid)
  220. logger.info(f"总共 {len(all_invalid)} 个表被标记为无效: {all_invalid}")
  221. # 过滤出有效表
  222. valid_tables = [t for t in tables_info if t['target_table'] not in all_invalid]
  223. logger.info(f"过滤后保留 {len(valid_tables)} 个有效表")
  224. return valid_tables
  225. def write_to_airflow_dag_schedule(exec_date, tables_info):
  226. """将表信息写入airflow_dag_schedule表"""
  227. conn = get_pg_conn()
  228. cursor = conn.cursor()
  229. try:
  230. # 清理当日数据,避免重复
  231. cursor.execute("""
  232. DELETE FROM airflow_dag_schedule WHERE exec_date = %s
  233. """, (exec_date,))
  234. logger.info(f"已清理执行日期 {exec_date} 的现有数据")
  235. # 批量插入新数据
  236. inserted_count = 0
  237. for table in tables_info:
  238. cursor.execute("""
  239. INSERT INTO airflow_dag_schedule (
  240. exec_date, source_table, target_table, target_table_label,
  241. target_table_status, is_directly_schedule, default_update_frequency,
  242. script_name, script_type, script_exec_mode
  243. ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
  244. """, (
  245. exec_date,
  246. table.get('source_table'),
  247. table['target_table'],
  248. table.get('target_table_label'),
  249. table.get('target_table_status', True),
  250. table.get('is_directly_schedule', False),
  251. table.get('default_update_frequency'),
  252. table.get('script_name'),
  253. table.get('script_type', 'python'),
  254. table.get('script_exec_mode', 'append')
  255. ))
  256. inserted_count += 1
  257. conn.commit()
  258. logger.info(f"成功插入 {inserted_count} 条记录到 airflow_dag_schedule 表")
  259. return inserted_count
  260. except Exception as e:
  261. logger.error(f"写入 airflow_dag_schedule 表时出错: {str(e)}")
  262. conn.rollback()
  263. # 重新抛出异常,确保错误被正确传播
  264. raise
  265. finally:
  266. cursor.close()
  267. conn.close()
  268. def prepare_dag_schedule(**kwargs):
  269. """准备DAG调度任务的主函数"""
  270. exec_date = kwargs.get('ds') or get_today_date()
  271. logger.info(f"开始准备执行日期 {exec_date} 的统一调度任务")
  272. # 1. 获取启用的表
  273. enabled_tables = get_enabled_tables()
  274. logger.info(f"从schedule_status表获取到 {len(enabled_tables)} 个启用的表")
  275. if not enabled_tables:
  276. logger.warning("没有找到启用的表,准备工作结束")
  277. return 0
  278. # 2. 获取表的详细信息
  279. tables_info = []
  280. for table_name in enabled_tables:
  281. table_info = get_table_info_from_neo4j(table_name)
  282. if table_info:
  283. tables_info.append(table_info)
  284. logger.info(f"成功获取 {len(tables_info)} 个表的详细信息")
  285. # 3. 处理依赖关系,添加被动调度的表
  286. enriched_tables = process_dependencies(tables_info)
  287. logger.info(f"处理依赖后,总共有 {len(enriched_tables)} 个表")
  288. # 4. 过滤无效表及其依赖
  289. valid_tables = filter_invalid_tables(enriched_tables)
  290. logger.info(f"过滤无效表后,最终有 {len(valid_tables)} 个有效表")
  291. # 5. 写入airflow_dag_schedule表
  292. inserted_count = write_to_airflow_dag_schedule(exec_date, valid_tables)
  293. # 6. 检查插入操作是否成功,如果失败则抛出异常
  294. if inserted_count == 0 and valid_tables:
  295. error_msg = f"插入操作失败,无记录被插入到airflow_dag_schedule表,但有{len(valid_tables)}个有效表需要处理"
  296. logger.error(error_msg)
  297. raise Exception(error_msg)
  298. # 7. 生成执行计划数据
  299. resource_tasks = []
  300. model_tasks = []
  301. for table in valid_tables:
  302. if table.get('target_table_label') == 'DataResource':
  303. resource_tasks.append({
  304. "source_table": table.get('source_table'),
  305. "target_table": table['target_table'],
  306. "target_table_label": "DataResource",
  307. "script_name": table.get('script_name'),
  308. "script_exec_mode": table.get('script_exec_mode', 'append')
  309. })
  310. elif table.get('target_table_label') == 'DataModel':
  311. model_tasks.append({
  312. "source_table": table.get('source_table'),
  313. "target_table": table['target_table'],
  314. "target_table_label": "DataModel",
  315. "script_name": table.get('script_name'),
  316. "script_exec_mode": table.get('script_exec_mode', 'append')
  317. })
  318. # 获取依赖关系
  319. model_table_names = [t['target_table'] for t in model_tasks]
  320. dependencies = {}
  321. driver = get_neo4j_driver()
  322. try:
  323. with driver.session() as session:
  324. for table_name in model_table_names:
  325. query = """
  326. MATCH (source:DataModel {en_name: $table_name})-[:DERIVED_FROM]->(target)
  327. RETURN source.en_name AS source, target.en_name AS target, labels(target) AS target_labels
  328. """
  329. result = session.run(query, table_name=table_name)
  330. deps = []
  331. for record in result:
  332. target = record.get("target")
  333. target_labels = record.get("target_labels", [])
  334. if target:
  335. table_type = next((label for label in target_labels if label in ["DataModel", "DataResource"]), None)
  336. deps.append({
  337. "table_name": target,
  338. "table_type": table_type
  339. })
  340. dependencies[table_name] = deps
  341. finally:
  342. driver.close()
  343. # 创建执行计划
  344. execution_plan = {
  345. "exec_date": exec_date,
  346. "resource_tasks": resource_tasks,
  347. "model_tasks": model_tasks,
  348. "dependencies": dependencies
  349. }
  350. # 将执行计划保存到XCom
  351. kwargs['ti'].xcom_push(key='execution_plan', value=json.dumps(execution_plan, default=json_serial))
  352. logger.info(f"准备了执行计划,包含 {len(resource_tasks)} 个资源表任务和 {len(model_tasks)} 个模型表任务")
  353. return inserted_count
  354. #############################################
  355. # 第二阶段: 数据处理阶段(Data Processing Phase)的函数
  356. #############################################
  357. def get_latest_date():
  358. """获取数据库中包含记录的最近日期"""
  359. conn = get_pg_conn()
  360. cursor = conn.cursor()
  361. try:
  362. cursor.execute("""
  363. SELECT DISTINCT exec_date
  364. FROM airflow_dag_schedule
  365. ORDER BY exec_date DESC
  366. LIMIT 1
  367. """)
  368. result = cursor.fetchone()
  369. if result:
  370. latest_date = result[0]
  371. logger.info(f"找到最近的包含记录的日期: {latest_date}")
  372. return latest_date
  373. else:
  374. logger.warning("未找到包含记录的日期,将使用当前日期")
  375. return get_today_date()
  376. except Exception as e:
  377. logger.error(f"查找最近日期时出错: {str(e)}")
  378. return get_today_date()
  379. finally:
  380. cursor.close()
  381. conn.close()
  382. def get_all_tasks(exec_date):
  383. """获取所有需要执行的任务(DataResource和DataModel)"""
  384. conn = get_pg_conn()
  385. cursor = conn.cursor()
  386. try:
  387. # 查询所有资源表任务
  388. cursor.execute("""
  389. SELECT source_table, target_table, target_table_label, script_name, script_exec_mode
  390. FROM airflow_dag_schedule
  391. WHERE exec_date = %s AND target_table_label = 'DataResource' AND script_name IS NOT NULL
  392. """, (exec_date,))
  393. resource_results = cursor.fetchall()
  394. # 查询所有模型表任务
  395. cursor.execute("""
  396. SELECT source_table, target_table, target_table_label, script_name, script_exec_mode
  397. FROM airflow_dag_schedule
  398. WHERE exec_date = %s AND target_table_label = 'DataModel' AND script_name IS NOT NULL
  399. """, (exec_date,))
  400. model_results = cursor.fetchall()
  401. # 整理资源表信息
  402. resource_tasks = []
  403. for row in resource_results:
  404. source_table, target_table, target_table_label, script_name, script_exec_mode = row
  405. if script_name: # 确保脚本名称不为空
  406. resource_tasks.append({
  407. "source_table": source_table,
  408. "target_table": target_table,
  409. "target_table_label": target_table_label,
  410. "script_name": script_name,
  411. "script_exec_mode": script_exec_mode or "append"
  412. })
  413. # 整理模型表信息
  414. model_tasks = []
  415. for row in model_results:
  416. source_table, target_table, target_table_label, script_name, script_exec_mode = row
  417. if script_name: # 确保脚本名称不为空
  418. model_tasks.append({
  419. "source_table": source_table,
  420. "target_table": target_table,
  421. "target_table_label": target_table_label,
  422. "script_name": script_name,
  423. "script_exec_mode": script_exec_mode or "append"
  424. })
  425. logger.info(f"获取到 {len(resource_tasks)} 个资源表任务和 {len(model_tasks)} 个模型表任务")
  426. return resource_tasks, model_tasks
  427. except Exception as e:
  428. logger.error(f"获取任务信息时出错: {str(e)}")
  429. return [], []
  430. finally:
  431. cursor.close()
  432. conn.close()
  433. def get_table_dependencies_for_data_phase(table_names):
  434. """获取表之间的依赖关系"""
  435. driver = get_neo4j_driver()
  436. dependency_dict = {name: [] for name in table_names}
  437. try:
  438. with driver.session() as session:
  439. # 获取所有模型表之间的依赖关系
  440. query = """
  441. MATCH (source:DataModel)-[:DERIVED_FROM]->(target)
  442. WHERE source.en_name IN $table_names
  443. RETURN source.en_name AS source, target.en_name AS target, labels(target) AS target_labels
  444. """
  445. result = session.run(query, table_names=table_names)
  446. for record in result:
  447. source = record.get("source")
  448. target = record.get("target")
  449. target_labels = record.get("target_labels", [])
  450. if source and target:
  451. # 将目标表添加到源表的依赖列表中
  452. dependency_dict[source].append({
  453. "table_name": target,
  454. "table_type": next((label for label in target_labels if label in ["DataModel", "DataResource"]), None)
  455. })
  456. logger.debug(f"依赖关系: {source} 依赖于 {target}")
  457. except Exception as e:
  458. logger.error(f"从Neo4j获取依赖关系时出错: {str(e)}")
  459. finally:
  460. driver.close()
  461. return dependency_dict
  462. def create_execution_plan(**kwargs):
  463. """准备执行计划的函数,使用从准备阶段传递的数据"""
  464. try:
  465. # 从XCom获取执行计划
  466. execution_plan = kwargs['ti'].xcom_pull(task_ids='prepare_phase.prepare_dag_schedule', key='execution_plan')
  467. # 如果找不到执行计划,则从数据库获取
  468. if not execution_plan:
  469. # 获取执行日期
  470. exec_date = get_latest_date()
  471. logger.info(f"未找到执行计划,从数据库获取。使用执行日期: {exec_date}")
  472. # 获取所有任务
  473. resource_tasks, model_tasks = get_all_tasks(exec_date)
  474. if not resource_tasks and not model_tasks:
  475. logger.warning(f"执行日期 {exec_date} 没有找到任务")
  476. return 0
  477. # 为所有模型表获取依赖关系
  478. model_table_names = [task["target_table"] for task in model_tasks]
  479. dependencies = get_table_dependencies_for_data_phase(model_table_names)
  480. # 创建执行计划
  481. new_execution_plan = {
  482. "exec_date": exec_date,
  483. "resource_tasks": resource_tasks,
  484. "model_tasks": model_tasks,
  485. "dependencies": dependencies
  486. }
  487. # 保存执行计划
  488. kwargs['ti'].xcom_push(key='execution_plan', value=json.dumps(new_execution_plan, default=json_serial))
  489. logger.info(f"创建新的执行计划,包含 {len(resource_tasks)} 个资源表任务和 {len(model_tasks)} 个模型表任务")
  490. return json.dumps(new_execution_plan, default=json_serial)
  491. logger.info(f"成功获取执行计划")
  492. return execution_plan
  493. except Exception as e:
  494. logger.error(f"创建执行计划时出错: {str(e)}")
  495. # 返回空执行计划
  496. empty_plan = {
  497. "exec_date": get_today_date(),
  498. "resource_tasks": [],
  499. "model_tasks": [],
  500. "dependencies": {}
  501. }
  502. return json.dumps(empty_plan, default=json_serial)
  503. def process_resource(target_table, script_name, script_exec_mode, exec_date):
  504. """处理单个资源表"""
  505. logger.info(f"执行资源表 {target_table} 的脚本 {script_name}")
  506. # 检查exec_date是否是JSON字符串
  507. if isinstance(exec_date, str) and exec_date.startswith('{'):
  508. try:
  509. # 尝试解析JSON字符串
  510. exec_date_data = json.loads(exec_date)
  511. exec_date = exec_date_data.get("exec_date")
  512. logger.info(f"从JSON中提取执行日期: {exec_date}")
  513. except Exception as e:
  514. logger.error(f"解析exec_date JSON时出错: {str(e)}")
  515. return execute_with_monitoring(
  516. target_table=target_table,
  517. script_name=script_name,
  518. script_exec_mode=script_exec_mode,
  519. exec_date=exec_date
  520. )
  521. def process_model(target_table, script_name, script_exec_mode, exec_date):
  522. """处理单个模型表"""
  523. logger.info(f"执行模型表 {target_table} 的脚本 {script_name}")
  524. # 检查exec_date是否是JSON字符串
  525. if isinstance(exec_date, str) and exec_date.startswith('{'):
  526. try:
  527. # 尝试解析JSON字符串
  528. exec_date_data = json.loads(exec_date)
  529. exec_date = exec_date_data.get("exec_date")
  530. logger.info(f"从JSON中提取执行日期: {exec_date}")
  531. except Exception as e:
  532. logger.error(f"解析exec_date JSON时出错: {str(e)}")
  533. return execute_with_monitoring(
  534. target_table=target_table,
  535. script_name=script_name,
  536. script_exec_mode=script_exec_mode,
  537. exec_date=exec_date
  538. )
  539. #############################################
  540. # 第三阶段: 汇总阶段(Summary Phase)的函数
  541. #############################################
  542. def get_execution_stats(exec_date):
  543. """获取当日执行统计信息"""
  544. conn = get_pg_conn()
  545. cursor = conn.cursor()
  546. try:
  547. # 查询总任务数
  548. cursor.execute("""
  549. SELECT COUNT(*) FROM airflow_dag_schedule WHERE exec_date = %s
  550. """, (exec_date,))
  551. result = cursor.fetchone()
  552. total_tasks = result[0] if result else 0
  553. # 查询每种类型的任务数
  554. cursor.execute("""
  555. SELECT target_table_label, COUNT(*)
  556. FROM airflow_dag_schedule
  557. WHERE exec_date = %s
  558. GROUP BY target_table_label
  559. """, (exec_date,))
  560. type_counts = {row[0]: row[1] for row in cursor.fetchall()}
  561. # 查询执行结果统计
  562. cursor.execute("""
  563. SELECT COUNT(*)
  564. FROM airflow_dag_schedule
  565. WHERE exec_date = %s AND exec_result IS TRUE
  566. """, (exec_date,))
  567. result = cursor.fetchone()
  568. success_count = result[0] if result else 0
  569. cursor.execute("""
  570. SELECT COUNT(*)
  571. FROM airflow_dag_schedule
  572. WHERE exec_date = %s AND exec_result IS FALSE
  573. """, (exec_date,))
  574. result = cursor.fetchone()
  575. fail_count = result[0] if result else 0
  576. cursor.execute("""
  577. SELECT COUNT(*)
  578. FROM airflow_dag_schedule
  579. WHERE exec_date = %s AND exec_result IS NULL
  580. """, (exec_date,))
  581. result = cursor.fetchone()
  582. pending_count = result[0] if result else 0
  583. # 计算执行时间统计
  584. cursor.execute("""
  585. SELECT AVG(exec_duration), MIN(exec_duration), MAX(exec_duration)
  586. FROM airflow_dag_schedule
  587. WHERE exec_date = %s AND exec_duration IS NOT NULL
  588. """, (exec_date,))
  589. time_stats = cursor.fetchone()
  590. # 确保时间统计不为None
  591. if time_stats and time_stats[0] is not None:
  592. avg_duration = float(time_stats[0])
  593. min_duration = float(time_stats[1]) if time_stats[1] is not None else None
  594. max_duration = float(time_stats[2]) if time_stats[2] is not None else None
  595. else:
  596. avg_duration = None
  597. min_duration = None
  598. max_duration = None
  599. # 查询失败任务详情
  600. cursor.execute("""
  601. SELECT target_table, script_name, target_table_label, exec_duration
  602. FROM airflow_dag_schedule
  603. WHERE exec_date = %s AND exec_result IS FALSE
  604. """, (exec_date,))
  605. failed_tasks = []
  606. for row in cursor.fetchall():
  607. task_dict = {
  608. "target_table": row[0],
  609. "script_name": row[1],
  610. "target_table_label": row[2],
  611. }
  612. if row[3] is not None:
  613. task_dict["exec_duration"] = float(row[3])
  614. else:
  615. task_dict["exec_duration"] = None
  616. failed_tasks.append(task_dict)
  617. # 计算成功率,避免除零错误
  618. success_rate = 0
  619. if total_tasks > 0:
  620. success_rate = (success_count / total_tasks) * 100
  621. # 汇总统计信息
  622. stats = {
  623. "exec_date": exec_date,
  624. "total_tasks": total_tasks,
  625. "type_counts": type_counts,
  626. "success_count": success_count,
  627. "fail_count": fail_count,
  628. "pending_count": pending_count,
  629. "success_rate": success_rate,
  630. "avg_duration": avg_duration,
  631. "min_duration": min_duration,
  632. "max_duration": max_duration,
  633. "failed_tasks": failed_tasks
  634. }
  635. return stats
  636. except Exception as e:
  637. logger.error(f"获取执行统计信息时出错: {str(e)}")
  638. return {}
  639. finally:
  640. cursor.close()
  641. conn.close()
  642. def update_missing_results(exec_date):
  643. """更新缺失的执行结果信息"""
  644. conn = get_pg_conn()
  645. cursor = conn.cursor()
  646. try:
  647. # 查询所有缺失执行结果的任务
  648. cursor.execute("""
  649. SELECT target_table, script_name
  650. FROM airflow_dag_schedule
  651. WHERE exec_date = %s AND exec_result IS NULL
  652. """, (exec_date,))
  653. missing_results = cursor.fetchall()
  654. update_count = 0
  655. for row in missing_results:
  656. target_table, script_name = row
  657. # 如果有开始时间但没有结束时间,假设执行失败
  658. cursor.execute("""
  659. SELECT exec_start_time
  660. FROM airflow_dag_schedule
  661. WHERE exec_date = %s AND target_table = %s AND script_name = %s
  662. """, (exec_date, target_table, script_name))
  663. start_time = cursor.fetchone()
  664. if start_time and start_time[0]:
  665. # 有开始时间但无结果,标记为失败
  666. now = datetime.now()
  667. duration = (now - start_time[0]).total_seconds()
  668. cursor.execute("""
  669. UPDATE airflow_dag_schedule
  670. SET exec_result = FALSE, exec_end_time = %s, exec_duration = %s
  671. WHERE exec_date = %s AND target_table = %s AND script_name = %s
  672. """, (now, duration, exec_date, target_table, script_name))
  673. logger.warning(f"任务 {target_table} 的脚本 {script_name} 标记为失败,开始时间: {start_time[0]}")
  674. update_count += 1
  675. else:
  676. # 没有开始时间且无结果,假设未执行
  677. logger.warning(f"任务 {target_table} 的脚本 {script_name} 未执行")
  678. conn.commit()
  679. logger.info(f"更新了 {update_count} 个缺失结果的任务")
  680. return update_count
  681. except Exception as e:
  682. logger.error(f"更新缺失执行结果时出错: {str(e)}")
  683. conn.rollback()
  684. return 0
  685. finally:
  686. cursor.close()
  687. conn.close()
  688. def generate_unified_execution_report(exec_date, stats):
  689. """生成统一执行报告"""
  690. # 构建报告
  691. report = []
  692. report.append(f"========== 统一数据运维系统执行报告 ==========")
  693. report.append(f"执行日期: {exec_date}")
  694. report.append(f"总任务数: {stats['total_tasks']}")
  695. # 任务类型分布
  696. report.append("\n--- 任务类型分布 ---")
  697. for label, count in stats.get('type_counts', {}).items():
  698. report.append(f"{label} 任务: {count} 个")
  699. # 执行结果统计
  700. report.append("\n--- 执行结果统计 ---")
  701. report.append(f"成功任务: {stats.get('success_count', 0)} 个")
  702. report.append(f"失败任务: {stats.get('fail_count', 0)} 个")
  703. report.append(f"未执行任务: {stats.get('pending_count', 0)} 个")
  704. report.append(f"成功率: {stats.get('success_rate', 0):.2f}%")
  705. # 执行时间统计
  706. report.append("\n--- 执行时间统计 (秒) ---")
  707. avg_duration = stats.get('avg_duration')
  708. min_duration = stats.get('min_duration')
  709. max_duration = stats.get('max_duration')
  710. report.append(f"平均执行时间: {avg_duration:.2f}" if avg_duration is not None else "平均执行时间: N/A")
  711. report.append(f"最短执行时间: {min_duration:.2f}" if min_duration is not None else "最短执行时间: N/A")
  712. report.append(f"最长执行时间: {max_duration:.2f}" if max_duration is not None else "最长执行时间: N/A")
  713. # 失败任务详情
  714. failed_tasks = stats.get('failed_tasks', [])
  715. if failed_tasks:
  716. report.append("\n--- 失败任务详情 ---")
  717. for i, task in enumerate(failed_tasks, 1):
  718. report.append(f"{i}. 表名: {task['target_table']}")
  719. report.append(f" 脚本: {task['script_name']}")
  720. report.append(f" 类型: {task['target_table_label']}")
  721. exec_duration = task.get('exec_duration')
  722. if exec_duration is not None:
  723. report.append(f" 执行时间: {exec_duration:.2f} 秒")
  724. else:
  725. report.append(" 执行时间: N/A")
  726. report.append("\n========== 报告结束 ==========")
  727. # 将报告转换为字符串
  728. report_str = "\n".join(report)
  729. # 记录到日志
  730. logger.info("\n" + report_str)
  731. return report_str
  732. def summarize_execution(**kwargs):
  733. """汇总执行情况的主函数"""
  734. try:
  735. exec_date = kwargs.get('ds') or get_today_date()
  736. logger.info(f"开始汇总执行日期 {exec_date} 的统一执行情况")
  737. # 1. 更新缺失的执行结果
  738. try:
  739. update_count = update_missing_results(exec_date)
  740. logger.info(f"更新了 {update_count} 个缺失的执行结果")
  741. except Exception as e:
  742. logger.error(f"更新缺失执行结果时出错: {str(e)}")
  743. update_count = 0
  744. # 2. 获取执行统计信息
  745. try:
  746. stats = get_execution_stats(exec_date)
  747. if not stats:
  748. logger.warning("未能获取执行统计信息,将使用默认值")
  749. stats = {
  750. "exec_date": exec_date,
  751. "total_tasks": 0,
  752. "type_counts": {},
  753. "success_count": 0,
  754. "fail_count": 0,
  755. "pending_count": 0,
  756. "success_rate": 0,
  757. "avg_duration": None,
  758. "min_duration": None,
  759. "max_duration": None,
  760. "failed_tasks": []
  761. }
  762. except Exception as e:
  763. logger.error(f"获取执行统计信息时出错: {str(e)}")
  764. stats = {
  765. "exec_date": exec_date,
  766. "total_tasks": 0,
  767. "type_counts": {},
  768. "success_count": 0,
  769. "fail_count": 0,
  770. "pending_count": 0,
  771. "success_rate": 0,
  772. "avg_duration": None,
  773. "min_duration": None,
  774. "max_duration": None,
  775. "failed_tasks": []
  776. }
  777. # 3. 生成执行报告
  778. try:
  779. report = generate_unified_execution_report(exec_date, stats)
  780. except Exception as e:
  781. logger.error(f"生成执行报告时出错: {str(e)}")
  782. report = f"生成执行报告时出错: {str(e)}\n基础统计: 总任务数: {stats.get('total_tasks', 0)}, 成功: {stats.get('success_count', 0)}, 失败: {stats.get('fail_count', 0)}"
  783. # 将报告和统计信息传递给下一个任务
  784. try:
  785. kwargs['ti'].xcom_push(key='execution_stats', value=json.dumps(stats, cls=DecimalEncoder))
  786. kwargs['ti'].xcom_push(key='execution_report', value=report)
  787. except Exception as e:
  788. logger.error(f"保存报告到XCom时出错: {str(e)}")
  789. return report
  790. except Exception as e:
  791. logger.error(f"汇总执行情况时出现未处理的错误: {str(e)}")
  792. # 返回一个简单的错误报告,确保任务不会失败
  793. return f"执行汇总时出现错误: {str(e)}"
  794. # 创建DAG
  795. with DAG(
  796. "dag_dataops_unified_scheduler",
  797. start_date=datetime(2024, 1, 1),
  798. schedule_interval="@daily",
  799. catchup=False,
  800. default_args={
  801. 'owner': 'airflow',
  802. 'depends_on_past': False,
  803. 'email_on_failure': False,
  804. 'email_on_retry': False,
  805. 'retries': 1,
  806. 'retry_delay': timedelta(minutes=5)
  807. }
  808. ) as dag:
  809. #############################################
  810. # 阶段1: 准备阶段(Prepare Phase)
  811. #############################################
  812. with TaskGroup("prepare_phase") as prepare_group:
  813. # 任务开始标记
  814. start_preparation = EmptyOperator(
  815. task_id="start_preparation"
  816. )
  817. # 准备调度任务
  818. prepare_task = PythonOperator(
  819. task_id="prepare_dag_schedule",
  820. python_callable=prepare_dag_schedule,
  821. provide_context=True
  822. )
  823. # 创建执行计划 - 从data_processing_phase移至这里
  824. create_plan = PythonOperator(
  825. task_id="create_execution_plan",
  826. python_callable=create_execution_plan,
  827. provide_context=True
  828. )
  829. # 准备完成标记
  830. preparation_completed = EmptyOperator(
  831. task_id="preparation_completed"
  832. )
  833. # 设置任务依赖 - 调整为包含create_plan
  834. start_preparation >> prepare_task >> create_plan >> preparation_completed
  835. #############################################
  836. # 阶段2: 数据处理阶段(Data Processing Phase)
  837. #############################################
  838. with TaskGroup("data_processing_phase") as data_group:
  839. # 过程完成标记
  840. processing_completed = EmptyOperator(
  841. task_id="processing_completed"
  842. )
  843. #############################################
  844. # 阶段3: 汇总阶段(Summary Phase)
  845. #############################################
  846. with TaskGroup("summary_phase") as summary_group:
  847. # 汇总执行情况
  848. summarize_task = PythonOperator(
  849. task_id="summarize_execution",
  850. python_callable=summarize_execution,
  851. provide_context=True
  852. )
  853. # 总结完成标记
  854. summary_completed = EmptyOperator(
  855. task_id="summary_completed"
  856. )
  857. # 设置任务依赖
  858. summarize_task >> summary_completed
  859. # 设置三个阶段之间的依赖关系 - 使用简单的TaskGroup依赖
  860. prepare_group >> data_group >> summary_group
  861. # 实际数据处理任务的动态创建逻辑
  862. # 这部分代码在DAG运行时执行,根据数据库数据和执行计划动态创建任务
  863. # 从执行计划JSON中获取信息
  864. execution_plan_json = '''{"exec_date": "2025-04-12", "resource_tasks": [], "model_tasks": [], "dependencies": {}}'''
  865. try:
  866. # 尝试从文件中读取最新的执行计划,仅用于构建DAG视图
  867. import os
  868. plan_path = os.path.join(os.path.dirname(__file__), 'last_execution_plan.json')
  869. if os.path.exists(plan_path):
  870. with open(plan_path, 'r') as f:
  871. execution_plan_json = f.read()
  872. except Exception as e:
  873. logger.warning(f"读取执行计划默认值时出错: {str(e)}")
  874. # 解析执行计划获取任务信息
  875. try:
  876. execution_plan = json.loads(execution_plan_json)
  877. exec_date = execution_plan.get("exec_date", get_today_date())
  878. resource_tasks = execution_plan.get("resource_tasks", [])
  879. model_tasks = execution_plan.get("model_tasks", [])
  880. dependencies = execution_plan.get("dependencies", {})
  881. # 任务字典,用于设置依赖关系
  882. task_dict = {}
  883. # 1. 创建资源表任务
  884. for task_info in resource_tasks:
  885. table_name = task_info["target_table"]
  886. script_name = task_info["script_name"]
  887. exec_mode = task_info.get("script_exec_mode", "append")
  888. # 创建安全的任务ID - 直接使用表名作为ID,更简洁易读
  889. safe_table_name = table_name.replace(".", "_").replace("-", "_")
  890. # 确保所有任务都是data_processing_phase的一部分
  891. with data_group:
  892. resource_task = PythonOperator(
  893. task_id=f"resource_{safe_table_name}", # 不需要加前缀,TaskGroup会自动添加
  894. python_callable=process_resource,
  895. op_kwargs={
  896. "target_table": table_name,
  897. "script_name": script_name,
  898. "script_exec_mode": exec_mode,
  899. "exec_date": """{{ ti.xcom_pull(task_ids='prepare_phase.create_execution_plan') }}"""
  900. },
  901. retries=TASK_RETRY_CONFIG["retries"],
  902. retry_delay=timedelta(minutes=TASK_RETRY_CONFIG["retry_delay_minutes"])
  903. )
  904. # 将任务添加到字典
  905. task_dict[table_name] = resource_task
  906. # 设置任务依赖 - 使用正确的引用方式
  907. preparation_completed >> resource_task
  908. # 创建有向图,用于检测模型表之间的依赖关系
  909. G = nx.DiGraph()
  910. # 将所有模型表添加为节点
  911. for task_info in model_tasks:
  912. table_name = task_info["target_table"]
  913. G.add_node(table_name)
  914. # 添加模型表之间的依赖边
  915. for source, deps in dependencies.items():
  916. for dep in deps:
  917. if dep.get("table_type") == "DataModel" and dep.get("table_name") in G.nodes():
  918. G.add_edge(dep.get("table_name"), source) # 依赖方向:依赖项 -> 目标
  919. # 检测循环依赖并处理
  920. cycles = list(nx.simple_cycles(G))
  921. if cycles:
  922. logger.warning(f"检测到循环依赖: {cycles}")
  923. for cycle in cycles:
  924. G.remove_edge(cycle[-1], cycle[0])
  925. logger.info(f"打破循环依赖: 移除 {cycle[-1]} -> {cycle[0]} 的依赖")
  926. # 生成拓扑排序,确定执行顺序
  927. try:
  928. execution_order = list(nx.topological_sort(G))
  929. logger.info(f"计算出的执行顺序: {execution_order}")
  930. except Exception as e:
  931. logger.error(f"生成拓扑排序失败: {str(e)}, 使用原始顺序")
  932. execution_order = [task_info["target_table"] for task_info in model_tasks]
  933. # 2. 按拓扑排序顺序创建模型表任务
  934. for table_name in execution_order:
  935. task_info = next((t for t in model_tasks if t["target_table"] == table_name), None)
  936. if not task_info:
  937. continue
  938. script_name = task_info["script_name"]
  939. exec_mode = task_info.get("script_exec_mode", "append")
  940. # 创建安全的任务ID
  941. safe_table_name = table_name.replace(".", "_").replace("-", "_")
  942. # 确保所有任务都是data_processing_phase的一部分
  943. with data_group:
  944. model_task = PythonOperator(
  945. task_id=f"model_{safe_table_name}", # 更简洁的ID
  946. python_callable=process_model,
  947. op_kwargs={
  948. "target_table": table_name,
  949. "script_name": script_name,
  950. "script_exec_mode": exec_mode,
  951. "exec_date": """{{ ti.xcom_pull(task_ids='prepare_phase.create_execution_plan') }}"""
  952. },
  953. retries=TASK_RETRY_CONFIG["retries"],
  954. retry_delay=timedelta(minutes=TASK_RETRY_CONFIG["retry_delay_minutes"])
  955. )
  956. # 将任务添加到字典
  957. task_dict[table_name] = model_task
  958. # 设置依赖关系
  959. deps = dependencies.get(table_name, [])
  960. has_dependency = False
  961. # 处理模型表之间的依赖
  962. for dep in deps:
  963. dep_table = dep.get("table_name")
  964. dep_type = dep.get("table_type")
  965. if dep_table in task_dict:
  966. task_dict[dep_table] >> model_task
  967. has_dependency = True
  968. logger.info(f"设置依赖: {dep_table} >> {table_name}")
  969. # 如果没有依赖,则依赖于资源表任务
  970. if not has_dependency:
  971. # 依赖于prepare_phase的完成
  972. preparation_completed >> model_task
  973. # 同时从所有资源表任务连接
  974. for resource_table in resource_tasks:
  975. resource_name = resource_table["target_table"]
  976. if resource_name in task_dict:
  977. task_dict[resource_name] >> model_task
  978. logger.info(f"设置资源依赖: {resource_name} >> {table_name}")
  979. # 如果没有模型表任务,将所有资源表任务视为终端任务
  980. if not model_tasks and resource_tasks:
  981. terminal_tasks = [task["target_table"] for task in resource_tasks]
  982. else:
  983. # 找出所有终端任务(没有下游依赖的任务)
  984. terminal_tasks = []
  985. # 检查所有模型表任务
  986. for table_name in execution_order:
  987. # 检查是否有下游任务
  988. has_downstream = False
  989. for source, deps in dependencies.items():
  990. if source == table_name: # 跳过自身
  991. continue
  992. for dep in deps:
  993. if dep.get("table_name") == table_name:
  994. has_downstream = True
  995. break
  996. if has_downstream:
  997. break
  998. # 如果没有下游任务,添加到终端任务列表
  999. if not has_downstream and table_name in task_dict:
  1000. terminal_tasks.append(table_name)
  1001. # 如果既没有模型表任务也没有资源表任务,已有默认依赖链
  1002. if not terminal_tasks:
  1003. logger.warning("未找到任何任务,使用默认依赖链")
  1004. else:
  1005. # 将所有终端任务连接到完成标记
  1006. for table_name in terminal_tasks:
  1007. if table_name in task_dict:
  1008. task_dict[table_name] >> processing_completed
  1009. logger.info(f"设置终端任务: {table_name} >> processing_completed")
  1010. except Exception as e:
  1011. logger.error(f"构建任务DAG时出错: {str(e)}")
  1012. import traceback
  1013. logger.error(traceback.format_exc())
  1014. # 确保即使出错,也有清晰的执行路径
  1015. # 已经有默认依赖链,不需要额外添加