Build reproducible GUI renderer verification and safe fleet installer
This commit is contained in:
parent
794a96b5f8
commit
72a11f0870
8 changed files with 407 additions and 3 deletions
|
|
@ -12,6 +12,7 @@ on:
|
|||
- 'network/resource-pack/shared/**'
|
||||
- 'network/content-assets/planet-artwork/profiles.json'
|
||||
- 'tools/*gameplay*'
|
||||
- 'tools/*plugin*'
|
||||
|
||||
jobs:
|
||||
plugins:
|
||||
|
|
@ -54,10 +55,13 @@ jobs:
|
|||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
python3 tools/test_plugin_fleet_install.py -v
|
||||
python3 tools/test_gameplay_resourcepack.py -v
|
||||
python3 tools/build-gameplay-resourcepack.py --from-gui-config DuneRealmsGUI/src/main/resources/gui-pack.yml --output "plugin-artifacts/DuneRealms-Gameplay-${GITHUB_SHA}.zip"
|
||||
python3 tools/write-plugin-manifest.py plugin-artifacts "$GITHUB_SHA"
|
||||
(cd plugin-artifacts && sha256sum -- *.jar *.zip *.json SOURCE_COMMIT > SHA256SUMS)
|
||||
cp tools/install-plugin-fleet.py plugin-artifacts/
|
||||
cp DuneMenus/docs/FLEET-INSTALL.md plugin-artifacts/
|
||||
(cd plugin-artifacts && sha256sum -- *.jar *.zip *.json *.py *.md SOURCE_COMMIT > SHA256SUMS)
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: DuneRealms-Plugins
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import java.security.MessageDigest
|
||||
plugins { java }
|
||||
group = "com.dunerealms"
|
||||
version = "2.0.1"
|
||||
|
|
@ -21,3 +22,30 @@ tasks.jar { archiveFileName.set("DuneMenus.jar") }
|
|||
tasks.processResources { filesMatching("plugin.yml") { expand("version" to project.version) } }
|
||||
|
||||
tasks.test { useJUnitPlatform() }
|
||||
|
||||
// Optional, reproducible verification against the privately supplied, pinned MCGUI runtime.
|
||||
// The third-party JAR is never bundled or committed.
|
||||
val mcguiRuntime = providers.gradleProperty("mcguiRuntime")
|
||||
val rendererRuntimeFiles = mcguiRuntime.map { files(it) }.getOrElse(files())
|
||||
val rendererTest by sourceSets.creating {
|
||||
compileClasspath += sourceSets.main.get().output + rendererRuntimeFiles
|
||||
runtimeClasspath += sourceSets.main.get().output + rendererRuntimeFiles
|
||||
}
|
||||
val verifyRendererRuntime by tasks.registering {
|
||||
doLast {
|
||||
require(mcguiRuntime.isPresent) { "Supply -PmcguiRuntime=<existing MCGUI-0.8.6.jar>" }
|
||||
val jar = file(mcguiRuntime.get())
|
||||
require(jar.isFile) { "MCGUI runtime file not found" }
|
||||
val hash = MessageDigest.getInstance("SHA-256").digest(jar.readBytes()).joinToString("") { "%02x".format(it) }
|
||||
require(hash == "69a454291cc27c36cdbc680bfbde245a90a3913de53cc1591c502a5a49124300") { "MCGUI runtime differs from reviewed test input" }
|
||||
logger.lifecycle("Renderer verification: MCGUI0.8.6 SHA-256 {}", hash)
|
||||
}
|
||||
}
|
||||
tasks.named(rendererTest.compileJavaTaskName) { dependsOn(verifyRendererRuntime) }
|
||||
tasks.register<JavaExec>("verifyMenuRenderer") {
|
||||
dependsOn(rendererTest.classesTaskName)
|
||||
classpath = rendererTest.runtimeClasspath
|
||||
mainClass.set("com.dunerealms.menus.RendererVerification")
|
||||
jvmArgs("-Djava.awt.headless=true")
|
||||
args(providers.gradleProperty("rendererOutput").getOrElse(layout.buildDirectory.dir("renderer-verification").get().asFile.absolutePath))
|
||||
}
|
||||
|
|
|
|||
11
DuneMenus/docs/FLEET-INSTALL.md
Normal file
11
DuneMenus/docs/FLEET-INSTALL.md
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
# Verified plugin fleet installation
|
||||
|
||||
Use only the installer and JARs emitted together by canonical plugin CI. This installer is for existing servers, not bootstrap provisioning. It never discovers or guesses server paths, assigns plugins to a server, removes unrelated backends, deploys website files, or installs private third-party dependencies.
|
||||
|
||||
The coordinator supplies an independently verified inventory JSON. Each `servers` entry requires `id`, absolute `root`, existing `serviceUnit`, and an explicit list of artifact filenames from `release-manifest.json`. Do not populate these from historical example paths. DuneMenus requires JARVIS, DunerealmsGUI and the existing MCGUI runtime; DuneNPC is retained.
|
||||
|
||||
First run a read-only plan with `--artifacts`, `--inventory`, and `--expected-source` set to the exact CI source SHA. Apply that same inventory with `--apply --backup-root` only through the authorised host deployment entry point. No SSH implementation is embedded in this tool.
|
||||
|
||||
All artifacts, descriptors, installed-file snapshots and backups are verified. Services must be fully stopped before JAR replacement; active services restart afterward, previously stopped services remain stopped. Old filenames are replaced by actual plugin identity. On an installation/start failure, original bytes and filenames are restored after verifying the service is stopped, and a rollback receipt is retained. A rollback that cannot stop the service halts without replacing active JARs. A multi-server failure may leave earlier servers installed; inspect each receipt.
|
||||
|
||||
An `installed-service-active` receipt proves file installation and systemd state only. It does not prove Minecraft finished loading or an NPC interaction worked. Verify server logs, enabled versions, resource-pack publication/configuration, actual GUI/NPC actions and retained progression separately before reporting rollout complete. Resource-pack hosting/configuration is not changed by this JAR installer.
|
||||
|
|
@ -17,6 +17,19 @@
|
|||
|
||||
The new Java renderer consumes the ZIP menu definitions and direct slot callbacks; it does not use old MenuDocument selected-card pages. Existing native service models are wrapped without replacing their callback implementations. Shared NativeMenus inventory entry points (including DuneNPC travel) also enter the replacement. Estate services retain the original claim/Home Block/deployment screens; website-only organisation functions link to their existing management pages. No new confirmation intermediary is added.
|
||||
|
||||
Local verification: 140 Java sources compile for release21 against cached Paper1.21.8 dependencies; 14 focused tests pass. Four resource-pack tests pass and validate item-card fonts/textures in the actual ZIP. Browser render fixtures are local design evidence only. Full CI, actual MCGUI renderer comparison and live NPC/function checks remain required before declaring deployment complete.
|
||||
Local verification: 140 Java sources compile for release21 against cached Paper1.21.8 dependencies; 14 focused tests pass. Four resource-pack tests pass and validate item-card fonts/textures in the actual ZIP. Browser render fixtures are local design evidence only. Actual MCGUI0.8.6 rendering additionally passed15 menu families and152 direct action hitboxes, including long-page scrolling; runtime SHA-256 is pinned in the optional verifyMenuRenderer build task. Full exact-head CI and live NPC/function checks remain required before declaring deployment complete.
|
||||
|
||||
Known visual work remains: the supplied preview's bespoke illustrations are reference artwork, while the dedicated canvas currently implements the gold/emerald frame, themed scenes, direct card grid, travel constellation and journal/council/bank layouts. Do not describe this as pixel-identical preview parity or a live install.
|
||||
|
||||
|
||||
Reproduce actual renderer verification through the build (the JAR stays private):
|
||||
|
||||
```sh
|
||||
gradle -p DuneMenus verifyMenuRenderer -PmcguiRuntime=/verified/private/MCGUI-0.8.6.jar
|
||||
```
|
||||
|
||||
The example path is a parameter, not a deployment location. This task checks the reviewed input hash and produces15 engine-rendered PNGs. Fixture entries are synthetic test data and never contact a game account or execute a purchase.
|
||||
|
||||
Local Java21 Gradle verification completed successfully using cached dependencies (`--offline`) after the local JDK trust store rejected online Maven TLS. `test jar verifyMenuRenderer` built the frontend and JARVIS dependency, ran their tests and rendered all15 families/152 hitboxes. Canonical CI uses Gradle9.2.1 and is reported separately by exact commit.
|
||||
|
||||
The build also ships the manifest-driven fleet installer and its tested rollback path. See FLEET-INSTALL.md. This is deployable tooling, not evidence that any host was changed.
|
||||
|
|
|
|||
|
|
@ -14,6 +14,6 @@ final class SuppliedDocument {
|
|||
b.append("</main><section class='facts'>");for(String line:info)b.append("<p>").append(escape(line)).append("</p>");return b.append("</section></div><footer><span class='seal'>◆ J.A.R.V.I.S. ◆</span></footer></div></body></html>").toString();
|
||||
}
|
||||
private static final String CSS="""
|
||||
*{box-sizing:border-box}body{margin:0;padding:12px;background:#03100f;color:#f1e7cd;font-family:Georgia,serif;font-size:13px}button{font-family:Georgia,serif;color:#f4df9d;cursor:pointer}.frame{min-height:570px;border:2px solid #b69149;outline:1px solid #645334;outline-offset:5px;background:#081e1b;position:relative;overflow:hidden}header{height:78px;border-bottom:2px solid #ae8943;background:linear-gradient(90deg,#102f29,#041512);display:flex;align-items:center;padding:8px 22px;gap:22px}.brand{display:flex;align-items:center;gap:8px;color:#d6ad58;font-size:38px;border-right:1px solid #7c683b;padding-right:20px}.brand span{font-size:16px;line-height:17px;letter-spacing:3px}.heading{flex:1}small{font-size:10px;letter-spacing:3px;color:#ad985f}h1{font-size:26px;margin:5px 0 0;color:#eed995;letter-spacing:1px}.close{width:31px;height:31px;border:1px solid #a58b4d;background:#112922;font-size:24px}.scene{position:relative;min-height:411px;padding:0 28px;overflow:hidden;background:linear-gradient(#162d30,#53665a 58%,#a88c52)}.quote{text-align:center;font-style:italic;position:relative;z-index:1;padding:12px 0 8px;margin:0;color:#f4e7bf}.dune{position:absolute;left:-12%;width:125%;height:180px;border-radius:55% 70% 0 0;pointer-events:none}.rear{bottom:0;background:#b4955a;transform:rotate(-8deg)}.front{bottom:-90px;background:#635a38;transform:rotate(9deg)}.moon{position:absolute;right:15%;top:23px;background:#e4dbb6;border-radius:50%;width:45px;height:45px;opacity:.55}main{position:relative;z-index:2}.doors,.bank{display:flex;flex-wrap:wrap;gap:12px;justify-content:center;padding:12px 0 35px}.card{background:linear-gradient(135deg,#173e35,#0c201d);border:1px solid #b59349;box-shadow:inset 0 0 0 3px #0a231f,0 3px 8px #071713;padding:12px;min-height:94px;display:flex;align-items:center;gap:12px;text-align:left;width:22.5%}.card:hover{background:linear-gradient(135deg,#315c45,#183c32);border-color:#f3d784}.emblem{font-size:34px;color:var(--accent);width:35px;flex-shrink:0;text-align:center}h2{font-size:16px;margin:0 0 6px}p{margin:3px 0;font-size:11px;line-height:1.35;color:#d1d3bc}.back{position:absolute;bottom:2px;left:0;background:#12372c;border:1px solid #ad8c48;padding:7px 12px;display:flex;align-items:center;gap:8px}.pager{border:1px solid #ad8c48;background:#12372c;padding:10px;display:flex;gap:8px;align-items:center}.back .emblem{font-size:17px;width:auto}.back h2{margin:0;font-size:12px}.back p{display:none}.hub .card{width:22%;min-height:89px}.hub .emblem{font-size:30px}.journal{display:flex;flex-direction:column;gap:8px;padding:8px 9% 45px}.journal .card{width:100%;min-height:68px;padding:8px 18px}.journal .card p{display:inline;margin-right:12px}.council{display:flex;flex-wrap:wrap;gap:16px;justify-content:center;padding:20px 8% 44px}.council .card{width:29%;min-height:115px;border-top:3px solid var(--accent)}.bank .card{width:30%;min-height:100px}.travel .scene{background:radial-gradient(ellipse at center,#123a40,#061317)}.travel .dune,.travel .moon{display:none}.constellation{height:350px;position:relative}.constellation .card{position:absolute;width:230px;min-height:83px;border-color:#74aeb6;background:linear-gradient(135deg,#173e43,#091c23)}.constellation .n0{top:0;left:36%}.constellation .n1{top:98px;left:0}.constellation .n2{top:98px;right:0}.constellation .n3{top:225px;left:12%}.constellation .n4{top:225px;right:12%}.constellation .back{bottom:0}.guild{position:absolute;top:168px;left:44%;font-size:52px;color:#c4dcdf;text-align:center}.guild span{display:block;font-size:11px;letter-spacing:2px}.orbit{position:absolute;border:1px solid #467b84;width:62%;height:170px;top:130px;left:19%;border-radius:50%;transform:rotate(24deg)}.orbit.two{transform:rotate(-24deg)}footer{height:76px;padding:9px 22px;background:#0b211c;border-top:1px solid #a88b47;display:flex;align-items:center;gap:22px}.facts{position:relative;padding:12px 0 24px;z-index:2}.facts p{font-size:11px;color:#c0c9b2}.seal{font-size:10px;letter-spacing:2px;color:#bda464}.war .scene{background:linear-gradient(#2e2424,#182c26)}.spice .scene{background:linear-gradient(#715232,#bc9251)}.politics .scene{background:linear-gradient(#2f2444,#132c27)}
|
||||
*{box-sizing:border-box}body{margin:0;padding:12px;background:#03100f;color:#f1e7cd;font-family:Georgia,serif;font-size:13px}button{font-family:Georgia,serif;color:#f4df9d;cursor:pointer}.frame{min-height:570px;border:2px solid #b69149;outline:1px solid #645334;outline-offset:5px;background:#081e1b;position:relative;overflow:hidden}header{height:78px;border-bottom:2px solid #ae8943;background:linear-gradient(90deg,#102f29,#041512);display:flex;align-items:center;padding:8px 22px;gap:22px}.brand{display:flex;align-items:center;gap:8px;color:#d6ad58;font-size:38px;border-right:1px solid #7c683b;padding-right:20px}.brand span{font-size:16px;line-height:17px;letter-spacing:3px}.heading{flex:1}small{font-size:10px;letter-spacing:3px;color:#ad985f}h1{font-size:26px;margin:5px 0 0;color:#eed995;letter-spacing:1px}.close{width:31px;height:31px;border:1px solid #a58b4d;background:#112922;font-size:24px}.scene{position:relative;min-height:411px;padding:0 28px;overflow:hidden;background:linear-gradient(#162d30,#53665a 58%,#a88c52)}.quote{text-align:center;font-style:italic;position:relative;z-index:1;padding:12px 0 8px;margin:0;color:#f4e7bf}.dune{position:absolute;left:-12%;width:125%;height:180px;border-radius:55% 70% 0 0;pointer-events:none}.rear{bottom:0;background:#b4955a;transform:rotate(-8deg)}.front{bottom:-90px;background:#635a38;transform:rotate(9deg)}.moon{position:absolute;right:15%;top:23px;background:#e4dbb6;border-radius:50%;width:45px;height:45px;opacity:.55}main{position:relative;z-index:2}.doors,.bank{display:flex;flex-wrap:wrap;gap:12px;justify-content:center;padding:12px 0 35px}.card{background:linear-gradient(135deg,#173e35,#0c201d);border:1px solid #b59349;box-shadow:inset 0 0 0 3px #0a231f,0 3px 8px #071713;padding:12px;min-height:94px;display:flex;align-items:center;gap:12px;text-align:left;width:22.5%}.card>div{min-width:0;flex:1}.card h2{overflow-wrap:break-word;white-space:normal}.card:hover{background:linear-gradient(135deg,#315c45,#183c32);border-color:#f3d784}.emblem{font-size:34px;color:var(--accent);width:35px;flex-shrink:0;text-align:center}h2{font-size:16px;margin:0 0 6px}p{margin:3px 0;font-size:11px;line-height:1.35;color:#d1d3bc}.back{position:absolute;bottom:2px;left:0;background:#12372c;border:1px solid #ad8c48;padding:7px 12px;display:flex;align-items:center;gap:8px}.pager{border:1px solid #ad8c48;background:#12372c;padding:10px;display:flex;gap:8px;align-items:center}.back .emblem{font-size:17px;width:auto}.back h2{margin:0;font-size:12px}.back p{display:none}.hub .card{width:22%;min-height:89px}.hub .emblem{font-size:30px}.journal{display:flex;flex-direction:column;gap:8px;padding:8px 9% 45px}.journal .card{width:100%;min-height:68px;padding:8px 18px}.journal .card p{display:inline;margin-right:12px}.council{display:flex;flex-wrap:wrap;gap:16px;justify-content:center;padding:20px 8% 44px}.council .card{width:29%;min-height:115px;border-top:3px solid var(--accent)}.bank .card{width:30%;min-height:100px}.travel .scene{background:radial-gradient(ellipse at center,#123a40,#061317)}.travel .dune,.travel .moon{display:none}.constellation{height:350px;position:relative}.constellation .card{position:absolute;width:230px;min-height:83px;border-color:#74aeb6;background:linear-gradient(135deg,#173e43,#091c23)}.constellation .n0{top:0;left:36%}.constellation .n1{top:98px;left:0}.constellation .n2{top:98px;right:0}.constellation .n3{top:225px;left:12%}.constellation .n4{top:225px;right:12%}.constellation .back{bottom:0}.guild{position:absolute;top:168px;left:44%;font-size:52px;color:#c4dcdf;text-align:center}.guild span{display:block;font-size:11px;letter-spacing:2px}.orbit{position:absolute;border:1px solid #467b84;width:62%;height:170px;top:130px;left:19%;border-radius:50%;transform:rotate(24deg)}.orbit.two{transform:rotate(-24deg)}footer{height:76px;padding:9px 22px;background:#0b211c;border-top:1px solid #a88b47;display:flex;align-items:center;gap:22px}.facts{position:relative;padding:12px 0 24px;z-index:2}.facts p{font-size:11px;color:#c0c9b2}.seal{font-size:10px;letter-spacing:2px;color:#bda464}.war .scene{background:linear-gradient(#2e2424,#182c26)}.spice .scene{background:linear-gradient(#715232,#bc9251)}.politics .scene{background:linear-gradient(#2f2444,#132c27)}
|
||||
""";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,26 @@
|
|||
package com.dunerealms.menus;
|
||||
import java.nio.file.*;import java.util.*;import java.awt.geom.*;import javax.imageio.ImageIO;import ai.resourcepack.ui.html.*;import ai.resourcepack.ui.html.css.Selector;
|
||||
public class RendererVerification {
|
||||
public static void main(String[]args)throws Exception{
|
||||
Path dir=Path.of(args[0]);Files.createDirectories(dir);var loader=new Page.Loader(false,dir.resolve("engine-cache"));int checked=0;
|
||||
for(String id:List.of("hub","travel","exchange","clan","company","missions","spice","war","politics","house","equipment","bank","atm","withdraw","transfer")){
|
||||
List<Card> cards=new ArrayList<>();int count=id.equals("exchange")?28:id.equals("travel")?5:8;
|
||||
for(int n=0;n<count;n++)cards.add(new Card(n,(n==0?"Imperial Postbank":"Entry "+(n+1)),List.of("Verified service detail","Amount: 100.00 DM"),id.equals("travel")?"compass":"emerald"));
|
||||
cards.add(new Card(45,"Back",List.of(),"arrow"));
|
||||
String html=SuppliedDocument.html(id,"DuneRealms · "+id,"Service information",cards,List.of("Read-only account and permission details"));
|
||||
Path file=dir.resolve(id+"-matrix.html");Files.writeString(file,html);var page=Page.of(html,file,loader);var frame=HtmlRenderer.render(page,1536,896,1.5,0,Selector.State.NONE);
|
||||
if(!page.problems.isEmpty())throw new AssertionError(id+" parser problems "+page.problems);
|
||||
ImageIO.write(frame.image(),"png",dir.resolve(id+"-matrix-engine.png").toFile());
|
||||
for(Card card:cards){
|
||||
var element=page.document.selectFirst("[data-slot='"+card.slot()+"']");var bounds=frame.boundsOf(element);
|
||||
if(bounds==null||bounds.getWidth()<=0||bounds.getHeight()<=0)throw new AssertionError(id+" invisible slot "+card.slot());
|
||||
double scroll=Math.max(0,Math.min(frame.maxScroll(),bounds.getCenterY()-260));var visible=HtmlRenderer.render(page,1536,896,1.5,scroll,Selector.State.NONE);
|
||||
var at=visible.elementAt(bounds.getCenterX(),bounds.getCenterY()-scroll);var button=at==null?null:at.closest("[data-slot]");
|
||||
if(button==null||!button.attr("data-slot").equals(""+card.slot()))throw new AssertionError(id+" hit slot "+card.slot()+" at "+bounds+" scroll="+scroll+" got="+button);
|
||||
checked++;
|
||||
}
|
||||
System.out.println(id+": parser clean; "+cards.size()+" action hitboxes; maxScroll="+frame.maxScroll());
|
||||
}
|
||||
System.out.println("PASS: "+checked+" direct action hitboxes across15 menu families.");
|
||||
}
|
||||
}
|
||||
194
tools/install-plugin-fleet.py
Normal file
194
tools/install-plugin-fleet.py
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
"""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
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import zipfile
|
||||
|
||||
|
||||
def digest(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
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))
|
||||
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')
|
||||
wanted = {files[name]['name'].casefold() for name in selected}
|
||||
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 name in selected:
|
||||
if (plugins / name).exists() and name not in old_names:
|
||||
raise ValueError('Artifact filename collides with another plugin: ' + name)
|
||||
servers.append({'id': sid, 'root': str(root), 'serviceUnit': unit,
|
||||
'artifacts': [files[name] for name in selected], 'previous': previous})
|
||||
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')
|
||||
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')
|
||||
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)
|
||||
import os
|
||||
os.close(fd)
|
||||
temporary = Path(temporary)
|
||||
try:
|
||||
shutil.copy2(entry['source'], temporary)
|
||||
if digest(temporary) != entry['sha256']:
|
||||
raise RuntimeError('Staged checksum differs')
|
||||
temporary.replace(plugins / entry['filename']); installed.append(entry['filename'])
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
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'])
|
||||
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()
|
||||
128
tools/test_plugin_fleet_install.py
Normal file
128
tools/test_plugin_fleet_install.py
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
import zipfile
|
||||
|
||||
spec = importlib.util.spec_from_file_location('installer', Path(__file__).with_name('install-plugin-fleet.py'))
|
||||
installer = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(installer)
|
||||
SOURCE = 'a' * 40
|
||||
|
||||
|
||||
def jar(path, name, version='1'):
|
||||
with zipfile.ZipFile(path, 'w') as archive:
|
||||
archive.writestr('plugin.yml', f'name: {name}\nversion: {version}\nmain: example.Main\n')
|
||||
|
||||
|
||||
class Service:
|
||||
def __init__(self, active=True, fail_start=False):
|
||||
self.active, self.fail_start, self.calls = active, fail_start, []
|
||||
|
||||
def __call__(self, *args):
|
||||
self.calls.append(args)
|
||||
status, text = 0, ''
|
||||
if args[0] == 'show':
|
||||
text = ('active\n' if self.active else 'inactive\n') if '--property=ActiveState' in args else 'loaded\n'
|
||||
elif args[0] == 'is-active':
|
||||
status = 0 if self.active else 3
|
||||
elif args[0] == 'stop':
|
||||
self.active = False
|
||||
elif args[0] == 'start':
|
||||
if self.fail_start:
|
||||
self.fail_start = False; status = 1
|
||||
else:
|
||||
self.active = True
|
||||
return subprocess.CompletedProcess(args, status, stdout=text, stderr='')
|
||||
|
||||
|
||||
class FleetInstallerTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(); self.addCleanup(self.temp.cleanup)
|
||||
self.base = Path(self.temp.name); self.artifacts = self.base / 'artifacts'; self.artifacts.mkdir()
|
||||
self.root = self.base / 'game'; self.root.mkdir(); (self.root / 'server.properties').write_text('')
|
||||
self.plugins = self.root / 'plugins'; self.plugins.mkdir()
|
||||
jar(self.artifacts / 'DunerealmsGUI.jar', 'DunerealmsGUI', '2')
|
||||
jar(self.plugins / 'legacy-gui.jar', 'DunerealmsGUI', '1')
|
||||
jar(self.plugins / 'DuneNPC.jar', 'DuneNPC')
|
||||
jar(self.plugins / 'MCGUI.jar', 'MCGUI')
|
||||
self.inventory = {'servers': [{'id': 'test', 'root': str(self.root.resolve()), 'serviceUnit': 'test-game.service', 'artifacts': ['DunerealmsGUI.jar']}]}
|
||||
entry = dict(installer.identity(self.artifacts / 'DunerealmsGUI.jar'), filename='DunerealmsGUI.jar', sha256=installer.digest(self.artifacts / 'DunerealmsGUI.jar'))
|
||||
(self.artifacts / 'release-manifest.json').write_text(json.dumps({'sourceCommit': SOURCE, 'plugins': [entry]}))
|
||||
|
||||
def deployment(self):
|
||||
return installer.plan(self.artifacts, self.inventory, SOURCE)
|
||||
|
||||
def test_planning_is_read_only_and_requires_exact_source_and_hash(self):
|
||||
before = {p.name: p.read_bytes() for p in self.plugins.iterdir()}
|
||||
self.deployment()
|
||||
self.assertEqual(before, {p.name: p.read_bytes() for p in self.plugins.iterdir()})
|
||||
with self.assertRaises(ValueError):
|
||||
installer.plan(self.artifacts, self.inventory, 'b' * 40)
|
||||
with (self.artifacts / 'DunerealmsGUI.jar').open('ab') as stream:
|
||||
stream.write(b'tampered')
|
||||
with self.assertRaises(ValueError):
|
||||
self.deployment()
|
||||
|
||||
def test_replaces_by_identity_and_preserves_backend_and_third_party(self):
|
||||
preserved = {n: (self.plugins / n).read_bytes() for n in ('DuneNPC.jar', 'MCGUI.jar')}
|
||||
service = Service()
|
||||
receipts = installer.apply(self.deployment(), self.base / 'backups', service)
|
||||
self.assertFalse((self.plugins / 'legacy-gui.jar').exists())
|
||||
self.assertEqual(installer.identity(self.plugins / 'DunerealmsGUI.jar')['version'], '2')
|
||||
for name, value in preserved.items():
|
||||
self.assertEqual((self.plugins / name).read_bytes(), value)
|
||||
self.assertTrue(service.active)
|
||||
self.assertEqual(json.loads(Path(receipts[0]).read_text())['status'], 'installed-service-active')
|
||||
self.assertTrue((Path(receipts[0]).parent / 'legacy-gui.jar').is_file())
|
||||
|
||||
def test_failed_start_restores_original_bytes_and_filename(self):
|
||||
before = {p.name: p.read_bytes() for p in self.plugins.iterdir()}
|
||||
service = Service(fail_start=True)
|
||||
with self.assertRaises(RuntimeError):
|
||||
installer.apply(self.deployment(), self.base / 'backups', service)
|
||||
self.assertEqual(before, {p.name: p.read_bytes() for p in self.plugins.iterdir()})
|
||||
self.assertTrue(service.active)
|
||||
receipt = next((self.base / 'backups').rglob('receipt.json'))
|
||||
self.assertEqual(json.loads(receipt.read_text())['status'], 'rolled-back')
|
||||
|
||||
def test_stopped_server_stays_stopped(self):
|
||||
service = Service(active=False)
|
||||
installer.apply(self.deployment(), self.base / 'backups', service)
|
||||
self.assertFalse(service.active)
|
||||
self.assertFalse(any(c[0] in ('stop', 'start') for c in service.calls))
|
||||
|
||||
def test_no_invented_module_mapping_or_filename_collision(self):
|
||||
self.inventory['servers'][0]['artifacts'] = []
|
||||
with self.assertRaises(ValueError):
|
||||
self.deployment()
|
||||
self.inventory['servers'][0]['artifacts'] = ['DunerealmsGUI.jar']
|
||||
jar(self.plugins / 'DunerealmsGUI.jar', 'SomeOtherPlugin')
|
||||
with self.assertRaises(ValueError):
|
||||
self.deployment()
|
||||
|
||||
def test_transitional_service_is_rejected_before_any_stop_or_write(self):
|
||||
service = Service()
|
||||
def transitional(*args):
|
||||
if '--property=ActiveState' in args:
|
||||
return subprocess.CompletedProcess(args, 0, stdout='activating\n', stderr='')
|
||||
return service(*args)
|
||||
before = {p.name: p.read_bytes() for p in self.plugins.iterdir()}
|
||||
with self.assertRaises(RuntimeError):
|
||||
installer.apply(self.deployment(), self.base / 'backups', transitional)
|
||||
self.assertEqual(before, {p.name: p.read_bytes() for p in self.plugins.iterdir()})
|
||||
self.assertFalse(any(c[0] == 'stop' for c in service.calls))
|
||||
|
||||
def test_installation_rejects_files_changed_since_plan(self):
|
||||
deployment = self.deployment()
|
||||
(self.plugins / 'legacy-gui.jar').write_bytes(b'changed')
|
||||
service = Service()
|
||||
with self.assertRaises(ValueError):
|
||||
installer.apply(deployment, self.base / 'backups', service)
|
||||
self.assertFalse(any(c[0] == 'stop' for c in service.calls))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Loading…
Reference in a new issue

Staff