infrastructure/control/app.js

146 lines
14 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const $ = id => document.getElementById(id);
// Actual driver phases. The optional marker limits a phase to that build mode so
// removed acceptance stages and disabled steps never appear in the UI.
const phases = [
['preflight','Подготовка окружения'],
['selecting-repository','Выбор репозитория'],
['freezing-and-compiling-source','Исходники, тесты, CLI'],
['updating-flatpak-cache','Кэш Flatpak · GNOME','iso'],
['updating-kde-flatpak-cache','Кэш Flatpak · KDE','iso'],
['building-software-adapter','Адаптер GNOME Software'],
['building-discover-adapter','Адаптер Discover'],
['building-core','Core'],
['building-gnome-purpose','GNOME'],
['building-kde-purpose','KDE'],
['building-container-runner','Container Runner'],
['archiving-artifacts','Архив артефактов'],
['preparing-publication','Проверка доказательств'],
['signing-and-publishing','Подпись и публикация'],
['verifying-public-endpoints','Проверка HTTPS'],
['publishing-container-runner','Публикация Container Runner'],
['cleaning-worker','Очистка worker']
];
let run = '', log = '', offset = 0, next = 0, size = 0, text = '', data = null, status = null, busy = false, logBusy = false;
let logsKey = '', runsKey = '', snapshotsKey = '';
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, parameters) {
document.querySelectorAll('.controls button').forEach(b=>b.disabled=true);
try {
const result=await api('/api/control',{method:'POST',headers:{'Content-Type':'application/json','X-Archipelago-Control':'1'},body:JSON.stringify(Object.assign({action},parameters||{}))});
if(action==='start'){
const req=result.request||{};
$('action-result').textContent=req.resume
? `Принято: продолжение прогона ${status?.runs?.[0]?.run||''} · снимок и режим прежние`
: `Принято: ${req.mode==='ostree'?'только OSTree':'ISO + OSTree'} · снимок ${req.snapshot}`;
run='';runsKey='';
} else {
$('action-result').textContent=({stop:'Остановка передана systemd','schedule-on':'Расписание включено','schedule-off':'Расписание отключено'})[action]||'Принято';
}
}
catch(e){showError(e);}finally{refresh();}
}
$('start').onclick=()=>control('start',{mode:$('build-mode').value,snapshot:$('build-snapshot').value});$('stop').onclick=()=>control('stop');
// A failed run continues under the same service unit: it keeps its own mode and
// immutable snapshot, so the stop button and the status always describe it.
$('resume').onclick=()=>control('start',{resume:true});
$('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'?'ISO+OSTree · 1-е число':'Приостановлено';
$('next').textContent='Следующий: '+(s.timer.ActiveState==='active' && s.next_release ? `${s.next_release.date} · ${s.next_release.mode} · ${s.next_release.time}` : '—');
$('start').disabled=active||stopping;$('stop').disabled=!active;$('toggle-schedule').disabled=false;
// Continue only a failed run; a complete one is a finished publication.
const latest=s.runs?.[0];
$('resume').disabled=active||stopping||!latest||latest.state!=='failed';
$('resume').textContent=latest&&latest.state==='failed'?`↻ Продолжить ${latest.run}`:'↻ Продолжить';
$('build-mode').disabled=active||stopping;$('build-snapshot').disabled=active||stopping;
const snapshots=s.snapshots||[];
$('snapshot').textContent=snapshots.length?snapshots[0].date:'Нет снимков';
$('snapshot-detail').textContent=snapshots.length?`Доступно: ${snapshots.length} · хранится не более трёх`:'Выберите «Новый снимок сейчас»';
const snapshotKey=snapshots.map(item=>item.date).join(',');
if(snapshotKey!==snapshotsKey){
snapshotsKey=snapshotKey;const select=$('build-snapshot');const current=select.value;
select.replaceChildren();const latest=node('option','','Последний снимок');latest.value='latest';select.append(latest);
const fresh=node('option','','Новый снимок сейчас');fresh.value='new';select.append(fresh);
for(const item of snapshots){const option=node('option','',item.date);option.value=item.date;select.append(option);}
select.value=[...select.options].some(item=>item.value===current)?current:'latest';
}
$('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 phasePlan(s, d, terminal) {
const byMode = phases.filter(([id,, mode]) => !mode || s.output_mode === mode);
if (d.instrumented && terminal) {
// A finished instrumented run shows only the phases it actually executed.
return byMode.filter(([id]) => d.events.some(e => e.phase === id));
}
if (d.instrumented) return byMode;
// Without a phase trace the plan may not claim stages that never ran: cut it
// after the stage the state names, or after the one that failed.
const reached = byMode.findIndex(([id]) => id === (s.failed_phase || s.state));
return reached < 0 ? byMode : byMode.slice(0, reached + 1);
}
function progressOf(s, d, plan) {
const total = plan.length;
if (!total) return {done: 0, total: 0, percent: 0};
if (s.state === 'complete') return {done: total, total, percent: 100};
let done = 0;
if (d.instrumented) {
// A phase counts once a later phase started; the current one is still running.
done = plan.filter(([id]) => {
const event = d.events.find(e => e.phase === id);
return event && d.events.some(e => e.time > event.time);
}).length;
} else {
done = Math.max(0, plan.findIndex(([id]) => id === (s.failed_phase || s.state)));
}
return {done, total, percent: Math.min(99, Math.round(done / total * 100))};
}
function drawRun(d) {
data=d;const s=d.state;const terminal=['failed','complete'].includes(s.state);const plan=phasePlan(s,d,terminal);
$('run-name').textContent=s.run;$('run-state').textContent=label(s.state);
$('run-state').className='badge'+(s.state==='failed'?' error':'');
$('run-meta').textContent=`${date(s.started)} · ${elapsed(s.started,terminal?(s.finished||s.updated):null)} · ${s.worker} · ${s.channel} · ${s.output_mode||'—'} · снимок ${s.snapshot||(s.snapshot_url||'').split('/arch-repo-snapshot/')[1]?.split('/')[0]||'—'}`;
$('run-error').hidden=!s.error;$('run-error').textContent=s.error_details||s.error||'';
const p=progressOf(s,d,plan);const track=$('run-progress-track');
track.setAttribute('aria-valuenow',String(p.percent));
track.className='progress-track'+(s.state==='failed'?' failed':s.state==='complete'?' complete':'');
$('run-progress').style.width=p.percent+'%';
$('run-progress-text').textContent=s.state==='complete'
? (d.instrumented?`Готово · ${p.total} этапов · ${elapsed(s.started,s.finished||s.updated)}`:'Завершён · подробная трассировка не записывалась')
: s.state==='failed'
? `Остановлено после ${p.done} из ${p.total} этапов · ${p.percent}%`
: `${p.done} из ${p.total} этапов · ${p.percent}% · идёт ${elapsed(s.started)}`;
$('phase-summary').textContent=d.instrumented?'Фактические переходы и время':'Исторический прогон · подробная трассировка не записывалась';
$('phases').replaceChildren();
for(const [id,title] of plan){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);