MC/tools/install-dunemenus-release.py

127 lines
7.7 KiB
Python

"""Install one recorded build into one backend, with bounded file/service recovery."""
from pathlib import Path
import datetime, hashlib, json, os, re, shutil, subprocess, sys, yaml
ALLOWED = {'/opt/dunerealms/lobby': 'dune-lobby.service', **{
f'/opt/dunerealms/servers/{x}': f'dune-{x}.service'
for x in ['arrakis', 'caladan', 'giedi_prime', 'kaitain', 'sigma_draconis_iv']}}
JARS = {'DuneMenus.jar', 'DuneRealms-Essentials.jar', 'DuneRealms-Lobby.jar',
'DuneRealms-Core.jar', 'jarvistranslator.jar'}
LEGACY = ('DunerealmsGUI.jar', 'DuneRealmsGUI.jar', 'DuneFullscreenPaper.jar', 'MCGUI.jar',
'DunerealmsGUI', 'DuneRealmsGUI', 'DuneFullscreenPaper', 'MCGUI')
PACK = 'DuneRealms-Network-Artwork-v7.zip'
def require(ok, message):
if not ok:
raise ValueError(message)
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def run(argv):
return subprocess.run(argv, check=True, timeout=120, capture_output=True, text=True)
def owned_replace(source, target):
info = target.stat()
tmp = target.with_name(target.name + '.build-staged')
require(not tmp.exists() and not tmp.is_symlink(), f'Staging path exists: {tmp}')
try:
shutil.copy2(source, tmp)
os.chmod(tmp, info.st_mode & 0o777)
if hasattr(os, 'chown'):
os.chown(tmp, info.st_uid, info.st_gid)
os.replace(tmp, target)
finally:
if tmp.exists():
tmp.unlink()
def install(bundle, root, unit, backup_base=Path('/root'), runner=run):
bundle, root = Path(bundle).resolve(), Path(root).resolve()
require(ALLOWED.get(str(root)) == unit, 'Unexpected backend/unit')
manifest = json.loads((bundle/'release.json').read_text())
require(re.fullmatch(r'[0-9a-f]{40}', manifest.get('source', '')), 'Missing source commit')
files = manifest['files']
for name, record in files.items():
require(name not in ('.', '..') and '/' not in name and '\\' not in name, 'Unsafe artifact name')
artifact = bundle/name
require(artifact.is_file() and not artifact.is_symlink(), 'Invalid artifact: '+name)
require(digest(artifact) == record['sha256'], 'Artifact checksum differs: '+name)
require(JARS <= files.keys() and PACK in files, 'Incomplete release')
require(hashlib.sha1((bundle/PACK).read_bytes()).hexdigest() == files[PACK]['sha1'], 'Pack SHA1 differs')
require(manifest['pack_url'] == 'https://www.dunerealms.com/downloads/'+PACK, 'Unexpected pack URL')
plugins = root/'plugins'; data = plugins/'DuneMenus'
require(not plugins.is_symlink() and not data.is_symlink(), 'Symlinked plugin directory')
configs = [data/'config.yml', data/'gui-pack.yml']
require(all(p.is_file() and not p.is_symlink() for p in configs), 'Missing/symlinked configuration')
require((plugins/'DuneMenus.jar').is_file(), 'DuneMenus is not installed')
config, pack = [yaml.safe_load(p.read_text()) or {} for p in configs]
require(isinstance(config, dict) and isinstance(pack, dict), 'Configuration must be a mapping')
require(isinstance(config.get('fullscreen', {}), dict), 'fullscreen must be a mapping')
config.setdefault('fullscreen', {})['enabled'] = True; config.pop('mcgui', None)
pin = {'url': manifest['pack_url'], 'sha1': files[PACK]['sha1']}
pack.update({'world': pin, 'lobby': pin})
jars = sorted(name for name in JARS if (plugins/name).is_file())
targets = [*[plugins/name for name in jars], *configs]
require(all(not p.is_symlink() for p in targets), 'Symlinked replacement target')
legacy = [plugins/name for name in LEGACY if (plugins/name).exists()]
if (data/'mcgui').exists(): legacy.append(data/'mcgui')
cache = plugins/'.paper-remapped'
if cache.exists():
require(not cache.is_symlink(), 'Symlinked remapped cache')
legacy += [p for p in cache.glob('*.jar') if p.name in JARS or
any(x in p.name.lower() for x in ('dunemenus', 'dunerealmsgui', 'dunefullscreen', 'mcgui'))]
require(all(not p.is_symlink() and p.resolve().is_relative_to(plugins.resolve()) for p in legacy), 'Unsafe legacy path')
excluded = set(jars) | set(LEGACY)
others = {p.name: digest(p) for p in plugins.glob('*.jar') if p.name not in excluded}
runner(['systemctl', 'is-active', '--quiet', unit])
stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
backup = Path(backup_base)/('dunemenus-before-'+stamp+'-'+root.name); backup.mkdir(mode=0o700)
originals = {}
for target in targets:
saved = backup/'files'/target.relative_to(plugins)
saved.parent.mkdir(parents=True, exist_ok=True); shutil.copy2(target, saved); originals[target] = saved
(backup/'other-jars.json').write_text(json.dumps(others, indent=2))
staged = backup/'prepared'; staged.mkdir()
for target, content in zip(configs, (config, pack)):
(staged/target.name).write_text(yaml.safe_dump(content, sort_keys=False, allow_unicode=True))
moved = []; changed = []; stop_attempted = False
try:
stop_attempted = True; runner(['systemctl', 'stop', unit])
require(all(digest(p) == digest(saved) for p, saved in originals.items()), 'Backend files changed after preflight')
for target in legacy:
saved = backup/'retired'/target.relative_to(plugins); saved.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(target), str(saved)); moved.append((target, saved))
for target in targets:
source = bundle/target.name if target.suffix == '.jar' else staged/target.name
changed.append(target); owned_replace(source, target)
require(all(digest(plugins/name) == files[name]['sha256'] for name in jars), 'Installed checksum differs')
require(others == {p.name: digest(p) for p in plugins.glob('*.jar') if p.name not in excluded}, 'Unrelated plugins changed')
require(all(not p.exists() for p in legacy), 'Retired GUI remains active')
runner(['systemctl', 'start', unit]); runner(['systemctl', 'is-active', '--quiet', unit])
except Exception as failure:
errors = []
if changed or moved:
try: runner(['systemctl', 'stop', unit])
except Exception as error: errors.append('Cannot stop backend for recovery: '+str(error))
if not errors:
for target in reversed(changed):
try: owned_replace(originals[target], target)
except Exception as error: errors.append('Restore failed: '+str(error))
for target, saved in reversed(moved):
try: shutil.move(str(saved), str(target))
except Exception as error: errors.append('Retired-file restore failed: '+str(error))
if stop_attempted and not errors:
try:
runner(['systemctl', 'start', unit]); runner(['systemctl', 'is-active', '--quiet', unit])
except Exception as error: errors.append('Recovery startup failed: '+str(error))
report = {'installed': False, 'error': str(failure), 'backup': str(backup), 'recovered': not errors, 'recovery_errors': errors}
(backup/'failure.json').write_text(json.dumps(report, indent=2))
raise RuntimeError(json.dumps(report)) from failure
report = {'source': manifest['source'], 'server': str(root), 'unit': unit, 'backup': str(backup),
'removed': [str(p.relative_to(plugins)) for p in legacy], 'jars': {name: files[name]['sha256'] for name in jars},
'pack': pin, 'other_plugins_unchanged': True, 'runtime_verified': False}
(backup/'deployment.json').write_text(json.dumps(report, indent=2)); return report
if __name__ == '__main__':
require(len(sys.argv) == 3, 'Usage: installer BACKEND UNIT')
print(json.dumps(install(Path(__file__).resolve().parent, sys.argv[1], sys.argv[2])))