524 lines
34 KiB
Python
524 lines
34 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
|
|
from plugin_fleet_rollback import rollback_receipt, metadata, restore_metadata
|
|
from plugin_backend_abi import contract_for_actual, verify as verify_backend_abi
|
|
from plugin_pillager_abi import verify as verify_pillager_abi, verify_menu_resources, verify_accepted_frontends, verify_terrain as verify_pillager_terrain, REVIEWED_TERRAIN_SHA256
|
|
import plugin_pack_properties as pack_properties
|
|
|
|
|
|
PRIVATE_PREREQUISITES = {
|
|
'MCGUI': {'sha256': '69a454291cc27c36cdbc680bfbde245a90a3913de53cc1591c502a5a49124300',
|
|
'name': 'MCGUI', 'version': '0.8.6', 'main': 'ai.resourcepack.ui.MCGUIPlugin',
|
|
'filename': 'MCGUI-0.8.6.jar'}
|
|
}
|
|
ARRAKIS_ROOT = Path('/opt/dunerealms/servers/arrakis')
|
|
CRYSKNIFE_PRIOR_JARVIS_SHA256 = '663c28c5fb246b3d5c14b2faeaf0b6c000e38a53b3d45459221e4d3b85f242c3'
|
|
|
|
|
|
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
|
|
|
|
|
|
DUNECHEST_PLANETS = {'arrakis', 'caladan', 'giedi_prime', 'kaitain', 'sigma_draconis_iv'}
|
|
DUNECHEST_FLEET_JAR = 'f797c8bea59817a761ab18d87b045258698881d38e9aff776462cedb7d94627a'
|
|
DUNECHEST_ORDOS_PREDECESSOR = '94e591f11f10c3174c821bbfc8734f50a9638981e17269db2682be6e36d8fb97'
|
|
DUNECHEST_PLANET_PREDECESSOR = 'a1cd67aeea65d4a9dc98b75b1466fd54a120213e3eef31582c9492d546e484c2'
|
|
|
|
|
|
def verify_dunechest_fleet_target(sid, root, unit, incoming, installed):
|
|
expected_root = Path('/opt/dunerealms/lobby') if sid == 'lobby' else Path('/opt/dunerealms/servers') / sid
|
|
if sid not in DUNECHEST_PLANETS | {'lobby'} or root != expected_root or unit != f'dune-{sid}.service':
|
|
raise ValueError('DuneChest fleet release requires an exact reviewed server root and unit')
|
|
if incoming != DUNECHEST_FLEET_JAR:
|
|
raise ValueError('Fleet release must install the exact reviewed DuneChest JAR')
|
|
allowed = {None, incoming} if sid == 'lobby' else {incoming}
|
|
if sid == 'sigma_draconis_iv':
|
|
allowed.add(DUNECHEST_ORDOS_PREDECESSOR)
|
|
elif sid in DUNECHEST_PLANETS:
|
|
allowed.add(DUNECHEST_PLANET_PREDECESSOR)
|
|
if installed not in allowed:
|
|
raise ValueError('Unexpected DuneChest fleet predecessor')
|
|
|
|
|
|
def plan(artifacts, inventory, expected_source):
|
|
mode=inventory.get('mode')
|
|
if mode not in {'gui-preserve-backends','pillager-preserve-economy','arrakis-crysknife','navigator','planet-dunechest','fleet-dunechest','arrakis-raw-spice','arrakis-jerboa'}:
|
|
raise ValueError('An explicit supported rollout mode is required')
|
|
jerboa=mode=='arrakis-jerboa'
|
|
raw_spice=mode=='arrakis-raw-spice'
|
|
pillager=mode=='pillager-preserve-economy'
|
|
crysknife=mode=='arrakis-crysknife'
|
|
navigator=mode=='navigator'
|
|
fleet_dunechest=mode=='fleet-dunechest'
|
|
dunechest=mode=='planet-dunechest' or fleet_dunechest
|
|
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'}
|
|
if dunechest:
|
|
allowed_names={'DuneChest'}
|
|
if jerboa:
|
|
allowed_names={'DuneTerrain'}
|
|
if raw_spice:
|
|
allowed_names={'JarvisTranslator'}
|
|
if inventory.get('menuPack') is not None:
|
|
raise ValueError('Raw spice rollout must retain current resource pack configuration')
|
|
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)
|
|
if (pillager or crysknife or navigator or dunechest or jerboa) and not(menu and menu.get('unified')):
|
|
raise ValueError('This rollout requires its verified unified item/skin pack')
|
|
if fleet_dunechest and menu['sha256'] != '25ae69ae7198002ebff65b1eafbb454be7df235f51cdc46bb6233aa0b3ceec7a':
|
|
raise ValueError('Fleet release must use the exact resource pack tested on Ordos')
|
|
if navigator:
|
|
from plugin_navigator_transition import verify_module as verify_navigator, verify_jarvis as verify_navigator_jarvis
|
|
transition=json.loads((artifacts/'navigator-transition.json').read_text())
|
|
if menu['sha256'] != transition['packSha256']:
|
|
raise ValueError('Navigator rollout must preserve the accepted Crysknife pack bytes')
|
|
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}
|
|
uses_menu='dunemenus' in wanted or bool(menu and menu.get('unified') and not (crysknife or dunechest or jerboa))
|
|
if menu and menu.get('unified') and not (crysknife or dunechest or jerboa) and 'dunerealmsgui' not in wanted:
|
|
raise ValueError('Unified pack rollout must select its matching DunerealmsGUI adapter')
|
|
if not (pillager or crysknife or navigator or dunechest or raw_spice or jerboa) and wanted - {'dunemenus','dunerealmsgui','dunenpc','dunelobby','mcgui'}:
|
|
raise ValueError('GUI rollout must retain working Ess/JARVIS/Core/Terrain binaries')
|
|
if jerboa and (sid != 'arrakis' or root != ARRAKIS_ROOT or unit != 'dune-arrakis.service'
|
|
or wanted != {'duneterrain'} or selected_prerequisites):
|
|
raise ValueError('Jerboa rollout may only replace Terrain on Arrakis')
|
|
if raw_spice and (sid != 'arrakis' or root != ARRAKIS_ROOT or unit != 'dune-arrakis.service'
|
|
or wanted != {'jarvistranslator'} or selected_prerequisites):
|
|
raise ValueError('Raw spice rollout may only replace JARVIS on Arrakis')
|
|
if crysknife and (
|
|
sid != 'arrakis' or unit != 'dune-arrakis.service'
|
|
or root != ARRAKIS_ROOT
|
|
or wanted != {'jarvistranslator','duneterrain'} or selected_prerequisites
|
|
):
|
|
raise ValueError('Crysknife rollout is restricted to the Arrakis JARVIS and Terrain pair')
|
|
if navigator:
|
|
planets={'arrakis','caladan','giedi_prime','kaitain','sigma_draconis_iv'}
|
|
target=(Path('/opt/dunerealms/lobby') if sid=='lobby' else Path('/opt/dunerealms/servers')/sid)
|
|
expected={'dunemenus','dunerealmsgui'} | ({'jarvistranslator'} if sid in planets else set())
|
|
if sid not in planets|{'lobby'} or root!=target or unit!=f'dune-{sid}.service' or wanted!=expected or selected_prerequisites:
|
|
raise ValueError('Navigator rollout requires its reviewed server root, unit and plugin selection')
|
|
if dunechest and (wanted!={'dunechest'} or selected_prerequisites):
|
|
raise ValueError('DuneChest rollout allows only the DuneChest artifact')
|
|
if dunechest and not fleet_dunechest and (
|
|
sid not in {'arrakis','caladan','giedi_prime','kaitain','sigma_draconis_iv'}
|
|
or root!=Path('/opt/dunerealms/servers')/sid or unit!=f'dune-{sid}.service'
|
|
):
|
|
raise ValueError('DuneChest rollout requires an exact planet root and only the DuneChest artifact')
|
|
if pillager:
|
|
if sid not in {'lobby','arrakis','caladan','giedi_prime','kaitain','sigma_draconis_iv'}:
|
|
raise ValueError('Pillager rollout requires a reviewed backend identity')
|
|
if wanted-{'jarvistranslator','duneterrain','dunerealmsgui','dunemenus'} or selected_prerequisites:
|
|
raise ValueError('Pillager rollout may replace only JARVIS, Arrakis Terrain and identical GUI bytes')
|
|
if 'duneterrain' in wanted and sid!='arrakis':raise ValueError('Terrain provenance is Arrakis-only')
|
|
if sid=='lobby' and wanted!={'dunerealmsgui','dunemenus'}:raise ValueError('Lobby receives only pack pins and resource-only menu artwork')
|
|
if 'dunemenus' not in wanted:raise ValueError('Pillager item cards require the matching resource-only menu artifact')
|
|
if sid!='lobby' and 'jarvistranslator' not in wanted:raise ValueError('Planet raid rollout requires the reviewed JARVIS artifact')
|
|
if sid=='arrakis' and 'duneterrain' not in wanted:raise ValueError('Arrakis mining requires its provenance Terrain artifact')
|
|
previous = []
|
|
existing_identities = set()
|
|
existing_paths = {}
|
|
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 existing_paths:raise ValueError("Duplicate retained plugin identity requires reconciliation")
|
|
existing_paths[old_id]=old
|
|
if old_id in wanted:
|
|
previous.append({'filename': old.name, 'sha256': digest(old), 'metadata':metadata(old)})
|
|
if uses_menu 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)
|
|
retained=[]; abi_result=None
|
|
if uses_menu and not navigator:
|
|
fixture=json.loads((artifacts/'preserved-backend-abi.json').read_text())
|
|
if pillager:
|
|
incoming=next((e for e in chosen if e['name'].casefold()=='jarvistranslator'),None)
|
|
if incoming is not None and digest(existing_paths['jarvistranslator'])==incoming['sha256']:
|
|
fixture['variants'].append({'kind':'jarvis','sha256':incoming['sha256']})
|
|
for plugin_name,kind in (('jarvistranslator','jarvis'),('dunecore','core'),('duneess','ess')):
|
|
path=existing_paths.get(plugin_name)
|
|
if path is None:raise ValueError('Verified retained backend is missing: '+plugin_name)
|
|
sha=digest(path)
|
|
if not any(row['kind']==kind and row['sha256']==sha for row in fixture['variants']):
|
|
raise ValueError('Retained backend is not a reviewed live variant: '+plugin_name)
|
|
if not(pillager and plugin_name in wanted):retained.append({'filename':path.name,'sha256':sha,'metadata':metadata(path)})
|
|
contract=contract_for_actual(existing_paths['jarvistranslator'],existing_paths['dunecore'],fixture)
|
|
frontend=[entry['source'] for entry in chosen if not entry.get('privatePrerequisite') and (not pillager or entry['name'].casefold()=='dunerealmsgui')]
|
|
if pillager and existing_paths.get('dunemenus'):frontend.append(existing_paths['dunemenus'])
|
|
abi_result=verify_backend_abi(frontend,contract)
|
|
if pillager:
|
|
incoming_gui=next(e for e in chosen if e['name'].casefold()=='dunerealmsgui')
|
|
if 'dunerealmsgui' not in existing_paths or 'dunemenus' not in existing_paths:raise ValueError('Accepted GUI/Menu runtimes must already exist')
|
|
incoming_menu=next(e for e in chosen if e['name'].casefold()=='dunemenus')
|
|
menu_resources=verify_menu_resources(incoming_menu['source'],existing_paths['dunemenus'])
|
|
verify_accepted_frontends(incoming_menu['source'],incoming_gui['source'],json.loads((artifacts/'pillager-accepted-frontends.json').read_text()))
|
|
abi_result=dict(abi_result or {},menuResources=menu_resources)
|
|
if digest(existing_paths['dunerealmsgui'])!=incoming_gui['sha256']:
|
|
raise ValueError('Pillager release must preserve exact accepted GUI runtime bytes')
|
|
if sid!='lobby':
|
|
vendor=existing_paths.get('medievalfactions')
|
|
if vendor is None:raise ValueError('Reviewed MedievalFactions runtime is required')
|
|
worldguard=existing_paths.get('worldguard')
|
|
if worldguard is None:raise ValueError('Reviewed WorldGuard runtime is required')
|
|
incoming=next(e for e in chosen if e['name'].casefold()=='jarvistranslator')
|
|
abi_result=dict(abi_result or {},pillager=verify_pillager_abi(incoming['source'],vendor,artifacts,worldguard))
|
|
if sid=='arrakis':
|
|
incoming=next(e for e in chosen if e['name'].casefold()=='duneterrain')
|
|
previous_terrain=existing_paths.get('duneterrain')
|
|
if previous_terrain is None or digest(previous_terrain) not in {REVIEWED_TERRAIN_SHA256,incoming['sha256']}:
|
|
raise ValueError('Arrakis Terrain is not the reviewed retained runtime')
|
|
abi_result=dict(abi_result or {},terrain=verify_pillager_terrain(incoming['source'],json.loads((artifacts/'retained-arrakis-terrain.json').read_text())))
|
|
retained_names={r['filename'] for r in retained}
|
|
for path in plugins.glob('*.jar'):
|
|
if path.name not in {p['filename'] for p in previous} and path.name not in retained_names:
|
|
retained.append({'filename':path.name,'sha256':digest(path),'metadata':metadata(path)})
|
|
if crysknife:
|
|
incoming = {entry['name'].casefold(): entry for entry in chosen}
|
|
pins = {'jarvistranslator': CRYSKNIFE_PRIOR_JARVIS_SHA256,
|
|
'duneterrain': REVIEWED_TERRAIN_SHA256}
|
|
for name, prior_pin in pins.items():
|
|
installed = existing_paths.get(name)
|
|
if installed is None or digest(installed) not in {prior_pin, incoming[name]['sha256']}:
|
|
raise ValueError('Crysknife rollout runtime differs from the reviewed pin: ' + name)
|
|
vendor, worldguard = (existing_paths.get(name) for name in ('medievalfactions', 'worldguard'))
|
|
if vendor is None or worldguard is None:
|
|
raise ValueError('Crysknife rollout requires the existing vendor runtimes')
|
|
abi_result = verify_pillager_abi(incoming['jarvistranslator']['source'], vendor, artifacts, worldguard)
|
|
abi_result['terrain'] = verify_pillager_terrain(incoming['duneterrain']['source'],
|
|
json.loads((artifacts/'retained-arrakis-terrain.json').read_text()))
|
|
replaced = {entry['filename'] for entry in previous}
|
|
retained = [{'filename': path.name, 'sha256': digest(path), 'metadata': metadata(path)}
|
|
for path in sorted(plugins.glob('*.jar')) if path.name not in replaced]
|
|
if navigator:
|
|
abi_result={}
|
|
runtime=existing_paths.get('mcgui')
|
|
if runtime is None or digest(runtime)!=PRIVATE_PREREQUISITES['MCGUI']['sha256']:
|
|
raise ValueError('Navigator rollout requires the pinned MCGUI runtime')
|
|
if sid=='lobby':
|
|
lobby_jarvis=existing_paths.get('jarvistranslator')
|
|
if lobby_jarvis is None or digest(lobby_jarvis)!=transition['lobbyJarvisSha256']:
|
|
raise ValueError('Navigator rollout requires the reviewed retained Lobby JARVIS')
|
|
for entry in chosen:
|
|
name=entry['name']
|
|
installed=existing_paths.get(name.casefold())
|
|
if installed is None:
|
|
raise ValueError('Navigator rollout requires an existing reviewed '+name)
|
|
prior=digest(installed)
|
|
guard=transition['modules'][name]
|
|
if name=='JarvisTranslator':
|
|
if prior!=entry['sha256'] and prior!=transition['jarvisByServer'][sid]:
|
|
raise ValueError('Navigator JARVIS baseline differs from the reviewed world runtime')
|
|
abi=json.loads((artifacts/'retained-jarvis-public-abi.json').read_text())
|
|
abi_result[name]=verify_navigator_jarvis(entry['source'],guard,abi,None if prior==entry['sha256'] else prior)
|
|
else:
|
|
abi_result[name]=verify_navigator(entry['source'],guard,None if prior==entry['sha256'] else prior)
|
|
replaced={entry['filename'] for entry in previous}
|
|
retained=[{'filename':path.name,'sha256':digest(path),'metadata':metadata(path)}
|
|
for path in sorted(plugins.glob('*.jar')) if path.name not in replaced]
|
|
if dunechest:
|
|
if not {'dunerealmsgui','mcgui'}.issubset(existing_paths):
|
|
raise ValueError('DuneChest pack delivery requires the installed GUI and MCGUI runtimes')
|
|
installed=existing_paths.get('dunechest')
|
|
approved_dunechest = {
|
|
chosen[0]['sha256'],
|
|
DUNECHEST_ORDOS_PREDECESSOR,
|
|
}
|
|
if fleet_dunechest:
|
|
verify_dunechest_fleet_target(sid, root, unit, chosen[0]['sha256'], digest(installed) if installed else None)
|
|
elif installed is not None and digest(installed) not in approved_dunechest:
|
|
raise ValueError('Existing DuneChest differs from the approved release or predecessor')
|
|
replaced={entry['filename'] for entry in previous}
|
|
retained=[{'filename':path.name,'sha256':digest(path),'metadata':metadata(path)}
|
|
for path in sorted(plugins.glob('*.jar')) if path.name not in replaced]
|
|
if jerboa:
|
|
from plugin_arrakis_jerboa import BASELINE_SHA256, verify_terrain
|
|
installed = existing_paths.get('duneterrain')
|
|
if installed is None or digest(installed) not in {BASELINE_SHA256, chosen[0]['sha256']}:
|
|
raise ValueError('Jerboa rollout requires the retained Arrakis Terrain')
|
|
if not {'dunerealmsgui', 'mcgui'}.issubset(existing_paths):
|
|
raise ValueError('Jerboa pack delivery requires the retained GUI and MCGUI runtimes')
|
|
verify_terrain(chosen[0]['source'])
|
|
replaced = {entry['filename'] for entry in previous}
|
|
retained = [{'filename': path.name, 'sha256': digest(path), 'metadata': metadata(path)}
|
|
for path in sorted(plugins.glob('*.jar')) if path.name not in replaced]
|
|
if raw_spice:
|
|
from plugin_arrakis_raw_spice import BASELINE_SHA256, verify_jar
|
|
installed = existing_paths.get('jarvistranslator')
|
|
if installed is None or digest(installed) not in {BASELINE_SHA256, chosen[0]['sha256']}:
|
|
raise ValueError('Raw spice rollout requires the retained Arrakis JARVIS')
|
|
verify_jar(chosen[0]['source'])
|
|
replaced = {entry['filename'] for entry in previous}
|
|
retained = [{'filename': path.name, 'sha256': digest(path), 'metadata': metadata(path)}
|
|
for path in sorted(plugins.glob('*.jar')) if path.name not in replaced]
|
|
configurations = []
|
|
if uses_menu or crysknife or dunechest or jerboa:
|
|
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')
|
|
if (crysknife or navigator or dunechest or jerboa) and relative == 'MCGUI/config.yml' and (
|
|
not target.is_file() or target.read_bytes() != content.encode()
|
|
):
|
|
raise ValueError('Rollout must preserve the existing MCGUI engine configuration')
|
|
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, 'previousMetadata':metadata(target) if target.exists() else None})
|
|
servers.append({'id': sid, 'root': str(root), 'serviceUnit': unit,
|
|
'artifacts': chosen, 'previous': previous, 'configurations': configurations, 'retained':retained, 'backendAbi':abi_result,
|
|
'serverProperties':pack_properties.plan(root,menu) if menu else None})
|
|
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 entry in server.get('retained',[]):
|
|
target=Path(server['root'])/'plugins'/entry['filename']
|
|
if digest(target)!=entry['sha256'] or metadata(target)!=entry['metadata']:
|
|
raise ValueError('Retained backend 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')
|
|
pack_properties.preflight(server['root'],server.get('serverProperties'))
|
|
|
|
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 = {'formatVersion':3,'sourceCommit': deployment['sourceCommit'], 'server': server, 'status': 'backed-up'}
|
|
pack_properties.backup(server['root'],backup,server.get('serverProperties'))
|
|
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
|
|
receipt['wasActive']=active;record.write_text(json.dumps(receipt,indent=2))
|
|
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')
|
|
pack_properties.install(server['root'],server.get('serverProperties'))
|
|
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()
|
|
for entry in server.get('retained',[]):
|
|
target=plugins/entry['filename']
|
|
if digest(target)!=entry['sha256'] or metadata(target)!=entry['metadata']:
|
|
raise RuntimeError('Retained backend changed during GUI installation')
|
|
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'])
|
|
if old.get('metadata') is not None:restore_metadata(plugins / old['filename'],old['metadata'])
|
|
pack_properties.restore(server['root'],backup,server.get('serverProperties'))
|
|
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 config.get('previousMetadata') is not None:restore_metadata(target,config['previousMetadata'])
|
|
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')
|
|
parser.add_argument('--inventory')
|
|
parser.add_argument('--expected-source', required=True)
|
|
parser.add_argument('--apply', action='store_true')
|
|
parser.add_argument('--backup-root')
|
|
parser.add_argument('--rollback-receipt')
|
|
parser.add_argument('--legacy-owner',help='Explicit verified UID:GID for receipts without original ownership')
|
|
parser.add_argument('--legacy-was-active',choices=['yes','no'])
|
|
args = parser.parse_args()
|
|
if args.rollback_receipt:
|
|
owner=tuple(map(int,args.legacy_owner.split(':'))) if args.legacy_owner else None
|
|
if owner is not None and (len(owner)!=2 or min(owner)<0):parser.error('Use verified non-negative UID:GID')
|
|
active=None if args.legacy_was_active is None else args.legacy_was_active=='yes'
|
|
print(json.dumps(rollback_receipt(args.rollback_receipt,args.expected_source,args.apply,legacy_owner=owner,legacy_was_active=active),indent=2));return
|
|
if not args.artifacts or not args.inventory:parser.error('--artifacts and --inventory are required for deployment planning')
|
|
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()
|

Staff