79 lines
7.3 KiB
Python
79 lines
7.3 KiB
Python
"""Athena host only: scoped cache overlay with authenticated drain."""
|
|
import sys,json,subprocess,time,hashlib,shutil,os,importlib.util
|
|
from pathlib import Path
|
|
R=Path('/opt/athena-deck-dev/cache-activation-17e7017'); B=Path('/opt/athena-deck-dev/runtime'); S=B/'state'; C=Path('/opt/athena-deck-dev/source'); RT=S/'basalt-runtime'
|
|
TAG='athena-deck-standalone:cache-17e7017'; OLD='athena-deck-dev-cache-rollback-17e7017'; FILES=('basalt_worker.py','basalt_sources.json'); SETTINGS=('profiles.json','endpoint.json','audio-policy.json','cpu-partition.json','reasoning-budget.json')
|
|
def run(*a,**kw):return subprocess.run(list(map(str,a)),check=True,**kw)
|
|
def out(*a):return subprocess.check_output(list(map(str,a)),text=True)
|
|
def info():return json.loads(out('docker','inspect','athena-deck-dev'))[0]
|
|
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
|
|
def save(d):p=R/'receipt.json';p.write_text(json.dumps(d,indent=2));p.chmod(0o600)
|
|
def load():return json.loads((R/'receipt.json').read_text())
|
|
def sandbox(d):
|
|
c=dict(d['Config']);c.pop('Image',None);c.pop('Hostname',None);c['Env']=sorted(c.get('Env') or []);return dict(config=c,host=d['HostConfig'])
|
|
def guard(d):
|
|
assert d['authenticated_status']==200 and d['origin']=='http://192.168.1.212:8108'
|
|
assert 0<=time.time()-d['checked_at']<60 and d['state']=='stopped'
|
|
assert 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
|
|
|
|
def prepare():
|
|
bundle=json.load(sys.stdin);assert set(bundle)==set(FILES);assert not R.exists();d=info();assert d['HostConfig']['Memory']==64424509440
|
|
assert out('docker','image','inspect','--format','{{.Id}}',d['Config']['Image']).strip()==d['Image']
|
|
assert json.loads((RT/'ready.json').read_text())['version']=='0.4.0'
|
|
pin=out('git','-c','safe.directory='+str(RT/'source'),'-C',RT/'source','rev-parse','HEAD').strip();assert pin=='99dc78cb51ac43555c3feed9a1ec14f056d05035'
|
|
original=out('git','-c','safe.directory='+str(RT/'source'),'-C',RT/'source','show','HEAD:serve/config.py').encode()
|
|
assert original==(RT/'source/serve/config.py.bak-20261122-claude').read_bytes()
|
|
R.mkdir(mode=0o700);(R/'image/app').mkdir(parents=True);(R/'before').mkdir();(R/'tmp').mkdir();os.chown(R/'tmp',65534,65534)
|
|
for n,text in bundle.items():
|
|
p=R/'image/app'/n;p.write_text(text);p.chmod(0o644);shutil.copy2(C/n,R/'before'/n)
|
|
for n in SETTINGS:shutil.copy2(S/n,R/'before'/n)
|
|
for n in ('source/serve/config.py','engine-overrides.json','engine-overrides.README.txt'):shutil.copy2(RT/n,R/'before'/Path(n).name)
|
|
(R/'image/Dockerfile').write_text('FROM '+d['Config']['Image']+'\nUSER root\nCOPY app/ /app/\nUSER 65534:65534\n')
|
|
with (R/'build.log').open('w') as log:run('docker','build','--network','none','--pull=false','-t',TAG,R/'image',stdout=log,stderr=subprocess.STDOUT,timeout=180)
|
|
probe="from pathlib import Path\nimport tempfile\nfrom server import Server\nwith tempfile.TemporaryDirectory() as tmp:\n s=Server(0,state_dir=Path(tmp));s.endpoint.close();s.video.close();s.dashboard.close();s.server_close()\nprint('Full isolated Server constructor passed')"
|
|
run('docker','run','--rm','--runtime','runc','--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(R/'tmp')+',dst=/test-tmp','--entrypoint','python3',TAG,'-B','-c',probe,timeout=60)
|
|
save(dict(phase='prepared',container=d['Id'],image_before=d['Image'],tag_before=d['Config']['Image'],image_after=out('docker','image','inspect','--format','{{.Id}}',TAG).strip(),settings={n:sha(S/n) for n in SETTINGS},sandbox=sandbox(d),pin=pin,source_before={n:sha(C/n) for n in FILES},source_after={n:sha(R/'image/app'/n) for n in FILES}))
|
|
print(json.dumps(dict(prepared=True,image=TAG,isolated_server=True)))
|
|
def endpoint_restore():
|
|
old=json.loads((R/'before/endpoint.json').read_text());now=json.loads((S/'endpoint.json').read_text());now['autostart']=old['autostart'];assert now==old
|
|
shutil.copy2(R/'before/endpoint.json',S/'endpoint.json')
|
|
def installer():
|
|
spec=importlib.util.spec_from_file_location('install',C/'deploy/install.py');m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m);return m
|
|
|
|
def apply():
|
|
guard(json.load(sys.stdin));a=load();d=info();assert a['phase']=='prepared' and d['Id']==a['container'] and d['Image']==a['image_before']
|
|
assert all(sha(S/n)==a['settings'][n] for n in SETTINGS if n!='endpoint.json');assert all(sha(C/n)==a['source_before'][n] for n in FILES)
|
|
endpoint_restore();a['phase']='applying';save(a)
|
|
run('docker','stop','--timeout','45','athena-deck-dev');run('docker','rename','athena-deck-dev',OLD)
|
|
for n in FILES:shutil.copy2(R/'image/app'/n,C/n)
|
|
m=installer();cfg=m.load_manifest(B);assert cfg['image']==a['tag_before'];cfg.update(image=TAG,previous_image=a['tag_before']);m.launch(cfg);m.ready(cfg);m.write_manifest(B,cfg)
|
|
deadline=time.monotonic()+100
|
|
while info()['State'].get('Health',{}).get('Status')=='starting' and time.monotonic()<deadline:time.sleep(1)
|
|
d=info();assert d['State']['Health']['Status']=='healthy' and d['Image']==a['image_after'];assert sandbox(d)==a['sandbox'];assert all(sha(S/n)==a['settings'][n] for n in SETTINGS)
|
|
a['phase']='activated';save(a);print(json.dumps(dict(activated=True,image=d['Image'],settings_unchanged=True)))
|
|
|
|
def unhook():
|
|
guard(json.load(sys.stdin));a=load();assert a['phase']=='activated'
|
|
p=RT/'source/serve/config.py';assert sha(p)==sha(R/'before/config.py')
|
|
backup=RT/'source/serve/config.py.bak-20261122-claude';assert backup.read_bytes()==out('git','-c','safe.directory='+str(RT/'source'),'-C',RT/'source','show','HEAD:serve/config.py').encode()
|
|
# Normal stop removes worker.json; prove the already observed launch and the
|
|
# immutable active image inputs instead of requiring that deleted file.
|
|
recipe=json.loads((C/'basalt_sources.json').read_text());assert recipe['tuning']['conversation_cache_mib']==0 and recipe['tuning']['conversation_cache_disk_mib']==16384
|
|
assert all(sha(C/n)==a['source_after'][n] for n in FILES)
|
|
lines=[x for x in (S/'basalt-worker/server.log').read_text().splitlines() if 'ram-cache=' in x]
|
|
assert lines and all(x in lines[-1] for x in ('ctx=262144','kv=int8','ram-cache=0MiB','disk-cache=16384MiB','batch=2'))
|
|
shutil.copy2(backup,p)
|
|
for n in ('engine-overrides.json','engine-overrides.README.txt'):
|
|
assert sha(RT/n)==sha(R/'before'/n);(RT/n).unlink()
|
|
a['phase']='unhooked';save(a);print(json.dumps(dict(unhooked=True,upstream_config_restored=True)))
|
|
def rollback():
|
|
guard(json.load(sys.stdin));a=load()
|
|
run('docker','stop','--timeout','45','athena-deck-dev');run('docker','rm','athena-deck-dev')
|
|
for n in FILES:shutil.copy2(R/'before'/n,C/n)
|
|
for n in ('source/serve/config.py','engine-overrides.json','engine-overrides.README.txt'):shutil.copy2(R/'before'/Path(n).name,RT/n)
|
|
endpoint_restore();run('docker','rename',OLD,'athena-deck-dev');run('docker','start','athena-deck-dev')
|
|
m=installer();cfg=m.load_manifest(B);cfg['image']=a['tag_before'];m.write_manifest(B,cfg);a['phase']='rolled_back';save(a);print('Rolled back; model restoration required')
|
|
if __name__=='__main__':
|
|
assert '--go' in sys.argv;globals()[sys.argv[1]]()
|