131 lines
7.2 KiB
Python
131 lines
7.2 KiB
Python
"""Read-only checks for review-gate-20260930: baseline / candidate / deployed.
|
|
|
|
Prints hashes and status only; never reads chat content, patients or credentials.
|
|
"""
|
|
from pathlib import Path
|
|
import argparse, hashlib, json, subprocess, urllib.error, urllib.request
|
|
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('mode', choices=['baseline', 'candidate', 'deployed'])
|
|
args = parser.parse_args()
|
|
RELEASE = 'review-gate-20260930'
|
|
folder = Path(__file__).resolve().parent
|
|
project = Path('/opt/im-admin')
|
|
base = json.loads((folder / 'server-baseline.json').read_text())
|
|
plan = json.loads((folder / 'release-plan.json').read_text())
|
|
manifest = json.loads((folder / 'manifest.json').read_text())
|
|
payload_rows = [row for row in manifest if row['path'].startswith('payload/')]
|
|
frontend = plan['frontendDir']
|
|
added = [frontend + '/' + rel for rel in plan['frontendAdded']]
|
|
sha = lambda data: hashlib.sha256(data).hexdigest()
|
|
image = lambda ref: subprocess.check_output(['docker', 'image', 'inspect', ref, '--format', '{{.Id}}'], text=True).strip()
|
|
SERVICES = {'api': 'im-admin-api-1', 'gateway': 'im-admin-gateway-1'}
|
|
UNTOUCHED = ['im-admin-knowledge-worker-1']
|
|
|
|
# The unpacked bundle itself must be intact.
|
|
for row in manifest:
|
|
path = (folder / row['path']).resolve()
|
|
assert path.is_relative_to(folder), row['path']
|
|
assert path.stat().st_size == row['bytes'] and sha(path.read_bytes()) == row['sha256'], row['path']
|
|
|
|
# project-relative path -> expected sha256
|
|
if args.mode == 'baseline':
|
|
expected = dict(base['expected'])
|
|
else:
|
|
expected = {row['path'][len('payload/'):]: row['sha256'] for row in payload_rows}
|
|
|
|
HASHES = ('from pathlib import Path;import hashlib,json,sys;names=json.load(sys.stdin);'
|
|
'print(json.dumps({n:(hashlib.sha256((Path("/app")/n).read_bytes()).hexdigest() '
|
|
'if (Path("/app")/n).is_file() else None) for n in names}))')
|
|
|
|
|
|
def in_container(code, target, container=None, ref=None):
|
|
command = (['docker', 'run', '--rm', '-i', '--network=none', '--entrypoint', 'python', ref, '-c', code]
|
|
if ref else ['docker', 'exec', '-i', container, 'python', '-c', code])
|
|
return json.loads(subprocess.check_output(command, input=json.dumps(target).encode()))
|
|
|
|
|
|
def inspect(container):
|
|
raw = json.loads(subprocess.check_output(['docker', 'inspect', container]))[0]
|
|
return {'id': raw['Id'], 'image': raw['Image'], 'running': raw['State']['Running'],
|
|
'restarts': raw['RestartCount'], 'health': raw['State'].get('Health', {}).get('Status', 'not_configured')}
|
|
|
|
|
|
current = image('zyt/wecom-admin:current')
|
|
result = {'mode': args.mode, 'release': RELEASE, 'image': current}
|
|
|
|
if args.mode == 'baseline':
|
|
states = {name: inspect(container) for name, container in SERVICES.items()}
|
|
assert states['api']['image'] == current == base['images']['api'], 'api is not on the recorded current image'
|
|
assert states['gateway']['image'] == base['images']['gateway'], 'gateway is not on the recorded image'
|
|
for name, state in states.items():
|
|
assert state['running'] and state['health'] == 'healthy', 'Not healthy: ' + name
|
|
others = {container: inspect(container) for container in UNTOUCHED}
|
|
for container, state in others.items():
|
|
assert state['running'] and state['image'] == base['images']['knowledge-worker'], 'Unexpected: ' + container
|
|
result['services'] = states
|
|
result['others'] = others
|
|
for name in added:
|
|
assert not (project / name).exists(), 'Would overwrite an existing file: ' + name
|
|
|
|
if args.mode in ('baseline', 'deployed'):
|
|
for name, wanted in expected.items():
|
|
assert sha((project / name).read_bytes()) == wanted, 'Host drift: ' + name
|
|
for service, container in SERVICES.items():
|
|
code = expected if service == 'api' else {k: v for k, v in expected.items() if k.startswith('wechat_rpa/')}
|
|
actual = in_container(HASHES, sorted(code), container=container)
|
|
assert actual == code, f'Running {service} container differs from expected code'
|
|
result['files'] = len(expected)
|
|
|
|
if args.mode == 'candidate':
|
|
candidate = 'zyt/wecom-admin:' + RELEASE
|
|
actual = in_container(HASHES, sorted(expected), ref=candidate)
|
|
assert actual == expected, 'Candidate image differs from manifest'
|
|
result['candidate'] = image(candidate)
|
|
result['files'] = len(expected)
|
|
|
|
if args.mode == 'deployed':
|
|
wanted = image('zyt/wecom-admin:' + RELEASE)
|
|
assert current == wanted, 'current tag does not point at the release image'
|
|
for service, container in SERVICES.items():
|
|
state = inspect(container)
|
|
assert state['image'] == wanted and state['running'] and state['restarts'] == 0, (service, state)
|
|
assert state['health'] == 'healthy', (service, state)
|
|
recorded = folder / 'baseline-check.json'
|
|
if recorded.exists():
|
|
before = json.loads(recorded.read_text())['others']
|
|
for container in UNTOUCHED:
|
|
now = inspect(container)
|
|
assert now['id'] == before[container]['id'] and now['running'], 'Unrelated container changed: ' + container
|
|
result['others_unchanged'] = UNTOUCHED
|
|
for url in ['http://127.0.0.1:18766/api/v2/health', 'http://127.0.0.1:18770/health']:
|
|
with urllib.request.urlopen(url, timeout=15) as response:
|
|
assert response.status == 200, url
|
|
with urllib.request.urlopen('http://127.0.0.1:18766/', timeout=15) as response:
|
|
assert b'jse/index-index-Caxwar90.js' in response.read(), 'admin index.html is not the new build'
|
|
# Patient/order routes still refuse anonymous callers. No login is attempted.
|
|
for path in ['/api/v2/archive/desktop/patients/search?keyword=x', '/api/v2/archive/desktop/patient-orders']:
|
|
try:
|
|
urllib.request.urlopen('http://127.0.0.1:18766' + path, timeout=15)
|
|
except urllib.error.HTTPError as exc:
|
|
assert exc.code == 401, (path, exc.code)
|
|
else:
|
|
raise AssertionError('Accessible without authentication: ' + path)
|
|
# 本次行为在运行中的容器里直接核对(不连 ZYT、不读数据库)。
|
|
api_code = ("import json,archive_api,zyt_patient_client as p,zyt_order_client as o,admin_backend as b;"
|
|
"e=archive_api._http_error(p.ZytPatientIpRestricted('x'));"
|
|
"r=archive_api._order_http_error(o.ZytOrderSessionExpired('x'));"
|
|
"rules=b.validate_review_rules([{'label':'t','enabled':True,'keywords':['服用,用法']}]);"
|
|
"print(json.dumps({'ip':[e.status_code,e.detail['code']],'order_expired_staff':'staff_message' in r.detail,"
|
|
"'split':rules[0]['keywords']},ensure_ascii=False))")
|
|
api = json.loads(subprocess.check_output(['docker', 'exec', '-i', SERVICES['api'], 'python', '-c', api_code]))
|
|
assert api == {'ip': [409, 'zyt_ip_restricted'], 'order_expired_staff': True, 'split': ['服用', '用法']}, api
|
|
gw_code = ("import json,model_gateway as g;"
|
|
"print(json.dumps({'max':g.JUDGE_MAX_TOKENS,'cap':g.JUDGE_MAX_TOKENS_CAP,'budget':g.TOTAL_BUDGET}))")
|
|
gateway = json.loads(subprocess.check_output(['docker', 'exec', '-i', SERVICES['gateway'], 'python', '-c', gw_code]))
|
|
assert gateway == {'max': 1024, 'cap': 4096, 'budget': 45.0}, gateway
|
|
result['behaviour'] = {'api': api, 'gateway': gateway}
|
|
|
|
result['status'] = 'passed'
|
|
print(json.dumps(result, ensure_ascii=False))
|