diff --git a/README.md b/README.md index a4ecb82..b9d81a3 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,15 @@ Accepted deployment: terra, https://mirror.nw-sys.ru/archipelago/ (D-071). Source registries: `Archipelago/core`, `Archipelago/purposes`; contracts: `Archipelago/rfc`. +## Private build control (2026-11-09) + +Personal portal on terra: **http://100.64.0.11:8099/** (Tailscale) or +**http://192.168.88.104:8099/** (LAN). No Ingress integration. +Start/stop, timer control, actual stage/action history and full paginated/downloadable +logs: [deployment and API](control/README.md). New builds run on terra SSD worker; +artifacts and retained logs on ZFS. Schedule: 15th/30th at 00:00 UTC (D-090). +The older yabloko/daily descriptions below are historical. + Temporary hardware-testing topology/retention and publication procedure: [`deploy/HARDWARE-TEST.md`](deploy/HARDWARE-TEST.md). Builds/tests now run on yabloko; repositories and published artifacts remain on terra. The hardware-test diff --git a/control/README.md b/control/README.md new file mode 100644 index 0000000..1ba4992 --- /dev/null +++ b/control/README.md @@ -0,0 +1,43 @@ +# Private build control portal + +Standalone Python stdlib service. No ingress, reverse proxy, Docker socket or +public-site route. The service binds **only** configured LAN/Tailscale/loopback +addresses, checks the peer subnet and Host header, and requires same-origin JSON +POSTs for the fixed systemd start/stop/schedule actions. It trusts users on those +private networks; it is a personal control surface, not an Internet-facing app. + +Terra deployment: `192.168.88.104:8099`, `100.64.0.11:8099`, `127.0.0.1:8099`. +Allowed peers: `192.168.88.0/24`, `100.64.0.0/10`, `127.0.0.0/8`. +Config `/etc/archipelago/control.json` includes `listen`, `hosts` (with port), +`allowed_networks`, `port`, `coordinator_root`, `worker_root`, `worker_source_root`. +Unit: `deploy/archipelago-control.service`. Source: `/opt/archipelago/control-source`. +LAN address changes require updating bind/Host config and restarting this service. + +## Monitoring contract + +- `/api/status`: actual systemd service/timer state, next trigger, history, source SHAs. +- `/api/run?run=ID`: ordered phase events, all invoked actions, complete argv, + start/end times, elapsed time, exit code/error, and inventory of nested logs. +- `/api/log?run=ID&id=LOG&offset=BYTE`: 256-KiB pages from any byte offset; + offset -1 tails. Every byte is reachable; the UI does not equate a tail to a full log. +- `download=1`: stream the complete file, without a size cap. No arbitrary path API. +- All output is rendered as text; log content never becomes HTML or executable code. +- Old runs expose all surviving logs but explicitly lack the new action timeline. +- Progress is measured phases/status/duration, not an invented overall percentage. + +New runs retain `action-NNNN.log` (stdout + stderr, no line limit), command metadata, +phase events and nested CLI/build/acceptance/serial/Flatpak logs on ZFS under +`/opt/archipelago/data/private/pipeline-monitor/ID`. Coordinator journald output is +also available by invocation ID. The worker's live files are available before archive. +Log history is separate from artifact-retention cleanup and is **not auto-deleted**. +Source revisions are frozen into each run's source archive; the overview shows the +next run's configured source revisions. Native executable logs retain their existing +format; monitoring does not substitute human CLI output for private detailed logs. + +Stopping the driver stops owned worker units and VM units, retains logs, and leaves +unfinished build artifacts for diagnosis rather than starting a lengthy archive. +No command shell or arbitrary service name is accepted over HTTP. Schedule buttons +control the existing 15th/30th 00:00 UTC timer and do not change its dates. + +Runtime API tests: `python3 tests/control_portal.py` on terra. They use a temporary +fixture and fake systemd responses; they never start or stop a real build. diff --git a/control/app.js b/control/app.js new file mode 100644 index 0000000..bc1c886 --- /dev/null +++ b/control/app.js @@ -0,0 +1,66 @@ +'use strict'; +const $ = id => document.getElementById(id); +const phases = [ + ['preflight','Подготовка'],['freezing-and-compiling-source','Исходники и тесты'], + ['updating-flatpak-cache','Flatpak / GNOME'],['updating-kde-flatpak-cache','Flatpak / KDE'], + ['building-software-adapter','GNOME Software'],['building-discover-adapter','Discover'], + ['building-core','Core / ISO'],['building-gnome-purpose-and-iso','GNOME / ISO'],['building-kde-purpose-and-iso','KDE / ISO'], + ['core-installed-acceptance','Приёмка Core'],['gnome-installed-acceptance','Приёмка GNOME'],['kde-installed-acceptance','Приёмка KDE'], + ['archiving-artifacts','Архив и целостность'],['preparing-publication','Подготовка публикации'], + ['signing-and-publishing','Подпись и публикация'],['verifying-public-endpoints','Проверка HTTPS'],['cleaning-worker','Очистка worker'] +]; +let run = '', log = '', offset = 0, next = 0, size = 0, text = '', data = null, status = null, busy = false, logBusy = false; +let logsKey = '', runsKey = ''; +const date = value => value ? new Date(value).toLocaleString('ru-RU') : '—'; +const bytes = value => value < 1024 ? value+' Б' : value < 1048576 ? (value/1024).toFixed(1)+' КиБ' : (value/1048576).toFixed(1)+' МиБ'; +const elapsed = (start,end) => {const s=Math.max(0,Math.floor(((end?new Date(end):new Date())-new Date(start))/1000));return s<60?s+' с':Math.floor(s/60)+' мин '+s%60+' с';}; +const label = s => ({complete:'Завершён',failed:'Остановлен / ошибка',starting:'Запуск',succeeded:'Готово',running:'В работе'}[s] || 'В работе'); +function node(tag, cls, content) {const n=document.createElement(tag);if(cls)n.className=cls;if(content!==undefined)n.textContent=content;return n;} +async function api(url, options) {const r=await fetch(url, options);const body=await r.json();if(!r.ok)throw Error(body.error || r.statusText);return body;} +function showError(error) {$('error').hidden=false;$('error').textContent=error.message;} +function selectRun(id) {run=id;log='';offset=0;logsKey='';runsKey='';data=null;$('log-content').textContent='Выберите лог';$('download').hidden=true;refresh();} +async function control(action) { + document.querySelectorAll('.controls button').forEach(b=>b.disabled=true); + try {await api('/api/control',{method:'POST',headers:{'Content-Type':'application/json','X-Archipelago-Control':'1'},body:JSON.stringify({action})});$('action-result').textContent=({start:'Запуск передан systemd',stop:'Остановка передана systemd','schedule-on':'Расписание включено','schedule-off':'Расписание отключено'})[action];if(action==='start'){run='';runsKey='';}} + catch(e){showError(e);}finally{refresh();} +} +$('start').onclick=()=>control('start');$('stop').onclick=()=>control('stop'); +$('toggle-schedule').onclick=()=>control(status?.timer.ActiveState==='active'?'schedule-off':'schedule-on'); +function drawStatus(s) { + status=s;const active=['active','activating'].includes(s.service.ActiveState);const stopping=s.service.ActiveState==='deactivating'; + $('service').textContent=stopping?'Останавливается':active?'Выполняется':'Ожидает запуска'; + $('service-detail').textContent=`systemd: ${s.service.ActiveState} / ${s.service.SubState}`; + $('schedule').textContent=s.timer.ActiveState==='active'?'15 / 30 · 00:00 UTC':'Приостановлено'; + $('next').textContent='Следующий: '+(s.timer.NextElapseUSecRealtime || '—'); + $('start').disabled=active||stopping;$('stop').disabled=!active;$('toggle-schedule').disabled=false; + $('toggle-schedule').textContent=s.timer.ActiveState==='active'?'Ⅱ Приостановить расписание':'↻ Включить расписание'; + const published=s.runs.find(r=>r.published);$('published').textContent=published?'Опубликовано':'Нет данных';$('published-detail').textContent=published?.run || 'Публикация не подтверждена'; + if(!run && s.runs.length){run=s.runs[0].run;logsKey='';} + const key=JSON.stringify(s.runs.map(r=>[r.run,r.state,r.published]))+run; + if(key!==runsKey){runsKey=key;$('runs').replaceChildren();for(const r of s.runs){const b=node('button','run-button'+(r.run===run?' selected':''));b.append(node('strong','',r.run),node('small','',label(r.state)+(r.published?' · опубликован':'')));b.onclick=()=>selectRun(r.run);$('runs').append(b);}} + $('run-count').textContent=s.runs.length; + $('sources').replaceChildren();for(const [name,sha] of Object.entries(s.sources)){const d=node('div','',name+' ');d.append(node('code','',sha.slice(0,12)));$('sources').append(d);} +} +function drawRun(d) { + data=d;const s=d.state;const terminal=['failed','complete'].includes(s.state); + $('run-name').textContent=s.run;$('run-state').textContent=label(s.state); + $('run-meta').textContent=`${date(s.started)} · ${elapsed(s.started,terminal?(s.finished||s.updated):null)} · ${s.worker} · ${s.channel}`; + $('run-error').hidden=!s.error;$('run-error').textContent=s.error_details||s.error||''; + $('phase-summary').textContent=d.instrumented?'Фактические переходы и время':'Исторический прогон · подробная трассировка не записывалась'; + $('phases').replaceChildren(); + for(const [id,title] of phases){const event=d.events.find(e=>e.phase===id);const end=event?d.events[d.events.indexOf(event)+1]:null;let state='waiting';if(event)state=end?'succeeded':'active';if(s.state===id)state='active';if(s.failed_phase===id)state='failed';if(!d.instrumented&&s.state==='complete')state='succeeded';const p=node('div','phase '+state);p.append(node('strong','',({waiting:'○ ',active:'◉ ',succeeded:'✓ ',failed:'× '})[state]+title),node('small','',event?elapsed(event.time,end?.time):state==='waiting'?'Не выполнялся / нет данных':id));$('phases').append(p);} + const opened = new Set([...$('actions').querySelectorAll('details[open]')].map(el=>el.dataset.id)); + $('action-count').textContent=`(${d.actions.length})`;$('actions').replaceChildren(); + for(const a of d.actions.filter(Boolean)){const el=node('details','action');el.append(node('summary','',`${a.id} · ${label(a.state)} · ${a.phase} · ${a.duration_seconds??'…'} с · exit ${a.returncode??'—'}`),node('pre','',a.command.join(' ')));if(a.error)el.append(node('p','',a.error));const link=node('a','', 'Открыть полный лог →');link.href='#log-content';link.onclick=()=>selectLog('monitor/'+a.log);el.append(link);$('actions').append(el);} + [...$('actions').children].forEach((el,i)=>{el.dataset.id=d.actions.filter(Boolean)[i].id;el.open=opened.has(el.dataset.id);}); + $('log-count').textContent=`${d.logs.length} файлов · ${bytes(d.logs.reduce((n,l)=>n+l.size,0))}`; + drawLogs(); +} +function drawLogs(){if(!data)return;const filter=$('log-filter').value.toLowerCase();const key=JSON.stringify(data.logs)+log+filter;if(key===logsKey)return;logsKey=key;$('log-files').replaceChildren();for(const item of data.logs.filter(l=>l.id.toLowerCase().includes(filter))){const b=node('button','log-file'+(item.id===log?' selected':''),item.id);b.append(node('small','',bytes(item.size)+' · '+new Date(item.modified*1000).toLocaleTimeString('ru-RU')));b.onclick=()=>selectLog(item.id);$('log-files').append(b);}} +function selectLog(id){log=id;offset=0;$('follow').checked=false;logsKey='';drawLogs();loadLog(0);} +function renderText(){const pre=$('log-content');pre.replaceChildren();const q=$('log-search').value;if(!q){pre.textContent=text;$('matches').textContent='';return;}let pos=0,count=0;const lower=text.toLowerCase(),term=q.toLowerCase();while(true){const hit=lower.indexOf(term,pos);if(hit<0)break;pre.append(document.createTextNode(text.slice(pos,hit)),node('mark','',text.slice(hit,hit+q.length)));pos=hit+q.length;count++;}pre.append(document.createTextNode(text.slice(pos)));$('matches').textContent=count+' совп.';} +async function loadLog(at){if(!run||!log||logBusy)return;logBusy=true;const selected=run+'/'+log;try{const q=new URLSearchParams({run,id:log,offset:String(at)});const r=await api('/api/log?'+q);if(selected!==run+'/'+log)return;offset=r.offset;next=r.next;size=r.size;text=r.text;$('log-name').textContent=log;$('log-range').textContent=`${offset.toLocaleString()}–${next.toLocaleString()} / ${size.toLocaleString()} байт`;$('log-prev').disabled=offset===0;$('log-next').disabled=next>=size;$('download').hidden=false;$('download').href='/api/log?'+new URLSearchParams({run,id:log,download:'1'});renderText();if($('follow').checked)$('log-content').scrollTop=$('log-content').scrollHeight;}catch(e){showError(e);}finally{logBusy=false;}} +$('log-filter').oninput=drawLogs;$('log-search').oninput=renderText; +$('log-first').onclick=()=>{$('follow').checked=false;loadLog(0);};$('log-prev').onclick=()=>{$('follow').checked=false;loadLog(Math.max(0,offset-262144));};$('log-next').onclick=()=>{$('follow').checked=false;loadLog(next);};$('log-tail').onclick=()=>{$('follow').checked=true;loadLog(-1);};$('follow').onchange=()=>{if($('follow').checked)loadLog(-1);}; +async function refresh(){if(busy)return;busy=true;try{const s=await api('/api/status');drawStatus(s);if(run){const selected=run;const d=await api('/api/run?'+new URLSearchParams({run}));if(run===selected)drawRun(d);}if(log&&$('follow').checked)await loadLog(-1);$('connection').textContent='Соединение установлено';$('connection-dot').className='online';$('updated').textContent=new Date().toLocaleTimeString('ru-RU');$('error').hidden=true;}catch(e){$('connection').textContent='Нет связи · данные не обновлены';$('connection-dot').className='';showError(e);}finally{busy=false;}} +refresh();setInterval(refresh,3000); diff --git a/control/index.html b/control/index.html new file mode 100644 index 0000000..0664339 --- /dev/null +++ b/control/index.html @@ -0,0 +1,36 @@ + + + + + Archipelago // Build control + + + +
archipelago_
● PRIVATE / TERRA LAN + TAILSCALE
+
+

/ BUILD CONTROL ROOM

Сборка под контролем.

От исходников до публикации. Каждый этап. Каждая строка.

Подключение…—
+ +
+
01 / PIPELINE—Чтение systemd
+
02 / SCHEDULE—15 и 30 числа · 00:00 UTC
+
03 / PUBLICATION—Только по результату конвейера
+
+
Лимит каждого действия: 4 часа
+
+ +

/ SELECTED RUN

Выберите прогон

—
+

Этапы конвейера

—
+
Все действия, команды и коды завершения
+
+
+

/ COMPLETE LOG EXPLORER

Ничего за кадром.

—
+
+
Выберите лог
+
—
+ +
Логи доступны целиком: навигация от первого байта до последнего и скачивание без ограничения размера.
+
+
+
+
+ diff --git a/control/server.py b/control/server.py new file mode 100644 index 0000000..1a5fa1c --- /dev/null +++ b/control/server.py @@ -0,0 +1,240 @@ +#!/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) +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), + '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() diff --git a/control/style.css b/control/style.css new file mode 100644 index 0000000..ff46e92 --- /dev/null +++ b/control/style.css @@ -0,0 +1 @@ +:root{color-scheme:dark;--bg:#080e12;--panel:#0d161c;--ink:#dce8ed;--muted:#8dabb8;--accent:#35d2d0;--line:#243741;--red:#ff8c87;--yellow:#e7c277;font-family:"SFMono-Regular",Consolas,"Liberation Mono",monospace;font-synthesis:none}*{box-sizing:border-box}body{margin:0;background:radial-gradient(ellipse at 90% 0,#1793d115,transparent 40%),var(--bg);color:var(--ink);font-size:13px;line-height:1.6}header,main,footer{max-width:1512px;margin:auto;padding-inline:40px}header{height:90px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line)}a{color:var(--accent);text-decoration:none}.brand{display:flex;align-items:center;gap:10px;color:var(--ink);font-size:23px;font-weight:700;letter-spacing:-1px}.brand span{color:var(--accent);margin-left:-8px}.private{font-size:10px;color:var(--accent);letter-spacing:1px}.private span{color:var(--muted);margin-left:20px}.heading{display:flex;justify-content:space-between;align-items:center;gap:24px;padding:42px 0 30px}.eyebrow{font-size:10px;color:var(--accent);letter-spacing:1.5px;margin:0 0 12px}h1{font-size:clamp(26px,3.4vw,48px);letter-spacing:-2px;line-height:1.2;margin:0 0 16px}h1 span{color:var(--accent)}h2{font-size:20px;letter-spacing:-.5px;margin:0}h3{font-size:13px;margin:0}.muted,small{color:var(--muted)}.connection{text-align:right;font-size:11px;white-space:nowrap}.connection small{display:block;margin-top:6px}.connection i{display:inline-block;width:7px;height:7px;background:var(--yellow);margin-right:8px}.connection i.online{background:var(--accent);box-shadow:0 0 12px #35d2d044}.overview{display:grid;grid-template-columns:repeat(3,1fr);border:1px solid var(--line);background:var(--panel)}.overview article{padding:23px 26px;min-width:0}.overview article+article{border-left:1px solid var(--line)}.overview strong{font-size:20px;font-weight:500;display:block;margin:10px 0 5px}.overview small{font-size:11px;display:block;overflow-wrap:anywhere}.toolbar{display:flex;justify-content:space-between;align-items:center;gap:18px;padding:22px 0 30px}.controls{display:flex;gap:10px;flex-wrap:wrap}button{font:inherit;font-size:11px;padding:10px 14px;color:var(--ink);background:var(--panel);border:1px solid var(--line);cursor:pointer}button:hover{border-color:var(--accent)}button:disabled{opacity:.4;cursor:default}.primary{color:var(--bg);background:var(--accent);border-color:var(--accent);font-weight:700}.danger{color:var(--red)}button:focus-visible,a:focus-visible,input:focus-visible,summary:focus-visible{outline:2px solid var(--accent);outline-offset:3px}#action-result{color:var(--muted);font-size:11px}.workspace{display:grid;grid-template-columns:275px minmax(0,1fr);gap:24px}.section-title{display:flex;justify-content:space-between;align-items:center;gap:15px;margin-bottom:16px}.section-title>span{font-size:11px;color:var(--muted)}aside{min-width:0}.runs{max-height:480px;overflow:auto}.run-button{display:block;width:100%;text-align:left;border-left:2px solid var(--line);margin-bottom:7px;padding:13px 12px}.run-button.selected{border-color:var(--accent);background:#35d2d00b}.run-button strong{display:block;font-size:12px;font-weight:400}.run-button small{display:block;font-size:10px;margin-top:4px}.run-button .run-status{float:right;font-size:9px}.run-panel{border:1px solid var(--line);padding:25px;background:var(--panel);min-width:0}.run-heading{display:flex;justify-content:space-between;gap:16px;align-items:center;margin-bottom:10px}.badge{padding:4px 9px;border:1px solid var(--line);font-size:10px;color:var(--accent)}#run-meta{font-size:11px;margin-bottom:25px}#run-error,#error{color:var(--red);border:1px solid #ff8c8755;background:#ff8c8709;padding:14px;white-space:pre-wrap;overflow-wrap:anywhere}#error{margin-bottom:20px}.phases{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:9px}.phase{padding:12px;border:1px solid var(--line);color:var(--muted);min-height:69px;font-size:10px}.phase strong{display:block;font-size:11px;font-weight:400;margin-bottom:5px}.phase.active{border-color:var(--accent);color:var(--accent);background:#35d2d00a}.phase.succeeded{color:var(--ink);border-left:2px solid var(--accent)}.phase.failed{color:var(--red);border-color:#ff8c8755}.phase small{font-size:9px}details{margin-top:20px;font-size:11px}summary{cursor:pointer;color:var(--muted)}.sources div{font-size:10px;overflow-wrap:anywhere;margin:6px 0}.sources code{color:var(--accent)}.action{padding:12px 0;border-bottom:1px solid var(--line)}.action pre{font:inherit;white-space:pre-wrap;overflow-wrap:anywhere;color:var(--muted)}.action a{cursor:pointer}.logs-panel{margin:35px 0 45px}.log-layout{display:grid;grid-template-columns:275px minmax(0,1fr);gap:24px}.log-sidebar label{display:block;color:var(--muted);font-size:10px;margin-bottom:7px}input[type=search]{width:100%;font:inherit;font-size:11px;background:var(--panel);border:1px solid var(--line);padding:10px;color:var(--ink)}#log-files{max-height:570px;overflow:auto;margin-top:12px}.log-file{width:100%;display:block;text-align:left;margin-bottom:5px;padding:10px;overflow-wrap:anywhere;font-size:10px}.log-file.selected{border-color:var(--accent);color:var(--accent)}.log-file small{display:block;font-size:9px;margin-top:4px}.terminal{border:1px solid #31505c;background:#070d10;min-width:0;box-shadow:5px 5px 0 #0d161c}.terminal-bar{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:13px 16px;border-bottom:1px solid var(--line);font-size:10px;overflow-wrap:anywhere}.terminal-bar a{white-space:nowrap}.log-controls{display:flex;align-items:center;gap:7px;flex-wrap:wrap;padding:10px 12px;border-bottom:1px solid var(--line)}.log-controls button{padding:5px 8px;font-size:10px}.log-controls label{font-size:10px;display:flex;align-items:center;gap:4px}input[type=checkbox]{accent-color:var(--accent)}#log-range{font-size:9px;color:var(--muted);margin-left:auto}.search-label{display:flex;align-items:center;gap:10px;padding:9px 13px;color:var(--muted);font-size:9px}.search-label input{max-width:280px;padding:5px}#log-content{font:11px/1.65 "SFMono-Regular",Consolas,monospace;margin:0;padding:18px;overflow:auto;height:510px;white-space:pre;tab-size:4;color:#c8dce4}mark{background:#e7c277;color:#080e12}footer{border-top:1px solid var(--line);padding-block:22px;display:flex;justify-content:space-between;font-size:9px;color:var(--muted);gap:20px}[hidden]{display:none!important}@media(max-width:1050px){header,main,footer{padding-inline:24px}.phases{grid-template-columns:repeat(2,minmax(0,1fr))}.workspace,.log-layout{grid-template-columns:220px minmax(0,1fr)}.toolbar{align-items:flex-start;flex-direction:column}}@media(max-width:700px){header,main,footer{padding-inline:16px}.private span{display:none}.brand{font-size:18px}.heading{display:block;padding:28px 0}.connection{text-align:left;margin-top:18px}.overview{grid-template-columns:1fr}.overview article+article{border-left:0;border-top:1px solid var(--line)}.overview article{padding:16px}.workspace,.log-layout{grid-template-columns:1fr}.runs{max-height:180px}.run-panel{padding:16px}#log-files{max-height:180px}.search-label{flex-wrap:wrap}.run-heading{align-items:flex-start;flex-direction:column}footer{flex-direction:column}#log-content{height:430px}} diff --git a/deploy/archipelago-control.service b/deploy/archipelago-control.service new file mode 100644 index 0000000..081cb49 --- /dev/null +++ b/deploy/archipelago-control.service @@ -0,0 +1,20 @@ +[Unit] +Description=Archipelago private build control portal +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +ExecStart=/usr/bin/python3 /opt/archipelago/control-source/control/server.py --config /etc/archipelago/control.json +Restart=on-failure +RestartSec=5 +UMask=0077 +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ProtectHome=true +ReadWritePaths=/opt/archipelago/data/private/pipeline-monitor +RestrictAddressFamilies=AF_INET AF_UNIX + +[Install] +WantedBy=multi-user.target diff --git a/pipeline/monitor.py b/pipeline/monitor.py new file mode 100644 index 0000000..ba2b4e9 --- /dev/null +++ b/pipeline/monitor.py @@ -0,0 +1,87 @@ +"""Durable, untruncated action logs and lifecycle events for the private portal.""" +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import shutil +import subprocess +import time + + +def now(): + return datetime.now(timezone.utc).isoformat() + + +def atomic(path, value): + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_suffix('.tmp') + temp.write_text(json.dumps(value, indent=2) + '\n') + temp.replace(path) + + +def log_files(root): + """Do not traverse package payloads, OSTree objects or build-tool roots.""" + if not root.exists(): + return + prune = {'repo', 'objects', 'tools', 'iso-work', 'profile', 'extractor', 'core-base', + 'purpose-stage', 'composed', 'layer', 'purpose-layer', 'purpose-input', + 'flatpak-seed', 'source', 'target', '.git', 'root.x86_64', 'node_modules'} + for directory, dirs, files in os.walk(root, followlinks=False): + here = Path(directory) + dirs[:] = sorted(d for d in dirs if d not in prune and not (here / d).is_symlink() + and not (d == 'core' and here.name == 'build')) + for name in sorted(files): + path = here / name + if not path.is_symlink() and (path.suffix in ('.log', '.serial', '.jsonl', '.txt') + or name in ('state.json', 'native-acceptance.json', 'summary.json')): + yield path + + +class Monitor: + def __init__(self, base, run): + self.root = base / 'data/private/pipeline-monitor' / run + self.root.mkdir(parents=True, exist_ok=True) + self.phase = 'starting' + self.number = 0 + + def event(self, kind, **data): + with (self.root / 'events.jsonl').open('a') as stream: + stream.write(json.dumps(dict(time=now(), event=kind, **data)) + '\n') + stream.flush() + os.fsync(stream.fileno()) + + def update(self, state): + if state['state'] != self.phase: + self.event('phase', previous=self.phase, phase=state['state'], error=state.get('error')) + self.phase = state['state'] + atomic(self.root / 'state.json', state) + + def call(self, argv, timeout=14400, check=True, capture=False): + self.number += 1 + identity = f'{self.number:04d}' + log = self.root / ('action-' + identity + '.log') + record = dict(id=identity, phase=self.phase, command=[str(x) for x in argv], + started=now(), state='running', timeout_seconds=timeout, log=log.name) + path = self.root / ('action-' + identity + '.json') + atomic(path, record) + self.event('action-start', **record) + start = time.monotonic() + try: + with log.open('ab', buffering=0) as stream: + result = subprocess.run(record['command'], check=check, timeout=timeout, stdout=stream, stderr=subprocess.STDOUT) + record.update(state='succeeded' if result.returncode == 0 else 'failed', returncode=result.returncode) + return log.read_text() if capture else result + except BaseException as error: + record.update(state='failed', returncode=getattr(error, 'returncode', None), error=str(error)) + raise + finally: + record.update(finished=now(), duration_seconds=round(time.monotonic() - start, 3)) + atomic(path, record) + self.event('action-finish', **record) + + def retain_logs(self, roots): + for label, root in roots.items(): + for source in log_files(Path(root)): + destination = self.root / 'retained' / label / source.relative_to(root) + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, destination) diff --git a/pipeline/release-cycle.py b/pipeline/release-cycle.py index 9f576cd..8fd43df 100644 --- a/pipeline/release-cycle.py +++ b/pipeline/release-cycle.py @@ -18,6 +18,7 @@ import signal import subprocess import urllib.request import importlib.util +import monitor cleanup_spec = importlib.util.spec_from_file_location('cleanup_cycle', Path(__file__).with_name('cleanup-cycle.py')) cleanup_module = importlib.util.module_from_spec(cleanup_spec) @@ -40,6 +41,7 @@ def write_status(base, state): parent = base / 'data/private/release-cycle' run = parent / state['run'] atomic(run / 'state.json', state) + monitor.atomic(base / 'data/private/pipeline-monitor' / state['run'] / 'state.json', state) atomic(parent / 'latest.json', state) atomic(base / 'data/public/pipeline.json', state) status_module.export(base) @@ -91,6 +93,7 @@ def main(): stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ') run = parent / stamp run.mkdir() + observer = monitor.Monitor(base, stamp) previous = json.loads((parent / 'latest.json').read_text()) if (parent / 'latest.json').exists() else None source = Path(__file__).resolve().parent shutil.copytree(source, run / 'pipeline', ignore=shutil.ignore_patterns('__pycache__')) @@ -107,9 +110,10 @@ def main(): def phase(name, **extra): state.update(state=name, stage_title=titles.get(name, name), updated=datetime.now(timezone.utc).isoformat(), **extra) write_status(base, state) + observer.update(state) print(json.dumps(state), flush=True) def call(argv, timeout=14400): - subprocess.run([str(x) for x in argv], check=True, timeout=timeout) + observer.call(argv, timeout) def remote(script, timeout=14400): nonlocal step step += 1 @@ -128,6 +132,19 @@ def main(): mounts += ['--mount', f'type=bind,src={config["signing_home"]},dst=/signing'] return ['docker', 'run', '--rm', '--network=none', '--env', 'ARCHIPELAGO_RELEASE_REASON', *mounts, config['coordinator_tools_image'], *map(str, argv)] + def retain_logs(): + roots = {'worker': Path(remote_root), 'archive': run} + for label, cache in (('flatpak-attempt', config.get('flatpak_cache')), + ('kde-flatpak-attempt', config.get('kde_flatpak_cache'))): + attempts = Path(cache) / 'runs' if cache else None + if attempts and attempts.exists(): + for attempt in attempts.iterdir(): + if re.fullmatch(r'[0-9]{8}T[0-9]{6}Z', attempt.name) and attempt.name >= stamp: + roots[label + '/' + attempt.name] = attempt + for label in ('flatpak', 'flatpak_kde'): + if state.get(label, {}).get('log'): + roots[label] = Path(state[label]['log']).parent + observer.retain_logs(roots) def interrupted(signum, frame): raise InterruptedError('Coordinator received signal ' + str(signum)) signal.signal(signal.SIGTERM, interrupted) @@ -213,6 +230,7 @@ python3 {remote_root}/source/src/composer/tests/artifact.py >> {remote_root}/com python3 {remote_root}/source/src/composer/tests/package_db.py >> {remote_root}/composer-filesystem-checks.log 2>&1 python3 {remote_root}/source/src/composer/tests/base.py >> {remote_root}/composer-filesystem-checks.log 2>&1 python3 {remote_root}/source/src/builder/tests/indexed_overlay.py >> {remote_root}/composer-filesystem-checks.log 2>&1 +python3 {remote_root}/source/src/infrastructure/tests/control_portal.py > {remote_root}/control-portal-checks.log 2>&1 sha256sum {remote_root}/archipelago > {remote_root}/inputs.sha256 sha256sum {remote_root}/archipelagod >> {remote_root}/inputs.sha256 sha256sum {remote_root}/source.tar >> {remote_root}/inputs.sha256 @@ -332,9 +350,9 @@ rm -rf {builds['core']}/iso-work {builds['core']}/profile {builds['core']}/extra for name in names: with (archived / name).open('rb') as stream: expected.append(hashlib.file_digest(stream, 'sha256').hexdigest()) - actual = subprocess.check_output(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=20', worker, + actual = observer.call(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=20', worker, 'cd ' + shlex.quote(builds[variant]) + ' && ' + shlex.join(['sha256sum', *names])], - text=True, timeout=300) + capture=True, timeout=300) if [line.split()[0] for line in actual.splitlines()] != expected: raise ValueError('Archived ISO or refs differ from worker: ' + variant) for part in ('repo', 'output', 'evidence'): @@ -425,6 +443,9 @@ rm -rf {builds['core']}/iso-work {builds['core']}/profile {builds['core']}/extra if response.read().decode().split()[0] != item['sha256']: raise ValueError('Public checksum mismatch') phase('cleaning-worker', releases=current) + # Local terra worker logs must survive removal of the build workspace. + # Preserve every nested build/CLI/guest/serial log, not just log tails. + retain_logs() reused = [dict(path=builds[item['variant']], variant=item['variant'], sha256=item['sha256']) for item in current if not Path(builds[item['variant']]).is_relative_to(remote_root) and re.fullmatch(re.escape(config['worker_root'] + '/build/release-cycle/') + @@ -452,8 +473,13 @@ rm -rf {builds['core']}/iso-work {builds['core']}/profile {builds['core']}/extra # Stop this run's VM before archiving diagnostics; never select host VMs # by broad process/name patterns. Preserve artifact bytes and evidence, # not disposable unpacked trees that would fill the worker every day. - subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', worker, - shlex.join(['systemctl', 'stop', vm_unit, kde_vm_unit, *worker_units])], timeout=120) + observer.call(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', worker, + shlex.join(['systemctl', 'stop', vm_unit, kde_vm_unit, *worker_units])], timeout=120, check=False) + retain_logs() + if isinstance(error, (InterruptedError, KeyboardInterrupt)): + # A stop means stop, not another multi-gigabyte artifact transfer. + # Worker artifacts stay in place; logs are already retained. + raise excluded = ['tools', 'iso-work', 'profile', 'extractor', 'core-base', 'purpose-stage', 'composed', 'layer', 'purpose-layer', 'purpose-input', 'flatpak-seed', '*.qcow2', '/core/build/core', '/gnome/build/core', '/kde/build/core'] @@ -466,16 +492,19 @@ rm -rf {builds['core']}/iso-work {builds['core']}/profile {builds['core']}/extra '-cf', '-', '.'] transfer = shlex.join(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=20', worker, shlex.join(archive_command)]) - archived = subprocess.run(['bash', '-o', 'pipefail', '-c', transfer + ' | ' + - shlex.join(['tar', '-C', str(destination), '-xf', '-'])], timeout=1800) + archived = observer.call(['bash', '-o', 'pipefail', '-c', transfer + ' | ' + + shlex.join(['tar', '-C', str(destination), '-xf', '-'])], timeout=1800, check=False) if archived.returncode == 0: remote('rm -rf ' + shlex.quote(remote_root)) raise finally: for unit in (vm_unit, kde_vm_unit): - subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', worker, + observer.call(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', worker, 'if systemctl is-active --quiet ' + shlex.quote(unit) + - '; then systemctl stop ' + shlex.quote(unit) + '; fi'], timeout=120) + '; then systemctl stop ' + shlex.quote(unit) + '; fi'], timeout=120, check=False) + if state.get('invocation_id'): + observer.call(['journalctl', '_SYSTEMD_INVOCATION_ID=' + state['invocation_id'], + '--no-pager', '--output=short-iso-precise'], timeout=60, check=False) if __name__ == '__main__': diff --git a/tests/control_portal.py b/tests/control_portal.py new file mode 100644 index 0000000..8f0e0f2 --- /dev/null +++ b/tests/control_portal.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""HTTP boundary, full log access, and durable action failures; no real systemd changes.""" +import importlib.util +import json +from pathlib import Path +import subprocess +import tempfile +import threading +import unittest +from urllib.error import HTTPError +from urllib.request import Request, urlopen + +spec = importlib.util.spec_from_file_location('control', Path(__file__).parents[1] / 'control/server.py') +control = importlib.util.module_from_spec(spec) +spec.loader.exec_module(control) + + +class Portal(unittest.TestCase): + def test_http_boundaries_and_complete_logs(self): + with tempfile.TemporaryDirectory() as directory: + base = Path(directory) + config = dict(coordinator_root=directory, worker_root=str(base / 'worker'), + worker_source_root=str(base / 'source'), allowed_networks=['127.0.0.0/8'], hosts=[]) + app = control.App(config) + identity = '20261109T000000Z' + root = app.history / identity + root.mkdir(parents=True) + (root / 'state.json').write_text(json.dumps(dict(run=identity, state='failed'))) + payload = b'first-line\n' + b'full output\n' * 40000 + b'last-line\n' + (root / 'large.log').write_bytes(payload) + (root / 'escape.log').symlink_to('/etc/passwd') + app.unit = lambda name: {'ActiveState': 'inactive'} + called = [] + app.control = lambda action: called.append(action) or {'accepted': True} + server = control.ThreadingHTTPServer(('127.0.0.1', 0), control.Handler) + server.app = app + host = f'127.0.0.1:{server.server_port}' + config['hosts'] = [host] + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + url = 'http://' + host + try: + with urlopen(url + '/api/run?run=' + identity) as response: + logs = json.load(response)['logs'] + self.assertNotIn('monitor/escape.log', [l['id'] for l in logs]) + address = url + '/api/log?run=' + identity + '&id=monitor/large.log' + reconstructed = b'' + while len(reconstructed) < len(payload): + with urlopen(address + '&offset=' + str(len(reconstructed))) as response: + page = json.load(response) + reconstructed += page['text'].encode() + self.assertEqual(reconstructed, payload) + with urlopen(address + '&download=1') as response: + self.assertEqual(response.read(), payload) + for bad in ('/api/run?run=../', '/api/log?run='+identity+'&id=monitor/../../etc/passwd'): + with self.assertRaises(HTTPError): + urlopen(url + bad) + headers = {'Content-Type': 'application/json', 'X-Archipelago-Control': '1'} + with self.assertRaises(HTTPError) as error: + urlopen(Request(url+'/api/control', data=b'{"action":"start"}', headers=headers)) + self.assertEqual(error.exception.code, 403) + headers['Origin'] = url + with urlopen(Request(url+'/api/control', data=b'{"action":"start"}', headers=headers)) as response: + self.assertEqual(response.status, 202) + self.assertEqual(called, ['start']) + with self.assertRaises(HTTPError): + urlopen(Request(url+'/', headers={'Host':'attacker.example'})) + finally: + server.shutdown() + server.server_close() + + def test_failed_action_is_durable(self): + with tempfile.TemporaryDirectory() as directory: + observer = control.monitor.Monitor(Path(directory), '20261109T000000Z') + with self.assertRaises(subprocess.CalledProcessError): + observer.call(['python3', '-c', 'import sys; print("diagnostic"); sys.exit(7)']) + action = json.loads((observer.root / 'action-0001.json').read_text()) + self.assertEqual(action['returncode'], 7) + self.assertEqual(action['state'], 'failed') + self.assertIn('diagnostic', (observer.root / action['log']).read_text()) + + +if __name__ == '__main__': + unittest.main()