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])
+10
View File
@@ -43,6 +43,11 @@ def hifox(cli, *args):
return result
def stage_bundle(inputs):
from cd_bundle_handoff import stage_bundle as stage
return stage(inputs)
def queue(task_id, cli, base=PATH):
cd.require(cd.matches(cd.UUID, task_id), 'use the triggering task UUID')
task = hifox(cli, 'task', 'view', task_id)
@@ -68,6 +73,11 @@ def queue(task_id, cli, base=PATH):
cd.require(result.get('inputs') == inputs, 'HiFox approval already used for a different release')
cd.require(result.get('state') == 'queued', 'dispatch outcome unknown; reconcile Gitea before retry')
return result
cd.require(stage_bundle(inputs) == inputs['bundle'], 'target archive handoff did not verify')
fresh_task = hifox(cli, 'task', 'view', task_id)
fresh_timeline = hifox(cli, 'api', 'get', f'/rest/v1/tasks/{task_id}/timeline')
cd.require(cd.release_approval(fresh_task, fresh_timeline, inputs) == (binding, approved_at),
'release approval changed during archive handoff')
result = {'state': 'submitting', 'inputs': inputs, 'started_at': cd.stamp()}
cd.record(claim, result)
response = forge('POST', DISPATCH, {'ref': 'main', 'inputs': inputs})
+15 -2
View File
@@ -152,7 +152,8 @@ class ProductionCD(unittest.TestCase):
task, timeline = self.hifox_fixture()
timeline[-1]['createdAt'] = '2026-11-22T18:00:01Z'
cd.atomic_write(self.root / 'active-since', b'2026-11-22T17:55:00Z\n')
with patch.object(trigger, 'hifox', side_effect=[task, timeline, task, timeline]), \
with patch.object(trigger, 'hifox', side_effect=[task, timeline] * 3), \
patch.object(trigger, 'stage_bundle', side_effect=lambda inputs: inputs['bundle']), \
patch.object(trigger, 'forge', return_value={'workflow_run_id': 42}) as dispatch:
first = trigger.queue(TASK, 'unused', self.root)
replay = trigger.queue(TASK, 'unused', self.root)
@@ -161,10 +162,22 @@ class ProductionCD(unittest.TestCase):
dispatch.assert_called_once_with('POST', trigger.DISPATCH, {'ref': 'main', 'inputs': first['inputs']})
self.assertEqual(first['inputs']['approval_event'], timeline[-1]['id'])
def test_missing_target_bundle_holds_dispatch_without_claim(self):
task, timeline = self.hifox_fixture()
cd.atomic_write(self.root / 'active-since', b'2026-11-22T17:55:00Z\n')
with patch.object(trigger, 'hifox', side_effect=[task, timeline]), \
patch.object(trigger, 'stage_bundle', create=True, side_effect=cd.CDError('archive unavailable')), \
patch.object(trigger, 'forge', return_value={'workflow_run_id': 42}) as dispatch:
with self.assertRaisesRegex(cd.CDError, 'archive unavailable'):
trigger.queue(TASK, 'unused', self.root)
dispatch.assert_not_called()
self.assertFalse((self.root / (timeline[-1]['id'] + '.json')).exists())
def test_unknown_dispatch_outcome_is_held(self):
task, timeline = self.hifox_fixture()
cd.atomic_write(self.root / 'active-since', b'2026-11-22T17:55:00Z\n')
with patch.object(trigger, 'hifox', side_effect=[task, timeline, task, timeline]), \
with patch.object(trigger, 'hifox', side_effect=[task, timeline] * 3), \
patch.object(trigger, 'stage_bundle', side_effect=lambda inputs: inputs['bundle']), \
patch.object(trigger, 'forge', side_effect=TimeoutError()) as dispatch:
with self.assertRaises(TimeoutError):
trigger.queue(TASK, 'unused', self.root)