69 lines
2.3 KiB
Python
69 lines
2.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Add the Archipelago route to a known Docker Caddy ingress configuration."""
|
|
from pathlib import Path
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
|
|
config = Path(sys.argv[1])
|
|
original = config.read_bytes()
|
|
text = original.decode()
|
|
sites = list(re.finditer(r'^mirror\.nw-sys\.ru \{\n.*?^\}', text, re.M | re.S))
|
|
if len(sites) != 1:
|
|
raise SystemExit('Expected exactly one standalone mirror site block')
|
|
site = sites[0]
|
|
block = site.group()
|
|
if '/archipelago' in block:
|
|
raise SystemExit('Archipelago route already present; review explicitly')
|
|
marker = ' handle /archlinux* {'
|
|
if block.count(marker) != 1 or 'reverse_proxy http://100.64.0.1:80' not in block:
|
|
raise SystemExit('Unexpected mirror routing; review explicitly')
|
|
snippet = ''' # BEGIN ARCHIPELAGO ingress
|
|
handle /archipelago {
|
|
redir /archipelago/ 308
|
|
}
|
|
handle /archipelago/* {
|
|
reverse_proxy http://100.64.0.1:80
|
|
}
|
|
# END ARCHIPELAGO ingress
|
|
|
|
'''
|
|
candidate = (text[:site.start()] + block.replace(marker, snippet + marker)
|
|
+ text[site.end():]).encode()
|
|
temporary = config.with_name(f'Caddyfile.archipelago-candidate-{time.time_ns()}')
|
|
command = ['docker', 'exec', 'caddy-caddy-1', 'caddy']
|
|
|
|
def write(data):
|
|
with config.open('wb') as stream:
|
|
stream.write(data)
|
|
stream.flush()
|
|
os.fsync(stream.fileno())
|
|
|
|
def reload():
|
|
subprocess.run(command + ['reload', '--config', '/etc/caddy/Caddyfile',
|
|
'--adapter', 'caddyfile'], check=True)
|
|
|
|
try:
|
|
with temporary.open('xb') as stream:
|
|
os.fchmod(stream.fileno(), 0o600)
|
|
stream.write(candidate)
|
|
subprocess.run(command + ['validate', '--config', '/etc/caddy/' + temporary.name,
|
|
'--adapter', 'caddyfile'], check=True)
|
|
if config.read_bytes() != original:
|
|
raise SystemExit('Configuration changed during validation; retry after review')
|
|
backup = config.with_name(f'Caddyfile.before-archipelago-{time.time_ns()}')
|
|
shutil.copy2(config, backup)
|
|
os.chmod(backup, 0o600)
|
|
try:
|
|
write(candidate)
|
|
reload()
|
|
except Exception:
|
|
write(original)
|
|
reload()
|
|
raise
|
|
print(f'Integrated ingress; backup: {backup}')
|
|
finally:
|
|
temporary.unlink(missing_ok=True)
|