Preserve live backends in GUI rollout and add receipt rollback
This commit is contained in:
parent
e19acd2549
commit
0ca1584d83
15 changed files with 2727 additions and 12 deletions
|
|
@ -44,6 +44,10 @@ jobs:
|
|||
mkdir -p plugin-artifacts
|
||||
for module in "${modules[@]}"; do
|
||||
gradle --no-daemon -p "$module" test jar
|
||||
done
|
||||
# This release restores presentation only. Never ship the known-incompatible
|
||||
# rebuilt economy/backend modules as accidental fleet install candidates.
|
||||
for module in DuneLobby DuneNPC DuneRealmsGUI DuneMenus; do
|
||||
for jar in "$module"/build/libs/*.jar; do
|
||||
test -f "$jar"
|
||||
artifact="plugin-artifacts/${jar##*/}"
|
||||
|
|
@ -59,11 +63,14 @@ jobs:
|
|||
set -euo pipefail
|
||||
python3 tools/test_plugin_fleet_install.py -v
|
||||
python3 tools/test_plugin_menu_pack.py -v
|
||||
python3 tools/test_plugin_backend_abi.py -v
|
||||
python3 tools/test_plugin_fleet_rollback.py -v
|
||||
python3 tools/test_gameplay_resourcepack.py -v
|
||||
python3 tools/build-menu-resourcepack.py --source "$GITHUB_SHA" --output "plugin-artifacts/DuneRealms-Menu-${GITHUB_SHA}.zip"
|
||||
python3 tools/write-plugin-manifest.py plugin-artifacts "$GITHUB_SHA"
|
||||
cp tools/install-plugin-fleet.py tools/plugin_menu_pack.py tools/publish-plugin-menu.py plugin-artifacts/
|
||||
cp DuneMenus/docs/FLEET-INSTALL.md DuneMenus/docs/MENU-PACK-ROLLOUT.md plugin-artifacts/
|
||||
cp tools/install-plugin-fleet.py tools/plugin_menu_pack.py tools/plugin_backend_abi.py tools/plugin_fleet_rollback.py tools/publish-plugin-menu.py plugin-artifacts/
|
||||
cp DuneMenus/src/test/resources/preserved-backend-abi.json plugin-artifacts/
|
||||
cp DuneMenus/docs/FLEET-INSTALL.md DuneMenus/docs/MENU-PACK-ROLLOUT.md DuneMenus/docs/CANARY-RECOVERY-20261129.md plugin-artifacts/
|
||||
(cd plugin-artifacts && sha256sum -- *.jar *.zip *.json *.py *.md SOURCE_COMMIT > SHA256SUMS)
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
|
|
|
|||
13
DuneMenus/docs/CANARY-RECOVERY-20261129.md
Normal file
13
DuneMenus/docs/CANARY-RECOVERY-20261129.md
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
# GUI canary recovery and revised boundary
|
||||
|
||||
Source e19acd25497de3501a9d9b62e9b9e23e5c1521ce passed canonical CI16 (API985). Its immutable composite menu pack was published and independently hash-verified. The lobby-only canary loaded MCGUI0.8.6, DunerealmsGUI1.1.32 and DuneMenus2.0.1 and reached Paper Done in 87.397 seconds. This is startup evidence, not connected-client proof.
|
||||
|
||||
At 02:23:39 the incoming rebuilt Essentials failed its Solaris database initialisation: PostgreSQL `UUID PRIMARY KEY` DDL was rejected by the actual MySQL backend. The wider rollout stopped. No planet was installed. This is a known unresolved compatibility limitation of the rebuilt Essentials module; excluding it from the GUI release does not fix it.
|
||||
|
||||
The authorised coordinator restored exact receipt-backed original lobby JAR/configuration bytes at 02:24:57 and verified original hashes. Original Paper reached Done at 02:26:23. The recovery report is stored alongside the canary receipt under the host's gui-e19acd2 backup. The incoming GUI runtime JARs were removed/restored with the receipt. All four restored original JARs were independently rechecked as UID988/GID988/mode0644. The legacy receipt had not recorded original owners; those recovered metadata values were explicitly set using independently verified service ownership, not recovered from the receipt.
|
||||
|
||||
Missing native-food projection warnings for chukka_cooked_meat and water_of_life also occurred with the original restored JARVIS. They are pre-existing baseline warnings, not evidence of a newly introduced JARVIS regression. They are outside this presentation correction.
|
||||
|
||||
The revised release preserves every live Essentials/JARVIS/Core/Terrain JAR. Only presentation/NPC/Lobby adapters and the private pinned MCGUI prerequisite may be installed. The frontend wraps only exact no-target Essentials menu/travel/exchange entry points; targeted travel, purchases, payments, permissions and other operations delegate unchanged to the existing executor. ABI fixtures contain public signatures and reviewed hashes from two live JARVIS, four Core and three Essentials variants, not private binaries or configuration. The tests audit compiled incoming JARs against every JARVIS/Core variant combination and verify the Essentials command roots. This verifies linkage boundaries, not a player session or a live transaction.
|
||||
|
||||
New receipt-based explicit rollback supports plugin-level readiness failure after systemd reports active. It verifies backup/current bytes, restores original filenames and metadata, and keeps world resource-pack properties untouched. A new successful canary and fleet readiness verification remain required before claiming deployment. Citizens conversion remains pending a verified compatible vendor runtime.
|
||||
|
|
@ -4,6 +4,8 @@ Use only the installer and JARs emitted together by canonical plugin CI. This in
|
|||
|
||||
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.
|
||||
|
||||
Inventory must explicitly set `"mode": "gui-preserve-backends"`. This release ships only DuneMenus.jar, DunerealmsGUI.jar, DuneRealms-NPC.jar and DuneRealms-Lobby.jar; select Lobby only on the lobby server. The installer rejects incoming JARVIS, Essentials, Core or Terrain. CI still compiles/tests their source, but those binaries are excluded from this GUI artifact. Retained JARVIS/Core/Essentials must match independently reviewed live hashes in preserved-backend-abi.json. Planning checks actual frontend method/field descriptors against those retained JARs, including reflective HouseBridge calls. Their bytes and current UID/GID/mode are checked again before installation and restart. The existing backend remains authoritative for transactions and permissions.
|
||||
|
||||
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.
|
||||
|
|
@ -14,3 +16,16 @@ An `installed-service-active` receipt proves file installation and systemd state
|
|||
A missing existing MCGUI runtime may be staged privately by the authorised coordinator. Inventory `privatePrerequisites.MCGUI` requires an absolute `path` and the reviewed SHA-256 `69a454291cc27c36cdbc680bfbde245a90a3913de53cc1591c502a5a49124300`; the server entry must explicitly list `prerequisites: ["MCGUI"]`. The installer verifies plugin name MCGUI, version0.8.6 and main ai.resourcepack.ui.MCGUIPlugin before including those privately staged bytes. They are never added to the public source/release artifact. Unknown private prerequisites or different bytes/identities fail planning. The private runtime's installation and rollback follow the same stopped-service, backup and checksum path as first-party JARs.
|
||||
|
||||
For selected DuneMenus, inventory menuPack.url is mandatory and actual public bytes must match the built composite. Owned config bytes are hashed, backed up and restored with JAR rollback; existing unmanaged config fails closed. Per-world server.properties is never written. See MENU-PACK-ROLLOUT.md for the persistent publication and external runtime contract.
|
||||
|
||||
## Rollback after application readiness failure
|
||||
|
||||
Systemd active is insufficient: check Paper startup and plugin readiness before proceeding beyond a canary. To restore a selected receipt after an application-level failure, use the same built tools:
|
||||
|
||||
```sh
|
||||
python3 install-plugin-fleet.py --rollback-receipt /verified/backup/receipt.json --expected-source EXACT_40_CHARACTER_SOURCE_SHA
|
||||
# Review the plan, then repeat with --apply.
|
||||
```
|
||||
|
||||
Version 2 receipts capture original filenames, hashes, UID/GID/mode, owned configuration bytes/metadata and whether the service was active. Rollback verifies backups and refuses to overwrite later unknown changes before stopping anything. It restores original metadata exactly and restarts only an originally active service. An already restored receipt is idempotent. Minecraft readiness still needs independent verification.
|
||||
|
||||
Legacy receipts lacking ownership/state require explicitly verified `--legacy-owner UID:GID --legacy-was-active yes|no`; never infer historical ownership from a backup copied as root. For the already recovered e19 lobby canary, the coordinator independently verified current restored JAR metadata as UID988/GID988/mode0644 and original active state. Original owner metadata was not captured in that legacy receipt. These facts do not authorise applying guessed values to other receipts.
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ public final class DuneMenusPlugin extends JavaPlugin implements TabExecutor {
|
|||
"spice", "war", "mentat", "lore", "politics", "house", "equipment", "bank", "atm", "withdraw");
|
||||
private static final String PACK_CONTROL = "dunerealms:pack_control";
|
||||
private Backend backend;
|
||||
private NativePresentationRoutes nativePresentationRoutes;
|
||||
private final Map<Player, String> loadedPacks = new HashMap<>();
|
||||
private final Map<UUID, Menu> openMenus = new HashMap<>();
|
||||
|
||||
|
|
@ -60,9 +61,11 @@ public final class DuneMenusPlugin extends JavaPlugin implements TabExecutor {
|
|||
}
|
||||
getCommand("dm").setExecutor(this);
|
||||
getCommand("dm").setTabCompleter(this);
|
||||
nativePresentationRoutes=new NativePresentationRoutes(this);
|
||||
}
|
||||
|
||||
@Override public void onDisable() {
|
||||
if(nativePresentationRoutes!=null)nativePresentationRoutes.close();
|
||||
for (Menu menu : List.copyOf(openMenus.values())) menu.closed();
|
||||
openMenus.clear();
|
||||
getServer().getServicesManager().unregisterAll(this);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,30 @@
|
|||
package com.dunerealms.menus;
|
||||
import java.util.*;
|
||||
import org.bukkit.command.*;
|
||||
import org.bukkit.entity.Player;
|
||||
/** Wrap only presentation entry points; retained Essentials keeps every targeted/financial operation. */
|
||||
final class NativePresentationRoutes implements AutoCloseable {
|
||||
private final Map<PluginCommand,CommandExecutor> originals=new IdentityHashMap<>();
|
||||
private final Map<PluginCommand,CommandExecutor> wrappers=new IdentityHashMap<>();
|
||||
NativePresentationRoutes(DuneMenusPlugin plugin){
|
||||
for(String label:List.of("duneess:duneess","duneess:server","duneess:dune","duneess:exchange")){
|
||||
PluginCommand command=plugin.getServer().getPluginCommand(label);
|
||||
if(command==null||!command.getPlugin().getName().equals("DuneEss")||originals.containsKey(command))continue;
|
||||
CommandExecutor original=command.getExecutor();
|
||||
CommandExecutor wrapper=(sender,called,alias,args)->{
|
||||
String menu=route(command.getName(),args);
|
||||
if(menu!=null&&sender instanceof Player player){plugin.openMenu(player,menu);return true;}
|
||||
return original.onCommand(sender,called,alias,args);
|
||||
};
|
||||
originals.put(command,original);wrappers.put(command,wrapper);command.setExecutor(wrapper);
|
||||
}
|
||||
}
|
||||
static String route(String command,String[] args){
|
||||
if(command.equalsIgnoreCase("duneess")&&args.length==1){if(args[0].equalsIgnoreCase("travel"))return "travel";if(args[0].equalsIgnoreCase("menu"))return "hub";if(args[0].equalsIgnoreCase("exchange"))return "exchange";}
|
||||
if(command.equalsIgnoreCase("exchange")&&args.length==0)return "exchange";
|
||||
if(command.equalsIgnoreCase("server")&&args.length==0)return "travel";
|
||||
if(command.equalsIgnoreCase("dune")&&args.length==1&&args[0].equalsIgnoreCase("menu"))return "hub";
|
||||
return null;
|
||||
}
|
||||
public void close(){originals.forEach((command,original)->{if(command.getExecutor()==wrappers.get(command))command.setExecutor(original);});originals.clear();wrappers.clear();}
|
||||
}
|
||||
|
|
@ -3,7 +3,7 @@ version: ${version}
|
|||
main: com.dunerealms.menus.DuneMenusPlugin
|
||||
api-version: '1.21'
|
||||
depend: [JarvisTranslator, DunerealmsGUI]
|
||||
softdepend: [floodgate]
|
||||
softdepend: [DuneEss, floodgate]
|
||||
commands:
|
||||
dm:
|
||||
description: Open a DuneRealms menu
|
||||
|
|
|
|||
|
|
@ -0,0 +1,6 @@
|
|||
package com.dunerealms.menus;
|
||||
import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.*;
|
||||
class NativePresentationRoutesTest {
|
||||
@Test void oldNpcAndLobbyTravelEntryOpensNewPresentation(){assertEquals("travel",NativePresentationRoutes.route("duneess",new String[]{"travel"}));assertEquals("travel",NativePresentationRoutes.route("server",new String[]{}));assertEquals("hub",NativePresentationRoutes.route("dune",new String[]{"menu"}));assertEquals("hub",NativePresentationRoutes.route("duneess",new String[]{"menu"}));assertEquals("exchange",NativePresentationRoutes.route("duneess",new String[]{"exchange"}));assertEquals("exchange",NativePresentationRoutes.route("exchange",new String[]{}));}
|
||||
@Test void targetedTravelAndFinancialAdministrationStayWithWorkingBackend(){for(String[] args:new String[][]{{"travel","arrakis"},{"pay","somebody","100"},{"sell"},{"balance"},{"admin","solari","set"},{"menu","reload"}})assertNull(NativePresentationRoutes.route("duneess",args));assertNull(NativePresentationRoutes.route("server",new String[]{"arrakis"}));assertNull(NativePresentationRoutes.route("dune",new String[]{"admin"}));}
|
||||
}
|
||||
2289
DuneMenus/src/test/resources/preserved-backend-abi.json
Normal file
2289
DuneMenus/src/test/resources/preserved-backend-abi.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -15,6 +15,8 @@ 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
|
||||
|
||||
|
||||
PRIVATE_PREREQUISITES = {
|
||||
|
|
@ -47,6 +49,8 @@ def identity(path):
|
|||
|
||||
|
||||
def plan(artifacts, inventory, expected_source):
|
||||
if inventory.get("mode") != "gui-preserve-backends":
|
||||
raise ValueError("This rollout requires explicit gui-preserve-backends mode")
|
||||
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:
|
||||
|
|
@ -106,8 +110,11 @@ def plan(artifacts, inventory, expected_source):
|
|||
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}
|
||||
if wanted - {'dunemenus','dunerealmsgui','dunenpc','dunelobby','mcgui'}:
|
||||
raise ValueError('GUI rollout must retain working Ess/JARVIS/Core/Terrain binaries')
|
||||
previous = []
|
||||
existing_identities = set()
|
||||
existing_paths = {}
|
||||
for old in plugins.glob('*.jar'):
|
||||
if old.is_symlink():
|
||||
raise ValueError('Symlinked plugin requires explicit operator reconciliation')
|
||||
|
|
@ -116,8 +123,10 @@ def plan(artifacts, inventory, expected_source):
|
|||
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)})
|
||||
previous.append({'filename': old.name, 'sha256': digest(old), 'metadata':metadata(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.
|
||||
|
|
@ -126,6 +135,18 @@ def plan(artifacts, inventory, expected_source):
|
|||
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 'dunemenus' in wanted:
|
||||
fixture=json.loads((artifacts/'preserved-backend-abi.json').read_text())
|
||||
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)
|
||||
retained.append({'filename':path.name,'sha256':sha,'metadata':metadata(path)})
|
||||
contract=contract_for_actual(existing_paths['jarvistranslator'],existing_paths['dunecore'],fixture)
|
||||
abi_result=verify_backend_abi([entry['source'] for entry in chosen if not entry.get('privatePrerequisite')],contract)
|
||||
configurations = []
|
||||
if 'dunemenus' in wanted:
|
||||
if menu is None:
|
||||
|
|
@ -140,9 +161,9 @@ def plan(artifacts, inventory, expected_source):
|
|||
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})
|
||||
'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})
|
||||
'artifacts': chosen, 'previous': previous, 'configurations': configurations, 'retained':retained, 'backendAbi':abi_result})
|
||||
ids.add(sid); roots.add(root); units.add(unit)
|
||||
if not servers:
|
||||
raise ValueError('Explicit fleet inventory is empty')
|
||||
|
|
@ -170,6 +191,11 @@ def apply(deployment, backup_root, control=systemctl):
|
|||
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
|
||||
|
|
@ -180,7 +206,7 @@ def apply(deployment, backup_root, control=systemctl):
|
|||
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'}
|
||||
receipt = {'formatVersion':2,'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']:
|
||||
|
|
@ -193,6 +219,7 @@ def apply(deployment, backup_root, control=systemctl):
|
|||
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:
|
||||
|
|
@ -224,6 +251,10 @@ def apply(deployment, backup_root, control=systemctl):
|
|||
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'
|
||||
|
|
@ -240,12 +271,14 @@ def apply(deployment, backup_root, control=systemctl):
|
|||
(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'])
|
||||
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
|
||||
|
|
@ -257,12 +290,21 @@ def apply(deployment, backup_root, control=systemctl):
|
|||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--artifacts', required=True)
|
||||
parser.add_argument('--inventory', required=True)
|
||||
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
|
||||
|
|
|
|||
99
tools/plugin_backend_abi.py
Normal file
99
tools/plugin_backend_abi.py
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
"""Read JVM descriptors without loading plugins or invoking any backend/data operation."""
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import struct
|
||||
import zipfile
|
||||
|
||||
|
||||
def parse_class(payload):
|
||||
stream = io.BytesIO(payload)
|
||||
def u1(): return struct.unpack('>B', stream.read(1))[0]
|
||||
def u2(): return struct.unpack('>H', stream.read(2))[0]
|
||||
def u4(): return struct.unpack('>I', stream.read(4))[0]
|
||||
if u4() != 0xCAFEBABE: raise ValueError('Invalid JVM class')
|
||||
u2(); u2(); count=u2(); cp=[None]*count; index=1
|
||||
while index<count:
|
||||
tag=u1()
|
||||
if tag==1: cp[index]=(tag,stream.read(u2()).decode('utf-8','replace'))
|
||||
elif tag in (3,4): stream.read(4)
|
||||
elif tag in (5,6): stream.read(8); index+=1
|
||||
elif tag in (7,8,16,19,20): cp[index]=(tag,u2())
|
||||
elif tag in (9,10,11,12,17,18): cp[index]=(tag,u2(),u2())
|
||||
elif tag==15: stream.read(3)
|
||||
else: raise ValueError('Unknown JVM constant tag '+str(tag))
|
||||
index+=1
|
||||
def text(index): return cp[index][1]
|
||||
def owner(index): return text(cp[index][1])
|
||||
def attributes():
|
||||
for _ in range(u2()): u2(); stream.seek(u4(),1)
|
||||
def members():
|
||||
result=[]
|
||||
for _ in range(u2()):
|
||||
access,name,descriptor=u2(),text(u2()),text(u2());attributes()
|
||||
if access&1: result.append([name,descriptor])
|
||||
return result
|
||||
u2(); name=owner(u2()); parent=u2(); parent=owner(parent) if parent else None
|
||||
for _ in range(u2()): u2()
|
||||
fields=members(); methods=members(); refs=[]
|
||||
for entry in cp:
|
||||
if entry and entry[0] in (9,10,11):
|
||||
target=cp[entry[2]]
|
||||
refs.append({'kind':'fields' if entry[0]==9 else 'methods','owner':owner(entry[1]),'name':text(target[1]),'descriptor':text(target[2])})
|
||||
return {'name':name,'super':parent,'fields':fields,'methods':methods,'refs':refs}
|
||||
|
||||
|
||||
def jar_classes(path):
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
return {name[:-6]:parse_class(archive.read(name)) for name in archive.namelist() if name.endswith('.class') and not name.startswith('META-INF/')}
|
||||
|
||||
|
||||
def reflection_requirements(source, backend):
|
||||
aliases={'UUID':'java/util/UUID','String':'java/lang/String','JsonObject':'com/google/gson/JsonObject'}
|
||||
primitives={'int':'I','long':'J','boolean':'Z'}
|
||||
rows=[]
|
||||
for match in re.finditer(r'getMethod\("([^"\n]+)"([^)]*)\)',source):
|
||||
name,args=match.groups(); descriptor='('
|
||||
for value in args.split(','):
|
||||
value=value.strip()
|
||||
if not value:continue
|
||||
if not value.endswith('.class'):raise ValueError('Reflection contract is not a literal type list')
|
||||
value=value[:-6];descriptor+=primitives.get(value) or 'L'+aliases.get(value,value.replace('.','/'))+';'
|
||||
descriptor+=')'
|
||||
matches=[item for item in backend['methods'] if item[0]==name and item[1].startswith(descriptor)]
|
||||
if len(matches)!=1:raise ValueError('Preserved JARVIS lacks exact reflected signature: '+name+descriptor)
|
||||
rows.append({'kind':'methods','owner':backend['name'],'name':name,'descriptor':matches[0][1]})
|
||||
return rows
|
||||
|
||||
|
||||
def verify(frontend_jars, contract, reflection_source=None):
|
||||
classes=contract['classes']; requirements=list(contract.get('reflectionRequirements',[]))
|
||||
for path in frontend_jars:
|
||||
for value in jar_classes(path).values():
|
||||
requirements.extend(ref for ref in value['refs'] if ref['owner'].startswith(('com/dunerealms/jarvis/','com/example/dunerealms/','com/example/duneess/')))
|
||||
if reflection_source is not None:
|
||||
requirements.extend(reflection_requirements(Path(reflection_source).read_text(encoding='utf-8'),classes['com/dunerealms/jarvis/JarvisTranslator']))
|
||||
unique={(item['kind'],item['owner'],item['name'],item['descriptor']) for item in requirements}
|
||||
failures=[]
|
||||
for kind,owner,name,descriptor in sorted(unique):
|
||||
current=owner;found=False;seen=set()
|
||||
while current in classes and current not in seen:
|
||||
seen.add(current); row=classes[current]
|
||||
if [name,descriptor] in row[kind]:found=True;break
|
||||
current=row.get('super')
|
||||
if not found:failures.append(owner+'.'+name+descriptor)
|
||||
if failures:raise ValueError('Preserved backend ABI mismatch: '+', '.join(failures))
|
||||
return {'requiredDescriptors':len(unique),'missing':[], 'backendSha256':contract['backendSha256']}
|
||||
|
||||
|
||||
def contract_for_actual(jarvis, core, fixture):
|
||||
import hashlib
|
||||
rows={}
|
||||
for path,kind in ((jarvis,'jarvis'),(core,'core')):
|
||||
value=hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
if not any(row['kind']==kind and row['sha256']==value for row in fixture['variants']):
|
||||
raise ValueError('Retained '+kind+' bytes are not a reviewed live variant')
|
||||
rows.update({key:{name:row[name] for name in ('name','super','fields','methods')} for key,row in jar_classes(path).items() if key.startswith(('com/dunerealms/jarvis/','com/example/dunerealms/'))})
|
||||
return {'classes':dict(fixture['parents'],**rows),'reflectionRequirements':fixture['reflectionRequirements'],
|
||||
'backendSha256':hashlib.sha256(Path(jarvis).read_bytes()).hexdigest()}
|
||||
95
tools/plugin_fleet_rollback.py
Normal file
95
tools/plugin_fleet_rollback.py
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
"""Explicit rollback of a verified plugin receipt after application-level readiness failure."""
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
|
||||
|
||||
def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
def metadata(path):
|
||||
row=Path(path).stat(); return {'uid':row.st_uid,'gid':row.st_gid,'mode':stat.S_IMODE(row.st_mode)}
|
||||
def restore_metadata(path, values):
|
||||
Path(path).chmod(values['mode'])
|
||||
if hasattr(os,'chown'):os.chown(path,values['uid'],values['gid'])
|
||||
def control(*args): return subprocess.run(['systemctl',*args],capture_output=True,text=True,check=False)
|
||||
|
||||
|
||||
def rollback_receipt(receipt_path, expected_source, apply=False, run=control, legacy_owner=None, legacy_was_active=None):
|
||||
receipt_path=Path(receipt_path).resolve(strict=True); backup=receipt_path.parent
|
||||
receipt=json.loads(receipt_path.read_text()); server=receipt['server']
|
||||
if not re.fullmatch('[a-f0-9]{40}',expected_source) or receipt.get('sourceCommit')!=expected_source:
|
||||
raise ValueError('Rollback source does not match the selected receipt')
|
||||
raw=Path(server['root']);root=raw.resolve(strict=True);plugins=root/'plugins';unit=server['serviceUnit']
|
||||
if not raw.is_absolute() or raw.is_symlink() or not plugins.is_dir() or plugins.is_symlink() or not (root/'server.properties').is_file():
|
||||
raise ValueError('Rollback root is not the explicit existing server')
|
||||
if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.@:-]*\.service',unit):raise ValueError('Invalid receipt service')
|
||||
was_active=receipt.get('wasActive',legacy_was_active)
|
||||
if not isinstance(was_active,bool):raise ValueError('Legacy receipt requires explicit original active-state')
|
||||
previous={}; selected={}
|
||||
for entry in server['artifacts']:
|
||||
name=entry['filename']
|
||||
if not re.fullmatch(r'[A-Za-z0-9_.-]+\.jar',name) or name in selected:raise ValueError('Unsafe receipt artifact')
|
||||
selected[name]=entry['sha256']
|
||||
for old in server['previous']:
|
||||
name=old['filename']
|
||||
if not re.fullmatch(r'[A-Za-z0-9_.-]+\.jar',name) or name in previous:raise ValueError('Unsafe receipt backup')
|
||||
saved=backup/name
|
||||
if not saved.is_file() or saved.is_symlink() or digest(saved)!=old['sha256']:raise ValueError('Rollback backup checksum differs: '+name)
|
||||
owner=old.get('metadata')
|
||||
if owner is None:
|
||||
if legacy_owner is None:raise ValueError('Legacy receipt requires explicitly verified UID:GID')
|
||||
owner={'uid':legacy_owner[0],'gid':legacy_owner[1],'mode':stat.S_IMODE(saved.stat().st_mode)}
|
||||
previous[name]=dict(old,metadata=owner)
|
||||
for name in set(previous)|set(selected):
|
||||
current=plugins/name
|
||||
allowed={selected.get(name),previous.get(name,{}).get('sha256')}
|
||||
if current.is_symlink() or (current.exists() and digest(current) not in allowed):
|
||||
raise ValueError('Rollback would overwrite later/unexpected plugin bytes: '+name)
|
||||
configs=server.get('configurations',[])
|
||||
for entry in configs:
|
||||
relative=entry['path']
|
||||
if relative not in ('MCGUI/config.yml','DunerealmsGUI/menu-pack.yml'):raise ValueError('Unsafe rollback configuration path')
|
||||
current=plugins/relative
|
||||
if current.is_symlink() or current.parent.is_symlink():raise ValueError('Symlinked rollback configuration')
|
||||
if current.exists() and digest(current) not in (entry['sha256'],entry['previousSha256']):raise ValueError('Configuration changed since deployment')
|
||||
if entry['previousSha256'] is not None:
|
||||
saved=backup/'configurations'/relative
|
||||
if not saved.is_file() or saved.is_symlink() or digest(saved)!=entry['previousSha256']:raise ValueError('Configuration backup differs')
|
||||
if entry.get('previousMetadata') is None and legacy_owner is None:raise ValueError('Legacy configuration owner requires explicit UID:GID')
|
||||
restored=all((plugins/name).is_file() and digest(plugins/name)==old['sha256'] and metadata(plugins/name)==old['metadata'] for name,old in previous.items())
|
||||
restored=restored and all(not (plugins/name).exists() for name in selected if name not in previous)
|
||||
for item in configs:
|
||||
target=plugins/item['path'];restored=restored and ((not target.exists()) if item['previousSha256'] is None else (target.is_file() and digest(target)==item['previousSha256']))
|
||||
if item['previousSha256'] is not None and target.is_file():
|
||||
expected_metadata=item.get('previousMetadata') or {'uid':legacy_owner[0],'gid':legacy_owner[1],'mode':stat.S_IMODE((backup/'configurations'/item['path']).stat().st_mode)}
|
||||
restored=restored and metadata(target)==expected_metadata
|
||||
report={'sourceCommit':expected_source,'server':server['id'],'receipt':str(receipt_path),'applied':False,'alreadyRestored':restored}
|
||||
if not apply or restored:return report
|
||||
loaded=run('show',unit,'--property=LoadState','--value')
|
||||
if loaded.returncode or loaded.stdout.strip()!='loaded':raise RuntimeError('Rollback service is not loaded')
|
||||
if run('stop',unit).returncode:raise RuntimeError('Could not stop rollback target')
|
||||
state=run('show',unit,'--property=ActiveState','--value')
|
||||
if state.returncode or state.stdout.strip() not in ('inactive','failed'):raise RuntimeError('Rollback target is not fully stopped')
|
||||
for name in selected:
|
||||
(plugins/name).unlink(missing_ok=True)
|
||||
for name,old in previous.items():
|
||||
target=plugins/name;shutil.copy2(backup/name,target);restore_metadata(target,old['metadata'])
|
||||
if digest(target)!=old['sha256'] or metadata(target)!=old['metadata']:raise RuntimeError('Restored plugin bytes/owner/mode differ')
|
||||
for entry in configs:
|
||||
target=plugins/entry['path']
|
||||
if entry['previousSha256'] is None:target.unlink(missing_ok=True)
|
||||
else:
|
||||
saved=backup/'configurations'/entry['path'];target.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(saved,target)
|
||||
owner=entry.get('previousMetadata') or {'uid':legacy_owner[0],'gid':legacy_owner[1],'mode':stat.S_IMODE(saved.stat().st_mode)}
|
||||
restore_metadata(target,owner)
|
||||
if digest(target)!=entry['previousSha256'] or metadata(target)!=owner:raise RuntimeError('Restored configuration differs')
|
||||
if was_active and (run('start',unit).returncode or run('is-active','--quiet',unit).returncode):
|
||||
raise RuntimeError('Original files restored but service did not become active')
|
||||
report.update(applied=True,status='restored-service-active' if was_active else 'restored-service-left-stopped',time=datetime.datetime.now(datetime.timezone.utc).isoformat())
|
||||
output=backup/'rollback-receipt.json';output.write_text(json.dumps(report,indent=2)+'\n');report['report']=str(output)
|
||||
return report
|
||||
41
tools/test_plugin_backend_abi.py
Normal file
41
tools/test_plugin_backend_abi.py
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parent))
|
||||
import plugin_backend_abi as abi
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
class PreservedBackendAbiTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.fixture=json.loads((ROOT/'DuneMenus/src/test/resources/preserved-backend-abi.json').read_text())
|
||||
cls.front=[ROOT/path for path in ('DuneMenus/build/libs/DuneMenus.jar','DuneRealmsGUI/build/libs/DunerealmsGUI.jar','DuneNPC/build/libs/DuneRealms-NPC.jar','DuneLobby/build/libs/DuneRealms-Lobby.jar')]
|
||||
cls.source=ROOT/'DuneRealmsGUI/src/main/java/com/dunerealms/gui/HouseBridge.java'
|
||||
def contract(self,j,c):return {'backendSha256':j['sha256'],'classes':dict(self.fixture['parents'],**j['classes'],**c['classes']),'reflectionRequirements':self.fixture['reflectionRequirements']}
|
||||
def test_current_compiled_gui_npc_and_lobby_link_to_all_actual_backend_variants(self):
|
||||
self.assertEqual(hashlib.sha256(self.source.read_text(encoding='utf-8').encode()).hexdigest(),self.fixture['reflectionSourceSha256'])
|
||||
jarvis=[v for v in self.fixture['variants'] if v['kind']=='jarvis'];cores=[v for v in self.fixture['variants'] if v['kind']=='core']
|
||||
self.assertEqual(len(jarvis),2);self.assertEqual(len(cores),4)
|
||||
for j in jarvis:
|
||||
for c in cores:
|
||||
with self.subTest(jarvis=j['filename'],core=c['filename']):
|
||||
result=abi.verify(self.front,self.contract(j,c),self.source);self.assertGreaterEqual(result['requiredDescriptors'],69);self.assertEqual(result['missing'],[])
|
||||
def test_retained_essentials_variants_expose_the_original_npc_command_roots(self):
|
||||
variants=[v for v in self.fixture['variants'] if v['kind']=='ess'];self.assertEqual(len(variants),3)
|
||||
for row in variants:self.assertTrue({'duneess','server','exchange'}.issubset(row['commands']))
|
||||
def test_missing_or_changed_backend_signature_fails_instead_of_assuming_version_compatibility(self):
|
||||
j=next(v for v in self.fixture['variants'] if v['kind']=='jarvis');c=next(v for v in self.fixture['variants'] if v['kind']=='core')
|
||||
broken=copy.deepcopy(self.contract(j,c));owner='com/dunerealms/jarvis/JarvisTranslator'
|
||||
broken['classes'][owner]['methods']=[row for row in broken['classes'][owner]['methods'] if row[0]!='requestExchange']
|
||||
with self.assertRaisesRegex(ValueError,'requestExchange'):abi.verify(self.front,broken,self.source)
|
||||
def test_missing_cash_enum_constant_is_detected(self):
|
||||
j=next(v for v in self.fixture['variants'] if v['kind']=='jarvis');c=next(v for v in self.fixture['variants'] if v['kind']=='core')
|
||||
broken=copy.deepcopy(self.contract(j,c));broken['classes']['com/dunerealms/jarvis/DunemarkDenomination']['fields']=[]
|
||||
with self.assertRaises(ValueError):abi.verify(self.front,broken,self.source)
|
||||
def test_invalid_classfile_is_rejected(self):
|
||||
with self.assertRaises(ValueError):abi.parse_class(b'not a class')
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
|
|
@ -51,7 +51,7 @@ class FleetInstallerTests(unittest.TestCase):
|
|||
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']}]}
|
||||
self.inventory = {'mode':'gui-preserve-backends','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]}))
|
||||
|
||||
|
|
@ -135,6 +135,17 @@ class FleetInstallerTests(unittest.TestCase):
|
|||
with self.assertRaises(ValueError):
|
||||
self.deployment()
|
||||
|
||||
def test_gui_profile_rejects_backend_replacement_and_requires_explicit_mode(self):
|
||||
self.inventory.pop('mode')
|
||||
with self.assertRaises(ValueError):self.deployment()
|
||||
self.inventory['mode']='gui-preserve-backends'
|
||||
jar(self.artifacts/'Ess.jar','DuneEss')
|
||||
data=json.loads((self.artifacts/'release-manifest.json').read_text())
|
||||
data['plugins'].append(dict(installer.identity(self.artifacts/'Ess.jar'),filename='Ess.jar',sha256=installer.digest(self.artifacts/'Ess.jar')))
|
||||
(self.artifacts/'release-manifest.json').write_text(json.dumps(data))
|
||||
self.inventory['servers'][0]['artifacts'].append('Ess.jar')
|
||||
with self.assertRaisesRegex(ValueError,'retain working'):self.deployment()
|
||||
|
||||
def test_transitional_service_is_rejected_before_any_stop_or_write(self):
|
||||
service = Service()
|
||||
def transitional(*args):
|
||||
|
|
|
|||
55
tools/test_plugin_fleet_rollback.py
Normal file
55
tools/test_plugin_fleet_rollback.py
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parent))
|
||||
import test_plugin_fleet_install as fixtures
|
||||
Service=fixtures.Service
|
||||
SOURCE=fixtures.SOURCE
|
||||
installer=fixtures.installer
|
||||
from plugin_fleet_rollback import rollback_receipt,metadata
|
||||
|
||||
class ReceiptRollbackTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.fixture=fixtures.FleetInstallerTests();self.fixture.setUp();self.addCleanup(self.fixture.temp.cleanup)
|
||||
self.service=Service();self.receipt=Path(installer.apply(self.fixture.deployment(),self.fixture.base/'backups',self.service)[0]);self.service.calls.clear()
|
||||
def test_readiness_failure_rollback_restores_original_names_hashes_owners_and_mode(self):
|
||||
old=json.loads(self.receipt.read_text())['server']['previous'][0]
|
||||
before=(self.fixture.root/'server.properties').read_bytes()
|
||||
self.assertFalse(rollback_receipt(self.receipt,SOURCE)['applied']);self.assertEqual(self.service.calls,[])
|
||||
result=rollback_receipt(self.receipt,SOURCE,True,self.service)
|
||||
self.assertTrue(result['applied']);self.assertTrue((self.fixture.plugins/'legacy-gui.jar').exists());self.assertFalse((self.fixture.plugins/'DunerealmsGUI.jar').exists())
|
||||
self.assertEqual(installer.digest(self.fixture.plugins/'legacy-gui.jar'),old['sha256']);self.assertEqual(metadata(self.fixture.plugins/'legacy-gui.jar'),old['metadata'])
|
||||
self.assertEqual((self.fixture.root/'server.properties').read_bytes(),before)
|
||||
calls=len(self.service.calls);self.assertTrue(rollback_receipt(self.receipt,SOURCE,True,self.service)['alreadyRestored']);self.assertEqual(calls,len(self.service.calls))
|
||||
def test_corrupt_backup_and_later_plugin_drift_stop_before_service_actions(self):
|
||||
(self.receipt.parent/'legacy-gui.jar').write_bytes(b'corrupt')
|
||||
with self.assertRaises(ValueError):rollback_receipt(self.receipt,SOURCE,True,self.service)
|
||||
self.assertEqual(self.service.calls,[])
|
||||
def test_unexpected_candidate_bytes_are_not_destroyed(self):
|
||||
(self.fixture.plugins/'DunerealmsGUI.jar').write_bytes(b'later owner change')
|
||||
with self.assertRaises(ValueError):rollback_receipt(self.receipt,SOURCE,True,self.service)
|
||||
self.assertEqual(self.service.calls,[])
|
||||
def test_legacy_receipt_requires_explicit_owner_and_original_state(self):
|
||||
data=json.loads(self.receipt.read_text());data.pop('formatVersion');data.pop('wasActive')
|
||||
for row in data['server']['previous']:row.pop('metadata')
|
||||
self.receipt.write_text(json.dumps(data));owner=metadata(self.fixture.plugins)
|
||||
with self.assertRaises(ValueError):rollback_receipt(self.receipt,SOURCE,True,self.service)
|
||||
with self.assertRaises(ValueError):rollback_receipt(self.receipt,SOURCE,True,self.service,legacy_was_active=True)
|
||||
result=rollback_receipt(self.receipt,SOURCE,True,self.service,legacy_owner=(owner['uid'],owner['gid']),legacy_was_active=True)
|
||||
self.assertTrue(result['applied']);self.assertTrue(self.service.active)
|
||||
def test_wrong_source_is_refused_without_stopping(self):
|
||||
with self.assertRaises(ValueError):rollback_receipt(self.receipt,'b'*40,True,self.service)
|
||||
self.assertEqual(self.service.calls,[])
|
||||
def test_application_readiness_rollback_restores_config_bytes_and_metadata(self):
|
||||
relative='MCGUI/config.yml';target=self.fixture.plugins/relative;target.parent.mkdir()
|
||||
original=b'# previous managed configuration\ntelemetry: false\n';candidate=b'# candidate\n'
|
||||
target.write_bytes(original);owner=metadata(target)
|
||||
saved=self.receipt.parent/'configurations'/relative;saved.parent.mkdir(parents=True);saved.write_bytes(original)
|
||||
target.write_bytes(candidate)
|
||||
data=json.loads(self.receipt.read_text());data['server']['configurations']=[{'path':relative,'sha256':installer.digest(target),'previousSha256':installer.digest(saved),'previousMetadata':owner}]
|
||||
self.receipt.write_text(json.dumps(data))
|
||||
rollback_receipt(self.receipt,SOURCE,True,self.service)
|
||||
self.assertEqual(target.read_bytes(),original);self.assertEqual(metadata(target),owner)
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
|
|
@ -79,7 +79,7 @@ class MenuPackTests(unittest.TestCase):
|
|||
def configuration_plan(self, existing=False):
|
||||
root = self.root / 'server'; root.mkdir(); plugins = root / 'plugins'; plugins.mkdir()
|
||||
(root / 'server.properties').write_bytes(b'resource-pack=existing-world.zip\nresource-pack-sha1=unchanged\n')
|
||||
for name in ('JarvisTranslator', 'DunerealmsGUI', 'MCGUI'):
|
||||
for name in ('JarvisTranslator', 'DunerealmsGUI', 'MCGUI','DuneCore','DuneEss'):
|
||||
jar(plugins / (name + '.jar'), name)
|
||||
jar(self.artifacts / 'DuneMenus.jar', 'DuneMenus', '2.0.1')
|
||||
entry = dict(installer.identity(self.artifacts / 'DuneMenus.jar'), filename='DuneMenus.jar', sha256=installer.digest(self.artifacts / 'DuneMenus.jar'))
|
||||
|
|
@ -88,7 +88,9 @@ class MenuPackTests(unittest.TestCase):
|
|||
for relative in contract.config_payloads(self.metadata):
|
||||
target = plugins / relative; target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(b'# Managed by DuneRealms plugin CI; previous release\nold: retained\n')
|
||||
inventory = {'menuPack': {'url': contract.menu_url(SOURCE)}, 'servers': [{'id': 'test', 'root': str(root.resolve()), 'serviceUnit': 'test.service', 'artifacts': ['DuneMenus.jar']}]}
|
||||
fixture={'parents':{},'reflectionRequirements':[],'variants':[{'kind':kind,'sha256':installer.digest(plugins/(name+'.jar'))} for kind,name in [('jarvis','JarvisTranslator'),('core','DuneCore'),('ess','DuneEss')]]}
|
||||
(self.artifacts/'preserved-backend-abi.json').write_text(json.dumps(fixture))
|
||||
inventory = {'mode':'gui-preserve-backends','menuPack': {'url': contract.menu_url(SOURCE)}, 'servers': [{'id': 'test', 'root': str(root.resolve()), 'serviceUnit': 'test.service', 'artifacts': ['DuneMenus.jar']}]}
|
||||
with patch.object(installer, 'verify_public_menu'):
|
||||
deployment = installer.plan(self.artifacts, inventory, SOURCE)
|
||||
return root, plugins, deployment
|
||||
|
|
@ -117,6 +119,13 @@ class MenuPackTests(unittest.TestCase):
|
|||
self.assertEqual((plugins / relative).read_bytes(), payload)
|
||||
self.assertEqual(next((self.root / 'backup').glob('*/test/configurations/' + relative)).read_bytes(), payload)
|
||||
|
||||
def test_retained_economy_bytes_cannot_change_between_plan_and_install(self):
|
||||
_, plugins, deployment = self.configuration_plan()
|
||||
(plugins/'DuneEss.jar').write_bytes(b'changed backend')
|
||||
service=Service()
|
||||
with self.assertRaisesRegex(ValueError,'Retained backend changed'):installer.apply(deployment,self.root/'backup',service)
|
||||
self.assertFalse(any(call[0]=='stop' for call in service.calls))
|
||||
|
||||
def test_reload_failure_restores_route_after_successful_nginx_validation(self):
|
||||
store = self.root / 'downloads'; store.mkdir(); snippet = self.root / 'routes.conf'
|
||||
before = b'# existing routes\n'; snippet.write_bytes(before); calls = []
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff