335 lines
17 KiB
Python
335 lines
17 KiB
Python
"""Pinned Arrakis-only Terrain install/reset. No database access and no recursive deletion."""
|
|
import argparse
|
|
from datetime import datetime, timezone
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import shutil
|
|
import stat
|
|
import subprocess
|
|
import zipfile
|
|
|
|
APPROVED_ROOT = Path('/opt/dunerealms/servers/arrakis')
|
|
UNIT = 'dune-arrakis.service'
|
|
CHUNKS = ('region', 'entities', 'poi')
|
|
OLD_TERRAIN_SHA = '012f9b0055020a94de955ec277cc46ca82a5efc8149e748ff30a333b6bc026dc'
|
|
|
|
|
|
def digest(path):
|
|
h = hashlib.sha256()
|
|
with Path(path).open('rb') as stream:
|
|
for block in iter(lambda: stream.read(1024 * 1024), b''): h.update(block)
|
|
return h.hexdigest()
|
|
|
|
|
|
def checked(path):
|
|
path = Path(path).absolute()
|
|
if path.is_symlink() or path.resolve(strict=True) != path: raise ValueError('Symlinked or noncanonical path')
|
|
return path
|
|
|
|
|
|
def tree(path):
|
|
result = {}
|
|
for file in sorted(checked(path).rglob('*')):
|
|
if file.is_symlink(): raise ValueError('Symlink in world data')
|
|
if file.is_file(): result[file.relative_to(path).as_posix()] = digest(file)
|
|
return result
|
|
|
|
|
|
def identity(path):
|
|
with zipfile.ZipFile(path) as jar: text = jar.read('plugin.yml').decode()
|
|
return {key: re.search(r'^' + key + r':\s*(.+?)\s*$', text, re.M).group(1).strip('"\'') for key in ('name', 'version', 'main')}
|
|
|
|
|
|
def metadata(path):
|
|
value = path.stat()
|
|
return {'mode': stat.S_IMODE(value.st_mode), 'uid': value.st_uid, 'gid': value.st_gid}
|
|
|
|
|
|
def set_metadata(path, value):
|
|
os.chmod(path, value['mode'])
|
|
if hasattr(os, 'chown'): os.chown(path, value['uid'], value['gid'])
|
|
|
|
|
|
def plugin_snapshot(folder, exclude=None):
|
|
return {p.name: {'sha256': digest(p), **metadata(p)} for p in sorted(folder.glob('*.jar')) if p != exclude}
|
|
|
|
|
|
def yaml_value(text, expected):
|
|
stack = []
|
|
for line in text.splitlines():
|
|
match = re.match(r'^( *)([A-Za-z0-9_-]+):[ \t]*(.*)$', line)
|
|
if not match: continue
|
|
indent, key, value = len(match[1]), match[2], match[3].strip()
|
|
stack = [entry for entry in stack if entry[0] < indent] + [(indent, key)]
|
|
if tuple(entry[1] for entry in stack) == expected: return value.strip('"\'')
|
|
return None
|
|
|
|
|
|
def protected(world):
|
|
prefixes = tuple('dimensions/minecraft/overworld/' + name + '/' for name in CHUNKS)
|
|
return {name: value for name, value in tree(world).items() if not name.startswith(prefixes)}
|
|
|
|
|
|
def config_pin(path):
|
|
if path.name != 'server.properties': return digest(path)
|
|
# Paper rewrites its generated comment timestamp on startup; compare actual settings.
|
|
settings = {}
|
|
for line in path.read_text().splitlines():
|
|
if line.strip() and not line.lstrip().startswith(('#', '!')):
|
|
key, separator, value = line.partition('=')
|
|
if not separator: raise ValueError('Unsupported server property syntax')
|
|
settings[key.strip()] = value.strip()
|
|
return hashlib.sha256(json.dumps(settings, sort_keys=True).encode()).hexdigest()
|
|
|
|
|
|
def plan(root, artifacts, expected_source, expected_old=OLD_TERRAIN_SHA):
|
|
root, artifacts = checked(root), checked(artifacts)
|
|
if root != APPROVED_ROOT.absolute(): raise ValueError('Only the verified Arrakis server root is permitted')
|
|
if not re.fullmatch('[a-f0-9]{40}', expected_source): raise ValueError('Exact source commit required')
|
|
manifest = json.loads((artifacts / 'release-manifest.json').read_text())
|
|
if manifest['sourceCommit'] != expected_source or (artifacts / 'SOURCE_COMMIT').read_text().strip() != expected_source: raise ValueError('Artifact source mismatch')
|
|
entries = manifest['plugins']
|
|
if len(entries) != 1 or entries[0]['name'] != 'DuneTerrain': raise ValueError('Terrain-only artifact required')
|
|
item = entries[0]
|
|
if Path(item['filename']).name != item['filename']: raise ValueError('Invalid artifact filename')
|
|
incoming = checked(artifacts / item['filename'])
|
|
if digest(incoming) != item['sha256'] or identity(incoming) != {k: item[k] for k in ('name', 'version', 'main')}: raise ValueError('Incoming Terrain identity/hash mismatch')
|
|
if item['main'] != 'com.example.duneterrain.DuneTerrain': raise ValueError('Unexpected Terrain entry point')
|
|
world = checked(root / 'arrakis')
|
|
dimension = checked(world / 'dimensions/minecraft/overworld')
|
|
if not (world / 'level.dat').is_file() or not (world / 'players').is_dir(): raise ValueError('Expected Paper 26.2 world/player layout missing')
|
|
for name in CHUNKS: checked(dimension / name)
|
|
props = (root / 'server.properties').read_text()
|
|
if not re.search(r'^\s*level-name\s*=\s*arrakis\s*$', props, re.M): raise ValueError('Server level-name is not Arrakis')
|
|
bukkit = (root / 'bukkit.yml').read_text()
|
|
if yaml_value(bukkit, ('worlds', 'arrakis', 'generator')) != 'DuneTerrain:arrakis': raise ValueError('Verified generator mapping missing')
|
|
plugins = checked(root / 'plugins')
|
|
installed = [p for p in plugins.glob('*.jar') if identity(p)['name'] == 'DuneTerrain']
|
|
if len(installed) != 1: raise ValueError('Expected one installed Terrain identity')
|
|
target = checked(installed[0])
|
|
if digest(target) != expected_old: raise ValueError('Installed Terrain differs from reviewed runtime')
|
|
configs = [root / 'server.properties', root / 'bukkit.yml', plugins / 'DuneTerrain/config.yml']
|
|
for file in configs: checked(file)
|
|
if yaml_value(configs[2].read_text(), ('server', 'planet')) != 'arrakis': raise ValueError('Terrain planet setting mismatch')
|
|
# Traversal also rejects symlinks before any service or world mutation.
|
|
tree(world)
|
|
return {'root': str(root), 'world': str(world), 'dimension': str(dimension), 'unit': UNIT,
|
|
'source': expected_source, 'incoming': str(incoming), 'incomingSha256': item['sha256'],
|
|
'target': str(target), 'previousSha256': expected_old, 'previousMetadata': metadata(target),
|
|
'retainedJars': plugin_snapshot(plugins, target), 'configs': {str(p.relative_to(root)): config_pin(p) for p in configs},
|
|
'resetDirectories': list(CHUNKS), 'preserved': 'All other world bytes, including players, data, level.dat, datapacks and dimension settings'}
|
|
|
|
|
|
def save(path, value):
|
|
temporary = path.with_suffix('.new')
|
|
temporary.write_text(json.dumps(value, indent=2) + '\n')
|
|
os.chmod(temporary, 0o600)
|
|
os.replace(temporary, path)
|
|
|
|
|
|
class Service:
|
|
def __init__(self, root):
|
|
directory = subprocess.check_output(['systemctl', 'show', UNIT, '--property=WorkingDirectory', '--value'], text=True).strip()
|
|
if Path(directory) != root: raise ValueError('Unit working directory mismatch')
|
|
def active(self): return subprocess.run(['systemctl', 'is-active', '--quiet', UNIT]).returncode == 0
|
|
def stop(self): subprocess.run(['systemctl', 'stop', UNIT], check=True)
|
|
def start(self): subprocess.run(['systemctl', 'start', UNIT], check=True)
|
|
|
|
|
|
def verify_retained(value):
|
|
root, target = Path(value['root']), Path(value['target'])
|
|
if plugin_snapshot(root / 'plugins', target) != value['retainedJars']: raise ValueError('A retained plugin changed')
|
|
for name, expected in value['configs'].items():
|
|
if config_pin(checked(root / name)) != expected: raise ValueError('A retained configuration changed')
|
|
|
|
|
|
def rollback(receipt, controller, internal=False):
|
|
receipt = checked(receipt)
|
|
value = json.loads(receipt.read_text())
|
|
root = checked(value['root'])
|
|
if root != APPROVED_ROOT.absolute() or value['unit'] != UNIT: raise ValueError('Rollback target mismatch')
|
|
if not receipt.is_relative_to(root / 'backups'): raise ValueError('Receipt is outside the private backup root')
|
|
dimension, target = checked(value['dimension']), checked(value['target'])
|
|
if dimension != root / 'arrakis/dimensions/minecraft/overworld' or target.parent != root / 'plugins': raise ValueError('Invalid receipt scope')
|
|
backup = receipt.parent
|
|
previous = checked(backup / 'previous-terrain.jar')
|
|
if digest(previous) != value['previousSha256']: raise ValueError('Original Terrain backup hash changed')
|
|
if identity(previous)['name'] != 'DuneTerrain' or identity(target)['name'] != 'DuneTerrain': raise ValueError('Rollback plugin identity mismatch')
|
|
for field in ('moved', 'restored'):
|
|
names = value.get(field, [])
|
|
if len(names) != len(set(names)) or not set(names).issubset(CHUNKS): raise ValueError('Invalid rollback directory list')
|
|
if value['state'].startswith('rolled-back'):
|
|
if digest(target) != value['previousSha256']: raise ValueError('Rolled-back Terrain changed')
|
|
if value['wasActive'] and not controller.active(): controller.start()
|
|
return value
|
|
if not internal and digest(target) not in {value['incomingSha256'], value['previousSha256'] if value['state'] == 'rolling-back' else value['incomingSha256']}: raise ValueError('Installed Terrain changed after this rollout')
|
|
verify_retained(value)
|
|
for name in value.get('moved', []):
|
|
original = backup / 'retired' / name
|
|
if name in value.get('restored', []): continue
|
|
source = original if original.exists() else dimension / name
|
|
if tree(checked(source)) != value['originalChunks'][name]: raise ValueError('Original chunk backup changed')
|
|
controller.stop()
|
|
if controller.active(): raise RuntimeError('Arrakis service did not stop')
|
|
failed = backup / 'replaced-after-rollback'
|
|
failed.mkdir(mode=0o700, exist_ok=True)
|
|
value['state'] = 'rolling-back'
|
|
save(receipt, value)
|
|
for name in value.get('moved', []):
|
|
if name in value.get('restored', []): continue
|
|
original = backup / 'retired' / name
|
|
current = dimension / name
|
|
if original.exists():
|
|
if current.exists(): checked(current).rename(failed / name)
|
|
checked(original).rename(current)
|
|
value.setdefault('restored', []).append(name)
|
|
save(receipt, value)
|
|
shutil.copy2(previous, target)
|
|
set_metadata(target, value['previousMetadata'])
|
|
verify_retained(value)
|
|
value['state'] = 'rolled-back; current player/world metadata retained'
|
|
save(receipt, value)
|
|
if value['wasActive']: controller.start()
|
|
return value
|
|
|
|
|
|
def apply(value, controller, stamp=None):
|
|
root, world, dimension, target = map(Path, (value['root'], value['world'], value['dimension'], value['target']))
|
|
stamp = stamp or datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S.%fZ')
|
|
base = root / 'backups'
|
|
base.mkdir(exist_ok=True)
|
|
if base.resolve() != base: raise ValueError('Symlinked backup root')
|
|
backup = base / ('arrakis-reset-' + value['source'][:7] + '-' + stamp)
|
|
backup.mkdir(mode=0o700)
|
|
receipt = backup / 'receipt.json'
|
|
value = {**value, 'wasActive': controller.active(), 'moved': [], 'state': 'preparing'}
|
|
save(receipt, value)
|
|
if value['wasActive']: controller.stop()
|
|
if controller.active(): raise RuntimeError('Arrakis service did not stop')
|
|
try:
|
|
if digest(target) != value['previousSha256'] or digest(value['incoming']) != value['incomingSha256']: raise ValueError('Terrain changed after planning')
|
|
verify_retained(value)
|
|
before, profiles = tree(world), protected(world)
|
|
shutil.copytree(world, backup / 'world-snapshot', copy_function=shutil.copy2)
|
|
if tree(backup / 'world-snapshot') != before: raise ValueError('Full world backup verification failed')
|
|
shutil.copy2(target, backup / 'previous-terrain.jar')
|
|
value['protectedBefore'] = profiles
|
|
value['originalChunks'] = {name: tree(dimension / name) for name in CHUNKS}
|
|
(backup / 'retired').mkdir(mode=0o700)
|
|
save(receipt, value)
|
|
for name in CHUNKS:
|
|
folder = dimension / name
|
|
attrs = metadata(folder)
|
|
value['moved'].append(name)
|
|
save(receipt, value)
|
|
folder.rename(backup / 'retired' / name)
|
|
folder.mkdir()
|
|
set_metadata(folder, attrs)
|
|
temporary = target.with_suffix('.incoming')
|
|
shutil.copy2(value['incoming'], temporary)
|
|
set_metadata(temporary, value['previousMetadata'])
|
|
os.replace(temporary, target)
|
|
if digest(target) != value['incomingSha256']: raise ValueError('Installed Terrain hash mismatch')
|
|
if protected(world) != profiles: raise ValueError('Protected world/player data changed')
|
|
verify_retained(value)
|
|
value['state'] = 'installed; awaiting runtime verification'
|
|
save(receipt, value)
|
|
if value['wasActive']: controller.start()
|
|
value['state'] = 'started; awaiting Paper readiness and generator acceptance' if value['wasActive'] else 'installed; service left stopped'
|
|
save(receipt, value)
|
|
return receipt
|
|
except Exception:
|
|
if value['moved']:
|
|
rollback(receipt, controller, internal=True)
|
|
elif value['wasActive']:
|
|
controller.start()
|
|
raise
|
|
|
|
|
|
def regenerate_without_backup(value, controller):
|
|
if not controller.active():
|
|
raise ValueError('Arrakis must be running before regeneration')
|
|
world, dimension, target = map(Path, (value['world'], value['dimension'], value['target']))
|
|
controller.stop()
|
|
if controller.active():
|
|
raise RuntimeError('Arrakis service did not stop')
|
|
destructive = False
|
|
temporary = target.with_suffix('.incoming')
|
|
staged_here = False
|
|
try:
|
|
if digest(target) != value['previousSha256'] or digest(value['incoming']) != value['incomingSha256']:
|
|
raise ValueError('Terrain changed after planning')
|
|
verify_retained(value)
|
|
profiles = protected(world)
|
|
chunks = []
|
|
for name in CHUNKS:
|
|
for file in sorted(checked(dimension / name).iterdir()):
|
|
if not re.fullmatch(r'[rc]\.-?\d+\.-?\d+\.(?:mca|mcc)', file.name) or not checked(file).is_file():
|
|
raise ValueError('Unexpected entry in Arrakis chunk storage')
|
|
chunks.append(file)
|
|
with temporary.open('xb') as staged:
|
|
staged_here = True
|
|
with Path(value['incoming']).open('rb') as source:
|
|
shutil.copyfileobj(source, staged)
|
|
set_metadata(temporary, value['previousMetadata'])
|
|
if digest(temporary) != value['incomingSha256']:
|
|
raise ValueError('Staged Terrain hash mismatch')
|
|
os.replace(temporary, target)
|
|
destructive = True
|
|
for file in chunks:
|
|
file.unlink()
|
|
if protected(world) != profiles:
|
|
raise ValueError('Protected world/player data changed')
|
|
verify_retained(value)
|
|
controller.start()
|
|
return len(chunks)
|
|
except Exception:
|
|
if not destructive:
|
|
if staged_here:
|
|
temporary.unlink(missing_ok=True)
|
|
controller.start()
|
|
raise
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--root', required=True)
|
|
parser.add_argument('--artifacts')
|
|
parser.add_argument('--expected-source', required=True)
|
|
parser.add_argument('--expected-terrain-sha', default=OLD_TERRAIN_SHA)
|
|
parser.add_argument('--apply-reset', action='store_true')
|
|
parser.add_argument('--no-backup', action='store_true')
|
|
parser.add_argument('--rollback-receipt')
|
|
args = parser.parse_args()
|
|
if args.no_backup and (not args.apply_reset or args.rollback_receipt):
|
|
parser.error('--no-backup requires --apply-reset without rollback')
|
|
value = None
|
|
if args.rollback_receipt:
|
|
value = json.loads(Path(args.rollback_receipt).read_text())
|
|
if value['source'] != args.expected_source or value['root'] != str(checked(args.root)): raise ValueError('Rollback source/root mismatch')
|
|
else:
|
|
if not args.artifacts: parser.error('--artifacts is required')
|
|
value = plan(args.root, args.artifacts, args.expected_source, args.expected_terrain_sha)
|
|
if not args.apply_reset:
|
|
print(json.dumps({k: value[k] for k in ('root', 'unit', 'source', 'resetDirectories', 'preserved')}, indent=2))
|
|
return
|
|
if os.name != 'posix' or os.geteuid() != 0: raise ValueError('Apply requires the verified Linux server administrator')
|
|
import fcntl
|
|
lock = checked(args.root) / '.arrakis-terrain-reset.lock'
|
|
if lock.is_symlink(): raise ValueError('Symlinked operation lock')
|
|
with lock.open('a') as stream:
|
|
fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
if args.rollback_receipt:
|
|
rollback(args.rollback_receipt, Service(checked(args.root)))
|
|
print('Receipt-backed Arrakis rollback completed; player metadata retained.')
|
|
elif args.no_backup:
|
|
removed = regenerate_without_backup(value, Service(checked(args.root)))
|
|
print(f'Removed {removed} Arrakis chunk files; awaiting Paper readiness.')
|
|
else:
|
|
print('Receipt:', apply(value, Service(checked(args.root))))
|
|
|
|
|
|
if __name__ == '__main__': main()
|

Staff