plugins/tools/install-plugin-fleet.py

275 lines
15 KiB
Python

"""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
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import zipfile
from plugin_menu_pack import load_menu, menu_url, verify_public_menu, config_payloads
PRIVATE_PREREQUISITES = {
'MCGUI': {'sha256': '69a454291cc27c36cdbc680bfbde245a90a3913de53cc1591c502a5a49124300',
'name': 'MCGUI', 'version': '0.8.6', 'main': 'ai.resourcepack.ui.MCGUIPlugin',
'filename': 'MCGUI-0.8.6.jar'}
}
def digest(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def set_owner(path, owner, mode):
Path(path).chmod(mode)
if hasattr(os, 'chown'):
os.chown(path, owner.st_uid, owner.st_gid)
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))
prerequisites = {}
for key, item in inventory.get('privatePrerequisites', {}).items():
if key not in PRIVATE_PREREQUISITES:
raise ValueError('Private prerequisite has no reviewed identity/hash: ' + key)
expected = PRIVATE_PREREQUISITES[key]
path = Path(item['path'])
if not path.is_absolute() or path.is_symlink() or not path.is_file():
raise ValueError('Private prerequisite path must identify an existing regular file')
if digest(path) != expected['sha256'] or item.get('sha256') != expected['sha256']:
raise ValueError('Private prerequisite differs from reviewed bytes: ' + key)
if identity(path) != {field: expected[field] for field in ('name', 'version', 'main')}:
raise ValueError('Private prerequisite identity differs: ' + key)
prerequisites[key] = dict(expected, source=str(path.resolve()), privatePrerequisite=True)
menu = None
if inventory.get('menuPack') is not None:
_, menu = load_menu(artifacts, expected_source)
verify_public_menu(inventory['menuPack']['url'], menu)
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')
selected_prerequisites = server.get('prerequisites', [])
if len(set(selected_prerequisites)) != len(selected_prerequisites) or any(key not in prerequisites for key in selected_prerequisites):
raise ValueError('Server private prerequisites must be explicitly provided and reviewed')
chosen = [files[name] for name in selected] + [prerequisites[key] for key in selected_prerequisites]
wanted = {entry['name'].casefold() for entry in chosen}
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 entry in chosen:
name = entry['filename']
if (plugins / name).exists() and name not in old_names:
raise ValueError('Artifact filename collides with another plugin: ' + name)
configurations = []
if 'dunemenus' in wanted:
if menu is None:
raise ValueError('DuneMenus requires a verified published built menu overlay')
for relative, content in config_payloads(menu).items():
target = plugins / relative
if target.is_symlink() or target.parent.is_symlink():
raise ValueError('Menu configuration path must not be a symlink')
previous_hash = None
if target.exists():
if not target.read_text().startswith('# Managed by DuneRealms plugin CI;'):
raise ValueError('Existing unmanaged menu configuration requires review')
previous_hash = digest(target)
configurations.append({'path': relative, 'content': content,
'sha256': hashlib.sha256(content.encode()).hexdigest(), 'previousSha256': previous_hash})
servers.append({'id': sid, 'root': str(root), 'serviceUnit': unit,
'artifacts': chosen, 'previous': previous, 'configurations': configurations})
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')
for config in server.get('configurations', []):
target = Path(server['root']) / 'plugins' / config['path']
current = digest(target) if target.exists() else None
if current != config['previousSha256']:
raise ValueError('Menu configuration 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')
for config in server.get('configurations', []):
if config['previousSha256'] is not None:
saved = backup / 'configurations' / config['path']; saved.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(plugins / config['path'], saved)
if digest(saved) != config['previousSha256']:
raise RuntimeError('Menu configuration 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)
os.close(fd)
temporary = Path(temporary)
try:
shutil.copy2(entry['source'], temporary)
if digest(temporary) != entry['sha256']:
raise RuntimeError('Staged checksum differs')
set_owner(temporary, plugins.stat(), 0o640)
temporary.replace(plugins / entry['filename']); installed.append(entry['filename'])
finally:
temporary.unlink(missing_ok=True)
for config in server.get('configurations', []):
target = plugins / config['path']; new_parent = not target.parent.exists()
target.parent.mkdir(parents=True, exist_ok=True)
if new_parent:
set_owner(target.parent, plugins.stat(), 0o750)
target.write_bytes(config['content'].encode())
set_owner(target, plugins.stat(), 0o640)
if digest(target) != config['sha256']:
raise RuntimeError('Written menu configuration hash differs')
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'])
for config in server.get('configurations', []):
target = plugins / config['path']
if config['previousSha256'] is None:
target.unlink(missing_ok=True)
else:
shutil.copy2(backup / 'configurations' / config['path'], target)
if digest(target) != config['previousSha256']:
raise RuntimeError('Menu configuration rollback hash differs')
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()