Files
app-autotest/site/static/app.js
T

439 lines
23 KiB
JavaScript

// window.APP — переменные из Jinja2 (заполняются в index.html)
// window.APP = { version, stand, hasUserToken };
/*
* === АРХИТЕКТУРА ФРОНТЕНДА ===
*
* Один HTML-файл, ванильный JS (без фреймворков).
* Три колонки: инфраструктура | сервисы | инстансы+операции+параметры.
*
* Глобальное состояние:
* svcInstances — кеш списка инстансов из /api/operations/{svcId}
* selectedInst — UID выбранного инстанса (null если не выбран)
* selectedOp — {opId, opName, svcId} выбранная операция
* pollTimer — setInterval таймер поллинга статуса операции
* currentSvcId — ID текущего выбранного сервиса (по умолчанию 1 = Болванка)
* AUTOTEST_PREFIX — префикс имён autotest-инстансов
*
* Потоки:
* CREATE: startCreate() → showParams(18,'create') → executeOp(pp) → poll → refresh
* MODIFY: toggleInstance() → runOp('modify',id) → showParams(id,'modify') → validate → executeOp
* БЕЗ ПАРАМЕТРОВ (delete/suspend/resume/redeploy): runOp() → confirm → executeOp({})
*
* Хелперы:
* _esc(s) — HTML-экранирование (" → &quot; & → &amp; < → &lt;)
* validateJson() — проверка JSON.parse для map-полей (onblur + перед отправкой)
* showStages() — отрисовка этапов выполнения операции (⏳/✅/❌)
*/
let svcInstances=[], selectedInst=null, selectedOp=null, pollTimer=null;
let currentSvcId=1; // динамический — обновляется при selectService()
let currentSvcName=''; // имя текущего сервиса (колонка «тип инстанса»)
const AUTOTEST_PREFIX='autotest-';
// Первый сервис из списка (рендерится Jinja2)
selectService(currentSvcId);
async function selectService(svcId){
currentSvcId=svcId;
selectedInst=null; selectedOp=null; stopPoll();
document.getElementById('params-area').style.display='none';
document.querySelectorAll('.stages-box').forEach(e=>e.remove());
// Подсветить активный сервис в боковой панели
document.querySelectorAll('.svc-item').forEach(e=>e.classList.remove('active'));
const svcEl=document.querySelector(`.svc-item[onclick*="${svcId}"]`);
if(svcEl) svcEl.classList.add('active');
const r=await fetch('/api/operations/'+svcId);
const d=await r.json();
svcInstances=d.instances||[];
currentSvcName=d.svc||'';
let currentSvcShort=d.svcShort||'';
// Обновить текст кнопки создания
const btnSpan=document.querySelector('#create-btn-area span');
if(btnSpan) btnSpan.textContent='+ Создать новый инстанс '+(currentSvcName||'сервиса');
let html='';
svcInstances.forEach(i=>{
const status=i.status||i.explainedStatus||'?';
const sc=status==='running'?'badge-success':'';
html+=`<div class="inst-item" onclick="toggleInstance('${i.instanceUid}')" data-iuid="${i.instanceUid}">
<span style="display:inline-block;width:220px;">${_esc(i.displayName)}</span>
<span style="display:inline-block;width:160px;color:var(--muted);font-size:11px;">${_esc(i.svc||'')}</span>
<span class="badge ${sc}" style="font-size:9px;">${_esc(status)}</span>
</div>`;
html+=`<div class="inst-ops" id="ops-${i.instanceUid}"></div>`;
});
document.getElementById('inst-list').innerHTML=html;
}
async function toggleInstance(iuid){
selectedInst=iuid; stopPoll();
document.querySelectorAll('[data-iuid]').forEach(e=>e.classList.toggle('active',e.dataset.iuid===iuid));
document.getElementById('params-area').style.display='none';
const opsEl=document.getElementById('ops-'+iuid);
if(opsEl.classList.contains('open')){opsEl.classList.remove('open');return;}
document.querySelectorAll('.inst-ops').forEach(e=>e.classList.remove('open'));
const r=await fetch('/api/operations/'+currentSvcId);
const d=await r.json();
const ops=d.operations.filter(o=>o.operation!=='reconcile'&&o.operation!=='create');
opsEl.innerHTML=ops.map(o=>
`<button class="btn btn-sm op-btn ${opClass(o.operation)}" onclick="runOp('${o.operation}',${o.svcOperationId})">${o.operation}</button>`
).join('');
opsEl.classList.add('open');
}
function opClass(opName){
if(opName==='modify') return 'op-btn-modify';
if(opName==='suspend') return 'op-btn-suspend';
if(opName==='resume') return 'op-btn-resume';
if(opName==='delete') return 'op-btn-delete';
if(opName==='redeploy') return 'op-btn-redeploy';
if(opName==='reconcile') return 'op-btn-reconcile';
return '';
}
async function startCreate(){
selectedInst=null; stopPoll();
document.querySelectorAll('[data-iuid]').forEach(e=>e.classList.remove('active'));
document.querySelectorAll('.inst-ops').forEach(e=>e.classList.remove('open'));
// Найти svcOperationId для create у текущего сервиса
try{
const r=await fetch('/api/operations/'+currentSvcId);
const d=await r.json();
const createOp=d.operations.find(o=>o.operation==='create');
const opId=createOp?createOp.svcOperationId:18; // fallback — Болванка
showParams(opId,'create');
}catch(e){
showParams(18,'create'); // fallback
}
}
function makeCreateDisplayName(){
const rand = (Math.random() * 46656 | 0).toString(36).padStart(3, '0');
return currentSvcShort ? currentSvcShort+'-'+rand : rand;
}
function runOp(opName,opId){
stopPoll();
selectedOp={opId,opName,svcId:currentSvcId};
if(opName==='modify'){
showParams(opId,opName);
}else{
// confirm and execute immediately
if(!confirm(`Запустить ${opName} для ${findInstName()}?`)) return;
executeOp({});
}
}
function findInstName(){
const i=svcInstances.find(x=>x.instanceUid===selectedInst);
return i?i.displayName:selectedInst;
}
function showParams(opId,opName){
selectedOp={opId,opName,svcId:currentSvcId};
document.getElementById('params-area').style.display='block';
document.querySelectorAll('.stages-box').forEach(e=>e.remove());
document.getElementById('test-status').textContent='';
const isCreate=opName==='create';
const qs=isCreate?'' : `?instanceUid=${selectedInst}`;
fetch('/api/params/'+opId+qs).then(r=>r.json()).then(async data=>{
if(data.error){document.getElementById('params-form').innerHTML=`<span style="color:var(--destructive);">Ошибка: ${_esc(data.error)}</span>`;return;}
const params=data.params||data;
if(!Array.isArray(params)){document.getElementById('params-form').innerHTML=`<span style="color:var(--destructive);">Неверный формат параметров</span>`;return;}
// Заранее загрузить все инстансы для refSvcId-параметров
let allInst=[];
const needRefs=params.some(p=>p.refSvcId);
if(needRefs){
try{
const r=await fetch('/api/instances/list');
const list=await r.json();
allInst=list||[];
}catch(e){}
}
const form=document.getElementById('params-form');
const displayNameValue=isCreate?makeCreateDisplayName():'';
const createHeader=isCreate?`<div style="font-weight:600;font-size:13px;margin-bottom:8px;color:var(--brand-primary);">Создание: ${currentSvcName}</div>`:'';
form.innerHTML=createHeader+(opName==='create'?`<div class="param-row"><label class="req">displayName</label><span style="font-size:12px;color:var(--muted);white-space:nowrap;">${AUTOTEST_PREFIX}</span><input type="text" id="param-displayname" value="${_esc(displayNameValue)}" autocomplete="off"></div>`:'')
+ params.map(p=>{
const req=p.isRequired;
const hasDfl=p.defaultValue!==null&&p.defaultValue!==undefined&&p.defaultValue!=='';
const labelCls=req?(hasDfl?'req':'req-nodfl'):'';
const dfl=hasDfl?p.defaultValue:(req?'':'');
const vl=p.valueList;
const isMap=(p.dataType||'').startsWith('map');
let input;
if(vl&&Array.isArray(vl)){
input=`<select name="p_${p.svcOperationCfsParamId}" data-type="${_esc(p.dataType)}">${vl.map(v=>`<option value="${_esc(v)}" ${v==dfl?'selected':''}>${_esc(v)}</option>`).join('')}</select>`;
}else if(p.refSvcId){
// Параметр ссылается на другой сервис — выпадающий список инстансов
const refInsts=allInst.filter(i=>i.serviceId===p.refSvcId&&i.explainedStatus!=='deleted');
let opts=refInsts.map(i=>`<option value="${_esc(i.instanceUid)}" ${i.instanceUid===dfl?'selected':''}>${_esc(i.displayName)}</option>`).join('');
if(!dfl) opts='<option value="">— выбрать —</option>'+opts;
input=`<select name="p_${p.svcOperationCfsParamId}" data-type="ref">${opts}</select>`;
}else if(p.dataType==='boolean'){
input=`<select name="p_${p.svcOperationCfsParamId}" data-type="boolean"><option value="true" ${dfl==='true'||dfl===true?'selected':''}>true</option><option value="false" ${dfl==='false'||dfl===false?'selected':''}>false</option></select>`;
}else if(p.dataDescriptor&&isMap){
// Раскрыть dataDescriptor — вложенные поля вместо JSON-строки
const dd=p.dataDescriptor;
let subHtml='';
let dflObj={};
try{dflObj=JSON.parse(dfl||'{}');}catch(e){}
Object.keys(dd).forEach(subKey=>{
const sub=dd[subKey];
const subDfl=dflObj[subKey]!==undefined?dflObj[subKey]:(sub.defaultValue||'');
const subVl=sub.valueList;
const subReq=sub.isRequired;
const subNoDfl=subReq&&!subDfl&&subDfl!==0&&subDfl!==false;
const subLblCls=subNoDfl?'req-nodfl':'';
let si;
if(subVl&&Array.isArray(subVl)){
si=`<select name="p_${p.svcOperationCfsParamId}.${subKey}" data-type="mapchild">${subVl.map(v=>`<option value="${_esc(v)}" ${v==subDfl?'selected':''}>${_esc(v)}</option>`).join('')}</select>`;
}else if(sub.dataType==='boolean'){
si=`<select name="p_${p.svcOperationCfsParamId}.${subKey}" data-type="mapchild"><option value="true" ${subDfl==='true'||subDfl===true?'selected':''}>true</option><option value="false" ${subDfl==='false'||subDfl===false?'selected':''}>false</option></select>`;
}else{
si=`<input type="text" name="p_${p.svcOperationCfsParamId}.${subKey}" value="${_esc(subDfl)}" data-type="mapchild">`;
}
subHtml+=`<div class="param-row"><label class="${subLblCls}">${_esc(subKey)}</label>${si}</div>`;
});
input=`<div style="border-left:2px solid var(--brand-gray);margin-left:8px;padding:0 0 4px 8px;">${subHtml}</div>`;
return `<div class="param-row"><label class="${labelCls}">${_esc(p.name)}</label></div>${input}`;
}else{
const dt=isMap?'map':'';
input=`<input type="text" name="p_${p.svcOperationCfsParamId}" value="${_esc(dfl)}" data-type="${dt}" placeholder="${req&&!hasDfl?'обязательно':''}"${isMap?' onblur="validateJson(this)"':''}>`;
if(isMap) input+=`<span class="json-err" style="display:none;color:var(--destructive);font-size:10px;margin-left:4px;"></span>`;
}
return `<div class="param-row"><label class="${labelCls}">${_esc(p.name)}</label>${input}</div>`;
}).join('');
const btn=document.getElementById('btn-test');
btn.style.display='inline-flex';
btn.textContent='Запустить';
btn.onclick=()=>{
// Проверить ВСЕ map-поля перед отправкой
let bad=[];
document.querySelectorAll('#params-form [data-type="map"]').forEach(el=>{
if(!validateJson(el,true)) bad.push(el);
});
if(bad.length>0){
document.getElementById('test-status').innerHTML=`<span class="badge">Ошибка</span> ${bad.length} полей с невалидным JSON — поправьте и нажмите Запустить снова`;
return;
}
const pp={};
const nested={}; // {parentKey: {subKey: value, ...}}
document.querySelectorAll('#params-form [name^="p_"]').forEach(el=>{
let v=el.value;
const dt=el.dataset.type||'';
if(dt==='mapchild'){
const name=el.name.replace('p_','');
const dot=name.indexOf('.');
const parentKey=name.substring(0,dot);
const subKey=name.substring(dot+1);
if(!nested[parentKey]) nested[parentKey]={};
nested[parentKey][subKey]=v;
return;
}
if(dt==='array'||dt.startsWith('array')) v=JSON.stringify([v]);
if(dt==='map'||dt==='map-fixed') v=v||'{}';
pp[el.name.replace('p_','')]=v;
});
// Сериализовать вложенные объекты в JSON строки
for(const pk in nested) pp[pk]=JSON.stringify(nested[pk]);
executeOp(pp);
};
}).catch(e=>{
document.getElementById('params-form').innerHTML=`<span style="color:var(--destructive);">Ошибка загрузки: ${_esc(e.message)}</span>`;
});
}
// === Хелперы ===
function _esc(s){
/* HTML-экранирование: " → &quot; & → &amp; < → &lt; */
return String(s||'').replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;');
}
function validateJson(el,quiet){
/* Проверить что значение в поле — валидный JSON.
quiet=true — не менять внешний вид (для batch-проверки перед отправкой). */
const errEl=el.parentElement.querySelector('.json-err');
const v=el.value.trim();
if(!v) return true; // пусто — ок
try{ JSON.parse(v); }
catch(e){
if(!quiet&&errEl){ errEl.style.display='inline'; errEl.textContent='Ошибка JSON: '+e.message; }
el.style.borderColor='var(--destructive)';
return false;
}
if(!quiet&&errEl) errEl.style.display='none';
el.style.borderColor='';
return true;
}
function setFinishedState(statusText, statusClass, statusError, statusDuration, instanceName){
const btn=document.getElementById('btn-test');
btn.disabled=false;
btn.textContent='Готово';
btn.onclick=null;
const opName=selectedOp?.opName||'операция';
const durationText=statusDuration!==undefined&&statusDuration!==null?`${statusDuration}s`:'0s';
const extra=statusError||'';
const instName=instanceName||findInstName()||selectedInst||'';
document.getElementById('test-status').innerHTML=` <span class="badge ${statusClass}">${statusText}</span> <span style="color:var(--muted);">${opName}</span> <span style="color:var(--muted);">${durationText}</span> <span style="color:var(--muted);">${instName}</span> ${extra}`;
}
function setRunningState(opName, displayName){
const btn=document.getElementById('btn-test');
const title=displayName || opName;
btn.textContent=opName+'...';
document.getElementById('test-status').textContent=' ⏳ '+title+' выполняется...';
}
async function executeOp(params){
stopPoll();
const isCreate=selectedOp?.opName==='create';
const displayNameInput=document.getElementById('param-displayname');
const displayNameSuffix=(displayNameInput?.value||'').trim();
const displayName=isCreate ? `${AUTOTEST_PREFIX}${displayNameSuffix || makeCreateDisplayName()}` : findInstName();
document.getElementById('params-area').style.display='block';
document.getElementById('params-form').innerHTML='';
const btn=document.getElementById('btn-test');
btn.style.display='inline-flex';
btn.textContent=selectedOp.opName+'...';
btn.disabled=true;
setRunningState(selectedOp.opName, displayName);
// Создать динамический stages-box после инстанса
const instId=selectedInst||'';
const afterEl=instId?document.getElementById('ops-'+instId):null;
document.querySelectorAll('.stages-box').forEach(e=>e.remove());
const stagesBox=document.createElement('div');
stagesBox.className='stages-box';
stagesBox.style.cssText='max-height:200px;overflow-y:auto;padding:4px 8px;margin-left:16px;background:var(--brand-grey-light);border-radius:4px;';
if(afterEl){afterEl.after(stagesBox);}
else{document.getElementById('create-btn-area').after(stagesBox);}
try{
const r=await fetch('/api/test',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({
serviceId:currentSvcId,
operation:selectedOp.opName,
svcOperationId:selectedOp.opId,
params,
instanceUid:selectedInst||'',
displayName:isCreate ? displayName : ''
})});
const d=await r.json();
if(d.status==='FAIL'){document.getElementById('test-status').innerHTML=` <span class="badge">FAIL</span> ${d.error||''}`;btn.disabled=false;return;}
// start polling
const opUid=d.opUid;
const instanceName=d.displayName||displayName||findInstName();
pollTimer=setInterval(async()=>{
const sr=await fetch('/api/test/status/'+opUid);
const sd=await sr.json();
showStages(sd.stages||[]);
if(sd.status!=='RUNNING'){
stopPoll();
setFinishedState(sd.status, sd.status==='OK'?'badge-success':'badge', sd.error||sd.errorLog, sd.duration, sd.displayName||instanceName);
if(sd.status==='OK'){
await refreshInstances();
}
if(historyOpen) await loadHistory();
}
},2000);
}catch(e){
document.getElementById('test-status').textContent=' Ошибка: '+e.message;
btn.disabled=false;
}
}
function showStages(stages){
if(!stages||!stages.length) return;
let html='<div style="font-size:11px;font-weight:600;color:var(--muted);margin-top:4px;">Этапы</div>';
stages.forEach(s=>{
const done=!!s.dtFinish;
const icon=done?(s.isSuccessful?'✅':'❌'):'⏳';
html+=`<div style="font-size:11px;padding:2px 0;">${icon} ${_esc(s.stage)}${(s.duration||0).toFixed(1)}s</div>`;
});
const boxes=document.querySelectorAll('.stages-box');
if(boxes.length) boxes[boxes.length-1].innerHTML=html;
}
function stopPoll(){
if(pollTimer){clearInterval(pollTimer);pollTimer=null;}
}
async function refreshInstances(){
const r=await fetch('/api/operations/'+currentSvcId);
const d=await r.json();
const newInsts=d.instances||[];
svcInstances=newInsts;
let html='';
svcInstances.forEach(i=>{
const status=i.status||i.explainedStatus||'?';
const sc=status==='running'?'badge-success':'';
html+=`<div class="inst-item" onclick="toggleInstance('${i.instanceUid}')" data-iuid="${i.instanceUid}">
<span style="display:inline-block;width:220px;">${_esc(i.displayName)}</span>
<span style="display:inline-block;width:160px;color:var(--muted);font-size:11px;">${_esc(i.svc||'')}</span>
<span class="badge ${sc}" style="font-size:9px;">${_esc(status)}</span>
</div>`;
html+=`<div class="inst-ops" id="ops-${i.instanceUid}"></div>`;
});
document.getElementById('inst-list').innerHTML=html;
}
// === История тестов ===
let historyOpen=false;
async function toggleHistory(){
const body=document.getElementById('history-body');
historyOpen=!historyOpen;
body.style.display=historyOpen?'block':'none';
if(historyOpen) await loadHistory();
}
async function loadHistory(){
const body=document.getElementById('history-body');
if(!body||body.style.display==='none') return;
try{
const r=await fetch('/api/history');
const rows=await r.json();
if(!rows||!rows.length){body.innerHTML='<span style="color:var(--muted);font-size:11px;">Нет записей</span>'; return;}
let html='<table style="width:100%;font-size:11px;">';
html+='<tr><th style="padding:2px 6px;">Время</th><th style="padding:2px 6px;">Операция</th><th style="padding:2px 6px;">Инстанс</th><th style="padding:2px 6px;">Статус</th><th style="padding:2px 6px;">Длит.</th></tr>';
rows.forEach(r=>{
const time=r.created_at?r.created_at.replace('T',' ').substring(0,19):'?';
const cls=r.status==='OK'?'badge-success':'';
html+=`<tr>
<td style="padding:2px 6px;">${time}</td>
<td style="padding:2px 6px;">${_esc(r.op_name||'?')}</td>
<td style="padding:2px 6px;">${_esc(r.display_name||r.instance_uid||'?')}</td>
<td style="padding:2px 6px;"><span class="badge ${cls}" style="font-size:9px;">${_esc(r.status||'?')}</span></td>
<td style="padding:2px 6px;">${r.duration_sec!=null?r.duration_sec.toFixed(1)+'s':'-'}</td>
</tr>`;
});
html+='</table>';
body.innerHTML=html;
}catch(e){body.innerHTML='<span style="color:var(--destructive);font-size:11px;">Ошибка загрузки</span>';}
}
// === Панель логов (скрыта, показывается по кнопке) ===
let logPollTimer=null;
function startLogPoll(){
if(logPollTimer) return;
logPollTimer=setInterval(async()=>{
const el=document.getElementById('log-panel');
if(!el||el.style.display==='none') return; // не дёргать если скрыта
try{
const r=await fetch('/api/log');
const lines=await r.json();
el.innerHTML=lines.map(l=>`<div>${l}</div>`).join('');
el.scrollTop=el.scrollHeight;
}catch(e){}
},2000);
}
function toggleLog(){
const el=document.getElementById('log-panel');
if(!el) return;
if(el.style.display==='none'){ el.style.display='block'; startLogPoll(); }
else el.style.display='none';
}
startLogPoll();