#!/usr/bin/env python3 """Athena host: authorized shared-Qwen Deck + existing static atelier update.""" import argparse,difflib,hashlib,importlib.util,json,shutil,subprocess,time from pathlib import Path ROOT=Path('/opt/athena-deck-dev/shared-qwen-activation-v2');BASE=Path('/opt/athena-deck-dev/runtime');STATE=BASE/'state';SOURCE=Path('/opt/athena-deck-dev/source');HELPER=Path('/opt/athena-deck-docker-helper/stimmatelier/app.js') IMAGE='athena-deck-standalone:shared-qwen';UI_STAGE='athena-stimmatelier:shared-qwen-candidate';UI_NAME='athena-stimmatelier' FILES=('audio_policy.py','inference.py','tts_test.py','tts_worker.py','voxcpm_test.py','server.py','voice-ui.js','deploy/stimmatelier/app.js','deploy/stimmatelier/index.html') SETTINGS=('profiles.json','endpoint.json','audio-policy.json','cpu-partition.json','reasoning-budget.json') HOST_KEYS=('NetworkMode','ReadonlyRootfs','CapDrop','CapAdd','SecurityOpt','PidsLimit','Memory','MemorySwap','NanoCpus','RestartPolicy','PortBindings','Mounts','LogConfig','Tmpfs') def info(name='athena-deck-dev'):return json.loads(subprocess.check_output(['docker','inspect',name],text=True))[0] def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest() def save(a): p=ROOT/'activation.json';p.write_text(json.dumps(a,indent=2));p.chmod(0o600);assert json.loads(p.read_text())==a def image_hashes(name,files): code='from pathlib import Path;import hashlib,json;print(json.dumps({n:hashlib.sha256((Path("/app")/n).read_bytes()).hexdigest() for n in '+repr(tuple(files))+'}))' return json.loads(subprocess.check_output(['docker','exec',name,'python3','-B','-c',code],text=True)) def build(context,tag): with (context/'build.log').open('w') as f:subprocess.run(['docker','build','--network','none','--pull=false','-t',tag,context],check=True,stdout=f,stderr=subprocess.STDOUT,timeout=180) def prepare(): assert not (ROOT/'activation.json').exists() d=info();ui=info(UI_NAME) for x in (d,ui):assert subprocess.check_output(['docker','image','inspect','--format','{{.Id}}',x['Config']['Image']],text=True).strip()==x['Image'] h=ui['HostConfig'];assert h['NetworkMode']=='none' and h['ReadonlyRootfs'] and h['CapDrop']==['ALL'] and not h.get('CapAdd') and not h.get('DeviceRequests') and not h.get('Devices') and not h.get('Privileged') assert h.get('Mounts')==[dict(Type='bind',Source=str(STATE/'stimmatelier-ui'),Target='/data')] assert ui['Config']['User']=='65534:65534' and ui['Config']['Entrypoint']==['python3','/app/app.py'] and not ui['Config']['Cmd'] before={n:sha(SOURCE/n) for n in FILES};after={n:sha(ROOT/'app'/n) for n in FILES} assert image_hashes('athena-deck-dev',FILES)==before ui_hashes=image_hashes(UI_NAME,['app.js','index.html']) assert sha(HELPER)==ui_hashes['app.js'] and sha(HELPER.parent/'index.html')==ui_hashes['index.html'] assert after['deploy/stimmatelier/index.html']==ui_hashes['index.html'],'Preserve the actual live atelier markup' diff=[] for n in FILES: p=ROOT/'before'/n;p.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(SOURCE/n,p) (ROOT/'app'/n).chmod(0o644) diff.extend(difflib.unified_diff((SOURCE/n).read_text().splitlines(True),(ROOT/'app'/n).read_text().splitlines(True),fromfile=n+' (live)',tofile=n+' (candidate)')) (ROOT/'candidate.diff').write_text(''.join(diff));shutil.copy2(HELPER,ROOT/'helper-app.before.js') (ROOT/'Dockerfile').write_text('FROM '+d['Config']['Image']+'\nUSER root\nCOPY app/ /app/\nUSER 65534:65534\n') (ROOT/'.dockerignore').write_text('*\n!Dockerfile\n!app/\n!app/**\n') build(ROOT,IMAGE) probe="from pathlib import Path;import tempfile;from server import Server;from stt import qwen_asr_request;t=tempfile.TemporaryDirectory();s=Server(0,state_dir=Path(t.name));assert s.voxcpm_tests.shared_tts is s.tts_tests;assert s.tts_tests.acquire==s.scheduler.tts_reservation;assert '' in qwen_asr_request(b'fixture','de')['messages'][-1]['content'];s.endpoint.close();s.video.close();s.dashboard.close();s.server_close();t.cleanup();print('Shared Qwen image: full isolated constructor and preserved ASR passed')" subprocess.run(['docker','run','--rm','--network','none','--read-only','--user','65534:65534','--memory','512m','--pids-limit','256','--cap-drop','ALL','-e','NVIDIA_VISIBLE_DEVICES=void','-e','DECK_REQUIRE_SETUP=0','-e','DECK_NETWORK_MODE=disabled','-e','TMPDIR=/test-tmp','--mount','type=bind,src='+str(STATE/'basalt-runtime/tmp')+',dst=/test-tmp','--entrypoint','python3',IMAGE,'-B','-c',probe],check=True,timeout=45) u=ROOT/'ui';u.mkdir();shutil.copy2(ROOT/'app/deploy/stimmatelier/app.js',u/'app.js') (u/'Dockerfile').write_text('FROM '+ui['Config']['Image']+'\nUSER root\nCOPY app.js /app/app.js\nUSER 65534:65534\n');build(u,UI_STAGE) subprocess.run(['docker','run','--rm','--network','none','--read-only','--entrypoint','python3',UI_STAGE,'-B','-c',"import ast;from pathlib import Path;ast.parse(Path('/app/app.py').read_text());assert 'voice/select' in Path('/app/app.js').read_text();print('Static atelier candidate checked')"],check=True,timeout=20) assert info()['State']['StartedAt']==d['State']['StartedAt'] and info(UI_NAME)['Id']==ui['Id'] image_id=subprocess.check_output(['docker','image','inspect','--format','{{.Id}}',IMAGE],text=True).strip();ui_image_id=subprocess.check_output(['docker','image','inspect','--format','{{.Id}}',UI_STAGE],text=True).strip() save(dict(phase='prepared',image_before=d['Config']['Image'],image_id_before=d['Image'],image_id_after=image_id,ui_image_id_after=ui_image_id,started_before=d['State']['StartedAt'],source_before=before,source_after=after,config=json.loads((BASE/'installation.json').read_text()),settings={n:(STATE/n).read_text() for n in SETTINGS},ui_before=ui,ui_before_hashes=ui_hashes)) print('Both images prepared; protected live processes unchanged',flush=True) def launch_ui(a): old=a['ui_before'];h=old['HostConfig'];c=old['Config'] args=['docker','run','-d','--name',UI_NAME,'--network','none','--read-only','--cap-drop','ALL','--security-opt','no-new-privileges:true','--restart',h['RestartPolicy']['Name'],'--pids-limit',str(h['PidsLimit']),'--memory',str(h['Memory']),'--memory-swap',str(h['MemorySwap']),'--cpus',str(h['NanoCpus']/1e9),'--user',c['User'],'--workdir',c['WorkingDir'],'--hostname',c['Hostname'],'--mount','type=bind,src='+str(STATE/'stimmatelier-ui')+',dst=/data'] if h.get('LogConfig',{}).get('Type'): args+=['--log-driver',h['LogConfig']['Type']] for k,v in h['LogConfig'].get('Config',{}).items():args+=['--log-opt',k+'='+v] for k,v in c.get('Labels',{}).items():args+=['--label',k+'='+v] for v in c.get('Env',[]):args+=['-e',v] args += [c['Image']] # The overlay inherits the complete original entrypoint/Cmd. subprocess.run(args,check=True,stdout=subprocess.DEVNULL) def apply(): a=json.loads((ROOT/'activation.json').read_text());assert a['phase']=='prepared' d=json.loads((ROOT/'drained.json').read_text());assert 0<=time.time()-d['checked_at']<60 and d['state']=='stopped' and type(d['active_requests']) is int and d['active_requests']==0 assert all(type(d['scheduler'][k]) is int and d['scheduler'][k]==0 for k in ('active_requests','waiting_requests','tts_waiting_requests','stt_waiting_requests')) and d['scheduler']['switching'] is False assert info()['Image']==a['image_id_before'] and info(UI_NAME)['Id']==a['ui_before']['Id'] assert subprocess.check_output(['docker','image','inspect','--format','{{.Id}}',IMAGE],text=True).strip()==a['image_id_after'] assert subprocess.check_output(['docker','image','inspect','--format','{{.Id}}',UI_STAGE],text=True).strip()==a['ui_image_id_after'] assert all(sha(SOURCE/n)==a['source_before'][n] for n in FILES) and sha(HELPER)==a['ui_before_hashes']['app.js'] assert all((STATE/n).read_text()==a['settings'][n] for n in SETTINGS if n!='endpoint.json') subprocess.run(['docker','stop','--timeout','45','athena-deck-dev'],check=True) assert not subprocess.check_output(['nvidia-smi','--query-compute-apps=pid','--format=csv,noheader,nounits'],text=True).strip() for n in FILES:shutil.copy2(ROOT/'app'/n,SOURCE/n) (STATE/'endpoint.json').write_text(a['settings']['endpoint.json']) subprocess.run(['docker','rm','athena-deck-dev'],check=True) spec=importlib.util.spec_from_file_location('deck_install',SOURCE/'deploy/install.py');assert spec and spec.loader;module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) config=dict(a['config'],image=IMAGE,previous_image=a['image_before']);module.launch(config);module.ready(config) deadline=time.monotonic()+90 while info()['State'].get('Health',{}).get('Status')=='starting' and time.monotonic()