fix(cd): 派发前交接并校验验收归档 #28
@@ -28,7 +28,7 @@
|
||||
|
||||
执行 `candidate_coordinator.py register <发布任务 UUID>`。脚本复验运行身份,逐项核对报告作者、候选版本和归档、时序与必测结果。全项通过后在发布任务登记附原始报告链接的汇总,再写入并读回 `cd_acceptance`。验收候选只接受专用 RDS 模式。
|
||||
|
||||
运维按[主站 CD 手册](PRODUCTION_CD_RUNBOOK.md)将已验收归档传到主站只读收件目录并核对摘要。发布负责人完成确认后,将发布任务转入「待发布」。已有自动化使用该 UUID 和归档部署并回写。部署后回写失败时使用现有回执重试回写。
|
||||
HiFox 触发器按[主站 CD 手册](PRODUCTION_CD_RUNBOOK.md)在派发前交接并校验验收归档。交接失败时可修复后重试同一事件,已派发事件仍回放原记录。发布负责人完成确认后,将发布任务转入「待发布」。已有自动化使用该 UUID 和归档部署并回写。部署后回写失败时使用现有回执重试回写。
|
||||
|
||||
## 执行器配置
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
```
|
||||
|
||||
4. 由验收人使用获授权的 HiFox CLI 登记业务结论,读回任务、验收字段和状态。`cd_acceptance` 是 JSON 字符串类型的 metadata,其解析结果为 `{"verdict":"passed","sha":"…","bundle":"…","evidence":"https://…"}`。录入人应先核对真实报告与运行身份。自动发布时,`evidence` 使用同一 HiFox 任务的验收报告评论链接(带 `#comment-<UUID>`)。评论须正文包含完整提交和归档清单摘要,并在发布人确认前完成。用 `task view --output json` 核对实际任务 UUID、空间、状态和验收字段。验收登记重试复用原归档摘要与原记录。以当前版本只接受一个任务,多个任务分别验收。
|
||||
5. 在首次发布前,由运维把四个文件放入云主站的 `/opt/knowledge-governance/cd/bundles/<release.json SHA256>/`。通过安全文件通道传到临时目录,核对摘要与内容后用同一文件系统上的目录重命名发布;已有目录先核对内容,匹配时复用。此目录仅供目标控制器读取,文件由该账号持有且组与其他用户无写权限。
|
||||
5. HiFox 触发器在派发 Gitea 前自动通过执行机的 `weknora-test` SSH 通道交接四个文件,并用主站控制器校验。人工 Actions 入口仍须由运维提前将四个文件放入云主站的 `/opt/knowledge-governance/cd/bundles/<release.json SHA256>/`。通过安全文件通道传到临时目录,核对摘要与内容后用同一文件系统上的目录重命名发布;已有目录先核对内容,匹配时复用。此目录仅供目标控制器读取,文件由该账号持有且组与其他用户无写权限。
|
||||
|
||||
## 在 HiFox 确认发布
|
||||
|
||||
@@ -49,5 +49,5 @@
|
||||
- 目标机安装仓库 `scripts/{production_cd.py,cd_migration_probe.py,deploy-api-web.sh,production-cd-ssh.sh}` 到 `/opt/knowledge-governance/cd/bin/`。创建私有 `receipts/`、`bundles/`、`hifox-home/`,初始化 `source.git` 为 bare Git 仓,并将 `.gitea/required-contexts.txt` 安装到该目录。仅发布运维可更新这些文件。
|
||||
- 填写目标机 `/opt/knowledge-governance/cd/deploy-production.yml`,内容与 Gitea 主分支的工作流逐字节相同。控制器用 Gitea 发布人账号 ID 和只读日志验证确认。目标端 `authorized_keys` 为 CI 单独公钥设置 `restrict,command="/opt/knowledge-governance/cd/bin/production-cd-ssh.sh"`。校验云主机 SSH host key 后将其按 `kg-governance-cd` 别名写入 `KG_CD_KNOWN_HOSTS`。对应独立 SSH 私钥保存在 `KG_CD_SSH_KEY`。Runner 标签为 `kg-production-cd`,使用 `KG_CD_SSH_HOST` 和 `KG_CD_SSH_PORT` 接入批准的 Tailscale 或本机 IPv6 隧道。
|
||||
- 将受控 HiFox CLI 安装至 `bin/hifox`,由账号持有人在目标主机使用 `hifox-home` 对应的私有配置目录完成登录。身份须能读取指定空间的任务、写 `cd_release` metadata 并完成对应状态迁移。状态绑定前分别读回组织状态和实际任务类型,复用原有待发布、已发布 ID,保留其余工作流配置。
|
||||
- 在专用发布 Agent 的 Ubuntu 开发机安装 `scripts/{production_cd.py,hifox_release_trigger.py}` 到 `~/.local/lib/kg-hifox-release/`。该机使用受控 HiFox 登录和已配置的 Gitea Git 凭据助手,凭据不传入自动化指令。使用私有目录 `~/.local/state/kg-hifox-release/` 存放 `active-since`(UTC,`YYYY-MM-DDTHH:MM:SSZ`)及调度记录。首次接通时,将 `active-since` 设为通道启用时刻,历史状态事件不追发。发布期间需要 Agent 执行机和 HiFox Daemon 在线。
|
||||
- 在专用发布 Agent 的 Ubuntu 开发机安装 `scripts/{production_cd.py,hifox_release_trigger.py,cd_bundle_handoff.py}` 到 `~/.local/lib/kg-hifox-release/`。该机使用受控 HiFox 登录和已配置的 Gitea Git 凭据助手,凭据不传入自动化指令。使用私有目录 `~/.local/state/kg-hifox-release/` 存放 `active-since`(UTC,`YYYY-MM-DDTHH:MM:SSZ`)及调度记录。首次接通时,将 `active-since` 设为通道启用时刻,历史状态事件不追发。发布期间需要 Agent 执行机和 HiFox Daemon 在线。
|
||||
- 常规 push CI 负责验证和静态预览。这个 workflow 的唯一事件是 `workflow_dispatch`。`make verify` 的 `contracts` 子项运行 CD 用例。真实切换的验收要求对应候选、现场前置条件和发布人确认。
|
||||
|
||||
@@ -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])
|
||||
@@ -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})
|
||||
|
||||
@@ -247,7 +247,7 @@ def release(host, request):
|
||||
require(existing and existing['state'] in ('deployed_hifox_pending', 'published'),
|
||||
'writeback requires a verified deployment receipt')
|
||||
require(all(existing[k] == request[k] for k in ('sha', 'task', 'bundle')), 'receipt binding mismatch')
|
||||
manifest = verify_bundle(host.bundle_path(request), request, archives=False)
|
||||
manifest = verify_bundle(host.bundle_path(request), request)
|
||||
host.approve(request)
|
||||
host.verify(manifest)
|
||||
return writeback(host, request, existing)
|
||||
@@ -268,7 +268,7 @@ def release(host, request):
|
||||
host.approve(request)
|
||||
require(accepted_task(host, request) == accepted, 'business acceptance changed before switch')
|
||||
except (CDError, OSError, ValueError, KeyError) as exc:
|
||||
receipt.update(state='failed_before_cutover')
|
||||
receipt.update(state='failed_before_cutover', failure=str(exc) if isinstance(exc, CDError) else type(exc).__name__)
|
||||
record(path, receipt)
|
||||
raise CDError(f'failed_before_cutover: {exc}' if isinstance(exc, CDError) else 'failed_before_cutover') from exc
|
||||
|
||||
@@ -418,6 +418,28 @@ def verify_archive(archive, expected):
|
||||
key not in descriptor.get('annotations', {}) for descriptor in oci['manifests']
|
||||
for key in ('org.opencontainers.image.ref.name', 'io.containerd.image.name')),
|
||||
'archive OCI index contains a mutable name')
|
||||
descriptor = oci['manifests'][0].get('digest')
|
||||
require(matches(IMAGE, descriptor), 'invalid OCI image descriptor')
|
||||
entry = t.getmember('blobs/sha256/' + descriptor[7:])
|
||||
require(entry.isfile() and entry.size < 2**20, 'unexpected OCI image manifest')
|
||||
raw = t.extractfile(entry).read()
|
||||
require('sha256:' + hashlib.sha256(raw).hexdigest() == descriptor, 'OCI manifest digest mismatch')
|
||||
require(json.loads(raw).get('config', {}).get('digest') == expected, 'OCI config digest mismatch')
|
||||
return descriptor
|
||||
return expected
|
||||
|
||||
|
||||
def engine_image(config, descriptor, revision):
|
||||
# Classic storage uses the config ID. Containerd storage can expose the OCI manifest ID.
|
||||
for ref in dict.fromkeys((descriptor, config)):
|
||||
try:
|
||||
info = image_inspect(ref)
|
||||
except CDError:
|
||||
continue
|
||||
require(info['Id'] in (descriptor, config) and info['Config']['Labels'].get(REVISION) == revision,
|
||||
'loaded image identity differs from approved archive')
|
||||
return info['Id']
|
||||
raise CDError('approved image unavailable by config and manifest digest')
|
||||
|
||||
|
||||
class LiveHost:
|
||||
@@ -601,13 +623,13 @@ class LiveHost:
|
||||
|
||||
def load(self, directory, manifest):
|
||||
archives = {role: directory / (role + '.tar') for role in ROLES}
|
||||
for role, archive in archives.items():
|
||||
verify_archive(archive, manifest['images'][role]['id'])
|
||||
descriptors = {role: verify_archive(archive, manifest['images'][role]['id'])
|
||||
for role, archive in archives.items()}
|
||||
self.loaded_images = {}
|
||||
for role, archive in archives.items():
|
||||
image = manifest['images'][role]['id']
|
||||
run(['docker', 'image', 'load', '-i', str(archive)], f'load {role} image', timeout=600)
|
||||
require(image_inspect(image)['Id'] == image and image_label(image) == manifest['sha'],
|
||||
f'{role} loaded image differs from approved build')
|
||||
self.loaded_images[role] = engine_image(image, descriptors[role], manifest['sha'])
|
||||
|
||||
@property
|
||||
def backup(self):
|
||||
@@ -616,7 +638,7 @@ class LiveHost:
|
||||
def switch(self, previous, manifest):
|
||||
current = self.compose.read_bytes()
|
||||
require(hashlib.sha256(current).hexdigest() == previous['compose_sha256'], 'Compose changed before switch')
|
||||
images = {role: manifest['images'][role]['id'] for role in ROLES}
|
||||
images = self.loaded_images
|
||||
changed = with_images(json.loads(current), images)
|
||||
for role, image in previous['images'].items():
|
||||
run(['docker', 'image', 'tag', image, f'knowledge-governance-cd-rollback:{self.request["bundle"]}-{role}'],
|
||||
@@ -651,7 +673,13 @@ class LiveHost:
|
||||
return assets
|
||||
|
||||
def verify(self, manifest):
|
||||
images = {role: manifest['images'][role]['id'] for role in ROLES}
|
||||
images = getattr(self, 'loaded_images', None)
|
||||
if images is None: # A separate writeback invocation must reconstruct the same identities.
|
||||
directory = self.bundle_path(self.request)
|
||||
images = {}
|
||||
for role, item in manifest['images'].items():
|
||||
descriptor = verify_archive(directory / (role + '.tar'), item['id'])
|
||||
images[role] = engine_image(item['id'], descriptor, manifest['sha'])
|
||||
def check():
|
||||
require(self.runtime() == images, 'running image IDs differ from approved bundle')
|
||||
require(api_identity(self.containers['api']) == manifest['sha'], 'running API SHA mismatches approval')
|
||||
|
||||
@@ -51,6 +51,30 @@ class ProductionCD(unittest.TestCase):
|
||||
self.host.switch.assert_not_called()
|
||||
self.host.callback.assert_not_called()
|
||||
|
||||
def test_archive_binds_engine_descriptor_to_approved_config(self):
|
||||
import io
|
||||
import tarfile
|
||||
config = b'{"architecture":"amd64"}'
|
||||
digest = lambda raw: 'sha256:' + hashlib.sha256(raw).hexdigest()
|
||||
expected = digest(config)
|
||||
for target in (expected, 'sha256:' + '0' * 64):
|
||||
blob = json.dumps({'schemaVersion': 2, 'config': {'digest': target}}).encode()
|
||||
manifest_id = digest(blob)
|
||||
archive = self.root / 'identity.tar'
|
||||
files = {'manifest.json': json.dumps([{'Config': 'config.json'}]).encode(), 'config.json': config,
|
||||
'index.json': json.dumps({'manifests': [{'digest': manifest_id}]}).encode(),
|
||||
'blobs/sha256/' + manifest_id[7:]: blob}
|
||||
with tarfile.open(archive, 'w') as tar:
|
||||
for name, raw in files.items():
|
||||
entry = tarfile.TarInfo(name)
|
||||
entry.size = len(raw)
|
||||
tar.addfile(entry, io.BytesIO(raw))
|
||||
if target == expected:
|
||||
self.assertEqual(cd.verify_archive(archive, expected), manifest_id)
|
||||
else:
|
||||
with self.assertRaisesRegex(cd.CDError, 'config digest'):
|
||||
cd.verify_archive(archive, expected)
|
||||
|
||||
def test_no_confirmation_has_zero_side_effects(self):
|
||||
self.request['confirm'] = ''
|
||||
with self.assertRaisesRegex(cd.CDError, 'confirmation'):
|
||||
@@ -152,7 +176,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 +186,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)
|
||||
|
||||
Reference in New Issue
Block a user