Files
baji-vc/scripts/deploy-gateway-source.py
T

110 lines
8.5 KiB
Python

#!/usr/bin/env python3
"""Canonical gateway/ deployment fenced to observed provider source. Default: isolated tests only."""
import argparse, base64, hashlib, json, subprocess
from pathlib import Path
REMOTE=r'''
import base64,hashlib,json,os,shutil,ssl,stat,subprocess,sys,tempfile,time,urllib.request,re
from pathlib import Path
root=Path('/home/gorios-spark-2/lan-voice');unit='lan-voice-gateway.service'
def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() if path.exists() else None
def health():
ctx=ssl.create_default_context(cafile=str(root/'.runtime/gateway-cert.pem'))
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
with opener.open('https://192.168.31.61:5011/health',timeout=3) as r:return json.load(r)
def atomic(path,content,mode):
path.parent.mkdir(parents=True,exist_ok=True)
tmp=path.with_name(path.name+'.v050.tmp');tmp.write_bytes(content);tmp.chmod(mode);tmp.replace(path)
def live_hashes():return {name:digest(root/name) for name in deploy_files}
original=live_hashes()
if original!=expected:
print(json.dumps({'status':'source_changed','mismatches':{name:{'expected':expected[name],'actual':original[name]} for name in expected if expected[name]!=original[name]},'applied':False}));raise SystemExit(1)
# Preserve complete unit and private environment loading relationships on server only.
unit_text=subprocess.check_output(['systemctl','--user','cat',unit])
fragment=subprocess.check_output(['systemctl','--user','show',unit,'-p','FragmentPath','--value'],text=True).strip()
dropins=subprocess.check_output(['systemctl','--user','show',unit,'-p','DropInPaths','--value'],text=True).split()
private_files=[Path(fragment)]+[Path(p) for p in dropins]+list((root/'.runtime').glob('*.env'))
for name in re.findall(r'^EnvironmentFile=-?(.+)$',unit_text.decode(),re.M):
p=Path(name.strip().strip('"'));assert p.is_absolute();private_files.append(p)
private_files=sorted(set(p for p in private_files if p.is_file()))
private_hashes={str(p):digest(p) for p in private_files}
def relation_unchanged():
return subprocess.check_output(['systemctl','--user','cat',unit])==unit_text and all(digest(Path(p))==h for p,h in private_hashes.items())
if apply and health().get('busy'): raise RuntimeError('gateway_busy_no_restart')
with tempfile.TemporaryDirectory(prefix='voice-v050-stage-') as folder:
stage=Path(folder)
for name,content in bundle.items():
path=stage/name;path.parent.mkdir(parents=True,exist_ok=True);path.write_bytes(base64.b64decode(content))
test_start=time.perf_counter()
result=subprocess.run([sys.executable,str(stage/'scripts/check-archive.py'),'--vad-model',str(root/'models/silero_vad.onnx')],cwd=stage,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=120,env={**os.environ,'PYTHONDONTWRITEBYTECODE':'1'})
summary={'status':'tests_passed' if result.returncode==0 else 'tests_failed','test_output':result.stdout.decode(errors='replace'),'test_elapsed_ms':round((time.perf_counter()-test_start)*1000,2),'applied':False,'expected_hashes':original}
if result.returncode: print(json.dumps(summary));raise SystemExit(1)
if apply:
if live_hashes()!=original:raise RuntimeError('source_changed_during_tests')
if not relation_unchanged():raise RuntimeError('environment_or_unit_changed_during_tests')
if health().get('busy'):raise RuntimeError('gateway_busy_after_tests_no_restart')
backup=root/'.runtime/backups'/time.strftime('voice-v050-%Y%m%d-%H%M%S');backup.mkdir(parents=True,mode=0o700)
# Save all actual runtime Python sources/tests, modes, plus unit/env privately. No logs/history/audio copied.
for path in list(root.glob('*.py'))+list((root/'tests').glob('*.py')):
dst=backup/path.relative_to(root);dst.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(path,dst)
for i,path in enumerate(private_files):
dst=backup/'private'/str(i);dst.parent.mkdir(parents=True,exist_ok=True,mode=0o700);shutil.copy2(path,dst)
(backup/'unit.txt').write_bytes(unit_text);(backup/'unit.txt').chmod(0o600)
existed={name:(root/name).exists() for name in deploy_files}
modes={name:stat.S_IMODE((root/name).stat().st_mode) if existed[name] else 0o644 for name in deploy_files}
(backup/'manifest.json').write_text(json.dumps(existed));(backup/'manifest.json').chmod(0o600)
(backup/'metadata.json').write_text(json.dumps({'modes':modes,'private_files':{str(p):{'backup':'private/'+str(i),'sha256':private_hashes[str(p)],'mode':stat.S_IMODE(p.stat().st_mode)} for i,p in enumerate(private_files)},'unit_sha256':hashlib.sha256(unit_text).hexdigest()}));(backup/'metadata.json').chmod(0o600)
if live_hashes()!=original or not relation_unchanged():raise RuntimeError('source_or_environment_changed_before_apply')
if health().get('busy'):raise RuntimeError('gateway_busy_before_apply_no_restart')
try:
for name in deploy_files:atomic(root/name,(stage/name).read_bytes(),modes[name])
subprocess.run(['systemctl','--user','restart',unit],check=True,timeout=30,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
for attempt in range(15):
try:
if health().get('status')=='ok':break
except Exception:pass
time.sleep(1)
else:raise RuntimeError('gateway_health_failed')
assert relation_unchanged(),'environment_loading_changed'
deployed=live_hashes()
assert deployed=={name:hashlib.sha256((stage/name).read_bytes()).hexdigest() for name in deploy_files}
except BaseException:
# Never overwrite an edit made by another operator, even while rolling back a failed restart.
staged_hashes={name:hashlib.sha256((stage/name).read_bytes()).hexdigest() for name in deploy_files}
if any(value not in (original[name],staged_hashes[name]) for name,value in live_hashes().items()):
raise RuntimeError('concurrent_source_change_refusing_automatic_rollback')
for name,present in existed.items():
if present:atomic(root/name,(backup/name).read_bytes(),modes[name])
elif (root/name).exists():(root/name).unlink()
subprocess.run(['systemctl','--user','restart',unit],timeout=30,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
raise
summary.update(status='deployed',applied=True,backup=str(backup),hashes=deployed,modes=modes,environment_unchanged=True,unit_sha256=hashlib.sha256(unit_text).hexdigest(),health='ok',restart_unit=unit)
print(json.dumps(summary))
'''
def main():
root=Path(__file__).resolve().parents[1]
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--apply',action='store_true');args=parser.parse_args()
source=root/'gateway';manifest=json.loads((source/'SOURCE_MANIFEST.json').read_text())
baseline=manifest['provider_baseline']['files']
files=sorted(set(baseline)|{p.relative_to(source).as_posix() for p in source.glob('*.py')}|{p.relative_to(source).as_posix() for p in (source/'tests').glob('*.py')})
assert all(n.endswith('.py') and not Path(n).is_absolute() and '..' not in Path(n).parts for n in files)
expected={name:baseline.get(name) for name in files}
record=root/'logs/voice-investigation/gateway-emotion-deploy.json'
if record.exists():
previous=json.loads(record.read_text())
if previous.get('applied'):expected=previous['hashes'];assert set(expected)==set(files)
bundle={}
for path in source.rglob('*'):
name=path.relative_to(source).as_posix()
if not path.is_file() or any(x.startswith('.') or x in ('__pycache__','models','logs') for x in path.relative_to(source).parts):continue
if path.suffix in ('.py','.json','.js','.html','.css'):bundle[name]=base64.b64encode(path.read_bytes()).decode()
payload='import json\nbundle='+repr(bundle)+'\ndeploy_files='+repr(files)+'\nexpected='+repr(expected)+'\napply='+repr(args.apply)+'\ntry:\n exec('+repr(REMOTE)+')\nexcept Exception as error:\n print(json.dumps({"status":"blocked","error_type":type(error).__name__,"reason":str(error) if isinstance(error,RuntimeError) else "remote_execution_error","applied":False}))\n raise SystemExit(1)\n'
command='cd /home/gorios-spark-2/lan-voice && exec .venv/bin/python -'
r=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61',command],input=payload.encode(),capture_output=True,timeout=210)
if r.stdout:
data=json.loads(r.stdout);out=record if data.get('applied') else record.with_name('gateway-emotion-staged.json');out.parent.mkdir(parents=True,exist_ok=True)
if out.exists() and data.get('applied'):out.with_name('gateway-emotion-deploy-previous.json').write_bytes(out.read_bytes())
out.write_text(json.dumps(data,indent=2)+'\n');print('Gateway '+data['status'])
if r.stderr:print('Remote stderr present (content suppressed); no concurrent hash check bypassed.')
raise SystemExit(r.returncode)
if __name__=='__main__':main()