fix(cd): 派发前交接并核验主站候选归档
build / build (push) Successful in 2m10s

This commit is contained in:
姚章浩
2026-11-23 21:10:50 +08:00
parent 9eef078ed0
commit 03e622e9c7
5 changed files with 111 additions and 5 deletions
+83
View File
@@ -0,0 +1,83 @@
"""Stage an accepted bundle on the governance host before dispatch."""
import json
import re
import shlex
import subprocess
from pathlib import Path
import production_cd as cd
ROOT = '/opt/knowledge-governance/cd/bundles'
FILES = ('release.json', 'api.tar', 'web.tar', 'worker.tar')
SSH = ['ssh', '-T', '-oBatchMode=yes', '-oStrictHostKeyChecking=yes', '-oClearAllForwardings=yes', '-oConnectTimeout=10']
HOST = 'weknora-test'
# Runs on the target using its installed controller. Exit 3 means absent only.
VERIFY = '''import json, os, runpy, stat, sys
from pathlib import Path
p = Path(sys.argv[1])
try:
info = p.lstat()
except FileNotFoundError:
sys.exit(3)
if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o022:
sys.exit('unsafe bundle directory')
files = {'release.json', 'api.tar', 'web.tar', 'worker.tar'}
if {f.name for f in p.iterdir()} != files or any(stat.S_IMODE(f.lstat().st_mode) != 0o600 for f in p.iterdir()):
sys.exit('unexpected bundle files or permissions')
cd = runpy.run_path('/opt/knowledge-governance/cd/bin/production_cd.py')
cd['verify_bundle'](p, dict(zip(('sha', 'task', 'bundle'), sys.argv[2:])))
print(sys.argv[4])'''
def remote(argv, *, allow_absent=False):
proc = subprocess.run([*SSH, HOST, shlex.join(argv)], capture_output=True, text=True, timeout=240)
if allow_absent and proc.returncode == 3:
return None
if proc.returncode:
raise cd.CDError('target archive handoff failed at ' + argv[0] + ': ' + proc.stderr.strip()[-300:])
return proc.stdout.strip()
def stage_bundle(request, candidates=None):
sha, task, digest = (request[k] for k in ('sha', 'task', 'bundle'))
cd.require(cd.matches(cd.SHA, sha) and cd.matches(cd.UUID, task) and cd.matches(cd.HASH, digest),
'invalid archive identity')
final = ROOT + '/' + digest
def verify(path, absent=False):
result = remote(['/usr/bin/python3', '-I', '-c', VERIFY, path, sha, task, digest], allow_absent=absent)
if absent and result is None:
return False
cd.require(result == digest, 'target archive verification returned a different digest')
return True
if verify(final, absent=True):
return digest
if candidates is None:
candidates = Path.home() / '.local/state/kg-candidate-release'
sources = []
for receipt in candidates.glob('*/ready.json'):
if not re.fullmatch('[0-9a-f]{64}', receipt.parent.name) or receipt.parent.is_symlink():
continue
ready = cd.read_json(cd.immutable_file(receipt))
if ready.get('mode') == 'acceptance' and all(ready.get(k) == request[k] for k in ('sha', 'task', 'bundle')):
sources.append(receipt.parent / 'bundle')
cd.require(len(sources) == 1, 'no unique accepted local archive matching task, commit and bundle')
source = sources[0]
cd.require(not source.is_symlink(), 'unexpected local archive directory')
cd.verify_bundle(source, request, archives=False)
paths = [str(cd.immutable_file(source / name)) for name in FILES]
temp = remote(['mktemp', '-d', ROOT + '/.handoff-XXXXXXXXXXXX'])
if not temp or not re.fullmatch(re.escape(ROOT) + r'/\.handoff-[A-Za-z0-9]{12}', temp):
raise cd.CDError('invalid target staging path')
try:
subprocess.run(['rsync', '-t', '--chmod=F600', '--perms', '-e', shlex.join(SSH), '--',
*paths, HOST + ':' + temp + '/'], check=True, timeout=1500)
verify(temp)
remote(['mv', '-Tn', '--', temp, final])
verify(final)
return digest
except (subprocess.SubprocessError, OSError) as exc:
raise cd.CDError('archive transfer incomplete before dispatch: ' + type(exc).__name__) from exc
finally:
remote(['rm', '-rf', '--', temp])