forked from unimatrix/web
Remove retired menu resources and recover failed backend installs
This commit is contained in:
parent
70098d57ff
commit
eeee72a91e
4 changed files with 279 additions and 64 deletions
|
|
@ -56,6 +56,15 @@ jobs:
|
|||
path: plugin-artifacts/
|
||||
if-no-files-found: error
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
- name: Test release installer failure recovery
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
python -m pip install PyYAML==6.0.3
|
||||
python -m unittest discover -s tools -p test_dunemenus_installer.py -v
|
||||
- name: Test and build the replacement DuneMenus plugin
|
||||
shell: bash
|
||||
run: |
|
||||
|
|
|
|||
|
|
@ -21,16 +21,6 @@ tasks.withType<JavaCompile> { options.encoding = "UTF-8" }
|
|||
tasks.jar { archiveFileName.set("DuneMenus.jar") }
|
||||
tasks.processResources {
|
||||
filesMatching("plugin.yml") { expand("version" to project.version) }
|
||||
from("../website/web/assets/dunerealms-season-logo-v2.png") { into("mcgui") }
|
||||
from("../DuneLobby/artwork/exchange.png") { into("mcgui/native") }
|
||||
from("../website/web/assets/seals") {
|
||||
include("house-aerdrecht-v1.png", "house-harkveen-v1.png", "house-korenholt-v1.png", "house-oordwijk-v1.png", "house-vrijduin-v1.png")
|
||||
into("mcgui/native")
|
||||
}
|
||||
from("../website/web/assets/gui") {
|
||||
include("mentat-atreides-v1.png", "mentat-harkonnen-v1.png", "mentat-corrino-v1.png", "mentat-ordos-v1.png", "mentat-fremen-v1.png")
|
||||
into("mcgui/native")
|
||||
}
|
||||
}
|
||||
|
||||
tasks.test { useJUnitPlatform() }
|
||||
|
|
|
|||
|
|
@ -1,55 +1,127 @@
|
|||
"""Install one verified build into one explicitly named backend. Called from the build artifact."""
|
||||
"""Install one recorded build into one backend, with bounded file/service recovery."""
|
||||
from pathlib import Path
|
||||
import datetime,hashlib,json,os,shutil,subprocess,sys,yaml
|
||||
bundle=Path(__file__).resolve().parent
|
||||
manifest=json.loads((bundle/'release.json').read_text())
|
||||
root=Path(sys.argv[1]).resolve();unit=sys.argv[2]
|
||||
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']}}
|
||||
assert allowed.get(str(root))==unit,'Unexpected backend/unit'
|
||||
for name,record in manifest['files'].items():
|
||||
assert '/' not in name and hashlib.sha256((bundle/name).read_bytes()).hexdigest()==record['sha256'],name
|
||||
plugins=root/'plugins';target=plugins/'DuneMenus.jar';data=plugins/'DuneMenus'
|
||||
assert target.is_file() and (data/'config.yml').is_file()
|
||||
jars=[name for name in manifest['files'] if name.endswith('.jar') and (plugins/name).exists()]
|
||||
assert 'DuneMenus.jar' in jars
|
||||
stamp=datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
|
||||
backup=Path('/root/dunemenus-before-'+stamp+'-'+root.name);backup.mkdir(mode=0o700)
|
||||
for p in [*[plugins/name for name in jars],data/'config.yml',data/'gui-pack.yml']:
|
||||
if p.exists():shutil.copy2(p,backup/p.name)
|
||||
excluded=set(jars)|{'DunerealmsGUI.jar','DuneFullscreenPaper.jar','MCGUI.jar'}
|
||||
others={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in plugins.glob('*.jar') if p.name not in excluded}
|
||||
(backup/'other-jars.json').write_text(json.dumps(others,indent=2))
|
||||
config=yaml.safe_load((data/'config.yml').read_text()) or {}
|
||||
config.setdefault('fullscreen',{})['enabled']=True
|
||||
config.pop('mcgui',None)
|
||||
pack=yaml.safe_load((data/'gui-pack.yml').read_text()) or {}
|
||||
pin={'url':manifest['pack_url'],'sha1':manifest['files']['DuneRealms-Network-Artwork-v7.zip']['sha1']}
|
||||
pack.update({'world':pin,'lobby':pin})
|
||||
subprocess.run(['systemctl','stop',unit],check=True,timeout=120)
|
||||
owner=target.stat();removed=[]
|
||||
for name in ['DunerealmsGUI.jar','DuneFullscreenPaper.jar','MCGUI.jar','DunerealmsGUI','DuneFullscreenPaper','MCGUI']:
|
||||
p=plugins/name
|
||||
if not p.exists():continue
|
||||
assert p.resolve().is_relative_to(plugins.resolve())
|
||||
shutil.move(str(p),str(backup/name));removed.append(name)
|
||||
for name in ['mcgui']:
|
||||
p=data/name
|
||||
if p.is_dir():shutil.move(str(p),str(backup/('DuneMenus-'+name)));removed.append('DuneMenus/'+name)
|
||||
for name in jars:
|
||||
dst=plugins/name;tmp=dst.with_suffix('.jar.build-staged');shutil.copy2(bundle/name,tmp);os.chown(tmp,owner.st_uid,owner.st_gid);os.replace(tmp,dst)
|
||||
for name,content in [('config.yml',config),('gui-pack.yml',pack)]:
|
||||
p=data/name;p.write_text(yaml.safe_dump(content,sort_keys=False,allow_unicode=True));os.chown(p,owner.st_uid,owner.st_gid)
|
||||
cache=plugins/'.paper-remapped'
|
||||
if cache.is_dir():
|
||||
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']):
|
||||
shutil.move(str(p),str(backup/('remapped-'+p.name)))
|
||||
after={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in plugins.glob('*.jar') if p.name not in excluded}
|
||||
assert others==after,'Unrelated plugins changed'
|
||||
assert hashlib.sha256(target.read_bytes()).hexdigest()==manifest['files']['DuneMenus.jar']['sha256']
|
||||
for name in jars:assert hashlib.sha256((plugins/name).read_bytes()).hexdigest()==manifest['files'][name]['sha256']
|
||||
subprocess.run(['systemctl','start',unit],check=True,timeout=120)
|
||||
report={'source':manifest['source'],'server':str(root),'unit':unit,'backup':str(backup),'removed':removed,'jars':{name:manifest['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));print(json.dumps(report))
|
||||
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])))
|
||||
|
|
|
|||
144
tools/test_dunemenus_installer.py
Normal file
144
tools/test_dunemenus_installer.py
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import pathlib
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
SPEC = importlib.util.spec_from_file_location('installer', pathlib.Path(__file__).with_name('install-dunemenus-release.py'))
|
||||
m = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(m)
|
||||
|
||||
|
||||
class InstallerTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
base = pathlib.Path(self.temp.name)
|
||||
self.bundle = base / 'bundle'
|
||||
self.bundle.mkdir()
|
||||
self.root = base / 'arrakis'
|
||||
self.plugins = self.root / 'plugins'
|
||||
self.data = self.plugins / 'DuneMenus'
|
||||
self.data.mkdir(parents=True)
|
||||
self.backup = base / 'backups'
|
||||
self.backup.mkdir()
|
||||
self.unit = 'test.service'
|
||||
guard = patch.dict(m.ALLOWED, {str(self.root.resolve()): self.unit})
|
||||
guard.start()
|
||||
self.addCleanup(guard.stop)
|
||||
files = {}
|
||||
for name in sorted(m.JARS | {m.PACK}):
|
||||
payload = ('new-' + name).encode()
|
||||
(self.bundle / name).write_bytes(payload)
|
||||
files[name] = {'sha256': hashlib.sha256(payload).hexdigest(), 'sha1': hashlib.sha1(payload).hexdigest()}
|
||||
if name in m.JARS:
|
||||
(self.plugins / name).write_bytes(('old-' + name).encode())
|
||||
(self.bundle / 'release.json').write_text(json.dumps({
|
||||
'source': 'a' * 40, 'files': files,
|
||||
'pack_url': 'https://www.dunerealms.com/downloads/' + m.PACK}))
|
||||
(self.data / 'config.yml').write_text('owner-setting: preserve\nfullscreen:\n enabled: false\n')
|
||||
(self.data / 'gui-pack.yml').write_text('unrelated: keep\n')
|
||||
(self.plugins / 'other.jar').write_bytes(b'unrelated')
|
||||
(self.plugins / 'MCGUI.jar').write_bytes(b'legacy')
|
||||
(self.data / 'mcgui').mkdir()
|
||||
(self.data / 'mcgui' / 'old.png').write_bytes(b'old-art')
|
||||
self.before = self.snapshot()
|
||||
self.calls = []
|
||||
|
||||
def snapshot(self):
|
||||
return {p.relative_to(self.plugins).as_posix(): p.read_bytes()
|
||||
for p in self.plugins.rglob('*') if p.is_file()}
|
||||
|
||||
def run_service(self, args):
|
||||
self.calls.append(args)
|
||||
|
||||
def invoke(self, runner=None):
|
||||
return m.install(self.bundle, self.root, self.unit, self.backup, runner or self.run_service)
|
||||
|
||||
def test_success_removes_legacy_and_preserves_unrelated_config(self):
|
||||
result = self.invoke()
|
||||
self.assertFalse(result['runtime_verified'])
|
||||
self.assertFalse((self.plugins / 'MCGUI.jar').exists())
|
||||
self.assertFalse((self.data / 'mcgui').exists())
|
||||
self.assertEqual((self.plugins / 'other.jar').read_bytes(), b'unrelated')
|
||||
self.assertIn('owner-setting: preserve', (self.data / 'config.yml').read_text())
|
||||
self.assertIn('unrelated: keep', (self.data / 'gui-pack.yml').read_text())
|
||||
for name in m.JARS:
|
||||
self.assertEqual((self.plugins / name).read_bytes(), (self.bundle / name).read_bytes())
|
||||
|
||||
def test_checksum_failure_does_not_stop_service(self):
|
||||
(self.bundle / 'DuneMenus.jar').write_bytes(b'corrupt')
|
||||
with self.assertRaisesRegex(ValueError, 'checksum'):
|
||||
self.invoke()
|
||||
self.assertEqual(self.calls, [])
|
||||
self.assertEqual(self.before, self.snapshot())
|
||||
|
||||
def test_missing_config_does_not_stop_service(self):
|
||||
(self.data / 'gui-pack.yml').unlink()
|
||||
with self.assertRaisesRegex(ValueError, 'configuration'):
|
||||
self.invoke()
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_partial_jar_and_config_failures_restore_all_files(self):
|
||||
for failing_name in ['DuneMenus.jar', 'gui-pack.yml']:
|
||||
real = m.owned_replace
|
||||
failed = False
|
||||
|
||||
def injected(source, target):
|
||||
nonlocal failed
|
||||
if target.name == failing_name and not failed:
|
||||
failed = True
|
||||
raise OSError('injected copy/config failure')
|
||||
return real(source, target)
|
||||
|
||||
with patch.object(m, 'owned_replace', side_effect=injected):
|
||||
with self.assertRaisesRegex(RuntimeError, 'injected'):
|
||||
self.invoke()
|
||||
self.assertEqual(self.before, self.snapshot())
|
||||
self.assertEqual(self.calls[-1], ['systemctl', 'is-active', '--quiet', self.unit])
|
||||
|
||||
def test_failed_start_restores_files_then_restarts_old_release(self):
|
||||
failed = False
|
||||
|
||||
def runner(args):
|
||||
nonlocal failed
|
||||
self.calls.append(args)
|
||||
if args[1] == 'start' and not failed:
|
||||
failed = True
|
||||
raise OSError('injected start failure')
|
||||
|
||||
with self.assertRaisesRegex(RuntimeError, 'injected start'):
|
||||
self.invoke(runner)
|
||||
self.assertEqual(self.before, self.snapshot())
|
||||
self.assertEqual(sum(c[1] == 'start' for c in self.calls), 2)
|
||||
|
||||
def test_recovery_start_failure_is_explicit(self):
|
||||
def runner(args):
|
||||
self.calls.append(args)
|
||||
if args[1] == 'start':
|
||||
raise OSError('cannot start')
|
||||
|
||||
with self.assertRaisesRegex(RuntimeError, 'Recovery startup failed'):
|
||||
self.invoke(runner)
|
||||
self.assertEqual(self.before, self.snapshot())
|
||||
|
||||
def test_changed_config_at_shutdown_is_preserved(self):
|
||||
def runner(args):
|
||||
self.calls.append(args)
|
||||
if args[1] == 'stop':
|
||||
(self.data / 'config.yml').write_text('new-owner-setting: keep\n')
|
||||
|
||||
with self.assertRaisesRegex(RuntimeError, 'changed after preflight'):
|
||||
self.invoke(runner)
|
||||
self.assertEqual((self.data / 'config.yml').read_text(), 'new-owner-setting: keep\n')
|
||||
|
||||
def test_wrong_backend_does_not_stop_service(self):
|
||||
with self.assertRaisesRegex(ValueError, 'Unexpected backend'):
|
||||
m.install(self.bundle, self.root, 'wrong', self.backup, self.run_service)
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Loading…
Reference in a new issue

Staff