Files
Athena-Deck/docs/maintenance/strata-pipeline-config-2026-10-28/activate.py
T

136 lines
7.3 KiB
Python

"""One authorized Athena-host rollout. SSH stdin carries the managed key in memory.
prepare builds a three-file overlay of the live image without touching production.
apply requires the normal GUI endpoint drain; no credential/session bypass exists.
Private rollback files remain outside Git in this host's maintenance directory.
"""
import argparse
import copy
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import subprocess
import sys
import time
sys.path.insert(0, '/opt/athena-deck-dev/strata-027-preparation-20261027')
import host_support as host # pyright: ignore[reportMissingImports] -- Athena-host helper
STAGE = Path('/opt/athena-deck-dev/strata-pipeline-config-20261028')
FILES = ('profiles.py', 'strata_worker.py', 'profiles-ui.js')
SOURCE = Path('/opt/athena-deck-dev/source')
TAG = 'athena-deck-standalone:strata-pipeline-config-20261028'
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def save(value):
path = STAGE / 'record.json'
path.write_text(json.dumps(value, indent=2) + '\n')
path.chmod(0o600)
assert json.loads(path.read_text()) == value
def atomic(path, data):
stat = path.stat()
temp = path.with_name(path.name + '.pipeline.tmp')
with temp.open('xb') as stream:
stream.write(data)
os.chmod(temp, stat.st_mode & 0o777)
os.chown(temp, stat.st_uid, stat.st_gid)
temp.replace(path)
assert path.read_bytes() == data
def prepare(data):
manifest, info = host.installed()
assert set(data['files']) == set(data['expected']) == set(FILES)
for name in FILES:
assert digest(SOURCE / name) == data['expected'][name], 'Concurrent canonical source change'
actual = json.loads(subprocess.check_output(['docker', 'exec', manifest['name'], 'python3', '-c',
'import hashlib,json;from pathlib import Path;print(json.dumps({n:hashlib.sha256((Path("/app")/n).read_bytes()).hexdigest() for n in ' + repr(FILES) + '}))'], text=True))
assert actual == data['expected'], 'Running app differs from reviewed source'
STAGE.mkdir(mode=0o700)
(STAGE / 'before').mkdir(mode=0o700)
(STAGE / 'image').mkdir(mode=0o700)
for name in FILES:
(STAGE / 'before' / name).write_bytes((SOURCE / name).read_bytes())
(STAGE / 'image' / name).write_text(data['files'][name])
for name in ('profiles.json', 'endpoint.json'):
(STAGE / 'before' / name).write_bytes((host.STATE / name).read_bytes())
(STAGE / 'before' / name).chmod(0o600)
worker = json.loads((host.STATE / 'strata-worker/worker.json').read_text())
rows = json.loads((STAGE / 'before/profiles.json').read_text())
profile = next(r for r in rows if r['api_id'] == worker['model_name'])
assert profile['parameters']['slots'] == 2 and profile['parameters']['chat_runtime'] == 'strata'
record = dict(manifest_before=manifest, image_before=info['Image'], started_before=info['State']['StartedAt'],
source_before=actual, source_after={n:digest(STAGE/'image'/n) for n in FILES},
settings_before=host.settings_hashes(), profile_id=profile['id'],
worker_before={n:worker.get(n) for n in ('args','gpu','gpu_order','layer_split','parallel','model_name','env')},
prepared=False, applied=False)
(STAGE / 'image/Dockerfile').write_text('FROM ' + info['Config']['Image'] + '\nUSER root\n' +
''.join('COPY --chmod=0644 ' + n + ' /app/' + n + '\n' for n in FILES) + 'USER 65534:65534\n')
subprocess.run(['docker','build','--network','none','--pull=false','-t',TAG,str(STAGE/'image')],check=True)
record['image_after'] = subprocess.check_output(['docker','image','inspect','--format','{{.Id}}',TAG],text=True).strip()
probe = 'import json;from profiles import chat_parameters;from strata_worker import StrataWorker;p=json.load(__import__("sys").stdin);p.update(strata_batch_groups="auto",strata_batch_mtp=False);p=chat_parameters(p);assert StrataWorker.parallel_arguments(2,p["strata_batch_groups"],p["strata_batch_mtp"])==["--batch-groups","auto"];print("Profile validation and worker argument generation passed")'
subprocess.run(['docker','run','--rm','--network','none','--cpus','0.5','--memory','512m','--read-only','--entrypoint','python3','-i',TAG,'-c',probe],input=json.dumps(profile['parameters']),text=True,check=True)
_, after = host.installed()
assert after['Image'] == record['image_before'] and after['State']['StartedAt'] == record['started_before']
record['prepared'] = True
save(record)
print(json.dumps({'prepared':True,'production_unchanged':True,'image':record['image_after']}))
def apply(data):
record = json.loads((STAGE/'record.json').read_text())
assert record['prepared'] and not record['applied']
manifest, info = host.installed()
assert manifest == record['manifest_before'] and info['Image'] == record['image_before']
host.assert_drained(data['key'],check_gpus=False)
assert all(digest(SOURCE/n) == record['source_before'][n] for n in FILES)
hashes = host.settings_hashes()
assert all(hashes[n] == v for n,v in record['settings_before'].items() if n != 'endpoint.json')
endpoint = json.loads((host.STATE/'endpoint.json').read_text())
original_endpoint = json.loads((STAGE/'before/endpoint.json').read_text())
assert endpoint == {**original_endpoint,'autostart':False}
rows = json.loads((host.STATE/'profiles.json').read_text())
original_rows = copy.deepcopy(rows)
profile = next(r for r in rows if r['id'] == record['profile_id'])
profile['parameters'].update(strata_batch_groups='auto',strata_batch_mtp=False)
profile.update(revision=profile['revision']+1,updated_at=time.time())
assert [r for r in rows if r['id'] != profile['id']] == [r for r in original_rows if r['id'] != profile['id']]
subprocess.run(['docker','stop','--time','45',manifest['name']],check=True)
# Change only stopped-app files and the selected profile, not another process's cache.
atomic(host.STATE/'profiles.json',(json.dumps(rows)+'\n').encode())
atomic(host.STATE/'endpoint.json',(STAGE/'before/endpoint.json').read_bytes())
for name in FILES:
atomic(SOURCE/name,(STAGE/'image'/name).read_bytes())
spec = importlib.util.spec_from_file_location('deck_install',SOURCE/'deploy/install.py')
installer = importlib.util.module_from_spec(spec)
spec.loader.exec_module(installer)
subprocess.run(['docker','rm',manifest['name']],check=True)
manifest['image'] = TAG
manifest['previous_image'] = record['manifest_before']['image']
installer.launch(manifest)
installer.ready(manifest)
installer.write_manifest(host.BASE,manifest)
record.update(applied=True,settings_after=host.settings_hashes(),profile_revision=profile['revision'])
assert all(record['settings_after'][n] == v for n,v in record['settings_before'].items() if n != 'profiles.json')
save(record)
print(json.dumps({'applied':True,'profile_id':profile['id'],'batch_groups':'auto','batch_mtp':False,'other_settings_unchanged':True}))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('operation',choices=['prepare','apply'])
parser.add_argument('--go',action='store_true')
options = parser.parse_args()
if not options.go:
parser.error('Explicit Michael Go required')
data = json.load(sys.stdin)
{'prepare':prepare,'apply':apply}[options.operation](data)