publish.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. r"""把 etl/to_wide.py 转出来的宽表那天目录推到算法服务器(rsync over SSH,或者 NFS 挂载点)。
  2. 配置在 config 的 [publish] 段(读法见 load()):
  3. rsync_target = deployor@10.10.20.31:/data/algo/wind104 # 走 ssh
  4. rsync_target = /mnt/algo/wind104 # 对端已经把目录 NFS 挂上了,直接本地 rsync
  5. rsync_target =(留空) # 不同步
  6. 规则:
  7. - **只增不删**:命令行里没有 --delete,远端已有的东西这个工具一律不碰;
  8. 同一天的文件重传靠 rsync 的 size+mtime 比对,没变就不搬;
  9. - **完成标记 .done 永远最后一步**(见 etl/sentinel.py):数据那趟 rsync 带 --exclude=.done,
  10. 传完再单独把本地 <当天目录>/.done 推上去。所以远端一旦出现 .done,就一定意味着
  11. 这一天全部落好了;算法团队只要轮询这个文件,不用猜目录里有几个 parquet。
  12. 为此有一个例外:正式传之前先精确删掉远端**当天目录里那一个** .done(只这一个文件名,
  13. 不碰任何别的文件、不碰任何目录),否则重传期间远端还挂着上一次的「已完成」;
  14. - 远端层级默认和本地一样带 年/月/日(remote_layout = keep),要平铺当天一层就 flat;
  15. - 目标没配就什么都不是(返回 0,转换照样算成功);配了 sync = on 但目标空,报错退出码 2,
  16. 免得你以为在同步其实一直没同步;
  17. - 每条命令失败重试 retries 次,间隔 retry_wait × 第几次;
  18. - **保留天数**(`remote_keep_days`,仓库里填 180,填 0 = 一个都不删):>0 就在每次推送成功后,
  19. 把目标上超过这个天数的整天目录删掉。**下限 180 天**(`MIN_KEEP_DAYS`,数据至少要能回溯半年):
  20. 填 90、30 这种小于 180 的值会被直接拒绝(退出码 2,一个目录都不删),要留更久就填更大的数。
  21. 只删目标根下、目录名严格是 年/月/日、且里面有 .done 完成标记的,一次最多
  22. remote_prune_max(默认 7)个;`remote_layout = flat` 下直接拒绝启用。本地 standard/ 一概不动。
  23. 除此之外(包括那一个 .done)这个工具永远只增不删;
  24. - 首次上线先跑 `python -m etl.publish --check`:它只建远端目录并试写一个探针文件,
  25. 确认 ssh 免密和目录权限通,再跑真正的转换。
  26. 用法:
  27. python -m etl.publish --date 20261019 # 单独补推某天
  28. python -m etl.publish --check # 只验连通和写权限
  29. python -m etl.publish --dry-run # 把要执行的命令打出来,什么都不跑
  30. """
  31. import argparse
  32. import configparser
  33. import datetime
  34. import os
  35. import re
  36. import shlex
  37. import subprocess
  38. import sys
  39. import time
  40. from etl import sentinel
  41. ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  42. DRIVE = re.compile(r'^[A-Za-z]$') # Windows 盘符,别把它当成 ssh 的 host
  43. def log(level, msg, *a):
  44. sys.stderr.write('%s %s %s\n' % (
  45. datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), level, msg % a if a else msg))
  46. class Target:
  47. """把 rsync_target 拆成(是不是远端、host、路径)。"""
  48. def __init__(self, spec):
  49. spec = (spec or '').strip().rstrip('/')
  50. if not spec:
  51. raise ValueError('rsync_target 是空的,没法同步')
  52. m = re.match(r'^(.+?):(/.+)$', spec)
  53. if m and not DRIVE.match(m.group(1)):
  54. self.remote, self.host, self.path = True, m.group(1), m.group(2)
  55. else:
  56. self.remote, self.host, self.path = False, '', spec.replace('\\', '/')
  57. if not self.remote and not os.path.isabs(self.path):
  58. raise ValueError('本地/NFS 目标要写绝对路径:%s' % spec)
  59. def __str__(self):
  60. return '%s:%s' % (self.host, self.path) if self.remote else self.path
  61. def load(path, section='publish'):
  62. cfg = configparser.ConfigParser(interpolation=None)
  63. if os.path.exists(path):
  64. cfg.read(path, encoding='utf-8')
  65. if not cfg.has_section(section):
  66. return {}
  67. return {k: v.strip() for k, v in cfg[section].items()}
  68. def dest_day(tgt, day, layout):
  69. """远端要落到哪个目录:keep = 和本地一样的 年/月/日,flat = 直接落 target 根。"""
  70. if layout == 'flat':
  71. return tgt.path
  72. return '%s/%04d/%02d/%02d' % (tgt.path, day.year, day.month, day.day)
  73. def ssh_opts(cfg):
  74. out = ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=%d' % int(cfg.get('connect_timeout', 15))]
  75. if cfg.get('ssh_key'):
  76. out += ['-i', os.path.abspath(cfg['ssh_key'])]
  77. port = (cfg.get('ssh_port') or '').strip()
  78. if port and port != '22':
  79. out += ['-p', port]
  80. return out
  81. def _run(cmd, env=None):
  82. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env,
  83. universal_newlines=True, encoding='utf-8', errors='replace')
  84. out = p.communicate()[0] or ''
  85. return p.returncode, out
  86. def execute(cmd, cfg, label, dry_run=False, lg=log):
  87. """跑一条命令,失败按 retries/retry_wait 重试。返回退出码(0 成功)。"""
  88. lg('INFO', '$ %s', ' '.join(shlex.quote(x) for x in cmd))
  89. if dry_run:
  90. return 0
  91. tries = max(1, int(cfg.get('retries', 3) or 3))
  92. wait = max(0, int(cfg.get('retry_wait', 20) or 0))
  93. code, out = 1, ''
  94. for i in range(1, tries + 1):
  95. code, out = _run(cmd)
  96. lines = [x for x in out.splitlines() if x.strip()]
  97. if code == 0:
  98. for line in lines:
  99. lg('INFO', ' %s | %s', label, line)
  100. return 0
  101. lg('WARN', '%s 第 %d/%d 次失败(退出码 %d):%s', label, i, tries, code,
  102. (lines or ['没有输出'])[-1])
  103. if i < tries and wait:
  104. time.sleep(wait * i)
  105. for line in lines[-10:]:
  106. lg('ERROR', ' %s | %s', label, line)
  107. return code or 1
  108. def rsync_cmd(src, dst, tgt, cfg, dry_run=False, exclude=()):
  109. cmd = ['rsync', '-a', '--partial', '--times', '--timeout=%d' %
  110. int(cfg.get('io_timeout', 120) or 120)]
  111. if dry_run:
  112. cmd.append('--dry-run')
  113. for name in exclude:
  114. cmd += ['--exclude=%s' % name]
  115. limit = (cfg.get('bandwidth_limit') or '').strip()
  116. if limit and limit not in ('0', ''):
  117. cmd.append('--bwlimit=%s' % limit) # KB/s:白天别让同步把采集的带宽抢走
  118. if tgt.remote:
  119. cmd += ['-e', ' '.join(['ssh'] + ssh_opts(cfg))] # 路径别带空格:rsync 是按空格拆 -e
  120. cmd += [src if src.endswith('/') else src + '/',
  121. ('%s:%s/' % (tgt.host, dst.rstrip('/'))) if tgt.remote else dst.rstrip('/') + '/']
  122. return cmd
  123. def drop_remote_sentinel(tgt, dst, cfg, dry_run=False, lg=log):
  124. """删掉远端当天目录里的那一个 .done —— 除了按保留天数清整天目录之外,唯一会删的文件。
  125. 不删的话:重传期间远端还挂着上一次的「已完成」,下游会读到半天的数据。
  126. """
  127. remote = '%s/%s' % (dst.rstrip('/'), sentinel.SENTINEL)
  128. lg('INFO', '先撤掉远端的完成标记:%s', remote)
  129. if dry_run:
  130. return 0
  131. if tgt.remote:
  132. return execute(['ssh'] + ssh_opts(cfg) +
  133. [tgt.host, 'rm -f %s' % shlex.quote(remote)],
  134. dict(cfg, retries=1), 'rm .done', False, lg)
  135. try:
  136. os.remove(remote)
  137. except OSError as e:
  138. if e.errno != 2:
  139. lg('ERROR', '撤远端 .done 失败:%s', e)
  140. return 1
  141. return 0
  142. def push_sentinel(tgt, src_dir, dst, cfg, dry_run=False, lg=log):
  143. """数据全落好之后,把本地 .done 单独推上去当最后一步。"""
  144. src_file = sentinel.path(src_dir)
  145. if not os.path.exists(src_file):
  146. lg('WARN', '本地没有 %s(to_wide 没写?),远端这次不会有完成标记,'
  147. '算法团队就看不到「今天到齐」', src_file)
  148. return 0
  149. remote = '%s/%s' % (dst.rstrip('/'), sentinel.SENTINEL)
  150. # 单文件对单文件:源和目标都不带结尾斜杠,跟上面目录那趟的写法不一样
  151. cmd = ['rsync', '-a', '--partial', '--times',
  152. '--timeout=%d' % int(cfg.get('io_timeout', 120) or 120)]
  153. if dry_run:
  154. cmd.append('--dry-run')
  155. if tgt.remote:
  156. cmd += ['-e', ' '.join(['ssh'] + ssh_opts(cfg)), src_file, '%s:%s' % (tgt.host, remote)]
  157. else:
  158. cmd += [src_file, remote]
  159. code = execute(cmd, cfg, 'rsync .done', dry_run, lg)
  160. if code == 0 and not dry_run:
  161. lg('INFO', '完成标记已推送,算法团队可以按 %s/%s 判断这一天到齐',
  162. tgt, dst.rstrip('/'))
  163. return code
  164. DAY_DIR = re.compile(r'^/(\d{4})/(\d{2})/(\d{2})/%s$' % re.escape(sentinel.SENTINEL))
  165. MIN_KEEP_DAYS = 180 # 数据在算法侧最少要能回溯 180 天,配置填小了一律拒绝清理
  166. def list_done_days(tgt, cfg, lg=log):
  167. """列出目标上「已经带完成标记」的那些天目录(绝对路径)。只读,dry-run 也照样列。
  168. 用哨兵当唯一入口:`.done` 在 = 这天是完整推上去的 = 有资格按保留天数清理;
  169. 没哨兵的目录(传一半失败的、别人放的)永远不动。
  170. """
  171. if tgt.remote:
  172. cmd = ['ssh'] + ssh_opts(cfg) + [
  173. tgt.host, 'find %s -mindepth 4 -maxdepth 4 -type f -name %s'
  174. % (shlex.quote(tgt.path), shlex.quote(sentinel.SENTINEL))]
  175. lg('INFO', '$ %s(只读,列出现有完成标记)', ' '.join(shlex.quote(x) for x in cmd))
  176. code, out = _run(cmd)
  177. if code:
  178. lg('WARN', '列不出目标上的完成标记(退出码 %d),本次不做保留清理', code)
  179. return []
  180. return [x.strip() for x in out.splitlines() if x.strip()]
  181. import glob
  182. return sorted(glob.glob(os.path.join(tgt.path.replace('\\', '/'), '*', '*', '*',
  183. sentinel.SENTINEL)))
  184. def old_day_dirs(tgt, sentinels, day, keep_days, lg=log):
  185. """从哨兵名单里挑出「比 day - keep_days 还早」的整天目录,最旧的排前面。
  186. 判断只看目录名(/<年>/<月>/<日>/.done),不看 mtime —— 补数、重传都会改 mtime,
  187. 按 mtime 清会把好端端的旧数据当新的留下、把刚补的当旧的删掉。
  188. """
  189. root = tgt.path.rstrip('/')
  190. cutoff = day - datetime.timedelta(days=keep_days)
  191. out = []
  192. for line in sentinels:
  193. p = line.replace('\\', '/')
  194. if not p.startswith(root + '/'):
  195. lg('WARN', '跳过不在目标根下的路径:%s', p)
  196. continue
  197. m = DAY_DIR.match(p[len(root):])
  198. if not m:
  199. continue
  200. try:
  201. d = datetime.date(*(int(x) for x in m.groups()))
  202. except ValueError: # /2026/13/99/.done 这种野目录
  203. continue
  204. if d < cutoff:
  205. day_dir = p[:len(root) + m.end() - len('/' + sentinel.SENTINEL)]
  206. out.append((d, day_dir))
  207. out.sort()
  208. return [p for _, p in out]
  209. def prune_old_days(tgt, cfg, day, dry_run=False, lg=log):
  210. """按 [publish] remote_keep_days 删目标上过期的整天目录。默认 0 = 什么都不删。
  211. 这是这个工具第二处会删的地方(第一处是当天目录里那一个 .done),所以护栏叠满:
  212. 只对 remote_keep_days>0 且 remote_layout=keep 生效;天数有硬下限 MIN_KEEP_DAYS(180),
  213. 填小了直接拒绝;只删目录名严格是 年/月/日、且里面有 .done 的;只删 target 根下面的;
  214. 一次最多删 remote_prune_max 个(默认 7),剩下的下次再删——万一配错或积压太多,
  215. 也不会一晚上传好的历史全没了。
  216. """
  217. keep = int(cfg.get('remote_keep_days') or 0)
  218. if keep <= 0:
  219. return 0
  220. if keep < MIN_KEEP_DAYS:
  221. lg('ERROR', 'remote_keep_days=%d 低于保留期下限 %d 天(约 6 个月),本次一个目录都不删:'
  222. '要清理就填 %d 或更大,想永远不删就填 0', keep, MIN_KEEP_DAYS, MIN_KEEP_DAYS)
  223. return 2
  224. if (cfg.get('remote_layout') or 'keep').lower() != 'keep':
  225. lg('ERROR', 'remote_keep_days=%d 只支持 remote_layout = keep(要按 年/月/日 认目录),'
  226. '现在是 %s,本次不清理', keep, cfg.get('remote_layout'))
  227. return 2
  228. if tgt.remote and not tgt.path.startswith('/'):
  229. lg('ERROR', '远端目标要绝对路径,不做清理:%s', tgt.path)
  230. return 2
  231. victims = old_day_dirs(tgt, list_done_days(tgt, cfg, lg), day, keep, lg)
  232. if not victims:
  233. lg('INFO', '保留 %d 天:目标上没有过期的整天目录', keep)
  234. return 0
  235. cap = max(1, int(cfg.get('remote_prune_max') or 7))
  236. if len(victims) > cap:
  237. lg('WARN', '过期的有 %d 天,本次只删最旧的 %d 个(remote_prune_max),其余下次再删',
  238. len(victims), cap)
  239. for p in victims[:cap]:
  240. if dry_run:
  241. lg('INFO', 'dry-run:会删 %s 上的 %s', tgt, p)
  242. continue
  243. if tgt.remote:
  244. code = execute(['ssh'] + ssh_opts(cfg) + [tgt.host, 'rm -rf -- %s'
  245. % shlex.quote(p)],
  246. dict(cfg, retries=1), 'prune', False, lg)
  247. else:
  248. real = os.path.realpath(p)
  249. if not real.startswith(os.path.realpath(tgt.path) + os.sep):
  250. lg('ERROR', '路径不在目标根下,跳过:%s', p)
  251. continue
  252. try:
  253. import shutil
  254. shutil.rmtree(real)
  255. code = 0
  256. lg('INFO', '已删 %s', real)
  257. except OSError as e:
  258. lg('ERROR', '删 %s 失败:%s', real, e)
  259. code = 1
  260. if code:
  261. lg('ERROR', '清理在 %s 这里失败了,后面的都不再删(别连着试第二次,先看是不是挂错目录了)', p)
  262. return code
  263. return 0
  264. def ancestors(path):
  265. """从这一级往上到根:/data/algo/wind104 -> ['/data/algo/wind104', '/data/algo', '/data', '/']。
  266. 只给只读诊断用:mkdir -p 失败时到底哪一级不存在、哪一级不归 ssh 用户,看一眼就知道。
  267. """
  268. out, p = [], os.path.dirname(path.rstrip('/')) or '/'
  269. while p != '/':
  270. out.append(p)
  271. p = os.path.dirname(p)
  272. out.append('/')
  273. return [path] + out
  274. def ensure_remote_dir(tgt, dst, cfg, dry_run=False, lg=log):
  275. """rsync 只会建最后一级目录,年/月/日 这种要先 mkdir -p。"""
  276. if not tgt.remote:
  277. return 0
  278. code = execute(['ssh'] + ssh_opts(cfg) + [tgt.host, 'mkdir -p %s' % shlex.quote(dst)],
  279. cfg, 'mkdir', dry_run, lg)
  280. if code and not dry_run:
  281. # mkdir -p 报「权限不够」时报的是它建不动的那一级根目录,八成是两件事之一:
  282. # 根目录不存在而 /data 不归这个 ssh 用户,或者你 ls 的那台机器和 ssh 落到的不是同一台。
  283. # 直接在远端把它自己的视角打出来,别让人对着本地目录猜。全是只读命令。
  284. probe = 'hostname; id; ls -ldZ %s 2>&1; df -hT / 2>&1 | tail -2' % \
  285. ' '.join(shlex.quote(p) for p in ancestors(tgt.path))
  286. execute(['ssh'] + ssh_opts(cfg) + [tgt.host, probe], dict(cfg, retries=1),
  287. '诊断', False, lg)
  288. user = tgt.host.partition('@')[0] or '这个 ssh 登录用户'
  289. lg('ERROR', '上面是 %s 自己的视角。要推的根 %s 必须存在且 %s 能写:'
  290. '在算法服务器上让 root 执行 mkdir -p %s && chown %s %s,'
  291. '或者把 [publish] rsync_target 换成 %s 已经能写的路径;'
  292. '修好后单独补推 python -X utf8 -m etl.publish --date <那一天>(宽表还在本地)',
  293. tgt.host, tgt.path, user, tgt.path, user, tgt.path, user)
  294. return code
  295. def run(publish_cfg, src_dir, day, dry_run=False, check=False, lg=log):
  296. """把 src_dir(某天的宽表目录)推到 [publish] 配的目标。返回退出码。"""
  297. cfg = {k: v.strip() for k, v in (publish_cfg or {}).items()}
  298. mode = (cfg.get('sync') or 'auto').lower()
  299. spec = cfg.get('rsync_target', '')
  300. disabled = mode in ('off', '0', 'no', 'false')
  301. if disabled and not check:
  302. lg('INFO', '[publish] sync = %s,不同步', mode)
  303. return 0
  304. if not spec:
  305. if mode in ('on', '1', 'yes', 'true') or check:
  306. lg('ERROR', '要同步但 config 的 [publish] rsync_target 是空的:'
  307. '填 user@host:/绝对路径(或者 NFS 挂载点路径)')
  308. return 2
  309. lg('INFO', '[publish] rsync_target 没配,跳过同步(宽表只在本地)')
  310. return 0
  311. try:
  312. tgt = Target(spec)
  313. except ValueError as e:
  314. lg('ERROR', 'rsync_target 写法不对:%s', e)
  315. return 2
  316. if not os.path.isdir(src_dir):
  317. lg('ERROR', '要推的目录不存在:%s', src_dir)
  318. return 2
  319. dst = dest_day(tgt, day, (cfg.get('remote_layout') or 'keep').lower())
  320. # tgt 自己就带根路径,dst 是完整的远端路径,两个一起打会把根写两遍
  321. dst_disp = '%s:%s' % (tgt.host, dst) if tgt.remote else dst
  322. lg('INFO', '同步 %s -> %s(%s)', src_dir, dst_disp,
  323. 'ssh/rsync' if tgt.remote else '本地路径(NFS 挂载点)')
  324. if check:
  325. probe = '%s/.wind104_write_ok' % dst
  326. code = ensure_remote_dir(tgt, dst, cfg, dry_run, lg)
  327. if code:
  328. lg('ERROR', '建远端目录失败,先确认 ssh 免密:ssh %s', tgt.host)
  329. return code
  330. if dry_run:
  331. lg('INFO', 'dry-run:本该在 %s 建一个探针文件 %s 再删掉', dst_disp,
  332. os.path.basename(probe))
  333. return 0
  334. if tgt.remote:
  335. code, _ = _run(['ssh'] + ssh_opts(cfg) +
  336. [tgt.host, 'touch %s && rm -f %s && echo OK' %
  337. (shlex.quote(probe), shlex.quote(probe))])
  338. else:
  339. try:
  340. open(probe, 'w').close()
  341. os.remove(probe)
  342. code = 0
  343. except OSError as e:
  344. lg('ERROR', '目标目录写不进去:%s', e)
  345. code = 1
  346. if code:
  347. lg('ERROR', '目标能连但写不进去(检查属主/权限):%s/%s', tgt, dst)
  348. return code or 1
  349. if not dry_run:
  350. lg('INFO', '连通和写权限都正常')
  351. return 0
  352. rc = ensure_remote_dir(tgt, dst, cfg, dry_run, lg)
  353. if rc:
  354. return rc
  355. # 顺序很重要:先撤远端的完成标记 -> 搬数据(这趟永远不带 .done)-> 最后补上完成标记。
  356. # 这样下游看到 .done 的时候,当天的文件一定已经全在里面了。
  357. rc = drop_remote_sentinel(tgt, dst, cfg, dry_run, lg)
  358. if rc:
  359. lg('ERROR', '远端旧的完成标记没撤掉,先别传(撤不掉就会一直骗下游):%s', dst)
  360. return rc
  361. rc = execute(rsync_cmd(src_dir, dst, tgt, cfg, dry_run, exclude=[sentinel.SENTINEL]),
  362. cfg, 'rsync', dry_run, lg)
  363. if rc:
  364. return rc
  365. rc = push_sentinel(tgt, src_dir, dst, cfg, dry_run, lg)
  366. if rc:
  367. return rc
  368. # 保留期清理放在最后:今天的数据已经全落好、完成标记也已经推上去了,才动旧日子
  369. return prune_old_days(tgt, cfg, day, dry_run, lg)
  370. def main(argv=None):
  371. ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
  372. ap.add_argument('--date', help='哪天 YYYYMMDD,默认昨天')
  373. ap.add_argument('--config', default=os.path.join(ROOT, 'config', 'config.linux.ini'))
  374. ap.add_argument('--src', help='要推的目录,默认 output_dir/wide_subdir/年/月/日')
  375. ap.add_argument('--check', action='store_true', help='只验连通和写权限,不传数据')
  376. ap.add_argument('--dry-run', action='store_true', help='把命令打出来,什么都不跑')
  377. a = ap.parse_args(argv)
  378. day = (datetime.datetime.strptime(a.date, '%Y%m%d').date() if a.date
  379. else datetime.date.today() - datetime.timedelta(days=1))
  380. cfg = configparser.ConfigParser(interpolation=None)
  381. if os.path.exists(a.config):
  382. cfg.read(a.config, encoding='utf-8')
  383. c = cfg['collect'] if cfg.has_section('collect') else {}
  384. base = os.path.dirname(os.path.abspath(a.config))
  385. src = a.src or os.path.join(os.path.abspath(os.path.join(base, c.get('output_dir', '../data'))),
  386. (c.get('wide_subdir') or 'standard').strip(),
  387. '%04d' % day.year, '%02d' % day.month, '%02d' % day.day)
  388. return run(load(a.config), src, day, dry_run=a.dry_run, check=a.check)
  389. if __name__ == '__main__':
  390. sys.exit(main())