plugins/tools/reset-planet-ores.py
unimatrixgit b262b5f90f
Some checks failed
Sigma Ore Palette Build / sigma-ore-palette (push) Successful in 5s
DuneRealms Resourcepack CI / resourcepack (push) Failing after 10s
DuneRealms Plugin CI / plugins (push) Successful in 2m28s
Keep Sigma mineral generation within its configured palette
2026-12-02 07:25:29 +01:00

234 lines
11 KiB
Python

"""Install the exact ore build and clear only one reviewed primary overworld."""
import argparse
from contextlib import ExitStack
import hashlib
import json
import os
from pathlib import Path
import re
import stat
import subprocess
import tempfile
from planet_ore_release import PLANETS, SIGMA_PACK, sha, sigma_pack, verify_terrain
ROOT = Path('/opt/dunerealms/servers')
DIMENSION = Path('dimensions/minecraft/overworld')
CHUNKS = ('region', 'entities', 'poi')
IDENTITY = ('data/minecraft/world_gen_settings.dat', 'data/paper/metadata.dat')
CONFIG = 'plugins/DuneTerrain/config.yml'
PACK = Path('datapacks/dunerealms-biomes.zip')
ASSETS = {'ore-heights.zip', 'PlanetOreTransition.java', 'planet_ore_release.py',
'reset-planet-ores.py', 'frozen_desert.json', 'SOURCE_COMMIT'}
def checked(path):
if path.resolve(strict=True) != path.absolute():
raise ValueError(f'Unexpected symlink or path: {path}')
return path
def fingerprint(path):
checked(path)
st = path.stat()
if not stat.S_ISREG(st.st_mode):
raise ValueError(f'Expected a regular file: {path}')
with path.open('rb') as stream:
digest = hashlib.file_digest(stream, 'sha256').hexdigest()
return (digest, st.st_uid, st.st_gid, stat.S_IMODE(st.st_mode))
def world_snapshot(world, exclusions):
result = {}
for folder, dirs, files in os.walk(checked(world)):
path = Path(folder)
for name in dirs:
checked(path / name)
if path == world / DIMENSION:
dirs[:] = [name for name in dirs if name not in CHUNKS]
for name in files:
entry = path / name
if entry not in exclusions:
result[entry.relative_to(world).as_posix()] = fingerprint(entry)
return result
def chunk_files(dimension):
result = []
for directory in CHUNKS:
folder = dimension / directory
if folder.is_symlink():
raise ValueError(f'Symlinked chunk directory: {folder}')
if not folder.exists():
if directory == 'region':
raise ValueError('Primary region directory is missing')
continue
for entry in sorted(checked(folder).iterdir()):
if not re.fullmatch(r'[rc]\.-?\d+\.-?\d+\.(mca|mcc)', entry.name) or not checked(entry).is_file():
raise ValueError(f'Unexpected chunk storage entry: {entry}')
result.append(entry)
return result
def service(*args):
return subprocess.run(['systemctl', *args], text=True, capture_output=True, check=True).stdout.strip()
def state(unit):
return service('show', unit, '--property=ActiveState', '--value')
def verify_bundle(bundle, source, expected=ASSETS):
rows = (bundle / 'SHA256SUMS').read_text().splitlines()
sums = dict(row.split(' ', 1)[::-1] for row in rows)
if not re.fullmatch(r'[0-9a-f]{40}', source) or len(rows) != len(expected) or sums.keys() != expected:
raise ValueError('Unexpected canonical artifact manifest')
if any(fingerprint(bundle / name)[0] != digest for name, digest in sums.items()):
raise ValueError('Canonical artifact checksum mismatch')
if (bundle / 'SOURCE_COMMIT').read_text().strip() != source:
raise ValueError('Canonical artifact source mismatch')
def snapshot_server(root):
properties = root / 'server.properties'
settings = dict(line.split('=', 1) for line in properties.read_text().splitlines() if '=' in line and not line.startswith('#'))
return {
'settings': settings,
'configs': {name: fingerprint(root / name) for name in (
CONFIG, 'bukkit.yml', 'plugins/MCGUI/config.yml', 'plugins/DunerealmsGUI/menu-pack.yml')},
'jars': {p.name: fingerprint(p) for p in (root / 'plugins').glob('*.jar')},
}
def stage(target, payload, expected, stack):
fd, filename = tempfile.mkstemp(prefix='.planet-ore-', dir=target.parent)
candidate = Path(filename)
stack.callback(candidate.unlink, missing_ok=True)
with os.fdopen(fd, 'wb') as stream:
stream.write(payload)
os.fchown(stream.fileno(), expected[1], expected[2])
os.fchmod(stream.fileno(), expected[3])
stream.flush()
os.fsync(stream.fileno())
return candidate
def run(planet, bundle, source, candidate, expected_candidate, apply, receipt):
verify_bundle(checked(bundle), source)
root = checked(ROOT / planet)
unit = f'dune-{planet}.service'
if state(unit) != 'active' or service('show', unit, '--property=WorkingDirectory', '--value') != str(root):
raise ValueError('Unexpected planet service or working directory')
before = snapshot_server(root)
if before['settings'].get('level-name') != planet:
raise ValueError('Unexpected primary world name')
bukkit = (root / 'bukkit.yml').read_text()
if not re.search(rf'^\s+generator:\s*[\'\"]?DuneTerrain:{planet}[\'\"]?\s*$', bukkit, re.M):
raise ValueError('Expected the current DuneTerrain generator')
world = checked(root / planet)
dimension = checked(world / DIMENSION)
identity = {name: fingerprint(dimension / name) for name in IDENTITY}
existing = [name for name, pin in before['jars'].items() if pin[0] == PLANETS[planet]]
if len(existing) != 1:
raise ValueError('Expected exactly one pinned Terrain variant')
jar = root / 'plugins' / existing[0]
if not re.fullmatch(r'[0-9a-f]{64}', expected_candidate) or fingerprint(candidate)[0] != expected_candidate:
raise ValueError('Assembled Terrain differs from the independently reviewed candidate hash')
verify_terrain(jar, candidate, bundle)
pack = world / PACK if planet == 'sigma_draconis_iv' else None
previous = {jar: fingerprint(jar)}
if pack:
previous[pack] = fingerprint(pack)
if previous[pack][0] != SIGMA_PACK:
raise ValueError('Sigma biome pack differs from the reviewed baseline')
with tempfile.TemporaryDirectory() as temp:
targets = {jar: candidate}
if pack:
targets[pack] = Path(temp) / 'sigma.zip'
sigma_pack(pack, bundle / 'frozen_desert.json', targets[pack])
report = {'source': source, 'planet': planet, 'unit': unit, 'world': str(world), 'identity': identity,
'incoming': {str(target): sha(candidate) for target, candidate in targets.items()},
'chunkFileCount': len(chunk_files(dimension)), 'status': 'planned'}
if not apply:
return report
return apply_transition(root, world, dimension, unit, before, identity, previous, targets, report, receipt)
def apply_transition(root, world, dimension, unit, before, identity, previous, targets, report, receipt):
with receipt.open('x') as stream, ExitStack() as stack:
os.fchmod(stream.fileno(), 0o600)
originals = {target: stage(target, target.read_bytes(), previous[target], stack) for target in targets}
staged = {target: stage(target, candidate.read_bytes(), previous[target], stack)
for target, candidate in targets.items()}
if any(fingerprint(path) != previous[target] for target, path in originals.items()):
raise ValueError('Previous bytes changed during staging')
if any(fingerprint(path)[0] != report['incoming'][str(target)] for target, path in staged.items()):
raise ValueError('Incoming bytes changed during staging')
replaced, deleting = [], False
try:
service('stop', unit)
if state(unit) not in {'inactive', 'failed'} or service('show', unit, '--property=MainPID', '--value') != '0':
raise ValueError('Planet service failed to stop')
if snapshot_server(root) != before or any(fingerprint(target) != value for target, value in previous.items()):
raise ValueError('Protected server files changed during shutdown')
if any(fingerprint(dimension / name) != value for name, value in identity.items()):
raise ValueError('Primary seed or Paper identity changed during shutdown')
exclusions = {target for target in targets if target.is_relative_to(world)}
exclusions.update(originals.values(), staged.values())
protected = world_snapshot(world, exclusions)
chunks = chunk_files(dimension)
for target, candidate in staged.items():
os.replace(candidate, target)
replaced.append(target)
for file in chunks:
file.unlink()
deleting = True
if world_snapshot(world, exclusions) != protected:
raise ValueError('Protected world files changed before restart')
expected_server = before
for target in targets:
if target.parent == root / 'plugins':
expected_server['jars'][target.name] = (report['incoming'][str(target)], *previous[target][1:])
if snapshot_server(root) != expected_server or any(
fingerprint(target) != (report['incoming'][str(target)], *previous[target][1:]) for target in targets):
raise ValueError('Installed or retained bytes changed before restart')
report['chunkFileCount'] = len(chunks)
report['protectedWorldFileCount'] = len(protected)
service('start', unit)
report['status'] = 'start-accepted'
except BaseException:
report['status'] = 'needs-review' if deleting else 'aborted-before-world-reset'
if not deleting:
for target in reversed(replaced):
os.replace(originals[target], target)
if state(unit) in {'inactive', 'failed'}:
service('start', unit)
raise
finally:
json.dump(report, stream, indent=2)
stream.write('\n')
return report
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('planet', choices=PLANETS)
parser.add_argument('--bundle', required=True, type=Path)
parser.add_argument('--expected-source', required=True)
parser.add_argument('--candidate', required=True, type=Path)
parser.add_argument('--candidate-sha256', required=True)
parser.add_argument('--apply-reset-no-backup', action='store_true')
parser.add_argument('--receipt', type=Path)
args = parser.parse_args()
if args.apply_reset_no_backup != (args.receipt is not None):
parser.error('An apply requires a new private receipt path')
if args.apply_reset_no_backup:
import fcntl
with Path('/run/lock/dunerealms-planet-ore-reset.lock').open('a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
result = run(args.planet, args.bundle, args.expected_source, args.candidate, args.candidate_sha256, True, args.receipt)
else:
result = run(args.planet, args.bundle, args.expected_source, args.candidate, args.candidate_sha256, False, None)
print(json.dumps(result, indent=2))