@@ -0,0 +1,180 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Coordinate candidate preparation and record independently authored QA evidence."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
from urllib.error import HTTPError
|
||||
|
||||
import candidate_release as candidate
|
||||
import candidate_runtime as runtime
|
||||
import hifox_release_trigger as hfx
|
||||
import production_cd as cd
|
||||
|
||||
STATE = Path.home() / '.local/state/kg-candidate-release'
|
||||
CLI = str(Path.home() / '.local/bin/hifox')
|
||||
WORKFLOW = candidate.API + '/actions/workflows/prepare-candidate.yml/dispatches?return_run_details=true'
|
||||
QA_AUTHORS = {cd.RELEASE_OWNER, '62a66d1e-4311-4b54-8004-bbb03c69c08c', 'bdf4f412-8c3f-45ab-84f4-638c60a43806'}
|
||||
WAIT_TEST = 'b59c34ee-94f4-41a8-8577-dea73b2c6414'
|
||||
TESTING = 'f8906482-bad7-4af8-9a3b-d52630eff3f7'
|
||||
QA_FENCE = re.compile(r'^```kg-qa-v1\s*\n(\{.*?\})\s*\n```\s*$', re.MULTILINE | re.DOTALL)
|
||||
|
||||
|
||||
def task(task_id):
|
||||
cd.require(cd.matches(cd.UUID, task_id), 'provide the task UUID')
|
||||
obj = hfx.hifox(CLI, 'task', 'view', task_id)
|
||||
if not isinstance(obj, dict) or obj.get('id') != task_id or obj.get('spaceId') != cd.SPACE:
|
||||
raise cd.CDError('task is outside the release space')
|
||||
return obj
|
||||
|
||||
|
||||
def timeline(task_id):
|
||||
rows = hfx.hifox(CLI, 'api', 'get', f'/rest/v1/tasks/{task_id}/timeline')
|
||||
cd.require(isinstance(rows, list), 'task timeline unavailable')
|
||||
return [row for row in rows if row.get('event') == 'commented']
|
||||
|
||||
|
||||
def owner_plan(task_id):
|
||||
task(task_id)
|
||||
matches = [candidate.FENCE.search(row.get('content') or '') for row in reversed(sorted(
|
||||
timeline(task_id), key=lambda row: row.get('createdAt', ''))) if (row.get('actor') or {}).get('id') == cd.RELEASE_OWNER]
|
||||
match = next((row for row in matches if row), None)
|
||||
if match is None:
|
||||
raise cd.CDError('release owner must post a kg-release-v1 plan on the release task')
|
||||
plan = json.loads(match[1])
|
||||
candidate.check_plan(plan)
|
||||
cd.require(plan['task'] == task_id, 'release plan belongs to another task')
|
||||
for item in plan['items']:
|
||||
requirement = task(item['task'])
|
||||
identifier = requirement.get('identifier')
|
||||
pr = candidate.read_forge(candidate.API + f'/pulls/{item["pr"]}')
|
||||
fields = ' '.join(str(v or '') for v in (pr.get('title'), pr.get('body'), (pr.get('head') or {}).get('ref')))
|
||||
cd.require(isinstance(identifier, str) and re.search(rf'(?<![\w-]){re.escape(identifier)}(?!\w)', fields, re.IGNORECASE),
|
||||
f"PR #{item['pr']} does not identify its HiFox requirement")
|
||||
return plan
|
||||
|
||||
|
||||
def queue(task_id):
|
||||
plan = owner_plan(task_id)
|
||||
STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
key = cd.acceptance_digest(plan)
|
||||
path = STATE / (key + '.dispatch.json')
|
||||
with cd.deploy_lock(STATE / 'dispatch.lock'):
|
||||
if path.exists():
|
||||
result = cd.read_json(cd.immutable_file(path))
|
||||
cd.require(result['state'] == 'queued', 'candidate dispatch outcome unknown; reconcile Gitea before retry')
|
||||
return result
|
||||
conf = Path.home() / '.config/knowledge-governance/qa.json'
|
||||
runtime.qa_database(conf)
|
||||
cd.record(path, {'state': 'submitting', 'plan': plan})
|
||||
result = hfx.forge('POST', WORKFLOW, {'ref': 'main', 'inputs': {'plan': json.dumps(plan), 'mode': 'prepare'}})
|
||||
run = str(result.get('workflow_run_id', ''))
|
||||
cd.require(cd.matches(hfx.RUN_ID, run), 'missing candidate run ID; reconcile Gitea before retry')
|
||||
receipt = {'state': 'queued', 'plan': plan, 'run': run, 'url': f'{cd.FORGE}/{cd.REPO}/actions/runs/{run}'}
|
||||
cd.record(path, receipt)
|
||||
return receipt
|
||||
|
||||
|
||||
def add_comment(task_id, key, body):
|
||||
marker = f'[KG candidate {key}]'
|
||||
|
||||
def existing():
|
||||
return [row for row in timeline(task_id) if marker in (row.get('content') or '')]
|
||||
|
||||
if not existing():
|
||||
hfx.hifox(CLI, 'task', 'comment', task_id, '--body', f'{marker}\n\n{body}')
|
||||
rows = existing()
|
||||
cd.require(len(rows) == 1 and cd.matches(cd.UUID, rows[0].get('id')) and body in rows[0].get('content', ''),
|
||||
'candidate comment not uniquely verified')
|
||||
return rows[0]['id']
|
||||
|
||||
|
||||
def publish_candidate(plan, receipt, run):
|
||||
body = (f'候选验收地址 {receipt["url"]}\n\n提交 `{receipt["sha"]}`\n\n'
|
||||
f'归档 `{receipt["bundle"]}`\n\n'
|
||||
f'构建记录 {cd.FORGE}/{cd.REPO}/actions/runs/{run}\n\n'
|
||||
f'发布任务 {task(plan["task"])["url"]}')
|
||||
key = 'ready ' + receipt['bundle']
|
||||
add_comment(plan['task'], key, body)
|
||||
for item in plan['items']:
|
||||
item_id = item['task']
|
||||
status = (task(item_id).get('status') or {}).get('id')
|
||||
if status == TESTING:
|
||||
cd.require(any(f'[KG candidate {key}]' in (row.get('content') or '') for row in timeline(item_id)),
|
||||
f'{item_id}: another QA round is already in progress')
|
||||
continue
|
||||
cd.require(status == WAIT_TEST, f'{item_id}: requirement must be in 待测试')
|
||||
add_comment(item_id, key, body)
|
||||
cd.require((task(item_id).get('status') or {}).get('id') == WAIT_TEST,
|
||||
f'{item_id}: task status changed during candidate handoff')
|
||||
hfx.hifox(CLI, 'task', 'edit', item_id, '--status', TESTING)
|
||||
cd.require((task(item_id).get('status') or {}).get('id') == TESTING, f'{item_id}: testing status not verified')
|
||||
|
||||
|
||||
def register(task_id):
|
||||
plan = owner_plan(task_id)
|
||||
directory = STATE / cd.acceptance_digest(plan)
|
||||
with cd.deploy_lock(directory / 'registration.lock'):
|
||||
receipt = cd.read_json(cd.immutable_file(directory / 'ready.json'))
|
||||
cd.require(receipt.get('mode') == 'acceptance', 'isolated smoke results are ineligible for publication')
|
||||
runtime.attest(directory / 'bundle', receipt)
|
||||
reports = {}
|
||||
tasks = [item['task'] for item in plan['items']] + [task_id]
|
||||
for item_id in tasks:
|
||||
obj = task(item_id)
|
||||
rows = sorted(timeline(item_id), key=lambda row: row.get('createdAt', ''), reverse=True)
|
||||
for row in rows:
|
||||
match = QA_FENCE.search(row.get('content') or '')
|
||||
if not match or (row.get('actor') or {}).get('id') not in QA_AUTHORS:
|
||||
continue
|
||||
result = json.loads(match[1])
|
||||
if result.get('bundle') == receipt['bundle']:
|
||||
reports[item_id] = (row, result)
|
||||
break
|
||||
if item_id in reports:
|
||||
row = reports[item_id][0]
|
||||
cd.require(cd.matches(cd.UUID, row.get('id')) and obj.get('url', '').startswith('https://app.hifox.com/'),
|
||||
'invalid QA evidence link')
|
||||
candidate.check_qa(plan, receipt, reports, QA_AUTHORS)
|
||||
fresh = owner_plan(task_id)
|
||||
cd.require(fresh == plan, 'release plan changed during registration')
|
||||
rel = task(task_id)
|
||||
cd.require((rel.get('status') or {}).get('id') not in (cd.READY, cd.PUBLISHED),
|
||||
'register QA before the owner moves the release task to 待发布')
|
||||
sha, bundle = receipt['sha'], receipt['bundle']
|
||||
links = '\n'.join(f'- {task(item)["url"]}#comment-{reports[item][0]["id"]}' for item in tasks)
|
||||
body = f'批次验收通过\n\n提交 `{sha}`\n\n归档 `{bundle}`\n\n需求验收与批次回归报告\n{links}'
|
||||
comment = add_comment(task_id, 'acceptance ' + bundle, body)
|
||||
acceptance = {'verdict': 'passed', 'sha': sha, 'bundle': bundle, 'evidence': rel['url'] + '#comment-' + comment}
|
||||
if cd.metadata(task(task_id), 'cd_acceptance') != acceptance:
|
||||
hfx.hifox(CLI, 'task', 'metadata', 'set', task_id, 'cd_acceptance', json.dumps(json.dumps(acceptance)))
|
||||
cd.require(cd.metadata(task(task_id), 'cd_acceptance') == acceptance, 'acceptance writeback not verified')
|
||||
return acceptance
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('prepare', 'register', 'status'))
|
||||
parser.add_argument('task')
|
||||
args = parser.parse_args()
|
||||
if args.action == 'prepare':
|
||||
result = queue(args.task)
|
||||
elif args.action == 'register':
|
||||
result = register(args.task)
|
||||
else:
|
||||
plan = owner_plan(args.task)
|
||||
key = cd.acceptance_digest(plan)
|
||||
results = [STATE / key / 'ready.json', STATE / (key + '.dispatch.json')]
|
||||
result = next((cd.read_json(cd.immutable_file(p)) for p in results if p.exists()), {'state': 'unprepared'})
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except HTTPError as exc:
|
||||
sys.exit(f'Candidate coordinator: HTTP {exc.code}; reconcile Gitea before retry')
|
||||
except (cd.CDError, runtime.qa_env.QAError, OSError, ValueError) as exc:
|
||||
sys.exit(f'Candidate coordinator: {exc}')
|
||||
@@ -0,0 +1,203 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate a release batch and build its immutable candidate bundle."""
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from types import SimpleNamespace
|
||||
|
||||
from urllib.request import Request
|
||||
|
||||
import hifox_release_trigger as integration
|
||||
import production_cd as cd
|
||||
|
||||
API = f'/api/v1/repos/{cd.REPO}'
|
||||
CONTEXTS = Path(__file__).resolve().parents[1] / '.gitea/required-contexts.txt'
|
||||
FENCE = re.compile(r'^```kg-release-v1\s*\n(\{.*?\})\s*\n```\s*$', re.MULTILINE | re.DOTALL)
|
||||
|
||||
|
||||
def read_forge(path):
|
||||
token = os.getenv('KG_CANDIDATE_READ_TOKEN')
|
||||
if not token:
|
||||
return integration.forge('GET', path)
|
||||
from urllib.request import ProxyHandler, build_opener
|
||||
server = os.getenv('KG_CANDIDATE_FORGE', cd.FORGE)
|
||||
cd.require(server in (cd.FORGE, 'http://192.168.50.223:3000'), 'untrusted Gitea origin')
|
||||
request = Request(server + path, headers={'Authorization': 'token ' + token})
|
||||
with build_opener(ProxyHandler({}), cd.NoRedirect()).open(request, timeout=20) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def check_plan(plan):
|
||||
cd.require(isinstance(plan, dict) and set(plan) == {'task', 'sha', 'base', 'items', 'extra'},
|
||||
'invalid release plan fields')
|
||||
cd.require(cd.matches(cd.UUID, plan['task']) and cd.matches(cd.SHA, plan['sha'])
|
||||
and cd.matches(cd.SHA, plan['base']) and plan['base'] != plan['sha'], 'invalid release task or SHA range')
|
||||
items = plan['items']
|
||||
cd.require(isinstance(items, list) and 0 < len(items) <= 100, 'require one to 100 requirements')
|
||||
for item in items:
|
||||
cd.require(isinstance(item, dict) and set(item) == {'task', 'pr'} and cd.matches(cd.UUID, item['task'])
|
||||
and item['task'] != plan['task'] and type(item['pr']) is int and item['pr'] > 0, 'invalid requirement or PR')
|
||||
cd.require(len({i['task'] for i in items}) == len(items) == len({i['pr'] for i in items}),
|
||||
'duplicate requirement or PR')
|
||||
extra = plan['extra']
|
||||
cd.require(isinstance(extra, list) and len(extra) <= 100 and all(cd.matches(cd.SHA, s) for s in extra)
|
||||
and len(set(extra)) == len(extra), 'invalid additional reviewed commits')
|
||||
|
||||
|
||||
def check_scope(plan, read_pr, first_parents):
|
||||
check_plan(plan)
|
||||
required = set(plan['extra'])
|
||||
for item in plan['items']:
|
||||
pr = read_pr(item['pr'])
|
||||
sha = pr.get('merge_commit_sha')
|
||||
cd.require(pr.get('merged') is True and (pr.get('base') or {}).get('ref') == 'main' and cd.matches(cd.SHA, sha),
|
||||
f"PR #{item['pr']} must be merged into main")
|
||||
cd.require(sha not in required, 'landed commit is listed in multiple scope entries')
|
||||
required.add(sha)
|
||||
cd.require(required == set(first_parents), 'commits outside the release scope, or planned commits absent from main range')
|
||||
|
||||
|
||||
def instant(value):
|
||||
cd.require(isinstance(value, str) and bool(re.search(r'(Z|[+-]\d\d:\d\d)$', value)), 'invalid QA timestamp')
|
||||
return datetime.datetime.fromisoformat(value.replace('Z', '+00:00'))
|
||||
|
||||
|
||||
def check_qa(plan, receipt, reports, authors):
|
||||
check_plan(plan)
|
||||
tasks = {item['task'] for item in plan['items']} | {plan['task']}
|
||||
cd.require(set(reports) == tasks, 'require reports on every requirement and the release task')
|
||||
cd.require(cd.matches(cd.HASH, receipt.get('bundle')) and receipt.get('sha') == plan['sha'], 'invalid candidate receipt')
|
||||
for task, (comment, report) in reports.items():
|
||||
cd.require((comment.get('actor') or {}).get('id') in authors, f'{task}: require authorized QA report author')
|
||||
cd.require(all(report.get(k) == receipt[k] for k in ('sha', 'bundle', 'url')), f'{task}: report is for a different candidate')
|
||||
cd.require(instant(comment.get('createdAt')) > instant(receipt['ready_at']), f'{task}: report predates candidate')
|
||||
cd.require(not comment.get('updatedAt') or instant(comment['updatedAt']) >= instant(comment['createdAt']),
|
||||
f'{task}: invalid report revision timestamp')
|
||||
values = [report.get(field) for field in ('required', 'passed', 'failed', 'blocked')]
|
||||
cd.require(all(type(v) is int for v in values) and values[0] > 0
|
||||
and values == [values[0], values[0], 0, 0] and report.get('verdict') == 'passed',
|
||||
f'{task}: required QA cases have not passed')
|
||||
|
||||
|
||||
def git(*args, cwd=None):
|
||||
env = dict(os.environ, GIT_TERMINAL_PROMPT='0')
|
||||
return cd.run(['git', *args], 'read candidate source', cwd=cwd, env=env, timeout=120).decode().strip()
|
||||
|
||||
|
||||
def verify_source(plan, repo):
|
||||
main_line = git('rev-list', '--first-parent', 'origin/main', cwd=repo).splitlines()
|
||||
sha, base = plan['sha'], plan['base']
|
||||
cd.require(sha in main_line and base in main_line and main_line.index(sha) < main_line.index(base),
|
||||
'candidate and baseline must be ordered commits on main first-parent history')
|
||||
check_scope(plan, lambda n: read_forge(API + f'/pulls/{n}'),
|
||||
main_line[main_line.index(sha):main_line.index(base)])
|
||||
contexts = {line.split('#', 1)[0].strip() for line in CONTEXTS.read_text().splitlines()} - {''}
|
||||
cd.verify_contexts(read_forge(API + f'/commits/{sha}/status'), contexts)
|
||||
|
||||
|
||||
def build(plan, repo, destination):
|
||||
check_plan(plan)
|
||||
verify_source(plan, repo)
|
||||
sha = plan['sha']
|
||||
destination = destination.resolve()
|
||||
if destination.exists():
|
||||
digest = cd.hash_file(destination / 'release.json')
|
||||
cd.verify_bundle(destination, {'task': plan['task'], 'sha': sha, 'bundle': digest})
|
||||
return digest
|
||||
destination.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
with tempfile.TemporaryDirectory(prefix='kg-candidate-source-') as name:
|
||||
src = Path(name) / 'source'
|
||||
git('clone', '--no-checkout', '--shared', str(repo.resolve()), str(src))
|
||||
git('checkout', '--detach', sha, cwd=src)
|
||||
cd.require(git('rev-parse', 'HEAD', cwd=src) == sha and not git('status', '--porcelain', cwd=src),
|
||||
'candidate checkout differs from selected commit')
|
||||
identity = json.loads(cd.run([sys.executable, 'scripts/version.py', '--identity'], 'read build version', cwd=src))
|
||||
cd.require(identity.get('commit_sha') == sha, 'version script returned another SHA')
|
||||
flags = {'VERSION': identity['release_version'] or 'dev', 'RELEASE_VERSION': identity['release_version'] or '',
|
||||
'BUILD_KIND': identity['build_kind'], 'COMMITS_SINCE_RELEASE': identity['commits_since_release'] or '',
|
||||
'COMMIT_SHA': sha, 'BUILD_TIME': identity['built_at']}
|
||||
common = ['docker', 'build', '--pull=false', '--label', f'{cd.REVISION}={sha}']
|
||||
# Only pass the explicitly configured build proxy, never the agent's inherited credentials.
|
||||
for variable in ('HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY'):
|
||||
value = os.getenv('KG_BUILD_' + variable)
|
||||
if value:
|
||||
cd.require('@' not in value, 'build proxy must not contain credentials')
|
||||
common += ['--build-arg', f'{variable}={value}']
|
||||
tags = {name: f'kg-release-candidate-{name}:{sha}' for name in ('backend', 'web')}
|
||||
for role, dockerfile in (('backend', 'Dockerfile'), ('web', 'Dockerfile.web')):
|
||||
args = common + ['-f', dockerfile, '-t', tags[role]]
|
||||
if role == 'backend':
|
||||
for key, value in flags.items():
|
||||
args += ['--build-arg', f'{key}={value}']
|
||||
subprocess.run(args + ['.'], cwd=src, check=True, timeout=1800)
|
||||
image_ids = {key: cd.image_inspect(tag)['Id'] for key, tag in tags.items()}
|
||||
# pack takes its migration list from this commit and validates the OCI revision and image IDs.
|
||||
original = Path.cwd()
|
||||
try:
|
||||
os.chdir(src)
|
||||
cd.pack(SimpleNamespace(sha=sha, task=plan['task'], api=image_ids['backend'], worker=image_ids['backend'],
|
||||
web=image_ids['web'], output=destination))
|
||||
finally:
|
||||
os.chdir(original)
|
||||
return cd.hash_file(destination / 'release.json')
|
||||
|
||||
|
||||
def event_plan(event, env):
|
||||
cd.require(env.get('GITHUB_EVENT_NAME') == 'workflow_dispatch' and env.get('GITHUB_REPOSITORY') == cd.REPO,
|
||||
'candidate workflow requires an explicit dispatch in the governance repository')
|
||||
inputs = event.get('inputs') or {}
|
||||
mode = inputs.get('mode')
|
||||
cd.require(mode in ('verify', 'prepare'), 'unknown candidate mode')
|
||||
if mode == 'prepare':
|
||||
cd.require(env.get('GITHUB_REF') == 'refs/heads/main', 'prepare requires the workflow from main')
|
||||
plan = json.loads(inputs['plan'])
|
||||
check_plan(plan)
|
||||
return plan, mode
|
||||
|
||||
|
||||
def proof(plan, mode):
|
||||
return 'KG_CANDIDATE_PLAN_V1 ' + cd.acceptance_digest({'plan': plan, 'mode': mode})
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
sub = parser.add_subparsers(dest='action', required=True)
|
||||
guard = sub.add_parser('guard')
|
||||
guard.add_argument('--event', required=True, type=Path)
|
||||
guard.add_argument('--repo', required=True, type=Path)
|
||||
for name in ('verify', 'build'):
|
||||
arg = sub.add_parser(name)
|
||||
arg.add_argument('--plan', required=True, type=Path)
|
||||
arg.add_argument('--repo', required=True, type=Path)
|
||||
if name == 'build':
|
||||
arg.add_argument('--output', required=True, type=Path)
|
||||
args = parser.parse_args()
|
||||
if args.action == 'guard':
|
||||
plan, mode = event_plan(cd.read_json(args.event), os.environ)
|
||||
verify_source(plan, args.repo)
|
||||
print(proof(plan, mode))
|
||||
return
|
||||
plan = cd.read_json(args.plan)
|
||||
check_plan(plan)
|
||||
if args.action == 'verify':
|
||||
verify_source(plan, args.repo)
|
||||
print(json.dumps({'state': 'verified', 'sha': plan['sha'], 'task': plan['task']}))
|
||||
else:
|
||||
digest = build(plan, args.repo, args.output)
|
||||
print(json.dumps({'state': 'built', 'sha': plan['sha'], 'task': plan['task'], 'bundle': digest}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except cd.CDError as exc:
|
||||
sys.exit(f'Candidate: {exc}')
|
||||
except (OSError, ValueError, KeyError, subprocess.SubprocessError) as exc:
|
||||
sys.exit(f'Candidate: {type(exc).__name__}; check build or release input')
|
||||
@@ -0,0 +1,151 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the sealed candidate on an isolated acceptance stack."""
|
||||
|
||||
import argparse
|
||||
import ipaddress
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import sys
|
||||
import tempfile
|
||||
from types import SimpleNamespace
|
||||
from urllib.parse import quote
|
||||
|
||||
import production_cd as cd
|
||||
import qa_env
|
||||
|
||||
|
||||
def isolated_subnet(exclude=()):
|
||||
nets = cd.run(['docker', 'network', 'ls', '-q'], 'list Docker networks').decode().split()
|
||||
data = json.loads(cd.run(['docker', 'network', 'inspect', *nets], 'read Docker networks')) if nets else []
|
||||
occupied = [ipaddress.ip_network(row['Subnet']) for net in data for row in net['IPAM']['Config'] or []
|
||||
if row.get('Subnet') and ':' not in row['Subnet']]
|
||||
routes = json.loads(cd.run(['ip', '-j', '-4', 'route'], 'read host routes'))
|
||||
occupied += [ipaddress.ip_network(route['dst'], strict=False) for route in routes if route['dst'] != 'default']
|
||||
occupied += [ipaddress.ip_network(subnet) for subnet in exclude]
|
||||
for subnet in ipaddress.ip_network('10.241.233.0/24').subnets(new_prefix=28):
|
||||
if not any(subnet.overlaps(other) for other in occupied):
|
||||
return str(subnet)
|
||||
raise cd.CDError('no available candidate subnet')
|
||||
|
||||
|
||||
def qa_database(path):
|
||||
db = qa_env.database_config(path)
|
||||
passfile, cert = [path.parent / name for name in ('qa.pgpass', 'rds-ca.pem')]
|
||||
qa_env.private_file(passfile)
|
||||
qa_env.private_file(cert)
|
||||
expected = f"{db['host']}:{db['port']}:{db['database']}:{db['user']}:"
|
||||
entries = [line for line in passfile.read_text().splitlines() if line and not line.startswith('#')]
|
||||
cd.require(len(entries) == 1 and entries[0].startswith(expected), 'pgpass must authorize exactly the dedicated QA database')
|
||||
password = re.sub(r'\\(.)', r'\1', entries[0][len(expected):])
|
||||
cd.require(bool(password), 'dedicated QA database password missing')
|
||||
url = (f"postgresql://{db['user']}:{quote(password, safe='')}@{db['host']}:{db['port']}/{db['database']}"
|
||||
'?sslmode=verify-full&sslrootcert=/run/qa/rds-ca.pem')
|
||||
return url, cert
|
||||
|
||||
|
||||
def ready(directory, bundle, test_database=None):
|
||||
bundle = bundle.resolve()
|
||||
manifest = cd.read_json(bundle / 'release.json')
|
||||
digest = cd.hash_file(bundle / 'release.json')
|
||||
request = {key: manifest[key] for key in ('sha', 'task')}
|
||||
request['bundle'] = digest
|
||||
cd.verify_bundle(bundle, request)
|
||||
project = 'kg-batch-' + digest[:20] + ('-smoke' if test_database is None else '')
|
||||
cf = directory / 'compose.json'
|
||||
receipt_path = directory / 'ready.json'
|
||||
cmd = ['docker', 'compose', '-p', project, '-f', str(cf)]
|
||||
if cf.exists():
|
||||
cd.require(receipt_path.exists(), 'candidate startup is unresolved; inspect its Compose project')
|
||||
receipt = cd.read_json(cd.immutable_file(receipt_path))
|
||||
cd.require(receipt['task'] == request['task'] and receipt['bundle'] == digest, 'candidate already holds another bundle')
|
||||
attest(bundle, receipt)
|
||||
return receipt
|
||||
services = {}
|
||||
env = {'APP_ADDR': '0.0.0.0:8080', 'TEST_WEKNORA_ENABLED': 'false', 'PP_SCAN_ENABLED': 'false',
|
||||
'RELEASE_WORKER_ENABLED': 'false', 'PRODUCTION_RELEASE_REQUESTS_ENABLED': 'false',
|
||||
'DOBOTAI_OPS_READ_ENABLED': 'false', 'DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED': 'false'}
|
||||
if test_database is None:
|
||||
password = secrets.token_hex(24)
|
||||
cd.atomic_write(directory / 'postgres.env', f'POSTGRES_USER=qa\nPOSTGRES_DB=governance\nPOSTGRES_PASSWORD={password}\n'.encode())
|
||||
env['DATA' + 'BASE_URL'] = f'postgres://qa:{password}@postgres:5432/governance?sslmode=disable'
|
||||
services['postgres'] = {'image': 'postgres:17-alpine', 'env_file': [str(directory / 'postgres.env')],
|
||||
'tmpfs': ['/var/lib/postgresql/data'],
|
||||
'healthcheck': {'test': ['CMD', 'pg_isready', '-U', 'qa', '-d', 'governance'],
|
||||
'interval': '2s', 'timeout': '2s', 'retries': 20}}
|
||||
else:
|
||||
url, cert = qa_database(test_database)
|
||||
env['DATA' + 'BASE_URL'] = url
|
||||
cd.atomic_write(directory / 'rds-ca.pem', cert.read_bytes(), mode=0o444)
|
||||
app_env = directory / 'app.env'
|
||||
cd.atomic_write(app_env, ''.join(f'{k}={v}\n' for k, v in env.items()).encode())
|
||||
names = {role: f'{project}-{role}' for role in cd.ROLES}
|
||||
for role, item in manifest['images'].items():
|
||||
archive = bundle / f'{role}.tar'
|
||||
cd.verify_archive(archive, item['id'])
|
||||
cd.run(['docker', 'load', '-i', str(archive)], 'load sealed candidate image', timeout=150)
|
||||
services[role] = {'image': item['id'], 'container_name': names[role]}
|
||||
for role in ('api', 'worker'):
|
||||
services[role]['env_file'] = [str(app_env)]
|
||||
if test_database is not None:
|
||||
services[role]['volumes'] = [f'{directory / "rds-ca.pem"}:/run/qa/rds-ca.pem:ro']
|
||||
services['api']['healthcheck'] = {'test': ['CMD', 'curl', '-fsS', 'http://127.0.0.1:8080/health'],
|
||||
'interval': '2s', 'timeout': '3s', 'retries': 45}
|
||||
if test_database is None:
|
||||
services['api']['depends_on'] = {'postgres': {'condition': 'service_healthy'}}
|
||||
services['worker'].update(command=['/app/worker'], depends_on={'api': {'condition': 'service_healthy'}})
|
||||
services['web'].update(ports=['127.0.0.1::8080'], depends_on={'api': {'condition': 'service_healthy'}})
|
||||
internal_subnet = isolated_subnet()
|
||||
networks = {'default': {'internal': test_database is None, 'ipam': {'config': [{'subnet': internal_subnet}]}}}
|
||||
if test_database is None:
|
||||
# The private smoke network has no NAT. Only the web container gets an ingress network.
|
||||
networks['ingress'] = {'ipam': {'config': [{'subnet': isolated_subnet([internal_subnet])}]}}
|
||||
services['web']['networks'] = {'default': {}, 'ingress': {}}
|
||||
cd.record(cf, {'services': services, 'networks': networks})
|
||||
try:
|
||||
cd.run(cmd + ['up', '-d', '--no-build', '--pull', 'never'], 'start candidate Compose project', timeout=130)
|
||||
raw_ports = json.loads(cd.run(['docker', 'inspect', '--format', '{{json .NetworkSettings.Ports}}', names['web']],
|
||||
'read candidate web binding'))
|
||||
port = (raw_ports or {}).get('8080/tcp') or []
|
||||
cd.require(len(port) == 1 and port[0].get('HostIp') == '127.0.0.1'
|
||||
and re.fullmatch(r'[1-9][0-9]{0,4}', port[0].get('HostPort', '')),
|
||||
'candidate web has no verified loopback binding')
|
||||
receipt = {**request, 'url': f'http://127.0.0.1:{port[0]["HostPort"]}', 'containers': names,
|
||||
'images': {role: image['id'] for role, image in manifest['images'].items()},
|
||||
'mode': 'smoke' if test_database is None else 'acceptance'}
|
||||
cd.wait_ready(lambda: attest(bundle, receipt), seconds=65)
|
||||
receipt['ready_at'] = cd.stamp()
|
||||
cd.record(receipt_path, receipt)
|
||||
return receipt
|
||||
except Exception:
|
||||
cd.run(cmd + ['down', '--timeout', '3'], 'stop unsuccessful candidate Compose project', timeout=40)
|
||||
raise
|
||||
|
||||
|
||||
def attest(bundle, receipt):
|
||||
cd.require(cd.hash_file(bundle / 'release.json') == receipt['bundle'], 'candidate bundle changed after deployment')
|
||||
cd.attest(SimpleNamespace(sha=receipt['sha'], task=receipt['task'], directory=bundle,
|
||||
test_url=receipt['url'], **receipt['containers']))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('bundle', type=Path)
|
||||
args = parser.parse_args()
|
||||
with tempfile.TemporaryDirectory(prefix='kg-candidate-smoke-') as temp:
|
||||
directory = Path(temp)
|
||||
try:
|
||||
print(json.dumps(ready(directory, args.bundle)))
|
||||
finally:
|
||||
if (directory / 'compose.json').exists():
|
||||
digest = cd.hash_file(args.bundle / 'release.json')
|
||||
cmd = ['docker', 'compose', '-p', 'kg-batch-' + digest[:20] + '-smoke', '-f', str(directory / 'compose.json')]
|
||||
cd.run(cmd + ['down', '--timeout', '3'], 'remove disposable rehearsal containers', timeout=45)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except (cd.CDError, qa_env.QAError, OSError, ValueError) as exc:
|
||||
sys.exit(f'Candidate runtime: {exc}')
|
||||
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Local build worker for authenticated Gitea candidate jobs."""
|
||||
|
||||
import hmac
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from urllib.error import URLError
|
||||
|
||||
import candidate_coordinator as coordinator
|
||||
import candidate_release as candidate
|
||||
import candidate_runtime as runtime
|
||||
import production_cd as cd
|
||||
|
||||
|
||||
def verify_job(run_id, plan, repo):
|
||||
cd.require(isinstance(run_id, str) and run_id.isascii() and run_id.isdigit() and 0 < len(run_id) < 16,
|
||||
'invalid candidate workflow run')
|
||||
target = candidate.API + f'/actions/runs/{run_id}'
|
||||
run = candidate.read_forge(target)
|
||||
sha = run.get('head_sha')
|
||||
cd.require(run.get('event') == 'workflow_dispatch' and run.get('path') == 'prepare-candidate.yml@refs/heads/main'
|
||||
and run.get('status') == 'in_progress' and (run.get('actor') or {}).get('id') == 1
|
||||
and cd.matches(cd.SHA, sha), 'untrusted candidate workflow run')
|
||||
file = '.gitea/workflows/prepare-candidate.yml'
|
||||
cd.require(candidate.git('show', f'{sha}:{file}', cwd=repo) == Path(__file__).resolve().parents[1].joinpath(file).read_text().strip(),
|
||||
'candidate workflow differs from locally installed instructions')
|
||||
jobs = candidate.read_forge(target + '/jobs').get('jobs', [])
|
||||
guard = [job for job in jobs if job.get('name') == 'guard' and job.get('conclusion') == 'success']
|
||||
cd.require(len(guard) == 1 and type(guard[0].get('id')) is int, 'candidate guard did not succeed')
|
||||
# Gitea logs are plaintext and may prefix each line with a timestamp.
|
||||
from urllib.request import ProxyHandler, build_opener
|
||||
from urllib.request import Request
|
||||
token = os.environ['KG_CANDIDATE_READ_TOKEN']
|
||||
request = Request(cd.FORGE + candidate.API + f'/actions/jobs/{guard[0]["id"]}/logs',
|
||||
headers={'Authorization': 'token ' + token})
|
||||
with build_opener(ProxyHandler({}), cd.NoRedirect()).open(request, timeout=15) as response:
|
||||
lines = response.read(2**20).decode().splitlines()
|
||||
cd.require(sum(line.strip().endswith(candidate.proof(plan, 'prepare')) for line in lines) == 1,
|
||||
'candidate input does not match Gitea guard proof')
|
||||
|
||||
|
||||
def main_site_sha():
|
||||
raw = cd.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=6', 'weknora-test',
|
||||
'docker compose -p knowledge-governance-cloud-test -f /opt/knowledge-governance/compose.json '
|
||||
'exec -T api /app/api --version-record-status'], 'read main site build identity',
|
||||
allowed=(0, 1), timeout=15)
|
||||
sha = json.loads(raw).get('commit_sha')
|
||||
cd.require(cd.matches(cd.SHA, sha), 'main site did not report a full SHA')
|
||||
return sha
|
||||
|
||||
|
||||
def prepare(payload, repo):
|
||||
cd.require(isinstance(payload, dict) and set(payload) == {'run', 'plan'}, 'invalid candidate job payload')
|
||||
plan = payload['plan']
|
||||
candidate.check_plan(plan)
|
||||
key = cd.acceptance_digest(plan)
|
||||
state = coordinator.STATE
|
||||
conf = Path.home() / '.config/knowledge-governance/qa.json'
|
||||
with cd.deploy_lock(state / 'runtime.lock'):
|
||||
cd.require(coordinator.owner_plan(plan['task']) == plan, 'release owner plan changed')
|
||||
runtime.qa_database(conf)
|
||||
candidate.git('fetch', 'origin', '+refs/heads/main:refs/remotes/origin/main', cwd=repo)
|
||||
verify_job(payload['run'], plan, repo)
|
||||
cd.require(main_site_sha() == plan['base'], 'release baseline differs from the live main site')
|
||||
directory = state / key
|
||||
directory.mkdir(mode=0o700, exist_ok=True)
|
||||
for existing in state.glob('*/compose.json'):
|
||||
cd.require(existing.parent == directory, 'another candidate owns the acceptance slot')
|
||||
candidate.build(plan, repo, directory / 'bundle')
|
||||
cd.require(coordinator.owner_plan(plan['task']) == plan, 'release plan changed after candidate build')
|
||||
receipt = runtime.ready(directory, directory / 'bundle', conf)
|
||||
coordinator.publish_candidate(plan, receipt, payload['run'])
|
||||
return receipt
|
||||
|
||||
|
||||
def serve(repo, access):
|
||||
secret = cd.immutable_file(access).read_text().strip()
|
||||
cd.require(cd.matches(cd.HASH, secret), 'invalid candidate access file')
|
||||
coordinator.STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *_args):
|
||||
pass
|
||||
|
||||
def respond(self, status, body):
|
||||
data = json.dumps(body).encode()
|
||||
self.send_response(status)
|
||||
self.send_header('Content-Type', 'application/json')
|
||||
self.send_header('Content-Length', str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_POST(self):
|
||||
if self.path != '/prepare' or not hmac.compare_digest(self.headers.get('Authorization', ''), 'Bearer ' + secret):
|
||||
self.respond(403, {'error': 'candidate authorization refused'})
|
||||
return
|
||||
try:
|
||||
size = int(self.headers.get('Content-Length', 0))
|
||||
cd.require(0 < size <= 65536, 'invalid candidate payload size')
|
||||
self.connection.settimeout(10)
|
||||
payload = json.loads(self.rfile.read(size))
|
||||
self.connection.settimeout(60)
|
||||
receipt = prepare(payload, repo)
|
||||
self.respond(200, receipt)
|
||||
except (cd.CDError, runtime.qa_env.QAError) as exc:
|
||||
self.respond(409, {'error': str(exc)})
|
||||
except (OSError, KeyError, ValueError, URLError) as exc:
|
||||
self.respond(502, {'error': f'candidate operation failed: {type(exc).__name__}'})
|
||||
|
||||
ThreadingHTTPServer(('127.0.0.1', 38984), Handler).serve_forever()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) != 3:
|
||||
sys.exit('usage: candidate_worker.py <source repository> <private access file>')
|
||||
serve(Path(sys.argv[1]).resolve(), Path(sys.argv[2]).resolve())
|
||||
@@ -360,10 +360,10 @@ def cmd_internal_contracts(go: str) -> int:
|
||||
cwd=ROOT).returncode
|
||||
if qa_rc:
|
||||
return qa_rc
|
||||
cd_rc = subprocess.run(py("-m", "unittest", "discover", "-s", "scripts", "-p", "test_production_cd.py", "-v"),
|
||||
cwd=ROOT).returncode
|
||||
if cd_rc:
|
||||
return cd_rc
|
||||
for pattern in ('test_production_cd.py', 'test_candidate_release.py'):
|
||||
cd_rc = subprocess.run(py('-m', 'unittest', 'discover', '-s', 'scripts', '-p', pattern, '-v'), cwd=ROOT).returncode
|
||||
if cd_rc:
|
||||
return cd_rc
|
||||
snapshot_rc = subprocess.run(py("scripts/development_snapshot.py","--self-test"),cwd=ROOT).returncode
|
||||
if snapshot_rc:
|
||||
return 1
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
|
||||
import candidate_release as candidate
|
||||
import production_cd as cd
|
||||
|
||||
BASE, A, B, OTHER = [c * 40 for c in 'abcd']
|
||||
TASK, QA1, QA2, OWNER = [f'{n:08d}-1111-2222-3333-444444444444' for n in range(1, 5)]
|
||||
RUN = {'sha': B, 'bundle': 'e' * 64, 'ready_at': '2026-11-01T10:00:00Z', 'url': 'http://127.0.0.1:39191'}
|
||||
|
||||
|
||||
class CandidateReleaseTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.plan = {'task': TASK, 'sha': B, 'base': BASE,
|
||||
'items': [{'task': QA1, 'pr': 20}, {'task': QA2, 'pr': 21}],
|
||||
'extra': []}
|
||||
self.prs = {n: {'merged': True, 'base': {'ref': 'main'}, 'merge_commit_sha': sha}
|
||||
for n, sha in ((20, A), (21, B))}
|
||||
self.report = {'actor': {'id': OWNER}, 'createdAt': '2026-11-01T11:00:00Z', 'id': OWNER}
|
||||
|
||||
def test_scope_accounts_for_entire_main_range(self):
|
||||
candidate.check_scope(self.plan, self.prs.__getitem__, [A, B])
|
||||
with self.assertRaisesRegex(cd.CDError, 'outside the release scope'):
|
||||
candidate.check_scope(self.plan, self.prs.__getitem__, [A, OTHER, B])
|
||||
|
||||
def test_pr_must_be_merged_on_main_and_match_range(self):
|
||||
self.prs[20]['base']['ref'] = 'test'
|
||||
with self.assertRaisesRegex(cd.CDError, 'merged into main'):
|
||||
candidate.check_scope(self.plan, self.prs.__getitem__, [A, B])
|
||||
|
||||
def test_require_all_qa_reports_and_shared_regression(self):
|
||||
sources = {QA1: (self.report, self.result()), QA2: (self.report, self.result())}
|
||||
with self.assertRaisesRegex(cd.CDError, 'every requirement and the release task'):
|
||||
candidate.check_qa(self.plan, RUN, sources, {OWNER})
|
||||
sources[TASK] = (self.report, self.result())
|
||||
candidate.check_qa(self.plan, RUN, sources, {OWNER})
|
||||
|
||||
def test_same_candidate_and_author_required(self):
|
||||
for result, author, reason in ((self.result(sha=OTHER), OWNER, 'different candidate'),
|
||||
(self.result(bundle='0' * 64), OWNER, 'different candidate'),
|
||||
(self.result(), QA1, 'authorized QA'),
|
||||
(self.result(failed=1), OWNER, 'not passed')):
|
||||
sources = {QA1: (dict(self.report, actor={'id': author}), result),
|
||||
QA2: (self.report, self.result()), TASK: (self.report, self.result())}
|
||||
with self.subTest(reason=reason), self.assertRaisesRegex(cd.CDError, reason):
|
||||
candidate.check_qa(self.plan, RUN, sources, {OWNER})
|
||||
|
||||
def test_preparation_rejected_from_review_branch(self):
|
||||
import json
|
||||
event = {'inputs': {'mode': 'prepare', 'plan': json.dumps(self.plan)}}
|
||||
env = {'GITHUB_EVENT_NAME': 'workflow_dispatch', 'GITHUB_REPOSITORY': cd.REPO,
|
||||
'GITHUB_REF': 'refs/heads/feat/candidate-release-batch'}
|
||||
with self.assertRaisesRegex(cd.CDError, 'workflow from main'):
|
||||
candidate.event_plan(event, env)
|
||||
event['inputs']['mode'] = 'verify'
|
||||
self.assertEqual(candidate.event_plan(event, env), (self.plan, 'verify'))
|
||||
|
||||
def result(self, **extra):
|
||||
return {**RUN, 'verdict': 'passed', 'required': 2, 'passed': 2, 'failed': 0, 'blocked': 0, **extra}
|
||||
Reference in New Issue
Block a user