Build reproducible GUI renderer verification and safe fleet installer
This commit is contained in:
parent
794a96b5f8
commit
72a11f0870
1 changed files with 407 additions and 3 deletions
194
tools/install-plugin-fleet.py
Normal file
194
tools/install-plugin-fleet.py
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
"""Install only hash-verified CI plugins into an explicitly supplied, verified fleet inventory.
|
||||
|
||||
Default is a read-only plan. This is not a bootstrap installer and never discovers server paths,
|
||||
assigns modules, installs third-party dependencies, or deletes unrelated plugin backends.
|
||||
"""
|
||||
import argparse
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import zipfile
|
||||
|
||||
|
||||
def digest(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def identity(path):
|
||||
with zipfile.ZipFile(path) as jar:
|
||||
text = jar.read('plugin.yml').decode('utf-8')
|
||||
result = {}
|
||||
for key in ('name', 'version', 'main'):
|
||||
match = re.search(r'^' + key + r':\s*(.+?)\s*$', text, re.M)
|
||||
if not match:
|
||||
raise ValueError(f'{path}: missing plugin {key}')
|
||||
result[key] = match.group(1).strip('"\'')
|
||||
return result
|
||||
|
||||
|
||||
def plan(artifacts, inventory, expected_source):
|
||||
artifacts = Path(artifacts).resolve(strict=True)
|
||||
manifest = json.loads((artifacts / 'release-manifest.json').read_text())
|
||||
if not re.fullmatch(r'[0-9a-f]{40}', expected_source) or manifest.get('sourceCommit') != expected_source:
|
||||
raise ValueError('Release source does not match the explicitly selected commit')
|
||||
allowed_names = {'DuneEss', 'DuneRealms', 'DuneCore', 'DuneLobby', 'DuneNPC', 'DunerealmsGUI', 'DuneTerrain', 'JarvisTranslator', 'DuneMenus'}
|
||||
files, names = {}, set()
|
||||
for entry in manifest['plugins']:
|
||||
name = entry['filename']
|
||||
if Path(name).name != name or not name.endswith('.jar') or name in files:
|
||||
raise ValueError('Unsafe or duplicate artifact filename')
|
||||
path = artifacts / name
|
||||
if path.is_symlink() or digest(path) != entry['sha256']:
|
||||
raise ValueError('Artifact checksum differs: ' + name)
|
||||
actual = identity(path)
|
||||
if any(actual[key] != entry[key] for key in ('name', 'version', 'main')):
|
||||
raise ValueError('Artifact descriptor differs: ' + name)
|
||||
if actual['name'] not in allowed_names or actual['name'].casefold() in names:
|
||||
raise ValueError('Unapproved or duplicate plugin identity: ' + actual['name'])
|
||||
names.add(actual['name'].casefold())
|
||||
files[name] = dict(entry, source=str(path))
|
||||
servers, ids, roots, units = [], set(), set(), set()
|
||||
for server in inventory['servers']:
|
||||
sid, unit = server['id'], server['serviceUnit']
|
||||
if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,80}', sid) or sid in ids:
|
||||
raise ValueError('Unsafe or duplicate server identity')
|
||||
if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.@:-]*\.service', unit) or unit in units:
|
||||
raise ValueError('Unsafe or duplicate service unit')
|
||||
raw_root = Path(server['root'])
|
||||
if not raw_root.is_absolute() or raw_root.is_symlink():
|
||||
raise ValueError('Server root must be explicit, absolute and not a symlink')
|
||||
root = raw_root.resolve(strict=True)
|
||||
plugins = root / 'plugins'
|
||||
if root in roots or not (root / 'server.properties').is_file() or not plugins.is_dir() or plugins.is_symlink():
|
||||
raise ValueError('Server root/plugins preconditions failed')
|
||||
selected = server['artifacts']
|
||||
if not selected or len(set(selected)) != len(selected) or any(name not in files for name in selected):
|
||||
raise ValueError('Server requires an explicit valid artifact list')
|
||||
wanted = {files[name]['name'].casefold() for name in selected}
|
||||
previous = []
|
||||
existing_identities = set()
|
||||
for old in plugins.glob('*.jar'):
|
||||
if old.is_symlink():
|
||||
raise ValueError('Symlinked plugin requires explicit operator reconciliation')
|
||||
try:
|
||||
old_id = identity(old)['name'].casefold()
|
||||
except (ValueError, KeyError, zipfile.BadZipFile, UnicodeDecodeError):
|
||||
continue
|
||||
existing_identities.add(old_id)
|
||||
if old_id in wanted:
|
||||
previous.append({'filename': old.name, 'sha256': digest(old)})
|
||||
if 'dunemenus' in wanted and not {'jarvistranslator', 'dunerealmsgui', 'mcgui'}.issubset(wanted | existing_identities):
|
||||
raise ValueError('DuneMenus requires preserved JARVIS, DunerealmsGUI and the existing MCGUI runtime')
|
||||
# Never overwrite a differently named plugin that happens to occupy a release filename.
|
||||
old_names = {row['filename'] for row in previous}
|
||||
for name in selected:
|
||||
if (plugins / name).exists() and name not in old_names:
|
||||
raise ValueError('Artifact filename collides with another plugin: ' + name)
|
||||
servers.append({'id': sid, 'root': str(root), 'serviceUnit': unit,
|
||||
'artifacts': [files[name] for name in selected], 'previous': previous})
|
||||
ids.add(sid); roots.add(root); units.add(unit)
|
||||
if not servers:
|
||||
raise ValueError('Explicit fleet inventory is empty')
|
||||
return {'sourceCommit': expected_source, 'servers': servers}
|
||||
|
||||
|
||||
def systemctl(*args):
|
||||
return subprocess.run(['systemctl', *args], text=True, capture_output=True, check=False)
|
||||
|
||||
|
||||
def apply(deployment, backup_root, control=systemctl):
|
||||
backup_root = Path(backup_root).resolve()
|
||||
stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S.%fZ')
|
||||
# Preflight the whole requested inventory before stopping any service.
|
||||
for server in deployment['servers']:
|
||||
loaded = control('show', server['serviceUnit'], '--property=LoadState', '--value')
|
||||
if loaded.returncode or loaded.stdout.strip() != 'loaded':
|
||||
raise RuntimeError('Verified service unit is not loaded: ' + server['serviceUnit'])
|
||||
state = control('show', server['serviceUnit'], '--property=ActiveState', '--value')
|
||||
if state.returncode or state.stdout.strip() not in ('active', 'inactive', 'failed'):
|
||||
raise RuntimeError('Service is in transition or its state cannot be verified')
|
||||
for entry in server['artifacts']:
|
||||
if digest(entry['source']) != entry['sha256']:
|
||||
raise ValueError('Artifact changed after planning')
|
||||
for old in server['previous']:
|
||||
if digest(Path(server['root']) / 'plugins' / old['filename']) != old['sha256']:
|
||||
raise ValueError('Installed plugin changed after planning')
|
||||
receipts = []
|
||||
for server in deployment['servers']:
|
||||
unit = server['serviceUnit']; plugins = Path(server['root']) / 'plugins'
|
||||
backup = backup_root / stamp / server['id']; backup.mkdir(parents=True, exist_ok=False)
|
||||
receipt = {'sourceCommit': deployment['sourceCommit'], 'server': server, 'status': 'backed-up'}
|
||||
for old in server['previous']:
|
||||
shutil.copy2(plugins / old['filename'], backup / old['filename'])
|
||||
if digest(backup / old['filename']) != old['sha256']:
|
||||
raise RuntimeError('Backup verification failed')
|
||||
record = backup / 'receipt.json'; record.write_text(json.dumps(receipt, indent=2))
|
||||
active = control('is-active', '--quiet', unit).returncode == 0
|
||||
installed = []
|
||||
try:
|
||||
if active and control('stop', unit).returncode:
|
||||
raise RuntimeError('Could not stop ' + unit)
|
||||
stopped = control('show', unit, '--property=ActiveState', '--value')
|
||||
if stopped.returncode or stopped.stdout.strip() not in ('inactive', 'failed'):
|
||||
raise RuntimeError('Refusing to replace plugins unless the service is fully stopped')
|
||||
for entry in server['artifacts']:
|
||||
fd, temporary = tempfile.mkstemp(prefix='.dune-ci-', suffix='.tmp', dir=plugins)
|
||||
import os
|
||||
os.close(fd)
|
||||
temporary = Path(temporary)
|
||||
try:
|
||||
shutil.copy2(entry['source'], temporary)
|
||||
if digest(temporary) != entry['sha256']:
|
||||
raise RuntimeError('Staged checksum differs')
|
||||
temporary.replace(plugins / entry['filename']); installed.append(entry['filename'])
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
for old in server['previous']:
|
||||
if old['filename'] not in installed:
|
||||
(plugins / old['filename']).unlink()
|
||||
if active and (control('start', unit).returncode or control('is-active', '--quiet', unit).returncode):
|
||||
raise RuntimeError('Service did not become active after installation')
|
||||
receipt['status'] = 'installed-service-active' if active else 'installed-service-left-stopped'
|
||||
except Exception as error:
|
||||
# Stop before restoring. Never mutate JARs while a service is active.
|
||||
stopped = control('show', unit, '--property=ActiveState', '--value')
|
||||
if stopped.returncode or stopped.stdout.strip() not in ('inactive', 'failed'):
|
||||
control('stop', unit)
|
||||
stopped = control('show', unit, '--property=ActiveState', '--value')
|
||||
if stopped.returncode or stopped.stdout.strip() not in ('inactive', 'failed'):
|
||||
receipt.update(status='rollback-blocked-service-active', error=str(error))
|
||||
record.write_text(json.dumps(receipt, indent=2)); raise
|
||||
for name in installed:
|
||||
(plugins / name).unlink(missing_ok=True)
|
||||
for old in server['previous']:
|
||||
shutil.copy2(backup / old['filename'], plugins / old['filename'])
|
||||
restarted = not active or control('start', unit).returncode == 0
|
||||
receipt.update(status='rolled-back', error=str(error), rollbackStartAccepted=restarted)
|
||||
record.write_text(json.dumps(receipt, indent=2)); raise
|
||||
record.write_text(json.dumps(receipt, indent=2)); receipts.append(str(record))
|
||||
return receipts
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--artifacts', required=True)
|
||||
parser.add_argument('--inventory', required=True)
|
||||
parser.add_argument('--expected-source', required=True)
|
||||
parser.add_argument('--apply', action='store_true')
|
||||
parser.add_argument('--backup-root')
|
||||
args = parser.parse_args()
|
||||
deployment = plan(args.artifacts, json.loads(Path(args.inventory).read_text()), args.expected_source)
|
||||
if not args.apply:
|
||||
print(json.dumps(deployment, indent=2)); return
|
||||
if not args.backup_root:
|
||||
parser.error('--backup-root is required when applying')
|
||||
print(json.dumps({'receipts': apply(deployment, args.backup_root)}, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Loading…
Reference in a new issue

Staff