132 lines
8.2 KiB
Python
132 lines
8.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Controlled gateway-only deployment from this workspace; ordinary shell required for SSH.
|
|
Default stages/tests only. --apply backs up and restarts ONLY lan-voice-gateway.service.
|
|
"""
|
|
import argparse
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import subprocess
|
|
|
|
REMOTE = r'''
|
|
import base64, hashlib, io, json, os, shutil, ssl, subprocess, sys, tempfile, time, unittest, urllib.request
|
|
from pathlib import Path
|
|
ROOT = Path('/home/gorios-spark-2/lan-voice')
|
|
UNIT = 'lan-voice-gateway.service'
|
|
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 decode(name): return base64.b64decode(bundle[name])
|
|
def atomic(path, content):
|
|
tmp=path.with_name(path.name+'.v040.tmp')
|
|
tmp.write_bytes(content); tmp.chmod(0o600); tmp.replace(path)
|
|
original=(ROOT/'gateway.py').read_bytes()
|
|
base_source = original
|
|
if hashlib.sha256(original).hexdigest()!=base_hash:
|
|
# A follow-up fix may replace only the exact version deployed by this script.
|
|
if not previous or hashlib.sha256(original).hexdigest()!=previous.get('gateway_sha256'):
|
|
raise RuntimeError('live_gateway_changed_refusing_patch')
|
|
backup_source = Path(previous['backup']).resolve()
|
|
if not backup_source.is_relative_to((ROOT/'.runtime/backups').resolve()):
|
|
raise RuntimeError('invalid_backup_path')
|
|
base_source = (backup_source/'gateway.py').read_bytes()
|
|
if hashlib.sha256(base_source).hexdigest()!=base_hash:
|
|
# A second follow-up backup contains a patched version. The immutable initial
|
|
# base snapshot is saved separately by the workspace deployment record.
|
|
initial = Path(previous.get('initial_backup', previous['backup'])).resolve()
|
|
if not initial.is_relative_to((ROOT/'.runtime/backups').resolve()): raise RuntimeError('invalid_backup_path')
|
|
base_source = (initial/'gateway.py').read_bytes()
|
|
if hashlib.sha256(base_source).hexdigest()!=base_hash: raise RuntimeError('base_backup_mismatch')
|
|
if apply and health().get('busy'): raise RuntimeError('gateway_busy_no_restart')
|
|
with tempfile.TemporaryDirectory(prefix='voice-v040-stage-') as folder:
|
|
stage=Path(folder)
|
|
for path in ROOT.glob('*.py'): shutil.copy2(path,stage/path.name)
|
|
shutil.copytree(ROOT/'tests',stage/'tests',ignore=shutil.ignore_patterns('__pycache__'))
|
|
for name in ('web','personas'):
|
|
if (ROOT/name).exists(): (stage/name).symlink_to(ROOT/name,target_is_directory=True)
|
|
(stage/'.runtime').mkdir()
|
|
if (ROOT/'.runtime/personas').exists(): (stage/'.runtime/personas').symlink_to(ROOT/'.runtime/personas',target_is_directory=True)
|
|
# Only gateway.py is patched. The other production file is enum/TTL validation.
|
|
(stage/'gateway.py').write_bytes(base_source)
|
|
(stage/'gateway.patch').write_bytes(decode('gateway.patch'))
|
|
subprocess.run(['patch','--batch','--fuzz=0','-p0','-i','gateway.patch'],cwd=stage,check=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
|
(stage/'face_context.py').write_bytes(decode('face_context.py'))
|
|
for name in ('test_face_context.py','test_gateway_reply_face.py'): (stage/'tests'/name).write_bytes(decode(name))
|
|
runner = """
|
|
import sys,unittest
|
|
sys.path[:0]=['.','tests']
|
|
modules=['test_gateway','test_continuity','test_history','test_v08','test_debug','test_segmentation','test_guests','test_personas','test_face_context','test_gateway_reply_face']
|
|
suite=unittest.TestSuite(unittest.defaultTestLoader.loadTestsFromName(name) for name in modules)
|
|
result=unittest.TextTestRunner(verbosity=2).run(suite)
|
|
raise SystemExit(not result.wasSuccessful())
|
|
"""
|
|
result=subprocess.run([sys.executable,'-c',runner],cwd=stage,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=90)
|
|
# Synthetic tests only. Never attach runtime reports, tokens, prompts or microphone audio.
|
|
if result.returncode:
|
|
print(json.dumps({'status':'tests_failed','test_output':result.stdout.decode(errors='replace')}))
|
|
raise SystemExit(1)
|
|
summary={'status':'tests_passed','test_output':result.stdout.decode(errors='replace'),'applied':False}
|
|
patched=(stage/'gateway.py').read_bytes()
|
|
if apply:
|
|
# Recheck after staged tests: no overwriting concurrent edits or interrupting an active user.
|
|
if (ROOT/'gateway.py').read_bytes()!=original: raise RuntimeError('gateway_changed_during_tests')
|
|
if health().get('busy'): raise RuntimeError('gateway_busy_after_tests_no_restart')
|
|
backup=ROOT/'.runtime/backups'/time.strftime('voice-v040-%Y%m%d-%H%M%S')
|
|
backup.mkdir(parents=True,mode=0o700)
|
|
existed={name:(ROOT/name).exists() for name in ('gateway.py','face_context.py')}
|
|
for name,present in existed.items():
|
|
if present: shutil.copy2(ROOT/name,backup/name)
|
|
(backup/'manifest.json').write_text(json.dumps(existed)); (backup/'manifest.json').chmod(0o600)
|
|
try:
|
|
atomic(ROOT/'face_context.py',decode('face_context.py'))
|
|
atomic(ROOT/'gateway.py',patched)
|
|
subprocess.run(['systemctl','--user','restart',UNIT],check=True,timeout=30,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
|
healthy=False
|
|
for attempt in range(15):
|
|
try:
|
|
if health().get('status')=='ok': healthy=True;break
|
|
except Exception: pass
|
|
time.sleep(1)
|
|
if not healthy: raise RuntimeError('gateway_health_failed')
|
|
except BaseException:
|
|
for name,present in existed.items():
|
|
if present: atomic(ROOT/name,(backup/name).read_bytes())
|
|
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,initial_backup=previous.get('initial_backup', previous['backup']) if previous else str(backup),backup=str(backup),gateway_sha256=hashlib.sha256(patched).hexdigest(),face_context_sha256=hashlib.sha256(decode('face_context.py')).hexdigest(),health='ok')
|
|
print(json.dumps(summary))
|
|
'''
|
|
|
|
|
|
def main():
|
|
parser=argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--apply',action='store_true')
|
|
args=parser.parse_args()
|
|
root=Path(__file__).resolve().parents[1]
|
|
bundle={name:base64.b64encode((root/'backend'/name).read_bytes()).decode() for name in
|
|
('gateway.patch','face_context.py','test_face_context.py','test_gateway_reply_face.py')}
|
|
record=root/'logs/voice-investigation/gateway-deploy.json'
|
|
previous=json.loads(record.read_text()) if record.exists() else None
|
|
payload='previous='+repr(previous)+'\n'+'bundle='+repr(bundle)+'\nbase_hash='+repr((root/'backend/gateway-base.sha256').read_text().strip())+'\napply='+repr(args.apply)+'\n'+REMOTE
|
|
remote=('cd /home/gorios-spark-2/lan-voice && '
|
|
'if [ -x .venv/bin/python ]; then exec .venv/bin/python -; '
|
|
'elif [ -x venv/bin/python ]; then exec venv/bin/python -; else exec python3 -; fi')
|
|
result=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61',remote],input=payload.encode(),capture_output=True,timeout=180)
|
|
directory=root/'logs/voice-investigation';directory.mkdir(parents=True,exist_ok=True)
|
|
if result.stdout:
|
|
data=json.loads(result.stdout)
|
|
if args.apply and data.get('applied') and record.exists():
|
|
(directory/'gateway-deploy-previous.json').write_bytes(record.read_bytes())
|
|
name = ('gateway-deploy.json' if data.get('applied') else 'gateway-apply-failed.json') if args.apply else 'gateway-staged-tests.json'
|
|
(directory/name).write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n')
|
|
print(f'Gateway {data["status"]}; details saved under logs/voice-investigation/')
|
|
if result.stderr: print('Remote execution stderr present; no raw payload printed.')
|
|
raise SystemExit(result.returncode)
|
|
|
|
|
|
if __name__=='__main__':
|
|
raise SystemExit('Historical v040 patch deployment disabled; use scripts/deploy-gateway-source.py for canonical provider + emotion source.')
|