| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443 |
- r"""把 etl/to_wide.py 转出来的宽表那天目录推到算法服务器(rsync over SSH,或者 NFS 挂载点)。
- 配置在 config 的 [publish] 段(读法见 load()):
- rsync_target = deployor@10.10.20.31:/data/algo/wind104 # 走 ssh
- rsync_target = /mnt/algo/wind104 # 对端已经把目录 NFS 挂上了,直接本地 rsync
- rsync_target =(留空) # 不同步
- 规则:
- - **只增不删**:命令行里没有 --delete,远端已有的东西这个工具一律不碰;
- 同一天的文件重传靠 rsync 的 size+mtime 比对,没变就不搬;
- - **完成标记 .done 永远最后一步**(见 etl/sentinel.py):数据那趟 rsync 带 --exclude=.done,
- 传完再单独把本地 <当天目录>/.done 推上去。所以远端一旦出现 .done,就一定意味着
- 这一天全部落好了;算法团队只要轮询这个文件,不用猜目录里有几个 parquet。
- 为此有一个例外:正式传之前先精确删掉远端**当天目录里那一个** .done(只这一个文件名,
- 不碰任何别的文件、不碰任何目录),否则重传期间远端还挂着上一次的「已完成」;
- - 远端层级默认和本地一样带 年/月/日(remote_layout = keep),要平铺当天一层就 flat;
- - 目标没配就什么都不是(返回 0,转换照样算成功);配了 sync = on 但目标空,报错退出码 2,
- 免得你以为在同步其实一直没同步;
- - 每条命令失败重试 retries 次,间隔 retry_wait × 第几次;
- - **保留天数**(`remote_keep_days`,仓库里填 180,填 0 = 一个都不删):>0 就在每次推送成功后,
- 把目标上超过这个天数的整天目录删掉。**下限 180 天**(`MIN_KEEP_DAYS`,数据至少要能回溯半年):
- 填 90、30 这种小于 180 的值会被直接拒绝(退出码 2,一个目录都不删),要留更久就填更大的数。
- 只删目标根下、目录名严格是 年/月/日、且里面有 .done 完成标记的,一次最多
- remote_prune_max(默认 7)个;`remote_layout = flat` 下直接拒绝启用。本地 standard/ 一概不动。
- 除此之外(包括那一个 .done)这个工具永远只增不删;
- - 首次上线先跑 `python -m etl.publish --check`:它只建远端目录并试写一个探针文件,
- 确认 ssh 免密和目录权限通,再跑真正的转换。
- 用法:
- python -m etl.publish --date 20261019 # 单独补推某天
- python -m etl.publish --check # 只验连通和写权限
- python -m etl.publish --dry-run # 把要执行的命令打出来,什么都不跑
- """
- import argparse
- import configparser
- import datetime
- import os
- import re
- import shlex
- import subprocess
- import sys
- import time
- from etl import sentinel
- ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- DRIVE = re.compile(r'^[A-Za-z]$') # Windows 盘符,别把它当成 ssh 的 host
- def log(level, msg, *a):
- sys.stderr.write('%s %s %s\n' % (
- datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), level, msg % a if a else msg))
- class Target:
- """把 rsync_target 拆成(是不是远端、host、路径)。"""
- def __init__(self, spec):
- spec = (spec or '').strip().rstrip('/')
- if not spec:
- raise ValueError('rsync_target 是空的,没法同步')
- m = re.match(r'^(.+?):(/.+)$', spec)
- if m and not DRIVE.match(m.group(1)):
- self.remote, self.host, self.path = True, m.group(1), m.group(2)
- else:
- self.remote, self.host, self.path = False, '', spec.replace('\\', '/')
- if not self.remote and not os.path.isabs(self.path):
- raise ValueError('本地/NFS 目标要写绝对路径:%s' % spec)
- def __str__(self):
- return '%s:%s' % (self.host, self.path) if self.remote else self.path
- def load(path, section='publish'):
- cfg = configparser.ConfigParser(interpolation=None)
- if os.path.exists(path):
- cfg.read(path, encoding='utf-8')
- if not cfg.has_section(section):
- return {}
- return {k: v.strip() for k, v in cfg[section].items()}
- def dest_day(tgt, day, layout):
- """远端要落到哪个目录:keep = 和本地一样的 年/月/日,flat = 直接落 target 根。"""
- if layout == 'flat':
- return tgt.path
- return '%s/%04d/%02d/%02d' % (tgt.path, day.year, day.month, day.day)
- def ssh_opts(cfg):
- out = ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=%d' % int(cfg.get('connect_timeout', 15))]
- if cfg.get('ssh_key'):
- out += ['-i', os.path.abspath(cfg['ssh_key'])]
- port = (cfg.get('ssh_port') or '').strip()
- if port and port != '22':
- out += ['-p', port]
- return out
- def _run(cmd, env=None):
- p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env,
- universal_newlines=True, encoding='utf-8', errors='replace')
- out = p.communicate()[0] or ''
- return p.returncode, out
- def execute(cmd, cfg, label, dry_run=False, lg=log):
- """跑一条命令,失败按 retries/retry_wait 重试。返回退出码(0 成功)。"""
- lg('INFO', '$ %s', ' '.join(shlex.quote(x) for x in cmd))
- if dry_run:
- return 0
- tries = max(1, int(cfg.get('retries', 3) or 3))
- wait = max(0, int(cfg.get('retry_wait', 20) or 0))
- code, out = 1, ''
- for i in range(1, tries + 1):
- code, out = _run(cmd)
- lines = [x for x in out.splitlines() if x.strip()]
- if code == 0:
- for line in lines:
- lg('INFO', ' %s | %s', label, line)
- return 0
- lg('WARN', '%s 第 %d/%d 次失败(退出码 %d):%s', label, i, tries, code,
- (lines or ['没有输出'])[-1])
- if i < tries and wait:
- time.sleep(wait * i)
- for line in lines[-10:]:
- lg('ERROR', ' %s | %s', label, line)
- return code or 1
- def rsync_cmd(src, dst, tgt, cfg, dry_run=False, exclude=()):
- cmd = ['rsync', '-a', '--partial', '--times', '--timeout=%d' %
- int(cfg.get('io_timeout', 120) or 120)]
- if dry_run:
- cmd.append('--dry-run')
- for name in exclude:
- cmd += ['--exclude=%s' % name]
- limit = (cfg.get('bandwidth_limit') or '').strip()
- if limit and limit not in ('0', ''):
- cmd.append('--bwlimit=%s' % limit) # KB/s:白天别让同步把采集的带宽抢走
- if tgt.remote:
- cmd += ['-e', ' '.join(['ssh'] + ssh_opts(cfg))] # 路径别带空格:rsync 是按空格拆 -e
- cmd += [src if src.endswith('/') else src + '/',
- ('%s:%s/' % (tgt.host, dst.rstrip('/'))) if tgt.remote else dst.rstrip('/') + '/']
- return cmd
- def drop_remote_sentinel(tgt, dst, cfg, dry_run=False, lg=log):
- """删掉远端当天目录里的那一个 .done —— 除了按保留天数清整天目录之外,唯一会删的文件。
- 不删的话:重传期间远端还挂着上一次的「已完成」,下游会读到半天的数据。
- """
- remote = '%s/%s' % (dst.rstrip('/'), sentinel.SENTINEL)
- lg('INFO', '先撤掉远端的完成标记:%s', remote)
- if dry_run:
- return 0
- if tgt.remote:
- return execute(['ssh'] + ssh_opts(cfg) +
- [tgt.host, 'rm -f %s' % shlex.quote(remote)],
- dict(cfg, retries=1), 'rm .done', False, lg)
- try:
- os.remove(remote)
- except OSError as e:
- if e.errno != 2:
- lg('ERROR', '撤远端 .done 失败:%s', e)
- return 1
- return 0
- def push_sentinel(tgt, src_dir, dst, cfg, dry_run=False, lg=log):
- """数据全落好之后,把本地 .done 单独推上去当最后一步。"""
- src_file = sentinel.path(src_dir)
- if not os.path.exists(src_file):
- lg('WARN', '本地没有 %s(to_wide 没写?),远端这次不会有完成标记,'
- '算法团队就看不到「今天到齐」', src_file)
- return 0
- remote = '%s/%s' % (dst.rstrip('/'), sentinel.SENTINEL)
- # 单文件对单文件:源和目标都不带结尾斜杠,跟上面目录那趟的写法不一样
- cmd = ['rsync', '-a', '--partial', '--times',
- '--timeout=%d' % int(cfg.get('io_timeout', 120) or 120)]
- if dry_run:
- cmd.append('--dry-run')
- if tgt.remote:
- cmd += ['-e', ' '.join(['ssh'] + ssh_opts(cfg)), src_file, '%s:%s' % (tgt.host, remote)]
- else:
- cmd += [src_file, remote]
- code = execute(cmd, cfg, 'rsync .done', dry_run, lg)
- if code == 0 and not dry_run:
- lg('INFO', '完成标记已推送,算法团队可以按 %s/%s 判断这一天到齐',
- tgt, dst.rstrip('/'))
- return code
- DAY_DIR = re.compile(r'^/(\d{4})/(\d{2})/(\d{2})/%s$' % re.escape(sentinel.SENTINEL))
- MIN_KEEP_DAYS = 180 # 数据在算法侧最少要能回溯 180 天,配置填小了一律拒绝清理
- def list_done_days(tgt, cfg, lg=log):
- """列出目标上「已经带完成标记」的那些天目录(绝对路径)。只读,dry-run 也照样列。
- 用哨兵当唯一入口:`.done` 在 = 这天是完整推上去的 = 有资格按保留天数清理;
- 没哨兵的目录(传一半失败的、别人放的)永远不动。
- """
- if tgt.remote:
- cmd = ['ssh'] + ssh_opts(cfg) + [
- tgt.host, 'find %s -mindepth 4 -maxdepth 4 -type f -name %s'
- % (shlex.quote(tgt.path), shlex.quote(sentinel.SENTINEL))]
- lg('INFO', '$ %s(只读,列出现有完成标记)', ' '.join(shlex.quote(x) for x in cmd))
- code, out = _run(cmd)
- if code:
- lg('WARN', '列不出目标上的完成标记(退出码 %d),本次不做保留清理', code)
- return []
- return [x.strip() for x in out.splitlines() if x.strip()]
- import glob
- return sorted(glob.glob(os.path.join(tgt.path.replace('\\', '/'), '*', '*', '*',
- sentinel.SENTINEL)))
- def old_day_dirs(tgt, sentinels, day, keep_days, lg=log):
- """从哨兵名单里挑出「比 day - keep_days 还早」的整天目录,最旧的排前面。
- 判断只看目录名(/<年>/<月>/<日>/.done),不看 mtime —— 补数、重传都会改 mtime,
- 按 mtime 清会把好端端的旧数据当新的留下、把刚补的当旧的删掉。
- """
- root = tgt.path.rstrip('/')
- cutoff = day - datetime.timedelta(days=keep_days)
- out = []
- for line in sentinels:
- p = line.replace('\\', '/')
- if not p.startswith(root + '/'):
- lg('WARN', '跳过不在目标根下的路径:%s', p)
- continue
- m = DAY_DIR.match(p[len(root):])
- if not m:
- continue
- try:
- d = datetime.date(*(int(x) for x in m.groups()))
- except ValueError: # /2026/13/99/.done 这种野目录
- continue
- if d < cutoff:
- day_dir = p[:len(root) + m.end() - len('/' + sentinel.SENTINEL)]
- out.append((d, day_dir))
- out.sort()
- return [p for _, p in out]
- def prune_old_days(tgt, cfg, day, dry_run=False, lg=log):
- """按 [publish] remote_keep_days 删目标上过期的整天目录。默认 0 = 什么都不删。
- 这是这个工具第二处会删的地方(第一处是当天目录里那一个 .done),所以护栏叠满:
- 只对 remote_keep_days>0 且 remote_layout=keep 生效;天数有硬下限 MIN_KEEP_DAYS(180),
- 填小了直接拒绝;只删目录名严格是 年/月/日、且里面有 .done 的;只删 target 根下面的;
- 一次最多删 remote_prune_max 个(默认 7),剩下的下次再删——万一配错或积压太多,
- 也不会一晚上传好的历史全没了。
- """
- keep = int(cfg.get('remote_keep_days') or 0)
- if keep <= 0:
- return 0
- if keep < MIN_KEEP_DAYS:
- lg('ERROR', 'remote_keep_days=%d 低于保留期下限 %d 天(约 6 个月),本次一个目录都不删:'
- '要清理就填 %d 或更大,想永远不删就填 0', keep, MIN_KEEP_DAYS, MIN_KEEP_DAYS)
- return 2
- if (cfg.get('remote_layout') or 'keep').lower() != 'keep':
- lg('ERROR', 'remote_keep_days=%d 只支持 remote_layout = keep(要按 年/月/日 认目录),'
- '现在是 %s,本次不清理', keep, cfg.get('remote_layout'))
- return 2
- if tgt.remote and not tgt.path.startswith('/'):
- lg('ERROR', '远端目标要绝对路径,不做清理:%s', tgt.path)
- return 2
- victims = old_day_dirs(tgt, list_done_days(tgt, cfg, lg), day, keep, lg)
- if not victims:
- lg('INFO', '保留 %d 天:目标上没有过期的整天目录', keep)
- return 0
- cap = max(1, int(cfg.get('remote_prune_max') or 7))
- if len(victims) > cap:
- lg('WARN', '过期的有 %d 天,本次只删最旧的 %d 个(remote_prune_max),其余下次再删',
- len(victims), cap)
- for p in victims[:cap]:
- if dry_run:
- lg('INFO', 'dry-run:会删 %s 上的 %s', tgt, p)
- continue
- if tgt.remote:
- code = execute(['ssh'] + ssh_opts(cfg) + [tgt.host, 'rm -rf -- %s'
- % shlex.quote(p)],
- dict(cfg, retries=1), 'prune', False, lg)
- else:
- real = os.path.realpath(p)
- if not real.startswith(os.path.realpath(tgt.path) + os.sep):
- lg('ERROR', '路径不在目标根下,跳过:%s', p)
- continue
- try:
- import shutil
- shutil.rmtree(real)
- code = 0
- lg('INFO', '已删 %s', real)
- except OSError as e:
- lg('ERROR', '删 %s 失败:%s', real, e)
- code = 1
- if code:
- lg('ERROR', '清理在 %s 这里失败了,后面的都不再删(别连着试第二次,先看是不是挂错目录了)', p)
- return code
- return 0
- def ancestors(path):
- """从这一级往上到根:/data/algo/wind104 -> ['/data/algo/wind104', '/data/algo', '/data', '/']。
- 只给只读诊断用:mkdir -p 失败时到底哪一级不存在、哪一级不归 ssh 用户,看一眼就知道。
- """
- out, p = [], os.path.dirname(path.rstrip('/')) or '/'
- while p != '/':
- out.append(p)
- p = os.path.dirname(p)
- out.append('/')
- return [path] + out
- def ensure_remote_dir(tgt, dst, cfg, dry_run=False, lg=log):
- """rsync 只会建最后一级目录,年/月/日 这种要先 mkdir -p。"""
- if not tgt.remote:
- return 0
- code = execute(['ssh'] + ssh_opts(cfg) + [tgt.host, 'mkdir -p %s' % shlex.quote(dst)],
- cfg, 'mkdir', dry_run, lg)
- if code and not dry_run:
- # mkdir -p 报「权限不够」时报的是它建不动的那一级根目录,八成是两件事之一:
- # 根目录不存在而 /data 不归这个 ssh 用户,或者你 ls 的那台机器和 ssh 落到的不是同一台。
- # 直接在远端把它自己的视角打出来,别让人对着本地目录猜。全是只读命令。
- probe = 'hostname; id; ls -ldZ %s 2>&1; df -hT / 2>&1 | tail -2' % \
- ' '.join(shlex.quote(p) for p in ancestors(tgt.path))
- execute(['ssh'] + ssh_opts(cfg) + [tgt.host, probe], dict(cfg, retries=1),
- '诊断', False, lg)
- user = tgt.host.partition('@')[0] or '这个 ssh 登录用户'
- lg('ERROR', '上面是 %s 自己的视角。要推的根 %s 必须存在且 %s 能写:'
- '在算法服务器上让 root 执行 mkdir -p %s && chown %s %s,'
- '或者把 [publish] rsync_target 换成 %s 已经能写的路径;'
- '修好后单独补推 python -X utf8 -m etl.publish --date <那一天>(宽表还在本地)',
- tgt.host, tgt.path, user, tgt.path, user, tgt.path, user)
- return code
- def run(publish_cfg, src_dir, day, dry_run=False, check=False, lg=log):
- """把 src_dir(某天的宽表目录)推到 [publish] 配的目标。返回退出码。"""
- cfg = {k: v.strip() for k, v in (publish_cfg or {}).items()}
- mode = (cfg.get('sync') or 'auto').lower()
- spec = cfg.get('rsync_target', '')
- disabled = mode in ('off', '0', 'no', 'false')
- if disabled and not check:
- lg('INFO', '[publish] sync = %s,不同步', mode)
- return 0
- if not spec:
- if mode in ('on', '1', 'yes', 'true') or check:
- lg('ERROR', '要同步但 config 的 [publish] rsync_target 是空的:'
- '填 user@host:/绝对路径(或者 NFS 挂载点路径)')
- return 2
- lg('INFO', '[publish] rsync_target 没配,跳过同步(宽表只在本地)')
- return 0
- try:
- tgt = Target(spec)
- except ValueError as e:
- lg('ERROR', 'rsync_target 写法不对:%s', e)
- return 2
- if not os.path.isdir(src_dir):
- lg('ERROR', '要推的目录不存在:%s', src_dir)
- return 2
- dst = dest_day(tgt, day, (cfg.get('remote_layout') or 'keep').lower())
- # tgt 自己就带根路径,dst 是完整的远端路径,两个一起打会把根写两遍
- dst_disp = '%s:%s' % (tgt.host, dst) if tgt.remote else dst
- lg('INFO', '同步 %s -> %s(%s)', src_dir, dst_disp,
- 'ssh/rsync' if tgt.remote else '本地路径(NFS 挂载点)')
- if check:
- probe = '%s/.wind104_write_ok' % dst
- code = ensure_remote_dir(tgt, dst, cfg, dry_run, lg)
- if code:
- lg('ERROR', '建远端目录失败,先确认 ssh 免密:ssh %s', tgt.host)
- return code
- if dry_run:
- lg('INFO', 'dry-run:本该在 %s 建一个探针文件 %s 再删掉', dst_disp,
- os.path.basename(probe))
- return 0
- if tgt.remote:
- code, _ = _run(['ssh'] + ssh_opts(cfg) +
- [tgt.host, 'touch %s && rm -f %s && echo OK' %
- (shlex.quote(probe), shlex.quote(probe))])
- else:
- try:
- open(probe, 'w').close()
- os.remove(probe)
- code = 0
- except OSError as e:
- lg('ERROR', '目标目录写不进去:%s', e)
- code = 1
- if code:
- lg('ERROR', '目标能连但写不进去(检查属主/权限):%s/%s', tgt, dst)
- return code or 1
- if not dry_run:
- lg('INFO', '连通和写权限都正常')
- return 0
- rc = ensure_remote_dir(tgt, dst, cfg, dry_run, lg)
- if rc:
- return rc
- # 顺序很重要:先撤远端的完成标记 -> 搬数据(这趟永远不带 .done)-> 最后补上完成标记。
- # 这样下游看到 .done 的时候,当天的文件一定已经全在里面了。
- rc = drop_remote_sentinel(tgt, dst, cfg, dry_run, lg)
- if rc:
- lg('ERROR', '远端旧的完成标记没撤掉,先别传(撤不掉就会一直骗下游):%s', dst)
- return rc
- rc = execute(rsync_cmd(src_dir, dst, tgt, cfg, dry_run, exclude=[sentinel.SENTINEL]),
- cfg, 'rsync', dry_run, lg)
- if rc:
- return rc
- rc = push_sentinel(tgt, src_dir, dst, cfg, dry_run, lg)
- if rc:
- return rc
- # 保留期清理放在最后:今天的数据已经全落好、完成标记也已经推上去了,才动旧日子
- return prune_old_days(tgt, cfg, day, dry_run, lg)
- def main(argv=None):
- ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
- ap.add_argument('--date', help='哪天 YYYYMMDD,默认昨天')
- ap.add_argument('--config', default=os.path.join(ROOT, 'config', 'config.linux.ini'))
- ap.add_argument('--src', help='要推的目录,默认 output_dir/wide_subdir/年/月/日')
- ap.add_argument('--check', action='store_true', help='只验连通和写权限,不传数据')
- ap.add_argument('--dry-run', action='store_true', help='把命令打出来,什么都不跑')
- a = ap.parse_args(argv)
- day = (datetime.datetime.strptime(a.date, '%Y%m%d').date() if a.date
- else datetime.date.today() - datetime.timedelta(days=1))
- cfg = configparser.ConfigParser(interpolation=None)
- if os.path.exists(a.config):
- cfg.read(a.config, encoding='utf-8')
- c = cfg['collect'] if cfg.has_section('collect') else {}
- base = os.path.dirname(os.path.abspath(a.config))
- src = a.src or os.path.join(os.path.abspath(os.path.join(base, c.get('output_dir', '../data'))),
- (c.get('wide_subdir') or 'standard').strip(),
- '%04d' % day.year, '%02d' % day.month, '%02d' % day.day)
- return run(load(a.config), src, day, dry_run=a.dry_run, check=a.check)
- if __name__ == '__main__':
- sys.exit(main())
|