infrastructure/control/app.js

66 lines
9.9 KiB
JavaScript
Raw 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);
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'?'OSTree: 3 дня · ISO: 30-го':'Приостановлено';
$('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;
$('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);