252 lines
13 KiB
Python
252 lines
13 KiB
Python
"""Remove the explicitly retired router; preserve Deck, shared secrets and backups.
|
|
|
|
This host-only maintenance tool has a fixed allowlist. --apply requires the
|
|
user's explicit authorization to discard the remaining legacy data.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import ipaddress
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import subprocess
|
|
import time
|
|
import urllib.request
|
|
|
|
CONTAINERS = '''mike-ai-mikes-applio-ui mike-ai-llama-dashboard mike-ai-router
|
|
mike-ai-image-worker mike-ai-realtime-voice mike-ai-qwen-asr-worker mike-ai-qwen-asr
|
|
mike-ai-llama-ultra mike-ai-profile-controller mike-ai-image-prompt-enhancer-i2i
|
|
mike-ai-image-prompt-enhancer-t2i mike-ai-flux-image-worker mike-ai-embedding
|
|
mike-ai-llama-medium mike-ai-llama-large mike-ai-qwen-cron-test mike-ai-ornith15-ab
|
|
mike-ai-bonsai2-ab mike-ai-llama-uncensored mike-ai-llama-fast mike-ai-applio-studio
|
|
mike-ai-backup mike-ai-wireguard-gateway mike-ai-yue2-playground mike-ai-music-ui
|
|
mike-ai-music-acestep-test mike-ai-trellis-studio mike-ai-tts-gateway
|
|
mike-ai-xvc-studio mike-ai-voice-studio mike-ai-stem-separator mike-ai-portainer
|
|
mike-ai-qwen3-tts mike-ai-mcp-athena-operator'''.split()
|
|
# These stopped comparison containers also depend on the retired /data/models.
|
|
PREVIEWS = ['athena-localai-preview', 'llama-swap-preview']
|
|
UNITS = ['mike-ai-athena-operator.service', 'mike-ai-container-vpn-guard.service',
|
|
'mike-ai-platform-context-snapshot.timer', 'mike-ai-platform-context-snapshot.service',
|
|
'athena-export-backup.timer', 'athena-export-backup.service',
|
|
'athena-disaster-backup.timer', 'athena-disaster-backup.service']
|
|
HELPERS = ['/usr/local/libexec/mike-ai-athena-operatord',
|
|
'/usr/local/libexec/mike-ai-platform-context-snapshot',
|
|
'/usr/local/sbin/mike-ai-container-vpn-guard',
|
|
'/usr/local/sbin/athena-export-backup', '/usr/local/sbin/athena-disaster-backup']
|
|
NETWORKS = ['mike-ai-music', 'mike-ai-tools', 'mike-ai-tools-egress',
|
|
'mike-ai_control', 'mike-ai_default', 'mike-ai_frontend', 'mike-ai_inference']
|
|
VOLUMES = ['mike-ai_piper-data', 'mike-ai_router-images', 'mike-ai_router-state', 'portainer_data']
|
|
DATA = ['/opt/mike-ai', '/data/models', '/data/music', '/data/voice',
|
|
'/data/video/ltx-desktop', '/data/audio/separation', '/data/trellis-studio',
|
|
'/data/llama-dashboard', '/data/image-control', '/data/mike-ai-operator',
|
|
'/data/mike-ai-platform-context', '/var/lib/mike-ai-platform-context', '/run/mike-ai-operator']
|
|
STATE = Path('/opt/athena-deck-dev/runtime/state')
|
|
RULES = [(11000, 'to', '172.30.0.0/16', 'main'),
|
|
(11010, 'from', '172.30.10.254/32', 'main'),
|
|
(11011, 'from', '172.30.50.254/32', 'main'),
|
|
(12010, 'from', '172.30.10.0/24', '51821'),
|
|
(12050, 'from', '172.30.50.0/24', '51825')]
|
|
|
|
|
|
def run(*args, check=True):
|
|
result = subprocess.run(args, capture_output=True, text=True)
|
|
if check and result.returncode:
|
|
raise RuntimeError('Maintenance command failed: ' + ' '.join(args[:3]))
|
|
return result
|
|
|
|
|
|
def inventory():
|
|
ids = run('docker', 'ps', '-aq').stdout.split()
|
|
return json.loads(run('docker', 'inspect', *ids).stdout) if ids else []
|
|
|
|
|
|
def inside(path, root):
|
|
return path == root or path.startswith(root + '/')
|
|
|
|
|
|
def deck_host_path(path):
|
|
# Catalog links may be absolute paths in the container's /var/lib/deck.
|
|
# Resolve their host counterpart without rewriting productive symlinks.
|
|
for _ in range(40):
|
|
resolved = str(path.resolve())
|
|
if inside(resolved, '/var/lib/deck'):
|
|
path = STATE / resolved.removeprefix('/var/lib/deck/').lstrip('/')
|
|
else:
|
|
return Path(resolved)
|
|
raise RuntimeError('Catalog symlink cycle.')
|
|
|
|
|
|
def validate_rule(row, expected):
|
|
priority, direction, address, table = expected
|
|
field = 'src' if direction == 'from' else 'dst'
|
|
try:
|
|
actual = row.get(field, '')
|
|
if '/' not in actual and field + 'len' in row:
|
|
actual += '/' + str(row[field + 'len'])
|
|
return (row.get('priority') == priority and str(row.get('table')) == table
|
|
and ipaddress.ip_network(actual, strict=False) == ipaddress.ip_network(address))
|
|
except ValueError:
|
|
return False
|
|
|
|
|
|
def preflight(rows):
|
|
targets = set(CONTAINERS + PREVIEWS)
|
|
for item in rows:
|
|
name = item['Name'].lstrip('/')
|
|
if name in targets:
|
|
if item['State']['Running']:
|
|
raise RuntimeError('Retired container unexpectedly running: ' + name)
|
|
else:
|
|
for mount in item['Mounts']:
|
|
if any(inside(mount['Source'], root) for root in DATA):
|
|
raise RuntimeError('Non-target container still uses retired data: ' + name)
|
|
if any(r['Name'].startswith('/mike-ai') and r['Name'].lstrip('/') not in targets for r in rows):
|
|
raise RuntimeError('Unknown legacy container; review before removing data.')
|
|
for root in DATA:
|
|
p = Path(root)
|
|
if p.is_symlink() or p.is_mount():
|
|
raise RuntimeError('Unexpected symlink or mount at removal target: ' + root)
|
|
for line in Path('/proc/self/mountinfo').read_text().splitlines():
|
|
mountpoint = line.split()[4]
|
|
if any(inside(mountpoint, root) for root in DATA):
|
|
raise RuntimeError('Mounted filesystem inside removal target: ' + mountpoint)
|
|
status = json.loads(Path('/data/athena-deck/backups/status.json').read_text())
|
|
if status.get('state') != 'complete' or not status.get('verified_files'):
|
|
raise RuntimeError('Verified Deck backup required.')
|
|
for profile in json.loads((STATE / 'profiles.json').read_text()):
|
|
ids = [profile['model_id'], *profile.get('components', {}).values(), profile.get('parameters', {}).get('vision_projector')]
|
|
for preset in profile.get('presets', []):
|
|
ids += [preset['model_id'], preset.get('parameters', {}).get('vision_projector')]
|
|
for ident in filter(None, ids):
|
|
entry = STATE / 'models' / ident
|
|
metadata = json.loads((entry / 'entry.json').read_text())
|
|
weight = entry / ('model' + Path(metadata['file']).suffix)
|
|
host_weight = deck_host_path(weight)
|
|
if not host_weight.is_file() or host_weight.stat().st_size != metadata['size']:
|
|
raise RuntimeError('Missing productive weight: ' + profile['name'])
|
|
if any(inside(str(host_weight), root) for root in DATA):
|
|
raise RuntimeError('Productive model still uses legacy file.')
|
|
for folder, dirs, files in os.walk(STATE, followlinks=False):
|
|
for name in dirs + files:
|
|
p = Path(folder) / name
|
|
if p.is_symlink() and any(inside(str(p.resolve()), root) for root in DATA):
|
|
raise RuntimeError('Deck symlink still uses legacy data: ' + str(p))
|
|
policy = json.loads(run('ip', '-j', 'rule', 'show').stdout)
|
|
for expected in RULES:
|
|
for row in policy:
|
|
if row.get('priority') == expected[0] and not validate_rule(row, expected):
|
|
raise RuntimeError('Policy rule changed; do not delete: ' + str(expected[0]))
|
|
|
|
|
|
def remove(include_previews):
|
|
if os.geteuid() != 0:
|
|
raise RuntimeError('Requires root on Athena.')
|
|
rows = inventory()
|
|
if not include_previews and any(r['Name'].lstrip('/') in PREVIEWS for r in rows):
|
|
raise RuntimeError('Stopped previews still mount old weights; --retire-previews required.')
|
|
preflight(rows)
|
|
targets = set(CONTAINERS + (PREVIEWS if include_previews else []))
|
|
protected = {r['Name']: r['Id'] for r in rows if r['Name'].lstrip('/') not in targets}
|
|
hashes = {n: hashlib.sha256((STATE / n).read_bytes()).hexdigest() for n in ('profiles.json', 'endpoint.json', 'auth.json')}
|
|
selected = [r for r in rows if r['Name'].lstrip('/') in targets]
|
|
report = dict(started=time.time(), containers=[], units=[], networks=[], volumes=[], data=[], images=[], image_retained=[])
|
|
report_path = Path('/opt/athena-deck-maintenance/legacy-removal-report.json')
|
|
def save():
|
|
report_path.write_text(json.dumps(report, indent=2) + '\n')
|
|
report_path.chmod(0o600)
|
|
save()
|
|
for unit in UNITS:
|
|
run('systemctl', 'disable', '--now', unit)
|
|
if run('systemctl', 'is-active', '--quiet', unit, check=False).returncode == 0:
|
|
raise RuntimeError('Legacy unit still active: ' + unit)
|
|
p = Path('/etc/systemd/system') / unit
|
|
if p.exists() or p.is_symlink():
|
|
p.unlink()
|
|
report['units'].append(unit)
|
|
run('systemctl', 'daemon-reload')
|
|
for unit in UNITS:
|
|
run('systemctl', 'reset-failed', unit, check=False)
|
|
for path in HELPERS:
|
|
Path(path).unlink(missing_ok=True)
|
|
for expected in RULES:
|
|
priority, direction, address, table = expected
|
|
current = json.loads(run('ip', '-j', 'rule', 'show').stdout)
|
|
for row in current:
|
|
if row.get('priority') == priority:
|
|
if not validate_rule(row, expected):
|
|
raise RuntimeError('Changed routing rule; abort.')
|
|
run('ip', 'rule', 'del', 'priority', str(priority), direction, address, 'table', table)
|
|
for table in ('51821', '51825'):
|
|
run('ip', 'route', 'flush', 'table', table, check=False)
|
|
report['routing_removed'] = [r[0] for r in RULES]
|
|
save()
|
|
for item in selected:
|
|
name = item['Name'].lstrip('/')
|
|
run('docker', 'rm', name)
|
|
report['containers'].append(name)
|
|
save()
|
|
for name in VOLUMES:
|
|
if run('docker', 'volume', 'inspect', name, check=False).returncode == 0:
|
|
remaining = inventory()
|
|
if any(m.get('Name') == name for r in remaining for m in r['Mounts']):
|
|
raise RuntimeError('Volume still used: ' + name)
|
|
run('docker', 'volume', 'rm', name)
|
|
report['volumes'].append(name)
|
|
for name in NETWORKS:
|
|
result = run('docker', 'network', 'inspect', name, check=False)
|
|
if result.returncode == 0:
|
|
if json.loads(result.stdout)[0]['Containers']:
|
|
raise RuntimeError('Network still used: ' + name)
|
|
run('docker', 'network', 'rm', name)
|
|
report['networks'].append(name)
|
|
save()
|
|
# Recheck every dependency after service/container shutdown, before rmtree.
|
|
preflight(inventory())
|
|
for root in DATA:
|
|
p = Path(root)
|
|
if p.exists():
|
|
if not p.is_dir():
|
|
raise RuntimeError('Unexpected non-directory: ' + root)
|
|
shutil.rmtree(p)
|
|
report['data'].append(root)
|
|
save()
|
|
used = {r['Image'] for r in inventory()}
|
|
for image in sorted({r['Config']['Image'] for r in selected}):
|
|
if image == 'mike-ai/omnivoice-studio:0.2.1':
|
|
report['image_retained'].append(dict(image=image, reason='Deck Voice-Web build base'))
|
|
continue
|
|
if not image.startswith('mike-ai/'):
|
|
continue # Do not remove third-party/shared image tags.
|
|
metadata = run('docker', 'image', 'inspect', image, check=False)
|
|
if metadata.returncode:
|
|
continue
|
|
if json.loads(metadata.stdout)[0]['Id'] in used:
|
|
raise RuntimeError('Image used by retained container: ' + image)
|
|
result = run('docker', 'image', 'rm', image, check=False)
|
|
if result.returncode:
|
|
report['image_retained'].append(dict(image=image, reason='Docker dependency; no forced deletion'))
|
|
else:
|
|
report['images'].append(image)
|
|
final = inventory()
|
|
if {r['Name']: r['Id'] for r in final} != protected:
|
|
raise RuntimeError('Retained container identity changed.')
|
|
if any(hashlib.sha256((STATE / n).read_bytes()).hexdigest() != sha for n, sha in hashes.items()):
|
|
raise RuntimeError('Productive configuration changed during maintenance.')
|
|
if urllib.request.urlopen('http://127.0.0.1:8108/api/v1/auth/status', timeout=5).status != 200:
|
|
raise RuntimeError('Deck unreachable.')
|
|
report.update(finished=time.time(), state='complete', productive_containers_unchanged=True, productive_config_unchanged=True)
|
|
save()
|
|
print(json.dumps({k: len(report[k]) for k in ('containers', 'units', 'networks', 'volumes', 'data', 'images')}), flush=True)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--apply', action='store_true')
|
|
parser.add_argument('--discard-legacy-data-approved', action='store_true')
|
|
parser.add_argument('--retire-previews', action='store_true')
|
|
args = parser.parse_args()
|
|
if not args.apply or not args.discard_legacy_data_approved:
|
|
parser.error('Explicit approval flags required; no changes made.')
|
|
remove(args.retire_previews)
|