diff --git a/.forgejo/workflows/plugins.yml b/.forgejo/workflows/plugins.yml index 3c6c287e..837231e1 100644 --- a/.forgejo/workflows/plugins.yml +++ b/.forgejo/workflows/plugins.yml @@ -56,15 +56,6 @@ jobs: path: plugin-artifacts/ if-no-files-found: error - - name: Test release installer failure recovery - shell: bash - run: | - set -euo pipefail - if ! python3 -c 'import yaml'; then - apt-get update - apt-get install -y --no-install-recommends python3-yaml - fi - python3 -m unittest discover -s tools -p test_dunemenus_installer.py -v - name: Test and build the replacement DuneMenus plugin shell: bash run: | diff --git a/DuneMenus/build.gradle.kts b/DuneMenus/build.gradle.kts index 595838a4..999ea2d1 100644 --- a/DuneMenus/build.gradle.kts +++ b/DuneMenus/build.gradle.kts @@ -21,6 +21,16 @@ tasks.withType { 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() } diff --git a/network/resource-pack/dunemenus-v7.nginx.conf b/network/resource-pack/dunemenus-v7.nginx.conf deleted file mode 100644 index 127cced7..00000000 --- a/network/resource-pack/dunemenus-v7.nginx.conf +++ /dev/null @@ -1,6 +0,0 @@ -location = /downloads/DuneRealms-Network-Artwork-v7.zip { - alias /var/lib/dunerealms-public-downloads/DuneRealms-Network-Artwork-v7.zip; - default_type application/zip; - add_header Cache-Control "public, max-age=31536000, immutable"; - add_header X-Content-Type-Options nosniff; -} diff --git a/tools/build-dunemenus-release.py b/tools/build-dunemenus-release.py index fa0c4fd6..3952cf8e 100644 --- a/tools/build-dunemenus-release.py +++ b/tools/build-dunemenus-release.py @@ -12,9 +12,6 @@ assets=[art/'assets/dunerealms/font/gui.json',*sorted((art/'assets/dunerealms/te assert len(assets)==13 font=json.loads(assets[0].read_text(encoding='utf-8')) for p in assets:entries[p.relative_to(art).as_posix()]=p.read_bytes() -for name in ['items/spy_module.json','models/item/spy_module.json','textures/item/spy_module.png']: - p=art/'assets/dunerealms'/name - entries[p.relative_to(art).as_posix()]=p.read_bytes() for provider in font['providers']: if provider.get('type')=='bitmap': namespace,path=provider['file'].split(':',1) @@ -23,11 +20,9 @@ pack=out/'DuneRealms-Network-Artwork-v7.zip' with zipfile.ZipFile(pack,'w',zipfile.ZIP_DEFLATED,compresslevel=9) as z: for name,data in sorted(entries.items()): zi=zipfile.ZipInfo(name,(2026,11,28,0,0,0));zi.compress_type=zipfile.ZIP_DEFLATED;z.writestr(zi,data) -for module,name in [('DuneMenus','DuneMenus.jar'),('DuneEss','DuneRealms-Essentials.jar'),('DuneLobby','DuneRealms-Lobby.jar'),('DuneRealms-minecraft-only','DuneRealms-Core.jar'),('DuneNPC','DuneRealms-NPC.jar'),('JarvisConnector','jarvistranslator.jar')]: +for module,name in [('DuneMenus','DuneMenus.jar'),('DuneEss','DuneRealms-Essentials.jar'),('DuneLobby','DuneRealms-Lobby.jar'),('DuneRealms-minecraft-only','DuneRealms-Core.jar'),('JarvisConnector','jarvistranslator.jar')]: shutil.copy2(root/module/'build/libs'/name,out/name) shutil.copy2(root/'tools/install-dunemenus-release.py',out/'install-dunemenus-release.py') -shutil.copy2(root/'network/resource-pack/dunemenus-v7.nginx.conf',out/'dunemenus-v7.nginx.conf') -shutil.copy2(root/'tools/publish-dunemenus-pack.py',out/'publish-dunemenus-pack.py') manifest={'source':subprocess.check_output(['git','rev-parse','HEAD'],cwd=root,text=True).strip(),'input_zip_sha256':'6d3cde343ba09fb7088a3a07b0c54c96eeb629c82c527993a76000013c305b60','pack_url':'https://www.dunerealms.com/downloads/'+pack.name,'files':{}} for p in sorted(out.iterdir()): if p.is_file() and p.name!='release.json': diff --git a/tools/install-dunemenus-release.py b/tools/install-dunemenus-release.py index 69d8b402..486f3053 100644 --- a/tools/install-dunemenus-release.py +++ b/tools/install-dunemenus-release.py @@ -1,155 +1,55 @@ -"""Install one recorded build into one backend, with bounded file/service recovery.""" +"""Install one verified build into one explicitly named backend. Called from the build artifact.""" from pathlib import Path -import datetime, hashlib, json, os, re, shutil, subprocess, sys, yaml -from zipfile import ZipFile - -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', 'DuneRealms-NPC.jar', 'jarvistranslator.jar'} -LEGACY = ('DunerealmsGUI.jar', 'DuneRealmsGUI.jar', 'DuneFullscreenPaper.jar', 'MCGUI.jar', - 'DunerealmsGUI', 'DuneRealmsGUI', 'DuneFullscreenPaper', 'MCGUI') -PACK = 'DuneRealms-Network-Artwork-v7.zip' -IDENTITIES = {'DuneMenus.jar': 'DuneMenus', 'DuneRealms-Essentials.jar': 'DuneEss', - 'DuneRealms-Lobby.jar': 'DuneLobby', 'DuneRealms-Core.jar': 'DuneCore', - 'DuneRealms-NPC.jar': 'DuneNPC', 'jarvistranslator.jar': 'JarvisTranslator'} - -def plugin_name(path): - with ZipFile(path) as archive: - return yaml.safe_load(archive.read('plugin.yml'))['name'] - -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}) - installed = {} - for jar in plugins.glob('*.jar'): - try: - identity = plugin_name(jar) - except Exception: - require(not any(jar.name.lower().startswith(prefix) for prefix in - ('dunemenus', 'dunecore', 'duneess', 'dunelobby', 'dunenpc', 'dunerealms-npc', 'dunerealms-core', - 'dunerealms-essentials', 'dunerealms-lobby', 'jarvistranslator')), - 'Unreadable first-party plugin: '+jar.name) - continue - if identity in IDENTITIES.values(): - require(identity not in installed, 'Duplicate installed plugin: '+identity) - installed[identity] = jar - require('DuneMenus' in installed, 'DuneMenus identity missing') - replacements = {} - for name, identity in IDENTITIES.items(): - require(plugin_name(bundle/name) == identity, 'Unexpected artifact plugin identity: '+name) - if identity in installed: - replacements[name] = installed[identity] - jars = sorted(replacements) - targets = [*replacements.values(), *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 p.name in {t.name for t in targets} 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 = {p.name for p in replacements.values()} | 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 = next((bundle/name for name, path in replacements.items() if path == target), staged/target.name) - changed.append(target); owned_replace(source, target) - require(all(digest(replacements[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': {replacements[name].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]))) +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)) diff --git a/tools/publish-dunemenus-pack.py b/tools/publish-dunemenus-pack.py deleted file mode 100644 index e2b0ebca..00000000 --- a/tools/publish-dunemenus-pack.py +++ /dev/null @@ -1,59 +0,0 @@ -"""Publish the recorded v7 pack at its exact existing DuneRealms download host.""" -from pathlib import Path -import datetime -import hashlib -import json -import os -import shutil -import subprocess - -bundle = Path(__file__).resolve().parent -manifest = json.loads((bundle / 'release.json').read_text()) -names = ['DuneRealms-Network-Artwork-v7.zip', 'dunemenus-v7.nginx.conf'] -for name in names: - if hashlib.sha256((bundle / name).read_bytes()).hexdigest() != manifest['files'][name]['sha256']: - raise ValueError('Publication checksum differs: ' + name) -downloads = Path('/var/lib/dunerealms-public-downloads') -parent = Path('/etc/nginx/snippets/dunerealms-gui-download-v3.conf') -route = Path('/etc/nginx/snippets/dunemenus-v7.nginx.conf') -pack = downloads / names[0] -if not downloads.is_dir() or not parent.is_file() or any(p.is_symlink() for p in [parent, route, pack]): - raise ValueError('Unexpected publication paths') -include = 'include /etc/nginx/snippets/dunemenus-v7.nginx.conf;' -old_parent = parent.read_bytes() -if include not in old_parent.decode() and names[0] in old_parent.decode(): - raise ValueError('An unmanaged v7 route already exists') -for path, source in [(pack, bundle / names[0]), (route, bundle / names[1])]: - if path.exists() and path.read_bytes() != source.read_bytes(): - raise ValueError('Refusing to overwrite different versioned content: ' + str(path)) -stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ') -backup = Path('/root/dunemenus-pack-before-' + stamp) -backup.mkdir(mode=0o700) -originals = {p: p.read_bytes() if p.exists() else None for p in [pack, route, parent]} -for path, content in originals.items(): - if content is not None: - shutil.copy2(path, backup / path.name) -try: - for destination, source in [(pack, bundle / names[0]), (route, bundle / names[1])]: - staged = destination.with_name(destination.name + '.build-staged') - if staged.exists() or staged.is_symlink(): - raise ValueError('Staging path exists') - shutil.copyfile(source, staged) - os.chmod(staged, 0o644) - os.replace(staged, destination) - if include not in old_parent.decode(): - parent.write_bytes(old_parent.rstrip() + b'\n' + include.encode() + b'\n') - subprocess.run(['nginx', '-t'], check=True, timeout=30) - subprocess.run(['systemctl', 'reload', 'nginx'], check=True, timeout=30) -except Exception: - for path, content in originals.items(): - if content is None: - if path.exists(): - path.unlink() - else: - path.write_bytes(content) - subprocess.run(['nginx', '-t'], check=True, timeout=30) - subprocess.run(['systemctl', 'reload', 'nginx'], check=True, timeout=30) - raise -print(json.dumps({'source': manifest['source'], 'backup': str(backup), 'url': manifest['pack_url'], - 'sha256': manifest['files'][names[0]]['sha256']})) diff --git a/tools/test_dunemenus_installer.py b/tools/test_dunemenus_installer.py deleted file mode 100644 index 94be3d81..00000000 --- a/tools/test_dunemenus_installer.py +++ /dev/null @@ -1,164 +0,0 @@ -import hashlib -import importlib.util -import json -import pathlib -import tempfile -import unittest -from unittest.mock import patch -from zipfile import ZipFile - -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) - if name in m.JARS: - with ZipFile(self.bundle / name, 'w') as archive: - archive.writestr('plugin.yml', 'name: ' + m.IDENTITIES[name]) - archive.writestr('build.txt', payload) - payload = (self.bundle / name).read_bytes() - files[name] = {'sha256': hashlib.sha256(payload).hexdigest(), 'sha1': hashlib.sha1(payload).hexdigest()} - if name in m.JARS: - with ZipFile(self.plugins / name, 'w') as archive: - archive.writestr('plugin.yml', 'name: ' + m.IDENTITIES[name]) - archive.writestr('build.txt', 'old-' + name) - (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, []) - - def test_legacy_versioned_filenames_are_replaced_without_duplicates(self): - aliases = {'DuneRealms-Core.jar': 'DuneCore-1.0.10.jar', - 'DuneRealms-Essentials.jar': 'DuneEss-1.0.2.jar', - 'DuneRealms-NPC.jar': 'DuneNPC-1.0.0.jar'} - for source, target in aliases.items(): - (self.plugins / source).rename(self.plugins / target) - result = self.invoke() - for source, target in aliases.items(): - self.assertFalse((self.plugins / source).exists()) - self.assertEqual((self.plugins / target).read_bytes(), (self.bundle / source).read_bytes()) - self.assertIn(target, result['jars']) - - -if __name__ == '__main__': - unittest.main()