164 lines
6.4 KiB
Python
164 lines
6.4 KiB
Python
"""Disable optional vendor integrations on an explicitly selected server."""
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import subprocess
|
|
import tempfile
|
|
|
|
|
|
SETTINGS = {
|
|
'Towny': (
|
|
'settings/config.yml', {
|
|
'plugin.update_notifications.alerts',
|
|
'new_world_settings.plot_management.block_delete.enabled',
|
|
'new_world_settings.plot_management.mayor_plotblock_delete.enabled',
|
|
},
|
|
),
|
|
'MedievalFactions': (
|
|
'config.yml', {
|
|
'addons.suggestions', 'dynmap.enableDynmapIntegration',
|
|
'update-check.enabled', 'usage-reporting.enabled',
|
|
},
|
|
),
|
|
}
|
|
MANIFEST = json.loads(Path(__file__).with_name('unused-vendor-settings.json').read_text(encoding='utf-8-sig'))
|
|
PINS = MANIFEST['configs']
|
|
YAML_KEY = re.compile(rb'^([ ]*)([a-zA-Z0-9_-]+):[ \t]*(.*?)(\r?\n)?$')
|
|
BOOL = re.compile(rb"^(['\"]?)(true|false)\1([ \t]*(?:#.*)?)$")
|
|
|
|
|
|
def patch(data, targets):
|
|
parents = []
|
|
seen = set()
|
|
output = []
|
|
for line in data.splitlines(keepends=True):
|
|
parsed = YAML_KEY.fullmatch(line)
|
|
if parsed:
|
|
spaces, key, value, _ = parsed.groups()
|
|
level = len(spaces)
|
|
while parents and parents[-1][0] >= level:
|
|
parents.pop()
|
|
parents.append((level, key.decode('ascii')))
|
|
path = '.'.join(name for _, name in parents)
|
|
if path in targets:
|
|
boolean = BOOL.fullmatch(value)
|
|
if path in seen or boolean is None:
|
|
raise ValueError(f'Expected one explicit boolean for {path}')
|
|
seen.add(path)
|
|
if boolean[2] == b'true':
|
|
start = parsed.start(3) + boolean.start(2)
|
|
line = line[:start] + b'false' + line[start + 4:]
|
|
output.append(line)
|
|
if seen != targets:
|
|
raise ValueError(f'Missing reviewed settings: {sorted(targets - seen)}')
|
|
return b''.join(output)
|
|
|
|
|
|
def digest(data):
|
|
return hashlib.sha256(data).hexdigest()
|
|
|
|
|
|
def patch_world(data):
|
|
if len(re.findall(rb'(?m)^usingPlotManagementRevert=false(?=\r?$)', data)) != 1:
|
|
raise ValueError('Expected Towny plot regeneration already disabled')
|
|
for field in (b'usingPlotManagementDelete', b'usingPlotManagementMayorDelete'):
|
|
prefix = rb'(?m)^' + field + b'='
|
|
if len(re.findall(prefix, data)) != 1:
|
|
raise ValueError(f'Expected one Towny world field: {field.decode()}')
|
|
data, count = re.subn(prefix + rb'true(?=\r?$)', field + b'=false', data)
|
|
if count != 1:
|
|
raise ValueError(f'Expected enabled Towny world field: {field.decode()}')
|
|
return data
|
|
|
|
|
|
def read_pinned(path, pin):
|
|
if not path.is_file() or path.resolve(strict=True) != path:
|
|
raise ValueError(f'Expected regular config at {path}')
|
|
data = path.read_bytes()
|
|
if digest(data) != pin:
|
|
raise ValueError(f'Unexpected config revision: {path}')
|
|
return data
|
|
|
|
|
|
def identity(metadata):
|
|
return (metadata.st_dev, metadata.st_ino, metadata.st_uid, metadata.st_gid,
|
|
metadata.st_mode, metadata.st_size, metadata.st_mtime_ns)
|
|
|
|
|
|
def write(path, data, original_stat):
|
|
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as handle:
|
|
staged = Path(handle.name)
|
|
try:
|
|
handle.write(data)
|
|
handle.flush()
|
|
os.fchown(handle.fileno(), original_stat.st_uid, original_stat.st_gid)
|
|
os.fchmod(handle.fileno(), original_stat.st_mode & 0o7777)
|
|
os.fsync(handle.fileno())
|
|
os.replace(staged, path)
|
|
finally:
|
|
staged.unlink(missing_ok=True)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('server', choices=sorted(PINS))
|
|
parser.add_argument('--apply', action='store_true', help='Apply while the instance is stopped')
|
|
args = parser.parse_args()
|
|
root = Path('/opt/dunerealms/lobby' if args.server == 'lobby' else
|
|
f'/opt/dunerealms/servers/{args.server}')
|
|
unit = f'dune-{args.server}.service'
|
|
state = subprocess.check_output(
|
|
['systemctl', 'show', '-p', 'WorkingDirectory', '-p', 'ActiveState', '-p', 'MainPID', unit],
|
|
text=True,
|
|
)
|
|
state = dict(line.split('=', 1) for line in state.splitlines())
|
|
if state['WorkingDirectory'] != str(root):
|
|
raise ValueError('Service has unexpected working directory')
|
|
if args.apply and (state['ActiveState'] not in {'inactive', 'failed'} or state['MainPID'] != '0'):
|
|
raise ValueError('Stop the reviewed service before applying')
|
|
changes = {}
|
|
for vendor, (relative, targets) in SETTINGS.items():
|
|
path = root / 'plugins' / vendor / relative
|
|
data = read_pinned(path, PINS[args.server][vendor])
|
|
changes[path] = (data, patch(data, targets), path.stat())
|
|
worlds = root / 'plugins/Towny/data/worlds'
|
|
reviewed = MANIFEST['worlds'][args.server]
|
|
if {path.stem for path in worlds.glob('*.txt')} != reviewed.keys():
|
|
raise ValueError('Towny world inventory differs from the reviewed scope')
|
|
for world, pin in reviewed.items():
|
|
if not re.fullmatch(r'[a-z0-9_]+', world):
|
|
raise ValueError('Invalid reviewed Towny world name')
|
|
path = worlds / f'{world}.txt'
|
|
data = read_pinned(path, pin)
|
|
changes[path] = (data, patch_world(data), path.stat())
|
|
written = []
|
|
if args.apply:
|
|
try:
|
|
for path, (before, after, metadata) in changes.items():
|
|
if path.read_bytes() != before or identity(path.stat()) != identity(metadata):
|
|
raise ValueError(f'Config changed after preflight: {path}')
|
|
if before != after:
|
|
write(path, after, metadata)
|
|
written.append(path)
|
|
for path, (_, after, _) in changes.items():
|
|
if path.read_bytes() != after:
|
|
raise ValueError(f'Config readback differs: {path}')
|
|
except Exception:
|
|
for path in reversed(written):
|
|
before, after, metadata = changes[path]
|
|
if path.read_bytes() == after:
|
|
write(path, before, metadata)
|
|
raise
|
|
print(json.dumps({
|
|
'unit': unit, 'status': 'applied' if args.apply else 'planned',
|
|
'changes': {str(path): {'before': digest(before), 'after': digest(after)}
|
|
for path, (before, after, _) in changes.items()},
|
|
}, indent=2))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|

Staff