@@ -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())
|
||||
Reference in New Issue
Block a user