115 lines
7.2 KiB
Python
115 lines
7.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Fixed owner-authorized Stage acceptance. No automatic retry or cost reconciliation."""
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import urllib.request
|
|
import uuid
|
|
|
|
SHA='860324e3a91b31c2b6d4e784e458f6d120582cb8'
|
|
SESSION='v4-ci-timeout-860324e-20261024'
|
|
REQUEST='6e82f843-45e4-49e3-9164-11a6879e39ba'
|
|
|
|
def proposal(prior):
|
|
if prior.get('state')!='FAILED' or prior.get('version')!=5: raise ValueError('Prior must remain FAILED v5')
|
|
scope=prior['metadata']['scope']
|
|
prefix='editorial-research-to-brief-v1\nTopic: '
|
|
suffix='\nResearch and evidence-backed brief only. No publication, release, production changes or execution authorization.'
|
|
if not scope.startswith(prefix) or not scope.endswith(suffix): raise ValueError('Exact prior scope required')
|
|
return dict(requestId=REQUEST,pilotKind='editorial-research-to-brief-v1',operationMode='PREPARE',environment='staging',scope='EDITORIAL_RESEARCH_TO_BRIEF',researchTopic=scope[len(prefix):-len(suffix)],acceptanceCriteria=prior['metadata']['acceptanceCriteria'],commitSha=SHA,budgetLimitCents=20)
|
|
|
|
def command(args,timeout=15):
|
|
return subprocess.check_output(args,stderr=subprocess.DEVNULL,timeout=timeout)
|
|
|
|
def http(base,token,route,body=None,method=None):
|
|
req=urllib.request.Request(base+'/'+route,data=None if body is None else json.dumps(body).encode(),headers={'Authorization':'Bearer '+token,'Content-Type':'application/json'},method=method or ('GET' if body is None else 'POST'))
|
|
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),NoRedirect())
|
|
with opener.open(req,timeout=10) as r:
|
|
raw=r.read(262145)
|
|
if len(raw)>262144: raise ValueError('Response bound')
|
|
return json.loads(raw)
|
|
|
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
def redirect_request(self,req,fp,code,msg,headers,newurl): return None
|
|
|
|
def ci_success(log):
|
|
return SHA in log and 'Deployment for develop completed successfully!' in log and '🏁 Job succeeded' in log
|
|
|
|
def verify_artifact(status,task):
|
|
artifact=status.get('artifact')
|
|
if status['state']!='VERIFYING' or not artifact: raise ValueError('Acceptance incomplete')
|
|
if hashlib.sha256(artifact['bytes'].encode()).hexdigest()!=artifact['sha256']: raise ValueError('Digest mismatch')
|
|
binding=json.loads(artifact['bytes'])
|
|
if binding['taskId']!=task or binding['commitSha']!=SHA or status['qaStatus']!='PENDING_INDEPENDENT_QA': raise ValueError('Artifact binding mismatch')
|
|
return artifact
|
|
|
|
def main():
|
|
if os.getuid()!=0 or Path('/.dockerenv').exists(): raise ValueError('Host only')
|
|
logs=Path('/opt/services/git/gitea/gitea/gitea/actions_log/parsa/canina')
|
|
if not any(ci_success(p.read_text()) for p in logs.glob('*/*.log')): raise ValueError('Exact deployed SHA CI success required')
|
|
actual=command(['docker','exec','canino_backend_stage','cat','/app/STAGE_TEST_ARTIFACT_SHA']).decode().strip()
|
|
deployed=json.loads(command(['docker','exec','canina-hermes','cat','/opt/data/editorial-v4/deployment.json']))
|
|
if actual!=SHA or deployed.get('commitSha')!=SHA: raise ValueError('Deployment mismatch')
|
|
# Strict private backend IP; no public bootstrap endpoint or direct DB writes.
|
|
networks=json.loads(command(['docker','inspect','--format','{{json .NetworkSettings.Networks}}','canino_backend_stage']))
|
|
ip=networks['stage_hermes_inventory_backend']['IPAddress']
|
|
import ipaddress
|
|
if not ipaddress.ip_address(ip).is_private: raise ValueError('Private backend required')
|
|
base='http://'+ip+':3000/api'
|
|
handle=json.loads(command(['docker','exec','canino_backend_stage','cat','/app/private-stage-test/'+SESSION+'.json']))
|
|
if handle['user']['role']!='SUPER_ADMIN' or handle['user']['id']=='pmo': raise ValueError('Independent reviewer required')
|
|
admin=handle['accessToken']; del handle
|
|
worker=command(['docker','exec','--user','hermes','canina-hermes','cat','/opt/data/editorial-v4/credentials/editorial-pmo-token']).decode().strip()
|
|
a=lambda route,body=None,method=None:http(base,admin,'admin/orchestration/'+route,body,method)
|
|
w=lambda route,body=None:http(base,worker,'internal/prepare-worker/'+route,body)
|
|
tasks=a('tasks')
|
|
prior=[t for t in tasks if t['id'].startswith('4a109')]
|
|
if len(prior)!=1: raise ValueError('Exact prior task missing')
|
|
prior=a('tasks/'+prior[0]['id'])
|
|
# Preserve all old unknown costs and fence previous failed attempts.
|
|
failed=[t for t in tasks if t.get('key','').startswith('editorial-v1:') and t['state']=='FAILED']
|
|
frozen={t['id']:a('tasks/'+t['id'])['budgetLedger'] for t in failed}
|
|
unknown=sum(sum(x['amountCents'] for x in ledger) for ledger in frozen.values())
|
|
if unknown!=60: raise ValueError('Prior unknown reservation must be 60')
|
|
p=w('editorial-proposals',proposal(prior))
|
|
if p['state']!='GATE1_PENDING' or p['version']!=2: raise ValueError('Fresh proposal only; never replay execution')
|
|
task=p['taskId']; route='tasks/'+task
|
|
approved=a(route+'/gates/1/decide',{'decision':'APPROVED','expectedVersion':p['version'],'idempotencyKey':SESSION+':gate1','expiresAt':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime(time.time()+450)),'notes':'Explicit owner-authorized bounded Stage acceptance only; no QA/publication/Production authority.'})
|
|
# Gate1 approval atomically queues PREPARE tasks; no second queue request.
|
|
if approved['state']!='READY': raise ValueError('Gate1 must enqueue READY')
|
|
# Exactly one process, as hermes. Installed runner has 120-second profile cap,
|
|
# CLI headroom30 and allowlisted timing evidence. Total330 fits window480.
|
|
code="import sys,json;sys.path.insert(0,'/opt/data/editorial-v4/runtime-package');import runner;from pathlib import Path;runner.run(Path('/opt/data'),sys.argv[1],total_seconds=330)"
|
|
try:
|
|
rc=subprocess.run(['docker','exec','--user','hermes','canina-hermes','python3','-c',code,task],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=430).returncode
|
|
except subprocess.TimeoutExpired:
|
|
# No second runner; read persisted state and fence only after its lease expires.
|
|
rc=1
|
|
status=w('editorial-proposals/'+task)
|
|
if status['state']=='RUNNING':
|
|
# Let last heartbeat lease expire, then fence the artifact-free unknown attempt.
|
|
time.sleep(31)
|
|
row=a(route)
|
|
runs=[r for r in row['runs'] if r['status']=='RUNNING']
|
|
if len(runs)!=1: raise ValueError('Ambiguous recovery')
|
|
a(route+'/editorial-failure',{'runId':runs[0]['id'],'expectedVersion':row['version'],'idempotencyKey':SESSION+':stopped','reason':'Bounded acceptance stopped; cost unknown and reservation retained; no retry.'})
|
|
status=w('editorial-proposals/'+task)
|
|
for old,ledger in frozen.items():
|
|
row=a('tasks/'+old)
|
|
if row['state']!='FAILED' or row['budgetLedger']!=ledger: raise ValueError('Prior fence changed')
|
|
row=a(route)
|
|
if sum(x['amountCents'] for x in row['budgetLedger'])!=20 or any(x['kind']=='RECONCILE' for x in row['budgetLedger']): raise ValueError('Reservation changed')
|
|
if rc: raise ValueError('Acceptance incomplete; fenced unknown20')
|
|
artifact=verify_artifact(status,task)
|
|
print(json.dumps({'taskId':task,'state':status['state'],'artifactSha256':artifact['sha256'],'qaStatus':status['qaStatus'],'priorUnknownReservedCents':60,'freshReservedCents':20,'commitSha':SHA}))
|
|
|
|
if __name__=='__main__':
|
|
try: main()
|
|
except Exception:
|
|
print('Stage acceptance stopped; no retry or cost reconciliation; read authenticated status',file=sys.stderr)
|
|
sys.exit(1)
|