tradingSystem/research/chip_accumulation_20261030/fetch.py

61 lines
2.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""通过155独立只读研究容器导出。凭证只在环境中传递,禁止写业务表。"""
import gzip
import hashlib
import json
import shlex
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent
SECRET_KEYS = ('PROXY_DB_URL', 'DB_MYSQL_URL')
WRAPPER = r'''
import json, os, subprocess, sys
r = json.load(sys.stdin)
i = json.loads(subprocess.check_output(['docker','inspect','pms-web']))[0]
v = dict(x.split('=',1) for x in i['Config']['Env'] if '=' in x)
if v.get('PMS_TABLE_PREFIX','') or v.get('PMS_STACK_PREFIX','') or i['Config']['Image'].startswith('pms-real'):
raise SystemExit('目标不是155模拟PMS配置,停止')
e = dict(os.environ)
a = ['docker','run','--rm','-i','--name','pms-chip-research-'+r['mode'].replace('_','-'),
'--label','pms.role=offline-research','--cpus','1','--memory','2g',
'--pids-limit','64','--read-only','--entrypoint','python']
for k in ['PROXY_DB_URL','DB_MYSQL_URL']:
if not v.get(k): raise SystemExit('缺源连接配置')
e[k] = v[k]; a += ['--env',k]
a += ['--env','PMS_TABLE_PREFIX=',i['Image'],'-',r['mode']]
print(json.dumps({'host':'155','prefix':'','source_image':i['Config']['Image'],
'image_id':i['Image'],'role':'readonly-research',
'business_mounts_inherited':False,'trading_credentials_inherited':False}),file=sys.stderr)
p = subprocess.run(a,input=r['code'].encode(),env=e)
raise SystemExit(p.returncode)
'''
def main():
mode = sys.argv[1]
if not all(c.isalnum() or c in '_-' for c in mode):
raise ValueError('模式格式错误')
path = ROOT/'raw'/(mode+'.json.gz')
path.parent.mkdir(exist_ok=True)
if path.exists():
json.load(gzip.open(path)); print(mode, '保留已有快照'); return
code = (ROOT/'remote.py').read_text()
if mode.startswith('chips_'):
day=mode.split('_')[1]
requested=json.loads((ROOT/'cache/chip_requests.json').read_text())[day]
code='REQUEST = '+repr(requested)+'\n'+code
with (path.parent/(mode+'.stderr')).open('wb') as log:
p = subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=8',
'-p','2280','factor@192.168.16.155',
'python3 -c '+shlex.quote(WRAPPER)],
input=json.dumps({'mode':mode,'code':code}).encode(),
stdout=subprocess.PIPE,stderr=log,timeout=600)
if p.returncode:
raise RuntimeError(f'只读导出失败,退出码{p.returncode};未回显连接异常正文')
obj = json.loads(gzip.decompress(p.stdout))
path.write_bytes(p.stdout)
print(mode, 'bytes', len(p.stdout), 'sha256', hashlib.sha256(p.stdout).hexdigest())
if mode in ('probe','coverage'): print(json.dumps(obj,ensure_ascii=False,indent=2))
if __name__ == '__main__': main()