209 lines
10 KiB
Python
209 lines
10 KiB
Python
#!/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, allowed=(0,)):
|
|
env = dict(os.environ, GIT_TERMINAL_PROMPT='0')
|
|
return cd.run(['git', *args], 'read candidate source', cwd=cwd, env=env, allowed=allowed,
|
|
timeout=120).decode().strip()
|
|
|
|
|
|
def verify_source(plan, repo):
|
|
check_plan(plan)
|
|
main_line = git('rev-list', '--first-parent', 'origin/main', cwd=repo).splitlines()
|
|
sha, base = plan['sha'], plan['base']
|
|
cd.require(sha in main_line, 'candidate must be on main first-parent history')
|
|
cd.require(git('merge-base', sha, base, cwd=repo, allowed=(0, 1)) == base,
|
|
'running baseline must be an ancestor of the candidate')
|
|
# A previously deployed branch may enter main as a second parent. Its reachable
|
|
# commits are already represented by the baseline, but the integration itself is in scope.
|
|
added = git('rev-list', '--first-parent', f'{base}..{sha}', cwd=repo).splitlines()
|
|
check_scope(plan, lambda n: read_forge(API + f'/pulls/{n}'), added)
|
|
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')
|