infrastructure/control/server.py

320 lines
16 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')
SNAPSHOT = re.compile(r'[0-9]{4}-[0-9]{2}-[0-9]{2}')
SERVICE = 'archipelago-release-cycle.service'
TIMER = 'archipelago-release-cycle.timer'
# Immutable mirror snapshots live on ZFS; the read-only bind views below are
# published by HTTP from the host mount namespace.
SNAPSHOT_DATASET = Path('/tank/archipelago/archlinux')
SNAPSHOT_PREFIX = 'monthly-'
SNAPSHOT_VIEW = 'data/public/arch-repo-snapshot'
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.snapshot_dataset = Path(config.get('snapshot_dataset', str(SNAPSHOT_DATASET)))
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)}
states = [s for name in names if (s := self.state(name))]
# Show the run that changed most recently first: a resumed run keeps an
# older identity but is the one actually progressing.
return sorted(states, key=lambda s: (s.get("updated") or s.get("started") or "", s.get("run") or ""), reverse=True)
def snapshots(self):
"""Immutable repository views, read from the dataset itself.
A bind view created moments ago exists only in the host mount namespace,
so listing the published directory would hide it from this unit. The ZFS
snapshot list is the source of truth; every listed entry is validated by
its Core database, which is what the cycle resolves packages from.
"""
root = self.snapshot_dataset / '.zfs/snapshot'
result = []
if root.is_dir():
for entry in root.glob(SNAPSHOT_PREFIX + '*'):
date = entry.name.removeprefix(SNAPSHOT_PREFIX)
if SNAPSHOT.fullmatch(date) and (entry / 'core/os/x86_64/core.db').is_file():
result.append({'date': date,
'url': '/archipelago/arch-repo-snapshot/' + date + '/$repo/os/$arch'})
return sorted(result, key=lambda item: item['date'], reverse=True)
def snapshot_date(self, choice):
"""Resolve a portal snapshot choice to one immutable view date."""
if choice == 'latest':
available = self.snapshots()
if not available:
raise ValueError('Нет доступных снимков: выберите «Новый снимок»')
return available[0]['date']
if choice == 'new':
# The creation script bind-mounts the read-only view for HTTP, and a
# mount made inside this unit's private namespace would be invisible
# to the web server, so it runs as a transient host unit.
unit = 'archipelago-snapshot-' + datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S')
command = self.config.get('snapshot_command', '/usr/local/sbin/archipelago-mirror-snapshot')
process = subprocess.run(['systemd-run', '--wait', '--pipe', '--collect', '--unit=' + unit,
'--property=Type=oneshot',
'--property=TimeoutStartSec=600', command],
capture_output=True, text=True, timeout=660)
output = process.stdout + process.stderr
if process.returncode:
raise ValueError('Снимок не создан: ' + output.strip()[-800:])
views = [line.split('arch-repo-snapshot/')[1].split('/')[0]
for line in output.splitlines() if 'arch-repo-snapshot/' in line]
if not views or not SNAPSHOT.fullmatch(views[-1]):
raise ValueError('Снимок создан без пригодного URL: ' + output.strip()[-400:])
return views[-1]
if not SNAPSHOT.fullmatch(choice):
raise ValueError('Некорректная дата снимка')
if not any(item['date'] == choice for item in self.snapshots()):
raise ValueError('Снимок ' + choice + ' не найден')
return choice
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, parameters=None):
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')
parameters = parameters or {}
with self.lock:
if action == 'start' and self.unit(SERVICE)['ActiveState'] in ('active', 'activating', 'deactivating'):
raise ValueError('Pipeline is already running or stopping')
if action == 'start':
mode = parameters.get('mode', 'iso')
if mode not in ('iso', 'ostree'):
raise ValueError('Неизвестный режим сборки')
# Pin the exact immutable repository before the cycle starts: a
# manual build must never silently reuse a different snapshot.
pinned = self.snapshot_date(parameters.get('snapshot', 'latest'))
parameters = {'mode': mode, 'snapshot': pinned,
'requested_at': datetime.now(timezone.utc).isoformat()}
path = self.archive / 'cycle-request.json'
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix('.tmp')
temporary.write_text(json.dumps(parameters) + '\n')
temporary.replace(path)
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, 'request': parameters}) + '\n')
return {'accepted': True, 'action': action, 'request': parameters if action == 'start' else None}
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(), 'snapshots': app.snapshots(),
'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'], body), 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()