Files
zyt/identity-admin/.test-runtime/kf-batch-inline-20261105/release_remote.py
T
2026-11-11 14:22:02 +08:00

274 lines
11 KiB
Python

import hashlib
import json
import os
import re
import shutil
import signal
import subprocess
import tarfile
import threading
import time
import urllib.request
from pathlib import Path
root = Path('/opt/im-admin')
work = root / 'deploy/batch-inline-20261105'
data = root / 'deploy/im-admin/data'
compose = data.parent / 'compose.yaml'
vhost = Path('/www/server/panel/vhost/nginx/im.zhenyangtang.cn.conf')
nginx = '/www/server/nginx/sbin/nginx'
static = root / 'admin-web/apps/web-antd/dist'
uploads = Path('/home/ps')
api_name = 'im-admin-api-1'
bridge_name = 'im-admin-batch-inline-bridge-20261105'
runtime_name = 'group-identity/batch-inline-bridge-runtime.json'
previous_image = 'zyt/wecom-admin:full-publish-20261105-a3a184ab6b'
marker = 'batch-inline-20261105'
work.mkdir(mode=0o700)
def sha(value):
return hashlib.sha256(value).hexdigest()
def run(*args, timeout=90):
result = subprocess.run(args, capture_output=True, text=True, timeout=timeout)
if result.returncode:
(work / 'command-error.log').write_text(result.stderr, encoding='utf-8')
raise RuntimeError(f'{args[0]} failed, see private command log')
return result.stdout
def inspect(name):
return json.loads(run('docker', 'inspect', name))[0]
def replace(path, content):
temp = path.with_name(path.name + '.batch-inline-staged')
with temp.open('xb') as f:
f.write(content)
if path.exists():
current = path.stat()
temp.chmod(current.st_mode & 0o777)
os.chown(temp, current.st_uid, current.st_gid)
else:
temp.chmod(0o644)
temp.replace(path)
def get(port, path):
request = urllib.request.Request(f'http://127.0.0.1:{port}{path}', headers={'Host': 'im.zhenyangtang.cn:8369'})
with urllib.request.urlopen(request, timeout=4) as response:
assert response.status == 200
return response.read(), response.headers.get('X-Deploy-Bridge')
def ready(port, entry_hash, expected_marker=None):
for _ in range(60):
try:
_, health_marker = get(port, '/api/v2/health')
entry, entry_marker = get(port, '/knowledge/center')
if health_marker == entry_marker == expected_marker and sha(entry) == entry_hash:
return
except (OSError, AssertionError):
pass
time.sleep(0.5)
raise RuntimeError(f'API readiness check failed on port {port}')
def set_vhost(content):
replace(vhost, content)
run(nginx, '-t')
run(nginx, '-s', 'reload')
def install_api(config):
replace(compose, config)
run('docker', 'compose', '-f', str(compose), 'up', '-d', '--no-deps', '--no-build', 'api', timeout=150)
def check_assets(port):
for file in files:
body, _ = get(port, '/' + file['path'])
assert sha(body) == file['sha256'], file['path']
def interrupted(signum, frame):
raise KeyboardInterrupt('release interrupted')
signal.signal(signal.SIGTERM, interrupted)
signal.signal(signal.SIGHUP, interrupted)
before = inspect(api_name)
assert before['State']['Running'] and before['Config']['Image'] == previous_image
assert before['Config']['User'] == 'app' and before['HostConfig']['ReadonlyRootfs']
assert [(m['Source'], m['Destination']) for m in before['Mounts']] == [(str(data), '/data')]
others = {name: inspect(name)['Id'] for name in ['im-admin-gateway-1', 'im-admin-knowledge-worker-1']}
original_compose = compose.read_bytes()
original_vhost = vhost.read_bytes()
original_entry = (static / 'index.html').read_bytes()
ready(18766, sha(original_entry))
(work / 'compose-before.yaml').write_bytes(original_compose)
(work / 'vhost-before.conf').write_bytes(original_vhost)
(work / 'index-before.html').write_bytes(original_entry)
fingerprint = (root / 'deploy/full-publish-20261105/directory-fingerprint.py').read_text()
access_before = json.loads(run('docker', 'exec', api_name, 'python', '-c', fingerprint))
release = json.loads((uploads / 'batch-inline-release.json').read_text())
archive = uploads / 'batch-inline-20261105.tgz'
assert sha(archive.read_bytes()) == release['sha256']
payload = work / 'payload'
payload.mkdir()
with tarfile.open(archive) as tar:
for item in tar:
target = (payload / item.name).resolve()
assert item.isfile() and target.is_relative_to(payload) and not target.exists()
target.parent.mkdir(parents=True, exist_ok=True)
with tar.extractfile(item) as source, target.open('wb') as dest:
shutil.copyfileobj(source, dest)
files = json.loads((payload / 'manifest.json').read_text())
assert len(files) == release['frontend_files']
for file in files:
source = (payload / 'frontend' / file['path']).resolve()
assert source.is_relative_to(payload / 'frontend')
assert sha(source.read_bytes()) == file['sha256']
existing = static / file['path']
if file['path'] != 'index.html' and existing.exists():
assert sha(existing.read_bytes()) == file['sha256'], f'asset collision: {file["path"]}'
base = 'zyt/wecom-admin:batch-inline-base-20261105'
image = 'zyt/wecom-admin:batch-inline-20261105-' + release['sha256'][:10]
rollback = 'zyt/wecom-admin:batch-inline-safe-20261105-' + release['sha256'][:10]
run('docker', 'tag', before['Image'], base)
dockerfile = 'USER root\nCOPY --chown=10001:10001 frontend/ /app/admin-web/apps/web-antd/dist/\n'
(payload / 'Dockerfile').write_text(f'FROM {base}\n{dockerfile}USER app\n')
run('docker', 'build', '--pull=false', '--network=none', '-t', image, str(payload), timeout=150)
(payload / 'old-index.html').write_bytes(original_entry)
(payload / 'Dockerfile.safe').write_text(f'FROM {image}\nUSER root\nCOPY --chown=10001:10001 old-index.html /app/admin-web/apps/web-antd/dist/index.html\nUSER app\n')
run('docker', 'build', '--pull=false', '--network=none', '-f', str(payload / 'Dockerfile.safe'), '-t', rollback, str(payload), timeout=150)
def api_config(tag):
pattern = r'(^ api:\n(?:(?!^ [A-Za-z_-]+:)[\s\S])*?^ image:) [^\n]+$'
updated, count = re.subn(pattern, lambda match: f'{match[1]} {json.dumps(tag)}', original_compose.decode(), count=1, flags=re.M)
assert count == 1
return updated.encode()
def render(path):
return json.loads(run('docker', 'compose', '-f', str(path), 'config', '--format', 'json'))['services']
staged = compose.with_name('compose.batch-inline-staged.yaml')
updated = api_config(image)
rollback_config = api_config(rollback)
original_services = render(compose)
assert original_services['api']['image'] == previous_image
with staged.open('xb') as f:
f.write(updated)
try:
staged.chmod(0o600)
expected = json.loads(json.dumps(original_services))
expected['api']['image'] = image
assert render(staged) == expected, 'compose change extends beyond the API image'
finally:
if staged.exists():
staged.unlink()
env_file = work / 'api-runtime.env'
assert all('\n' not in entry and '\r' not in entry for entry in before['Config']['Env'])
command = list(before['Config']['Cmd'])
command[command.index('--runtime-file') + 1] = '/data/' + runtime_name
assert original_vhost.count(b'http://127.0.0.1:18766') == 3
bridge_vhost = original_vhost.replace(b'server {', b'server {\n add_header X-Deploy-Bridge batch-inline-20261105 always;', 1).replace(b'http://127.0.0.1:18766', b'http://127.0.0.1:18768')
samples = []
stop_monitor = threading.Event()
def monitor():
while not stop_monitor.is_set():
for path in ('/api/v2/health', '/knowledge/center', '/gateway/health'):
try:
get(8369, path)
samples.append(True)
except Exception:
samples.append(False)
stop_monitor.wait(0.5)
thread = threading.Thread(target=monitor, daemon=True)
bridge_started = False
routed = False
api_changed = False
bridge_can_stop = True
try:
env_file.write_text(''.join(entry + '\n' for entry in before['Config']['Env']))
env_file.chmod(0o600)
run('docker', 'run', '-d', '--name', bridge_name, '--restart=no', '--read-only', '--tmpfs', '/tmp:size=64m,mode=1777',
'--cap-drop=ALL', '--security-opt', 'no-new-privileges:true', '--env-file', str(env_file),
'-v', f'{data}:/data', '-p', '127.0.0.1:18768:8766', image, *command)
bridge_started = True
ready(18768, release['entry_sha256'])
check_assets(18768)
assert json.loads(run('docker', 'exec', bridge_name, 'python', '-c', fingerprint)) == access_before
assert compose.read_bytes() == original_compose and vhost.read_bytes() == original_vhost
assert inspect(api_name)['Id'] == before['Id']
thread.start()
routed = True
bridge_can_stop = False
set_vhost(bridge_vhost)
ready(8369, release['entry_sha256'], marker)
api_changed = True
run('docker', 'stop', '--time', '180', api_name, timeout=195)
install_api(updated)
ready(18766, release['entry_sha256'])
live = inspect(api_name)
assert live['Config']['Image'] == image
assert sorted(live['Config']['Env']) == sorted(before['Config']['Env'])
for field in ('Cmd', 'User'):
assert live['Config'][field] == before['Config'][field]
for name, identity in others.items():
state = inspect(name)
assert state['Id'] == identity and state['State']['Running'], name
for file in sorted(files, key=lambda item: item['path'] == 'index.html'):
destination = static / file['path']
destination.parent.mkdir(parents=True, exist_ok=True)
if not destination.exists() or sha(destination.read_bytes()) != file['sha256']:
replace(destination, (payload / 'frontend' / file['path']).read_bytes())
set_vhost(original_vhost)
ready(8369, release['entry_sha256'])
bridge_can_stop = True
check_assets(8369)
assert json.loads(run('docker', 'exec', api_name, 'python', '-c', fingerprint)) == access_before
stop_monitor.set()
thread.join(timeout=10)
assert samples and all(samples), 'non-200 response during cutover'
except BaseException:
if api_changed:
# Keep the candidate serving until the rollback API is healthy.
bridge_can_stop = False
set_vhost(bridge_vhost)
ready(8369, release['entry_sha256'], marker)
install_api(rollback_config)
ready(18766, sha(original_entry))
replace(static / 'index.html', original_entry)
if routed:
set_vhost(original_vhost)
ready(8369, sha(original_entry))
bridge_can_stop = True
raise
finally:
stop_monitor.set()
if bridge_started and bridge_can_stop:
run('docker', 'stop', '--time', '180', bridge_name, timeout=195)
run('docker', 'rm', bridge_name)
(data / runtime_name).unlink(missing_ok=True)
env_file.unlink(missing_ok=True)
receipt = {'deployed': True, 'api_image': image, 'rollback_image': rollback, 'frontend_files_verified': len(files),
'traffic_checks': len(samples), 'traffic_failures': 0, 'gateway_worker_containers_retained': True,
'identity_fingerprints_preserved': True, 'vhost_restored': vhost.read_bytes() == original_vhost}
(work / 'result.json').write_text(json.dumps(receipt, indent=2))
print(json.dumps(receipt))