dag_dataops_prepare_scheduler.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. # dag_dataops_prepare_scheduler.py
  2. from airflow import DAG
  3. from airflow.operators.python import PythonOperator
  4. from airflow.operators.empty import EmptyOperator
  5. from datetime import datetime, timedelta
  6. import pendulum
  7. import logging
  8. from common import get_pg_conn, get_neo4j_driver, get_today_date
  9. from config import PG_CONFIG, NEO4J_CONFIG
  10. import networkx as nx
  11. # 创建日志记录器
  12. logger = logging.getLogger(__name__)
  13. def get_enabled_tables():
  14. """获取所有启用的表"""
  15. conn = get_pg_conn()
  16. cursor = conn.cursor()
  17. try:
  18. cursor.execute("""
  19. SELECT owner_id, table_name
  20. FROM schedule_status
  21. WHERE schedule_is_enabled = TRUE
  22. """)
  23. result = cursor.fetchall()
  24. return [row[1] for row in result] # 只返回表名
  25. except Exception as e:
  26. logger.error(f"获取启用表失败: {str(e)}")
  27. return []
  28. finally:
  29. cursor.close()
  30. conn.close()
  31. def check_table_directly_subscribed(table_name):
  32. """检查表是否在schedule_status表中直接订阅"""
  33. conn = get_pg_conn()
  34. cursor = conn.cursor()
  35. try:
  36. cursor.execute("""
  37. SELECT schedule_is_enabled
  38. FROM schedule_status
  39. WHERE table_name = %s
  40. """, (table_name,))
  41. result = cursor.fetchone()
  42. return result and result[0] is True
  43. except Exception as e:
  44. logger.error(f"检查表订阅状态失败: {str(e)}")
  45. return False
  46. finally:
  47. cursor.close()
  48. conn.close()
  49. def get_table_info_from_neo4j(table_name):
  50. """从Neo4j获取表的详细信息"""
  51. driver = get_neo4j_driver()
  52. # 检查表是否直接订阅
  53. is_directly_schedule = check_table_directly_subscribed(table_name)
  54. table_info = {
  55. 'target_table': table_name,
  56. 'is_directly_schedule': is_directly_schedule, # 初始值设为True,从schedule_status表获取
  57. }
  58. try:
  59. with driver.session() as session:
  60. # 查询表标签和状态
  61. query_table = """
  62. MATCH (t {en_name: $table_name})
  63. RETURN labels(t) AS labels, t.status AS status, t.frequency AS frequency
  64. """
  65. result = session.run(query_table, table_name=table_name)
  66. record = result.single()
  67. if record:
  68. labels = record.get("labels", [])
  69. table_info['target_table_label'] = [label for label in labels if label in ["DataResource", "DataModel", "DataSource"]][0] if labels else None
  70. table_info['target_table_status'] = record.get("status", True) # 默认为True
  71. table_info['default_update_frequency'] = record.get("frequency")
  72. # 根据标签类型查询关系和脚本信息
  73. if "DataResource" in labels:
  74. query_rel = """
  75. MATCH (target {en_name: $table_name})-[rel:ORIGINATES_FROM]->(source)
  76. RETURN source.en_name AS source_table, rel.script_name AS script_name,
  77. rel.script_type AS script_type, rel.script_exec_mode AS script_exec_mode
  78. """
  79. elif "DataModel" in labels:
  80. query_rel = """
  81. MATCH (target {en_name: $table_name})-[rel:DERIVED_FROM]->(source)
  82. RETURN source.en_name AS source_table, rel.script_name AS script_name,
  83. rel.script_type AS script_type, rel.script_exec_mode AS script_exec_mode
  84. """
  85. else:
  86. logger.warning(f"表 {table_name} 不是DataResource或DataModel类型")
  87. return table_info
  88. result = session.run(query_rel, table_name=table_name)
  89. record = result.single()
  90. if record:
  91. table_info['source_table'] = record.get("source_table")
  92. # 检查script_name是否为空
  93. script_name = record.get("script_name")
  94. if not script_name:
  95. logger.warning(f"表 {table_name} 的关系中没有script_name属性,可能导致后续处理出错")
  96. table_info['script_name'] = script_name
  97. # 设置默认值,确保即使属性为空也有默认值
  98. table_info['script_type'] = record.get("script_type", "python") # 默认为python
  99. table_info['script_exec_mode'] = record.get("script_exec_mode", "append") # 默认为append
  100. else:
  101. logger.warning(f"未找到表 {table_name} 的关系信息")
  102. else:
  103. logger.warning(f"在Neo4j中找不到表 {table_name} 的信息")
  104. except Exception as e:
  105. logger.error(f"获取表 {table_name} 的信息时出错: {str(e)}")
  106. finally:
  107. driver.close()
  108. return table_info
  109. def process_dependencies(tables_info):
  110. """处理表间依赖关系,添加被动调度的表"""
  111. # 存储所有表信息的字典
  112. all_tables = {t['target_table']: t for t in tables_info}
  113. driver = get_neo4j_driver()
  114. try:
  115. with driver.session() as session:
  116. for table_name, table_info in list(all_tables.items()):
  117. if table_info.get('target_table_label') == 'DataModel':
  118. # 查询其依赖表
  119. query = """
  120. MATCH (dm {en_name: $table_name})-[:DERIVED_FROM]->(dep)
  121. RETURN dep.en_name AS dep_name, labels(dep) AS dep_labels,
  122. dep.status AS dep_status, dep.frequency AS dep_frequency
  123. """
  124. result = session.run(query, table_name=table_name)
  125. for record in result:
  126. dep_name = record.get("dep_name")
  127. dep_labels = record.get("dep_labels", [])
  128. dep_status = record.get("dep_status", True)
  129. dep_frequency = record.get("dep_frequency")
  130. # 处理未被直接调度的依赖表
  131. if dep_name and dep_name not in all_tables:
  132. logger.info(f"发现被动依赖表: {dep_name}, 标签: {dep_labels}")
  133. # 获取依赖表详细信息
  134. dep_info = get_table_info_from_neo4j(dep_name)
  135. dep_info['is_directly_schedule'] = False
  136. # 处理调度频率继承
  137. if not dep_info.get('default_update_frequency'):
  138. dep_info['default_update_frequency'] = table_info.get('default_update_frequency')
  139. all_tables[dep_name] = dep_info
  140. except Exception as e:
  141. logger.error(f"处理依赖关系时出错: {str(e)}")
  142. finally:
  143. driver.close()
  144. return list(all_tables.values())
  145. def filter_invalid_tables(tables_info):
  146. """过滤无效表及其依赖,使用NetworkX构建依赖图"""
  147. # 构建表名到索引的映射
  148. table_dict = {t['target_table']: i for i, t in enumerate(tables_info)}
  149. # 找出无效表
  150. invalid_tables = set()
  151. for table in tables_info:
  152. if table.get('target_table_status') is False:
  153. invalid_tables.add(table['target_table'])
  154. logger.info(f"表 {table['target_table']} 的状态为无效")
  155. # 构建依赖图
  156. G = nx.DiGraph()
  157. # 添加所有节点
  158. for table in tables_info:
  159. G.add_node(table['target_table'])
  160. # 查询并添加依赖边
  161. driver = get_neo4j_driver()
  162. try:
  163. with driver.session() as session:
  164. for table in tables_info:
  165. if table.get('target_table_label') == 'DataModel':
  166. query = """
  167. MATCH (source {en_name: $table_name})-[:DERIVED_FROM]->(target)
  168. RETURN target.en_name AS target_name
  169. """
  170. result = session.run(query, table_name=table['target_table'])
  171. for record in result:
  172. target_name = record.get("target_name")
  173. if target_name and target_name in table_dict:
  174. # 添加从目标到源的边,表示目标依赖于源
  175. G.add_edge(table['target_table'], target_name)
  176. logger.debug(f"添加依赖边: {table['target_table']} -> {target_name}")
  177. except Exception as e:
  178. logger.error(f"构建依赖图时出错: {str(e)}")
  179. finally:
  180. driver.close()
  181. # 找出依赖于无效表的所有表
  182. downstream_invalid = set()
  183. for invalid_table in invalid_tables:
  184. # 获取可从无效表到达的所有节点
  185. try:
  186. descendants = nx.descendants(G, invalid_table)
  187. downstream_invalid.update(descendants)
  188. logger.info(f"表 {invalid_table} 的下游无效表: {descendants}")
  189. except Exception as e:
  190. logger.error(f"处理表 {invalid_table} 的下游依赖时出错: {str(e)}")
  191. # 合并所有无效表
  192. all_invalid = invalid_tables.union(downstream_invalid)
  193. logger.info(f"总共 {len(all_invalid)} 个表被标记为无效: {all_invalid}")
  194. # 过滤出有效表
  195. valid_tables = [t for t in tables_info if t['target_table'] not in all_invalid]
  196. logger.info(f"过滤后保留 {len(valid_tables)} 个有效表")
  197. return valid_tables
  198. def write_to_airflow_dag_schedule(exec_date, tables_info):
  199. """将表信息写入airflow_dag_schedule表"""
  200. conn = get_pg_conn()
  201. cursor = conn.cursor()
  202. try:
  203. # 清理当日数据,避免重复
  204. cursor.execute("""
  205. DELETE FROM airflow_dag_schedule WHERE exec_date = %s
  206. """, (exec_date,))
  207. logger.info(f"已清理执行日期 {exec_date} 的现有数据")
  208. # 批量插入新数据
  209. inserted_count = 0
  210. for table in tables_info:
  211. cursor.execute("""
  212. INSERT INTO airflow_dag_schedule (
  213. exec_date, source_table, target_table, target_table_label,
  214. target_table_status, is_directly_schedule, default_update_frequency,
  215. script_name, script_type, script_exec_mode
  216. ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
  217. """, (
  218. exec_date,
  219. table.get('source_table'),
  220. table['target_table'],
  221. table.get('target_table_label'),
  222. table.get('target_table_status', True),
  223. table.get('is_directly_schedule', False),
  224. table.get('default_update_frequency'),
  225. table.get('script_name'),
  226. table.get('script_type', 'python'),
  227. table.get('script_exec_mode', 'append')
  228. ))
  229. inserted_count += 1
  230. conn.commit()
  231. logger.info(f"成功插入 {inserted_count} 条记录到 airflow_dag_schedule 表")
  232. return inserted_count
  233. except Exception as e:
  234. logger.error(f"写入 airflow_dag_schedule 表时出错: {str(e)}")
  235. conn.rollback()
  236. # 不要返回0,而是重新抛出异常,确保错误被正确传播
  237. raise
  238. finally:
  239. cursor.close()
  240. conn.close()
  241. def prepare_dag_schedule(**kwargs):
  242. """准备DAG调度任务的主函数"""
  243. exec_date = kwargs.get('ds') or get_today_date()
  244. logger.info(f"开始准备执行日期 {exec_date} 的调度任务")
  245. # 1. 获取启用的表
  246. enabled_tables = get_enabled_tables()
  247. logger.info(f"从schedule_status表获取到 {len(enabled_tables)} 个启用的表")
  248. if not enabled_tables:
  249. logger.warning("没有找到启用的表,准备工作结束")
  250. return 0
  251. # 2. 获取表的详细信息
  252. tables_info = []
  253. for table_name in enabled_tables:
  254. table_info = get_table_info_from_neo4j(table_name)
  255. if table_info:
  256. tables_info.append(table_info)
  257. logger.info(f"成功获取 {len(tables_info)} 个表的详细信息")
  258. # 3. 处理依赖关系,添加被动调度的表
  259. enriched_tables = process_dependencies(tables_info)
  260. logger.info(f"处理依赖后,总共有 {len(enriched_tables)} 个表")
  261. # 4. 过滤无效表及其依赖
  262. valid_tables = filter_invalid_tables(enriched_tables)
  263. logger.info(f"过滤无效表后,最终有 {len(valid_tables)} 个有效表")
  264. # 5. 写入airflow_dag_schedule表
  265. inserted_count = write_to_airflow_dag_schedule(exec_date, valid_tables)
  266. # 6. 检查插入操作是否成功,如果失败则抛出异常
  267. if inserted_count == 0 and valid_tables:
  268. error_msg = f"插入操作失败,无记录被插入到airflow_dag_schedule表,但有{len(valid_tables)}个有效表需要处理"
  269. logger.error(error_msg)
  270. raise Exception(error_msg)
  271. return inserted_count
  272. # 创建DAG
  273. with DAG(
  274. "dag_dataops_prepare_scheduler",
  275. start_date=datetime(2024, 1, 1),
  276. schedule_interval="@daily",
  277. catchup=False,
  278. default_args={
  279. 'owner': 'airflow',
  280. 'depends_on_past': False,
  281. 'email_on_failure': False,
  282. 'email_on_retry': False,
  283. 'retries': 1,
  284. 'retry_delay': timedelta(minutes=5)
  285. }
  286. ) as dag:
  287. # 任务开始标记
  288. start_preparation = EmptyOperator(
  289. task_id="start_preparation",
  290. dag=dag
  291. )
  292. # 准备调度任务
  293. prepare_task = PythonOperator(
  294. task_id="prepare_dag_schedule",
  295. python_callable=prepare_dag_schedule,
  296. provide_context=True,
  297. dag=dag
  298. )
  299. # 准备完成标记
  300. preparation_completed = EmptyOperator(
  301. task_id="preparation_completed",
  302. dag=dag
  303. )
  304. # 设置任务依赖
  305. start_preparation >> prepare_task >> preparation_completed