dag_dataops_pipeline_data_scheduler.py 67 KB

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