entry.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. # -*- coding:utf-8 -*-
  2. """
  3. DataX 入口门面(对应 bin/datax-{hive-import,hdfs-export}-starter.{sh,py} 底层)。
  4. - DataxImport: 目标=Hive/HDFS,自动预建 Hive 分区;典型 jobs/raw/
  5. - DataxExport: 源=HDFS,导出到外部;典型 jobs/ads/,无分区预建
  6. 共同流程:expand ini → for each (串/并行) → runner.run_job。
  7. Import 在 for 之前额外调 partition.execute_ddls 预建 Hive 分区。
  8. 分布式 worker 选择当前仍保留(老参数平迁);若 kb/93 ADR-02 正式采纳,
  9. worker.select_worker 会降级为"永远返回 current_host",此处无需改。
  10. """
  11. import getpass
  12. import os
  13. import socket
  14. from datetime import datetime, timedelta
  15. from typing import List, Optional
  16. from dw_base.datax import batch, partition, path_utils, runner, worker
  17. def _is_release_user(release_user: str) -> bool:
  18. return getpass.getuser() == release_user
  19. def _is_in_release_dir(base_dir: str, release_root_dir: str, project_name: str) -> bool:
  20. expected = os.path.abspath(os.path.join(release_root_dir, project_name))
  21. return os.path.abspath(base_dir).startswith(expected)
  22. def _resolve_relative_to_base(path: str, base_dir: str) -> str:
  23. """ini / inis 相对路径按 base_dir 解析(不依赖 Python 进程 cwd)。绝对路径原样返回。"""
  24. if os.path.isabs(path):
  25. return path
  26. return os.path.join(base_dir, path)
  27. class _BaseDatax:
  28. """共享基类:加载 workers pool、解析环境、构造 run_one 闭包。"""
  29. def __init__(self,
  30. base_dir: str,
  31. workers_ini_path: str,
  32. release_user: str,
  33. release_root_dir: str,
  34. python3_path: str,
  35. datax_home: str,
  36. log_root_dir: str,
  37. log_module: str):
  38. self.base_dir = os.path.abspath(base_dir)
  39. self.pool = worker.load_workers_ini(workers_ini_path)
  40. self.release_user = release_user
  41. self.release_root_dir = release_root_dir
  42. self.python3_path = python3_path
  43. self.datax_home = datax_home
  44. self.log_root_dir = log_root_dir
  45. self.log_module = log_module
  46. self.project_name = os.path.basename(self.base_dir)
  47. self.current_host = socket.gethostname().split('.')[0]
  48. def _make_run_one(self,
  49. start_date: str,
  50. stop_date: str,
  51. host: Optional[str],
  52. use_random: bool,
  53. parallel: bool,
  54. skip_datax: bool,
  55. skip_check: bool):
  56. is_rel_user = _is_release_user(self.release_user)
  57. is_in_rel_dir = _is_in_release_dir(self.base_dir, self.release_root_dir, self.project_name)
  58. def _run_one(ini_path: str) -> int:
  59. w = worker.select_worker(
  60. self.pool,
  61. is_release_user=is_rel_user,
  62. is_in_release_dir=is_in_rel_dir,
  63. current_host=self.current_host,
  64. host=host,
  65. use_random=use_random,
  66. )
  67. job_name = path_utils.job_name_from_ini(ini_path)
  68. log_file = path_utils.log_path(self.log_root_dir, self.log_module, start_date, job_name)
  69. os.makedirs(os.path.dirname(log_file), exist_ok=True)
  70. print('[datax] ini={j} worker={w} log={lf}'.format(j=job_name, w=w, lf=log_file))
  71. # 并行:每任务独立 log 文件(输出不回父 stdout,对齐老 > LOG 2>&1 &)
  72. # 串行:tee 到独立 log 文件 + 父 stdout(对齐老 | tee LOG_FILE)
  73. if parallel:
  74. with open(log_file, 'a', encoding='utf-8') as fh:
  75. rc = runner.run_job(
  76. ini_path=ini_path, start_date=start_date, stop_date=stop_date,
  77. worker_host=w, current_host=self.current_host,
  78. base_dir=self.base_dir, python3_path=self.python3_path,
  79. datax_home=self.datax_home,
  80. skip_datax=skip_datax,
  81. skip_check=skip_check,
  82. stdout=fh, stderr=fh,
  83. )
  84. print('[datax] ini={j} done rc={rc}'.format(j=job_name, rc=rc))
  85. return rc
  86. with open(log_file, 'a', encoding='utf-8') as fh:
  87. rc = runner.run_job(
  88. ini_path=ini_path, start_date=start_date, stop_date=stop_date,
  89. worker_host=w, current_host=self.current_host,
  90. base_dir=self.base_dir, python3_path=self.python3_path,
  91. datax_home=self.datax_home,
  92. skip_datax=skip_datax,
  93. skip_check=skip_check,
  94. tee_to=fh,
  95. )
  96. print('[datax] ini={j} done rc={rc}'.format(j=job_name, rc=rc))
  97. return rc
  98. return _run_one
  99. class DataxImport(_BaseDatax):
  100. """目标=Hive 导入(自动预建分区)。"""
  101. def __init__(self, **kwargs):
  102. super().__init__(log_module='datax', **kwargs)
  103. def run(self,
  104. inis: List[str],
  105. inis_dirs: List[str],
  106. start_date: str,
  107. stop_date: str,
  108. host: Optional[str] = None,
  109. use_random: bool = False,
  110. parallel: bool = False,
  111. skip_partition: bool = False,
  112. skip_datax: bool = False,
  113. skip_check: bool = False,
  114. extra_partition_tables: Optional[List[str]] = None) -> int:
  115. """
  116. Returns: 失败任务数(0 = 全部成功)
  117. """
  118. resolved_inis = [_resolve_relative_to_base(p, self.base_dir) for p in inis]
  119. resolved_dirs = [_resolve_relative_to_base(p, self.base_dir) for p in inis_dirs]
  120. ini_list = batch.expand_ini_inputs(resolved_inis, resolved_dirs)
  121. if not ini_list:
  122. return 0
  123. if not skip_partition:
  124. ddls = []
  125. for ini in ini_list:
  126. ddl = partition.parse_ini_partition(ini, stop_date)
  127. if ddl:
  128. ddls.append(ddl)
  129. if extra_partition_tables:
  130. dt = partition.compute_partition_dt(stop_date)
  131. for tbl in extra_partition_tables:
  132. ddls.append('ALTER TABLE {tbl} ADD IF NOT EXISTS PARTITION(dt={dt});'.format(
  133. tbl=tbl, dt=dt))
  134. partition.execute_ddls(ddls)
  135. run_one = self._make_run_one(start_date, stop_date, host, use_random, parallel, skip_datax, skip_check)
  136. _success, failed = batch.run_batch(ini_list, run_one, parallel=parallel)
  137. return failed
  138. def backfill(self,
  139. inis: List[str],
  140. inis_dirs: List[str],
  141. start_date: str,
  142. stop_date: str,
  143. host: Optional[str] = None,
  144. use_random: bool = False,
  145. parallel: bool = False,
  146. skip_partition: bool = False,
  147. skip_datax: bool = False,
  148. skip_check: bool = False,
  149. extra_partition_tables: Optional[List[str]] = None) -> int:
  150. """
  151. 存量回填:start_date/stop_date 作外层范围 [含, 不含),按日循环调 self.run() 单日语义。
  152. 失败不中断,继续下一天;返回跨天失败任务总数(0 = 全部成功)。
  153. """
  154. day = datetime.strptime(start_date, '%Y%m%d').date()
  155. stop = datetime.strptime(stop_date, '%Y%m%d').date()
  156. if stop <= day:
  157. raise ValueError('backfill: stop_date 必须大于 start_date')
  158. total_days = (stop - day).days
  159. print('[backfill] 开始回填 {n} 天:{s} → {e}'.format(
  160. n=total_days, s=day.strftime('%Y%m%d'),
  161. e=(stop - timedelta(days=1)).strftime('%Y%m%d'),
  162. ))
  163. total_failed = 0
  164. failed_days = []
  165. while day < stop:
  166. day_plus_1 = day + timedelta(days=1)
  167. sd = day.strftime('%Y%m%d')
  168. ed = day_plus_1.strftime('%Y%m%d')
  169. print('[backfill] {d} 开始'.format(d=sd))
  170. failed = self.run(
  171. inis=inis, inis_dirs=inis_dirs,
  172. start_date=sd, stop_date=ed,
  173. host=host, use_random=use_random,
  174. parallel=parallel,
  175. skip_partition=skip_partition,
  176. skip_datax=skip_datax,
  177. skip_check=skip_check,
  178. extra_partition_tables=extra_partition_tables,
  179. )
  180. if failed > 0:
  181. total_failed += failed
  182. failed_days.append(sd)
  183. print('[backfill] {d} 失败任务 {f} 个'.format(d=sd, f=failed))
  184. day = day_plus_1
  185. print('[backfill] 完成:成功 {s} 天 / 失败 {f} 天 / 失败任务总 {t} 个'.format(
  186. s=total_days - len(failed_days), f=len(failed_days), t=total_failed))
  187. if failed_days:
  188. print('[backfill] 失败天列表:' + ','.join(failed_days))
  189. return total_failed
  190. class DataxExport(_BaseDatax):
  191. """源=HDFS 导出(无分区预建)。HDFS 源存在性 check 默认开启,missing/empty → 失败;-skip-check 关闭后走老 silent skip。"""
  192. def __init__(self, **kwargs):
  193. super().__init__(log_module='datax', **kwargs)
  194. def run(self,
  195. inis: List[str],
  196. inis_dirs: List[str],
  197. start_date: str,
  198. stop_date: str,
  199. host: Optional[str] = None,
  200. use_random: bool = False,
  201. parallel: bool = False,
  202. skip_datax: bool = False,
  203. skip_check: bool = False) -> int:
  204. """
  205. Returns: 失败任务数(0 = 全部成功)
  206. """
  207. resolved_inis = [_resolve_relative_to_base(p, self.base_dir) for p in inis]
  208. resolved_dirs = [_resolve_relative_to_base(p, self.base_dir) for p in inis_dirs]
  209. ini_list = batch.expand_ini_inputs(resolved_inis, resolved_dirs)
  210. if not ini_list:
  211. return 0
  212. run_one = self._make_run_one(start_date, stop_date, host, use_random, parallel, skip_datax, skip_check)
  213. _success, failed = batch.run_batch(ini_list, run_one, parallel=parallel)
  214. return failed