Add private build control portal and durable full pipeline logs
This commit is contained in:
parent
b0199c76f1
commit
de2c8187f0
10 changed files with 624 additions and 9 deletions
|
|
@ -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
|
||||
|
|
|
|||
43
control/README.md
Normal file
43
control/README.md
Normal file
|
|
@ -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.
|
||||
66
control/app.js
Normal file
66
control/app.js
Normal file
|
|
@ -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);
|
||||
36
control/index.html
Normal file
36
control/index.html
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="theme-color" content="#080e12"><title>Archipelago // Build control</title>
|
||||
<link rel="icon" href="/mark.svg"><link rel="stylesheet" href="/style.css"><script src="/app.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<header><a class="brand" href="/"><img src="/mark.svg" width="30" height="30" alt="">archipelago<span>_</span></a><div class="private">● PRIVATE / TERRA <span>LAN + TAILSCALE</span></div></header>
|
||||
<main>
|
||||
<section class="heading"><div><p class="eyebrow">/ BUILD CONTROL ROOM</p><h1>Сборка под <span>контролем.</span></h1><p class="muted">От исходников до публикации. Каждый этап. Каждая строка.</p></div><div class="connection"><i id="connection-dot"></i><span id="connection">Подключение…</span><small id="updated">—</small></div></section>
|
||||
<div id="error" role="alert" hidden></div>
|
||||
<section class="overview">
|
||||
<article><span class="eyebrow">01 / PIPELINE</span><strong id="service">—</strong><small id="service-detail">Чтение systemd</small></article>
|
||||
<article><span class="eyebrow">02 / SCHEDULE</span><strong id="schedule">—</strong><small id="next">15 и 30 числа · 00:00 UTC</small></article>
|
||||
<article><span class="eyebrow">03 / PUBLICATION</span><strong id="published">—</strong><small id="published-detail">Только по результату конвейера</small></article>
|
||||
</section>
|
||||
<section class="toolbar"><div class="controls"><button id="start" class="primary" disabled>▶ Запустить сборку</button><button id="stop" class="danger" disabled>■ Остановить</button><button id="toggle-schedule" disabled>Расписание</button></div><span id="action-result" role="status">Лимит каждого действия: 4 часа</span></section>
|
||||
<div class="workspace">
|
||||
<aside><div class="section-title"><h2>Прогоны</h2><span id="run-count">0</span></div><div id="runs" class="runs"></div><details class="sources"><summary>Закреплённые исходники</summary><div id="sources"></div></details></aside>
|
||||
<section class="run-panel"><div class="run-heading"><div><p class="eyebrow">/ SELECTED RUN</p><h2 id="run-name">Выберите прогон</h2></div><span id="run-state" class="badge">—</span></div><div id="run-meta" class="muted"></div><p id="run-error" hidden></p>
|
||||
<div class="section-title"><h3>Этапы конвейера</h3><small id="phase-summary">—</small></div><div id="phases" class="phases"></div>
|
||||
<details id="action-details"><summary>Все действия, команды и коды завершения <span id="action-count"></span></summary><div id="actions"></div></details>
|
||||
</section>
|
||||
</div>
|
||||
<section class="logs-panel"><div class="section-title"><div><p class="eyebrow">/ COMPLETE LOG EXPLORER</p><h2>Ничего за кадром.</h2></div><span id="log-count" class="muted">—</span></div>
|
||||
<div class="log-layout"><div class="log-sidebar"><label for="log-filter">Найти файл лога</label><input id="log-filter" type="search" placeholder="build, guest, serial, action…"><div id="log-files"></div></div>
|
||||
<div class="terminal"><div class="terminal-bar"><span id="log-name">Выберите лог</span><a id="download" hidden>↓ Полный файл</a></div>
|
||||
<div class="log-controls"><button id="log-first">В начало</button><button id="log-prev">← Раньше</button><button id="log-next">Дальше →</button><button id="log-tail">В конец</button><label><input id="follow" type="checkbox" checked> Следить</label><span id="log-range">—</span></div>
|
||||
<label class="search-label" for="log-search">Поиск в открытом фрагменте <input id="log-search" type="search" placeholder="ошибка, warning, пакет…"><span id="matches"></span></label>
|
||||
<pre id="log-content" tabindex="0">Логи доступны целиком: навигация от первого байта до последнего и скачивание без ограничения размера.</pre>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main><footer><span>ARCHIPELAGO / PRIVATE OPERATIONS</span><span>Обновление каждые 3 секунды · время в вашем часовом поясе</span></footer>
|
||||
</body></html>
|
||||
240
control/server.py
Normal file
240
control/server.py
Normal file
|
|
@ -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()
|
||||
1
control/style.css
Normal file
1
control/style.css
Normal file
File diff suppressed because one or more lines are too long
20
deploy/archipelago-control.service
Normal file
20
deploy/archipelago-control.service
Normal file
|
|
@ -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
|
||||
87
pipeline/monitor.py
Normal file
87
pipeline/monitor.py
Normal file
|
|
@ -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)
|
||||
|
|
@ -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__':
|
||||
|
|
|
|||
84
tests/control_portal.py
Normal file
84
tests/control_portal.py
Normal file
|
|
@ -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()
|
||||
Loading…
Add table
Reference in a new issue