将发布人的状态变更与业务验收报告绑定,复用 Gitea 发布及回滚链路。 从部署回执写入运行身份、镜像及主站登录入口,避免重复调度和回写。
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Submit a HiFox-approved release from the designated CD Agent host."""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import ProxyHandler, Request, build_opener
|
||||
|
||||
import production_cd as cd
|
||||
|
||||
|
||||
DISPATCH = f'/api/v1/repos/{cd.REPO}/actions/workflows/deploy-production.yml/dispatches?return_run_details=true'
|
||||
PATH = Path.home() / '.local/state/kg-hifox-release'
|
||||
RUN_ID = re.compile('[1-9][0-9]{0,14}')
|
||||
|
||||
|
||||
def forge(method, path, payload=None):
|
||||
request = Request(cd.FORGE + path, method=method,
|
||||
data=json.dumps(payload).encode() if payload is not None else None)
|
||||
env = {**os.environ, 'GIT_TERMINAL_PROMPT': '0', 'GIT_ASKPASS': '/bin/false'}
|
||||
fields = dict(line.split('=', 1) for line in cd.run(
|
||||
['/usr/bin/git', 'credential', 'fill'], 'read Gitea credential', cwd='/', env=env,
|
||||
input_data=f'url={cd.FORGE}/{cd.REPO}.git\n\n'.encode()).decode().splitlines() if '=' in line)
|
||||
cd.require(fields.get('username') and fields.get('password'), 'Gitea credential unavailable')
|
||||
auth = base64.b64encode(f'{fields["username"]}:{fields["password"]}'.encode()).decode()
|
||||
request.add_header('Authorization', 'Basic ' + auth)
|
||||
request.add_header('Content-Type', 'application/json')
|
||||
with build_opener(ProxyHandler({}), cd.NoRedirect()).open(request, timeout=20) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def hifox(cli, *args):
|
||||
env = {'PATH': '/usr/local/bin:/usr/bin:/bin', 'HOME': str(Path.home()), 'CI': '1'}
|
||||
raw = cd.run([cli, '--organization-id', cd.ORG, *args, '--output', 'json'], 'read HiFox release record', env=env)
|
||||
result = json.JSONDecoder().raw_decode(raw.decode().strip())[0]
|
||||
cd.require(isinstance(result, (dict, list)) and (not isinstance(result, dict)
|
||||
or (result.get('success') is not False and not result.get('error'))), 'HiFox record unavailable')
|
||||
return result
|
||||
|
||||
|
||||
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)
|
||||
if not isinstance(task, dict) or task.get('id') != task_id or task.get('spaceId') != cd.SPACE:
|
||||
raise cd.CDError('task is outside the release space')
|
||||
acceptance = cd.metadata(task, 'cd_acceptance') or {}
|
||||
cd.require(isinstance(acceptance, dict) and cd.matches(cd.SHA, acceptance.get('sha'))
|
||||
and cd.matches(cd.HASH, acceptance.get('bundle')), 'skip: no registered candidate acceptance')
|
||||
inputs = dict(action='deploy', confirm='deploy-production', sha=acceptance['sha'], bundle=acceptance['bundle'], task=task_id)
|
||||
timeline = hifox(cli, 'api', 'get', f'/rest/v1/tasks/{task_id}/timeline')
|
||||
if not isinstance(timeline, list):
|
||||
raise cd.CDError('HiFox timeline unavailable')
|
||||
binding, approved_at = cd.release_approval(task, timeline, inputs)
|
||||
inputs.update(binding)
|
||||
since = cd.immutable_file(base / 'active-since').read_text().strip()
|
||||
cd.require(re.fullmatch(r'\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ', since) and approved_at > since,
|
||||
'status approval predates activation; enter 待发布 again after acceptance')
|
||||
|
||||
claim = base / (binding['approval_event'] + '.json')
|
||||
with cd.deploy_lock(base / 'dispatch.lock'):
|
||||
if claim.exists():
|
||||
result = cd.read_json(cd.immutable_file(claim))
|
||||
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
|
||||
result = {'state': 'submitting', 'inputs': inputs, 'started_at': cd.stamp()}
|
||||
cd.record(claim, result)
|
||||
response = forge('POST', DISPATCH, {'ref': 'main', 'inputs': inputs})
|
||||
run_id = str(response.get('workflow_run_id', ''))
|
||||
cd.require(cd.matches(RUN_ID, run_id), 'dispatch response has no valid run ID; reconcile before retry')
|
||||
result.update(state='queued', run_id=run_id, run_url=f'{cd.FORGE}/{cd.REPO}/actions/runs/{run_id}')
|
||||
cd.record(claim, result)
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('task', help='UUID of the task that entered 待发布')
|
||||
args = parser.parse_args()
|
||||
executable = Path.home() / '.local/bin/hifox'
|
||||
try:
|
||||
print(json.dumps(queue(args.task, str(executable)), ensure_ascii=False))
|
||||
except HTTPError as exc:
|
||||
sys.exit(f'CD: Gitea dispatch HTTP {exc.code}; reconcile before retry')
|
||||
except cd.CDError as exc:
|
||||
sys.exit(f'CD: {exc}')
|
||||
except (OSError, KeyError, ValueError, TypeError) as exc:
|
||||
sys.exit(f'CD: {type(exc).__name__}; inspect the dispatch record')
|
||||
Reference in New Issue
Block a user