117 lines
6.2 KiB
Python
117 lines
6.2 KiB
Python
"""Read-only checks for perm-tree-20261008 (admin frontend only): baseline / candidate / deployed.
|
||
|
||
Prints hashes and status only; never reads chat content, knowledge text, users 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 = 'perm-tree-20261008'
|
||
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/')]
|
||
added = [plan['frontendDir'] + '/' + 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', 'knowledge-worker': 'im-admin-knowledge-worker-1'}
|
||
HEALTHCHECKED = {'api', 'gateway'}
|
||
|
||
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']
|
||
|
||
expected = dict(base['expected']) if args.mode == 'baseline' else \
|
||
{row['path'][len('payload/'):]: row['sha256'] for row in payload_rows}
|
||
# 后端一个字节都不变:三个容器里的 rbac.py 都还是 perm-button 的版本
|
||
unchanged = dict(base['backendUnchanged'])
|
||
|
||
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(target, container=None, ref=None):
|
||
command = (['docker', 'run', '--rm', '-i', '--network=none', '--entrypoint', 'python', ref, '-c', HASHES]
|
||
if ref else ['docker', 'exec', '-i', container, 'python', '-c', HASHES])
|
||
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'], 'started': raw['State']['StartedAt'],
|
||
'restarts': raw['RestartCount'], 'health': raw['State'].get('Health', {}).get('Status', 'not_configured')}
|
||
|
||
|
||
def healthy(name, state):
|
||
return state['running'] and (state['health'] == 'healthy' if name in HEALTHCHECKED else True)
|
||
|
||
|
||
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()}
|
||
for name, state in states.items():
|
||
assert state['image'] == base['images'][name], f'{name} is not on the recorded image'
|
||
assert healthy(name, state), 'Not healthy: ' + name
|
||
assert states['api']['image'] == current, 'current tag moved'
|
||
result['services'] = states
|
||
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
|
||
assert in_container(sorted(expected), container=SERVICES['api']) == expected, 'api container differs'
|
||
for container in SERVICES.values():
|
||
assert in_container(sorted(unchanged), container=container) == unchanged, 'backend changed in ' + container
|
||
result['files'] = len(expected)
|
||
|
||
if args.mode == 'candidate':
|
||
candidate = 'zyt/wecom-admin:' + RELEASE
|
||
assert in_container(sorted(expected), ref=candidate) == expected, 'Candidate image differs from manifest'
|
||
assert in_container(sorted(unchanged), ref=candidate) == unchanged, 'Candidate backend differs'
|
||
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'
|
||
before = json.loads((folder / 'baseline-check.json').read_text())['services']
|
||
states = {}
|
||
for service, container in SERVICES.items():
|
||
state = inspect(container)
|
||
if service == 'api':
|
||
assert state['image'] == wanted and state['restarts'] == 0 and healthy(service, state), (service, state)
|
||
else:
|
||
# 本次只重建 api:gateway、knowledge-worker 必须还是原来那个容器
|
||
assert state['id'] == before[service]['id'] and healthy(service, state), (service, state)
|
||
states[service] = state
|
||
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
|
||
entry = next(rel for rel in plan['frontendAdded'] if rel.startswith('jse/index-index-'))
|
||
for origin in ('http://127.0.0.1:18766/', 'http://127.0.0.1:8369/'):
|
||
with urllib.request.urlopen(origin, timeout=15) as response:
|
||
assert entry.encode() in response.read(), origin + ' does not serve the new build'
|
||
roles = next(rel for rel in plan['frontendAdded'] if rel.startswith('js/roles-'))
|
||
with urllib.request.urlopen('http://127.0.0.1:8369/' + roles, timeout=15) as response:
|
||
assert '收起到页面'.encode() in response.read(), 'role editor is not the tree version'
|
||
try:
|
||
urllib.request.urlopen('http://127.0.0.1:18766/api/v2/permissions', timeout=15)
|
||
except urllib.error.HTTPError as exc:
|
||
assert exc.code == 401, exc.code
|
||
else:
|
||
raise AssertionError('permissions accessible without authentication')
|
||
logs = subprocess.run(['docker', 'logs', '--since', states['api']['started'], SERVICES['api']], capture_output=True, text=True)
|
||
assert 'Traceback' not in logs.stdout + logs.stderr, 'api logged a traceback after the switch'
|
||
|
||
result['status'] = 'passed'
|
||
print(json.dumps(result, ensure_ascii=False))
|