infrastructure/control/server.py

244 lines
12 KiB
Python

#!/usr/bin/env python3
"""Private LAN/Tailscale pipeline control; fixed systemd actions, byte-range logs."""
import argparse
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import importlib.util
import ipaddress
import json
import mimetypes
import os
from pathlib import Path
import re
import subprocess
import threading
from urllib.parse import parse_qs, urlsplit
SPEC = importlib.util.spec_from_file_location('monitor', Path(__file__).parents[1] / 'pipeline/monitor.py')
monitor = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(monitor)
SCHEDULE_SPEC = importlib.util.spec_from_file_location('release_schedule', Path(__file__).parents[1] / 'pipeline/release-schedule.py')
schedule = importlib.util.module_from_spec(SCHEDULE_SPEC)
SCHEDULE_SPEC.loader.exec_module(schedule)
RUN = re.compile(r'[0-9]{8}T[0-9]{6}Z')
SERVICE = 'archipelago-release-cycle.service'
TIMER = 'archipelago-release-cycle.timer'
def read_json(path, default=None):
try:
return json.loads(path.read_text())
except (FileNotFoundError, json.JSONDecodeError):
return default
class App:
def __init__(self, config):
self.config = config
self.base = Path(config['coordinator_root'])
self.archive = self.base / 'data/private/release-cycle'
self.history = self.base / 'data/private/pipeline-monitor'
self.worker = Path(config['worker_root']) / 'build/release-cycle'
self.lock = threading.Lock()
self.networks = [ipaddress.ip_network(n) for n in config['allowed_networks']]
def unit(self, name):
out = subprocess.run(['systemctl', 'show', name, '--no-pager',
'--property=ActiveState,SubState,MainPID,Result,UnitFileState,NextElapseUSecRealtime'],
capture_output=True, text=True, timeout=10, check=True).stdout
return dict(line.split('=', 1) for line in out.splitlines() if '=' in line)
def state(self, run):
if not RUN.fullmatch(run):
raise ValueError('Invalid run identity')
return read_json(self.history / run / 'state.json') or read_json(self.archive / run / 'state.json')
def runs(self):
names = {p.name for root in (self.archive, self.history) if root.exists()
for p in root.iterdir() if RUN.fullmatch(p.name)}
return [s for name in sorted(names, reverse=True) if (s := self.state(name))]
def logs(self, run):
if not self.state(run):
raise FileNotFoundError('Run not found')
roots = {'monitor': self.history / run, 'worker': self.worker / run, 'archive': self.archive / run}
# Flatpak writes a detailed refresh log outside the build directory.
state = self.state(run)
# In-flight Flatpak refresh writes outside the run workspace before its
# final status.json exists. Expose those complete logs immediately.
end = state.get('finished') or (state.get('updated') if state['state'] in ('complete', 'failed') else None)
end_stamp = datetime.fromisoformat(end).strftime('%Y%m%dT%H%M%SZ') if end else '99999999T999999Z'
cache = Path(self.config['worker_root']) / 'cache/flatpak'
for name, folder in (('flatpak-live', cache / 'runs'), ('kde-flatpak-live', cache / 'kde/runs')):
if folder.exists():
for attempt in folder.iterdir():
if RUN.fullmatch(attempt.name) and run <= attempt.name <= end_stamp:
roots[name + '/' + attempt.name] = attempt
for label in ('flatpak', 'flatpak_kde'):
log = state.get(label, {}).get('log')
if log:
path = Path(log)
cache = Path(self.config['worker_root']) / 'cache/flatpak'
if path.resolve().is_relative_to(cache.resolve()):
roots[label] = path.parent
found = {}
for label, root in roots.items():
for path in monitor.log_files(root):
if path.resolve().is_relative_to(root.resolve()):
found[label + '/' + str(path.relative_to(root))] = path
return found
def control(self, action):
commands = {'start': ['start', '--no-block', SERVICE], 'stop': ['stop', '--no-block', SERVICE],
'schedule-on': ['enable', '--now', TIMER], 'schedule-off': ['disable', '--now', TIMER]}
if action not in commands:
raise ValueError('Unknown action')
with self.lock:
if action == 'start' and self.unit(SERVICE)['ActiveState'] in ('active', 'activating', 'deactivating'):
raise ValueError('Pipeline is already running or stopping')
subprocess.run(['systemctl', *commands[action]], check=True, capture_output=True, timeout=15)
self.history.mkdir(parents=True, exist_ok=True)
with (self.history / 'control.jsonl').open('a') as stream:
stream.write(json.dumps({'time': datetime.now(timezone.utc).isoformat(), 'action': action}) + '\n')
return {'accepted': True, 'action': action}
class Handler(BaseHTTPRequestHandler):
server_version = 'ArchipelagoControl/1'
def allowed(self):
peer = ipaddress.ip_address(self.client_address[0])
host = self.headers.get('Host', '')
return any(peer in network for network in self.server.app.networks) and host in self.server.app.config['hosts']
def response_headers(self, status, content_type, length, download=False):
self.send_response(status)
self.send_header('Content-Type', content_type)
self.send_header('Content-Length', str(length))
self.send_header('Cache-Control', 'no-store')
self.send_header('X-Content-Type-Options', 'nosniff')
self.send_header('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self'; frame-ancestors 'none'; base-uri 'none'")
if download:
self.send_header('Content-Disposition', 'attachment; filename="pipeline.log"')
self.end_headers()
def result(self, value, status=200):
body = json.dumps(value, ensure_ascii=False).encode()
self.response_headers(status, 'application/json; charset=utf-8', len(body))
self.wfile.write(body)
def do_GET(self):
if not self.allowed():
return self.result({'error': 'Private endpoint'}, 403)
try:
self.get()
except (ValueError, FileNotFoundError, KeyError) as error:
self.result({'error': str(error)}, 400)
except (BrokenPipeError, ConnectionResetError):
pass
except Exception as error:
self.log_error('%s', error)
self.result({'error': str(error)}, 500)
def get(self):
app = self.server.app
url = urlsplit(self.path)
query = parse_qs(url.query)
if url.path == '/api/status':
return self.result({'service': app.unit(SERVICE), 'timer': app.unit(TIMER),
'next_release': schedule.next_release(datetime.now(timezone.utc)),
'runs': app.runs(), 'time': datetime.now(timezone.utc).isoformat(),
'sources': read_json(Path(app.config['worker_source_root']) / 'src/source-revisions.json', {})})
if url.path == '/api/run':
run = query['run'][0]
state = app.state(run)
if state is None:
raise FileNotFoundError('Run not found')
root = app.history / run
invocation = state.get('invocation_id', '')
if re.fullmatch(r'[0-9a-f]{32}', invocation):
root.mkdir(parents=True, exist_ok=True)
with app.lock:
temporary = root / 'coordinator.log.tmp'
with temporary.open('wb') as output:
subprocess.run(['journalctl', '_SYSTEMD_INVOCATION_ID=' + invocation,
'--no-pager', '--output=short-iso-precise'], stdout=output, stderr=subprocess.STDOUT, timeout=15, check=True)
temporary.replace(root / 'coordinator.log')
actions = [read_json(p) for p in sorted(root.glob('action-*.json'))]
events = []
if (root / 'events.jsonl').exists():
for line in (root / 'events.jsonl').read_text().splitlines():
try:
value = json.loads(line)
if value['event'] == 'phase':
events.append(value)
except json.JSONDecodeError:
pass
logs = [{'id': key, 'size': path.stat().st_size, 'modified': path.stat().st_mtime}
for key, path in app.logs(run).items() if path.exists()]
return self.result({'state': state, 'actions': actions, 'events': events, 'logs': logs,
'instrumented': (root / 'events.jsonl').exists()})
if url.path == '/api/log':
path = app.logs(query['run'][0])[query['id'][0]]
with path.open('rb') as stream:
size = os.fstat(stream.fileno()).st_size
if query.get('download') == ['1']:
self.response_headers(200, 'text/plain; charset=utf-8', size, True)
remaining = size
while remaining:
chunk = stream.read(min(1024 * 1024, remaining))
if not chunk:
break
self.wfile.write(chunk)
remaining -= len(chunk)
return
offset = int(query.get('offset', ['0'])[0])
if offset < 0:
offset = max(0, size - 262144)
offset = min(offset, size)
stream.seek(offset)
chunk = stream.read(262144)
return self.result({'offset': offset, 'next': offset + len(chunk), 'size': size,
'text': chunk.decode('utf-8', errors='replace')})
assets = {'/': 'index.html', '/app.js': 'app.js', '/style.css': 'style.css'}
if url.path == '/mark.svg':
path = Path(__file__).parents[1] / 'portal/mark.svg'
else:
path = Path(__file__).parent / assets[url.path]
body = path.read_bytes()
self.response_headers(200, mimetypes.guess_type(str(path))[0] or 'application/octet-stream', len(body))
self.wfile.write(body)
def do_POST(self):
if not self.allowed() or self.headers.get('Origin') != 'http://' + self.headers.get('Host', '') or self.headers.get('X-Archipelago-Control') != '1':
return self.result({'error': 'Same-origin private control required'}, 403)
try:
if self.path != '/api/control' or self.headers.get('Content-Type') != 'application/json':
raise ValueError('Invalid control request')
length = int(self.headers.get('Content-Length', '0'))
if not 0 < length <= 1024:
raise ValueError('Invalid request size')
body = json.loads(self.rfile.read(length))
self.result(self.server.app.control(body['action']), 202)
except Exception as error:
self.result({'error': str(error)}, 409)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--config', required=True, type=Path)
args = parser.parse_args()
app = App(json.loads(args.config.read_text()))
servers = []
for address in app.config['listen']:
server = ThreadingHTTPServer((address, app.config['port']), Handler)
server.daemon_threads = True
server.app = app
servers.append(server)
for server in servers[:-1]:
threading.Thread(target=server.serve_forever, daemon=True).start()
servers[-1].serve_forever()
if __name__ == '__main__':
main()