Disable unused Towny and MedievalFactions vendor settings
This commit is contained in:
parent
dc8a2bd290
commit
e867121f02
4 changed files with 232 additions and 0 deletions
33
.forgejo/workflows/unused-vendor-settings.yml
Normal file
33
.forgejo/workflows/unused-vendor-settings.yml
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
name: Unused Vendor Settings Operations Build
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: ['ops/unused-vendor-settings-*']
|
||||
|
||||
jobs:
|
||||
unused-vendor-settings:
|
||||
runs-on: dune-ci
|
||||
steps:
|
||||
- name: Check out exact revision
|
||||
shell: bash
|
||||
env:
|
||||
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git init .
|
||||
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA"
|
||||
git checkout --detach FETCH_HEAD
|
||||
- name: Validate and package the scoped vendor configuration operation
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
python3 tools/test_unused_vendor_settings.py -v
|
||||
mkdir unused-vendor-artifacts
|
||||
cp tools/disable-unused-vendor-settings.py tools/unused-vendor-settings.json unused-vendor-artifacts/
|
||||
printf '%s\n' "$(git rev-parse HEAD)" > unused-vendor-artifacts/SOURCE_COMMIT
|
||||
(cd unused-vendor-artifacts && sha256sum -- *.py *.json SOURCE_COMMIT > SHA256SUMS)
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: DuneRealms-Unused-Vendor-Settings
|
||||
path: unused-vendor-artifacts/
|
||||
if-no-files-found: error
|
||||
131
tools/disable-unused-vendor-settings.py
Normal file
131
tools/disable-unused-vendor-settings.py
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
"""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'},
|
||||
),
|
||||
'MedievalFactions': (
|
||||
'config.yml', {
|
||||
'addons.suggestions', 'dynmap.enableDynmapIntegration',
|
||||
'update-check.enabled', 'usage-reporting.enabled',
|
||||
},
|
||||
),
|
||||
}
|
||||
PINS = json.loads(Path(__file__).with_name('unused-vendor-settings.json').read_text(encoding='utf-8-sig'))
|
||||
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 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
|
||||
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) != PINS[args.server][vendor]:
|
||||
raise ValueError(f'Unexpected config revision: {path}')
|
||||
changes[path] = (data, patch(data, targets), 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()
|
||||
42
tools/test_unused_vendor_settings.py
Normal file
42
tools/test_unused_vendor_settings.py
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import re
|
||||
import runpy
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
MODULE = runpy.run_path(str(Path(__file__).with_name('disable-unused-vendor-settings.py')))
|
||||
patch = MODULE['patch']
|
||||
|
||||
|
||||
class UnusedVendorSettingsTest(unittest.TestCase):
|
||||
def test_preserves_quotes_comments_line_endings_and_unrelated_settings(self):
|
||||
source = (b'plugin:\r\n update_notifications:\r\n alerts: "true" # vendor\r\n'
|
||||
b' major_only: true\r\nother:\r\n alerts: true')
|
||||
targets = MODULE['SETTINGS']['Towny'][1]
|
||||
self.assertEqual(patch(source, targets), source.replace(b'"true"', b'"false"'))
|
||||
|
||||
def test_nested_paths_and_already_disabled_values(self):
|
||||
source = (b'addons:\n suggestions: true\ndynmap:\n enableDynmapIntegration: true\n'
|
||||
b'update-check:\n enabled: true\nusage-reporting:\n enabled: false\n'
|
||||
b'dpc-api:\n login-reminder: true\n')
|
||||
targets = MODULE['SETTINGS']['MedievalFactions'][1]
|
||||
after = patch(source, targets)
|
||||
self.assertEqual(after, source.replace(b': true', b': false', 3))
|
||||
self.assertEqual(patch(after, targets), after)
|
||||
|
||||
def test_refuses_missing_invalid_and_duplicate_target(self):
|
||||
for data in (b'a: true', b'b: yes', b'b: true\nb: false'):
|
||||
with self.subTest(data=data), self.assertRaises(ValueError):
|
||||
patch(data, {'b'})
|
||||
|
||||
def test_pins_cover_only_six_servers_and_exact_vendors(self):
|
||||
pins = MODULE['PINS']
|
||||
self.assertEqual(set(pins), {'lobby', 'arrakis', 'caladan', 'giedi_prime',
|
||||
'kaitain', 'sigma_draconis_iv'})
|
||||
for vendors in pins.values():
|
||||
self.assertEqual(vendors.keys(), MODULE['SETTINGS'].keys())
|
||||
self.assertTrue(all(re.fullmatch(r'[0-9a-f]{64}', sha) for sha in vendors.values()))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
26
tools/unused-vendor-settings.json
Normal file
26
tools/unused-vendor-settings.json
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
{
|
||||
"arrakis": {
|
||||
"Towny": "7189d2eb3a1e09c4bb9ab5cb10abed23733f77ede426200b217afb5cdea0a07e",
|
||||
"MedievalFactions": "d8c325ca1b41aa17df580b72b4e8e79714691215a51f3dc7c8332a3f24e99d57"
|
||||
},
|
||||
"caladan": {
|
||||
"Towny": "6bfa13a9d3e7be27731f3a27e995987cf2870c52a56253d626b55b6ea5efdbff",
|
||||
"MedievalFactions": "95c94f07e91f8599f676bdc03ef333d0682338f2bf7d6f0f9d5f31cd6fabe652"
|
||||
},
|
||||
"giedi_prime": {
|
||||
"Towny": "7440231da22718cba4c402d8b07594484aacd840b3c01ab81c4d2a6f1fcfac1f",
|
||||
"MedievalFactions": "d8c325ca1b41aa17df580b72b4e8e79714691215a51f3dc7c8332a3f24e99d57"
|
||||
},
|
||||
"kaitain": {
|
||||
"Towny": "30a82b404c01fd5e496451db8bfe552ba63fe7accea5b9a385b76a81e9a55bd2",
|
||||
"MedievalFactions": "d8c325ca1b41aa17df580b72b4e8e79714691215a51f3dc7c8332a3f24e99d57"
|
||||
},
|
||||
"lobby": {
|
||||
"Towny": "f5cd49775e87df639278450ff097b48d25c52740c1c86a682d77d11293cd06bb",
|
||||
"MedievalFactions": "987b468f275f55dc42363a622196d2632c096754dce5d42c5b630e0c493159bc"
|
||||
},
|
||||
"sigma_draconis_iv": {
|
||||
"Towny": "aa4c3f796decb6ffac0edd35bfc93629432f3fcd9cd4edece6beff99f5374858",
|
||||
"MedievalFactions": "d8c325ca1b41aa17df580b72b4e8e79714691215a51f3dc7c8332a3f24e99d57"
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue

Staff