Async ops + progressive stages + buttons + confirm, v1.0.42

This commit is contained in:
2026-07-26 13:56:27 +04:00
parent 62717b0e74
commit fed7260654
3 changed files with 153 additions and 127 deletions
+1 -1
View File
@@ -6,7 +6,7 @@ from routes.main import bp as main_bp
from routes.api import bp as api_bp from routes.api import bp as api_bp
from routes.api_test import bp as api_test_bp from routes.api_test import bp as api_test_bp
VERSION = "1.0.41" VERSION = "1.0.42"
app = Flask(__name__, template_folder="templates", static_folder="static") app = Flask(__name__, template_folder="templates", static_folder="static")
app.config["NUBES_API_ENDPOINT"] = os.getenv("NUBES_API_ENDPOINT", "https://lk-api-gateway-dev.ngcloud.ru/api/v1/svc") app.config["NUBES_API_ENDPOINT"] = os.getenv("NUBES_API_ENDPOINT", "https://lk-api-gateway-dev.ngcloud.ru/api/v1/svc")
+54 -52
View File
@@ -79,8 +79,8 @@ def api_params(op_id):
@bp.route("/api/test", methods=["POST"]) @bp.route("/api/test", methods=["POST"])
def api_test(): def api_test():
"""Запустить одну операцию — логика 1:1 с Terraform.""" """Запустить операцию — возвращает opUid сразу, выполнение в фоне."""
import time import threading, time
data = request.get_json() data = request.get_json()
svc_id = data["serviceId"] svc_id = data["serviceId"]
@@ -91,45 +91,34 @@ def api_test():
display_name = data.get("displayName", f"autotest-{svc_id}") display_name = data.get("displayName", f"autotest-{svc_id}")
client = _client() client = _client()
t0 = time.time()
try: try:
if op_name == "create": if op_name == "create":
# 1. POST /instances → instanceUid
payload = {"serviceId": svc_id, "displayName": display_name, "descr": ""} payload = {"serviceId": svc_id, "displayName": display_name, "descr": ""}
resp = client.post("/instances", payload) resp = client.post("/instances", payload)
instance_uid = resp.get("instanceUid") or _find_uid(resp) or _uid_from_location(resp.get("_location", "")) instance_uid = resp.get("instanceUid") or _find_uid(resp) or _uid_from_location(resp.get("_location", ""))
if not instance_uid: if not instance_uid:
return jsonify({"status": "FAIL", "error": "Не удалось получить instanceUid"}), 500 return jsonify({"status": "FAIL", "error": "Не удалось получить instanceUid"}), 500
# 2. POST /instanceOperations → opUid
op_payload = {"instanceUid": instance_uid, "operation": "create"} op_payload = {"instanceUid": instance_uid, "operation": "create"}
op_resp = client.post("/instanceOperations", op_payload) op_resp = client.post("/instanceOperations", op_payload)
op_uid = _find_uid(op_resp) or _uid_from_location(op_resp.get("_location", "")) op_uid = _find_uid(op_resp) or _uid_from_location(op_resp.get("_location", ""))
if not op_uid: if not op_uid:
return jsonify({"status": "FAIL", "error": "Не удалось получить opUid"}), 500 return jsonify({"status": "FAIL", "error": "Не удалось получить opUid"}), 500
# 3. POST /instanceOperationCfsParams ×N
for pid, pval in params.items(): for pid, pval in params.items():
client.post("/instanceOperationCfsParams", client.post("/instanceOperationCfsParams",
{"instanceOperationUid": op_uid, "svcOperationCfsParamId": int(pid), "paramValue": str(pval)}) {"instanceOperationUid": op_uid, "svcOperationCfsParamId": int(pid), "paramValue": str(pval)})
# 4. POST /run
client.post(f"/instanceOperations/{op_uid}/run") client.post(f"/instanceOperations/{op_uid}/run")
# 5. waitForOperationFinish (dtFinish-based) # фоном ждать завершения
result = _wait_op(client, op_uid, t0) threading.Thread(target=_finish_op, args=(client, op_uid, instance_uid, svc_id, display_name, True), daemon=True).start()
if result["status"] == "OK": return jsonify({"status": "RUNNING", "opUid": op_uid, "instanceUid": instance_uid})
tracker_add(instance_uid, svc_id, display_name)
result["instanceUid"] = instance_uid
return jsonify(result)
else: else:
# modify / suspend / delete / resume / redeploy
if not instance_uid: if not instance_uid:
return jsonify({"status": "FAIL", "error": "Нет instanceUid"}), 400 return jsonify({"status": "FAIL", "error": "Нет instanceUid"}), 400
# redeploy: без параметров, сразу /run
if op_name == "redeploy": if op_name == "redeploy":
op_payload = {"instanceUid": instance_uid, "svcOperationId": svc_op_id, "operation": op_name} op_payload = {"instanceUid": instance_uid, "svcOperationId": svc_op_id, "operation": op_name}
op_resp = client.post("/instanceOperations", op_payload) op_resp = client.post("/instanceOperations", op_payload)
@@ -137,43 +126,36 @@ def api_test():
if not op_uid: if not op_uid:
return jsonify({"status": "FAIL", "error": "Не удалось получить opUid"}), 500 return jsonify({"status": "FAIL", "error": "Не удалось получить opUid"}), 500
client.post(f"/instanceOperations/{op_uid}/run") client.post(f"/instanceOperations/{op_uid}/run")
result = _wait_op(client, op_uid, t0) else:
result["instanceUid"] = instance_uid op_payload = {"instanceUid": instance_uid, "svcOperationId": svc_op_id, "operation": op_name}
return jsonify(result) op_resp = client.post("/instanceOperations", op_payload)
op_uid = _find_uid(op_resp) or _uid_from_location(op_resp.get("_location", ""))
if not op_uid:
return jsonify({"status": "FAIL", "error": "Не удалось получить opUid"}), 500
for pid, pval in params.items():
client.post("/instanceOperationCfsParams",
{"instanceOperationUid": op_uid, "svcOperationCfsParamId": int(pid), "paramValue": str(pval)})
client.post(f"/instanceOperations/{op_uid}/run")
# modify/suspend/delete/resume: с параметрами # фоном ждать завершения
op_payload = {"instanceUid": instance_uid, "svcOperationId": svc_op_id, "operation": op_name} is_delete = (op_name == "delete")
op_resp = client.post("/instanceOperations", op_payload) threading.Thread(target=_finish_op, args=(client, op_uid, instance_uid, svc_id, display_name, False, is_delete), daemon=True).start()
op_uid = _find_uid(op_resp) or _uid_from_location(op_resp.get("_location", "")) return jsonify({"status": "RUNNING", "opUid": op_uid, "instanceUid": instance_uid})
if not op_uid:
return jsonify({"status": "FAIL", "error": "Не удалось получить opUid"}), 500
for pid, pval in params.items():
client.post("/instanceOperationCfsParams",
{"instanceOperationUid": op_uid, "svcOperationCfsParamId": int(pid), "paramValue": str(pval)})
client.post(f"/instanceOperations/{op_uid}/run")
result = _wait_op(client, op_uid, t0)
result["instanceUid"] = instance_uid
if result["status"] == "OK" and op_name == "delete":
tracker_remove(instance_uid)
return jsonify(result)
except Exception as e: except Exception as e:
import traceback import traceback
return jsonify({ return jsonify({"status": "FAIL", "error": str(e) + " | " + traceback.format_exc()[-200:]})
"status": "FAIL",
"error": str(e) + " | " + traceback.format_exc()[-200:],
"instanceUid": instance_uid,
"duration": round(time.time() - t0, 1),
})
def _wait_op(client, op_uid, t0): # Результаты фоновых операций: opUid → {status, error, stages, duration}
"""Поллинг операции до dtFinish — 1:1 с waitForOperationFinish.""" _op_results = {}
def _finish_op(client, op_uid, instance_uid, svc_id, display_name, is_create, is_delete=False):
"""Фоном ждать dtFinish и сохранить результат."""
import time import time
deadline = time.time() + 300 t0 = time.time()
deadline = t0 + 300
while time.time() < deadline: while time.time() < deadline:
try: try:
data = client.get(f"/instanceOperations/{op_uid}?fields=dtFinish,isSuccessful,errorLog,isInProgress,duration,stages") data = client.get(f"/instanceOperations/{op_uid}?fields=dtFinish,isSuccessful,errorLog,isInProgress,duration,stages")
@@ -182,25 +164,45 @@ def _wait_op(client, op_uid, t0):
continue continue
op = data.get("instanceOperation", {}) op = data.get("instanceOperation", {})
dt_finish = op.get("dtFinish") dt_finish = op.get("dtFinish")
# Обновляем stages по мере появления
_op_results[op_uid] = {
"status": "RUNNING",
"stages": op.get("stages", []),
"duration": round(time.time() - t0, 1),
}
if dt_finish and str(dt_finish).strip(): if dt_finish and str(dt_finish).strip():
is_ok = op.get("isSuccessful") is_ok = op.get("isSuccessful")
if not is_ok: err = op.get("errorLog") or ""
err = op.get("errorLog") or "неизвестная ошибка" _op_results[op_uid] = {
return {"status": "FAIL", "error": str(err), "duration": round(time.time() - t0, 1), "stages": op.get("stages", [])} "status": "OK" if is_ok else "FAIL",
return {"status": "OK", "duration": round(time.time() - t0, 1), "stages": op.get("stages", [])} "error": str(err) if err else "",
"stages": op.get("stages", []),
"duration": round(time.time() - t0, 1),
}
if is_ok:
if is_create:
tracker_add(instance_uid, svc_id, display_name)
elif is_delete:
tracker_remove(instance_uid)
return
time.sleep(5) time.sleep(5)
return {"status": "TIMEOUT", "duration": round(time.time() - t0, 1)} _op_results[op_uid] = {"status": "TIMEOUT", "duration": round(time.time() - t0, 1)}
@bp.route("/api/test/status/<op_uid>") @bp.route("/api/test/status/<op_uid>")
def api_test_status(op_uid): def api_test_status(op_uid):
"""Получить текущий статус операции (для поллинга с UI).""" """Получить текущий статус операции (поллинг с UI)."""
# сначала проверяем фоновый трекер
if op_uid in _op_results:
return jsonify(_op_results[op_uid])
# иначе спрашиваем API напрямую
try: try:
data = _client().get(f"/instanceOperations/{op_uid}?fields=dtFinish,isSuccessful,errorLog,isInProgress,duration,stages") data = _client().get(f"/instanceOperations/{op_uid}?fields=dtFinish,isSuccessful,errorLog,isInProgress,duration,stages")
op = data.get("instanceOperation", {}) op = data.get("instanceOperation", {})
dt_finish = op.get("dtFinish") dt_finish = op.get("dtFinish")
done = bool(dt_finish and str(dt_finish).strip()) done = bool(dt_finish and str(dt_finish).strip())
return jsonify({ return jsonify({
"status": "OK" if (done and op.get("isSuccessful")) else ("FAIL" if done else "RUNNING"),
"done": done, "done": done,
"isSuccessful": op.get("isSuccessful"), "isSuccessful": op.get("isSuccessful"),
"isInProgress": op.get("isInProgress"), "isInProgress": op.get("isInProgress"),
+98 -74
View File
@@ -97,16 +97,15 @@
</div> </div>
<script> <script>
let svcInstances=[], selectedInst=null, selectedOp=null; let svcInstances=[], selectedInst=null, selectedOp=null, pollTimer=null;
const SVC_ID=1; const SVC_ID=1;
// Загрузка при старте
selectService(SVC_ID); selectService(SVC_ID);
async function selectService(svcId){ async function selectService(svcId){
selectedInst=null; selectedOp=null; selectedInst=null; selectedOp=null; stopPoll();
document.getElementById('params-card').style.display='none'; document.getElementById('params-card').style.display='none';
document.getElementById('btn-test').style.display='none'; document.getElementById('stages-box').style.display='none';
const r=await fetch('/api/operations/'+svcId); const r=await fetch('/api/operations/'+svcId);
const d=await r.json(); const d=await r.json();
@@ -121,7 +120,6 @@ async function selectService(svcId){
</div>`; </div>`;
html+=`<div class="inst-ops" id="ops-${i.instanceUid}"></div>`; html+=`<div class="inst-ops" id="ops-${i.instanceUid}"></div>`;
}); });
// Кнопка создать
html+=`<div class="inst-item" style="margin-top:8px;border-top:1px solid var(--brand-gray);padding-top:8px;" onclick="startCreate()"> html+=`<div class="inst-item" style="margin-top:8px;border-top:1px solid var(--brand-gray);padding-top:8px;" onclick="startCreate()">
<span style="flex:1;color:var(--brand-primary);">+ Создать новый инстанс</span> <span style="flex:1;color:var(--brand-primary);">+ Создать новый инстанс</span>
</div>`; </div>`;
@@ -129,16 +127,12 @@ async function selectService(svcId){
} }
async function toggleInstance(iuid){ async function toggleInstance(iuid){
selectedInst=iuid; selectedInst=iuid; stopPoll();
document.querySelectorAll('[data-iuid]').forEach(e=>e.classList.toggle('active',e.dataset.iuid===iuid)); document.querySelectorAll('[data-iuid]').forEach(e=>e.classList.toggle('active',e.dataset.iuid===iuid));
document.getElementById('params-card').style.display='none';
const opsEl=document.getElementById('ops-'+iuid); const opsEl=document.getElementById('ops-'+iuid);
if(opsEl.classList.contains('open')){ if(opsEl.classList.contains('open')){opsEl.classList.remove('open');return;}
opsEl.classList.remove('open');
document.getElementById('params-card').style.display='none';
return;
}
// Закрыть все
document.querySelectorAll('.inst-ops').forEach(e=>e.classList.remove('open')); document.querySelectorAll('.inst-ops').forEach(e=>e.classList.remove('open'));
const r=await fetch('/api/operations/'+SVC_ID); const r=await fetch('/api/operations/'+SVC_ID);
@@ -146,71 +140,86 @@ async function toggleInstance(iuid){
const ops=d.operations.filter(o=>o.operation!=='reconcile'&&o.operation!=='create'); const ops=d.operations.filter(o=>o.operation!=='reconcile'&&o.operation!=='create');
opsEl.innerHTML=ops.map(o=> opsEl.innerHTML=ops.map(o=>
`<div class="inst-item" style="margin-left:0;"> `<div class="inst-item" style="margin-left:0;">
<span style="flex:1;">${o.operation}</span> <button class="btn btn-sm" onclick="runOp('${o.operation}',${o.svcOperationId})">${o.operation}</button>
<button class="btn btn-primary btn-sm" onclick="startOperation(${o.svcOperationId},'${o.operation}')">Тест</button>
</div>` </div>`
).join(''); ).join('');
opsEl.classList.add('open'); opsEl.classList.add('open');
} }
function startCreate(){ function startCreate(){
selectedInst=null; selectedInst=null; stopPoll();
document.querySelectorAll('[data-iuid]').forEach(e=>e.classList.remove('active')); document.querySelectorAll('[data-iuid]').forEach(e=>e.classList.remove('active'));
document.querySelectorAll('.inst-ops').forEach(e=>e.classList.remove('open')); document.querySelectorAll('.inst-ops').forEach(e=>e.classList.remove('open'));
loadParams(18,'create'); // svcOperationId for create = 18 showParams(18,'create');
} }
function startOperation(opId,opName){ function runOp(opName,opId){
loadParams(opId,opName); stopPoll();
selectedOp={opId,opName,svcId:SVC_ID};
if(opName==='modify'){
showParams(opId,opName);
}else{
// confirm and execute immediately
if(!confirm(`Запустить ${opName} для ${findInstName()}?`)) return;
executeOp({});
}
} }
async function loadParams(opId,opName){ function findInstName(){
const i=svcInstances.find(x=>x.instanceUid===selectedInst);
return i?i.displayName:selectedInst;
}
function showParams(opId,opName){
selectedOp={opId,opName,svcId:SVC_ID}; selectedOp={opId,opName,svcId:SVC_ID};
document.getElementById('params-card').style.display='block'; document.getElementById('params-card').style.display='block';
document.getElementById('btn-test').style.display='inline-flex'; document.getElementById('stages-box').style.display='none';
const r=await fetch('/api/params/'+opId);
const params=await r.json();
const form=document.getElementById('params-form');
const displayName=opName==='create'?('autotest-1-'+Date.now().toString(36)):'';
form.innerHTML=(opName==='create'?`<div class="param-row"><label class="req">displayName</label><input type="text" id="param-displayname" value="${displayName}"></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;
let input;
if(vl&&Array.isArray(vl)){
input=`<select name="p_${p.svcOperationCfsParamId}" data-type="${p.dataType}">${vl.map(v=>`<option value="${v}" ${v==dfl?'selected':''}>${v}</option>`).join('')}</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{
input=`<input type="text" name="p_${p.svcOperationCfsParamId}" value="${dfl}" placeholder="${req&&!hasDfl?'обязательно':''}">`;
}
return `<div class="param-row"><label class="${labelCls}">${p.name}</label>${input}</div>`;
}).join('');
document.getElementById('test-status').textContent=''; document.getElementById('test-status').textContent='';
fetch('/api/params/'+opId).then(r=>r.json()).then(params=>{
const form=document.getElementById('params-form');
const displayName=opName==='create'?('autotest-1-'+Date.now().toString(36)):'';
form.innerHTML=(opName==='create'?`<div class="param-row"><label class="req">displayName</label><input type="text" id="param-displayname" value="${displayName}"></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;
let input;
if(vl&&Array.isArray(vl)){
input=`<select name="p_${p.svcOperationCfsParamId}" data-type="${p.dataType}">${vl.map(v=>`<option value="${v}" ${v==dfl?'selected':''}>${v}</option>`).join('')}</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{
input=`<input type="text" name="p_${p.svcOperationCfsParamId}" value="${dfl}" placeholder="${req&&!hasDfl?'обязательно':''}">`;
}
return `<div class="param-row"><label class="${labelCls}">${p.name}</label>${input}</div>`;
}).join('');
const btn=document.getElementById('btn-test');
btn.style.display='inline-flex';
btn.textContent='Запустить';
btn.onclick=()=>{
const pp={};
document.querySelectorAll('#params-form [name^="p_"]').forEach(el=>{
let v=el.value;
const dt=el.dataset.type||'';
if(dt==='array'||dt.startsWith('array')) v=JSON.stringify([v]);
if(dt==='map'||dt==='map-fixed') v=v||'{}';
pp[el.name.replace('p_','')]=v;
});
executeOp(pp);
};
});
} }
async function runTest(){ async function executeOp(params){
if(!selectedOp) return; stopPoll();
const btn=document.getElementById('btn-test'); const btn=document.getElementById('btn-test');
btn.disabled=true; btn.disabled=true;
document.getElementById('test-status').textContent=' ⏳ выполняется...'; document.getElementById('test-status').textContent=' ⏳ выполняется...';
const stagesBox=document.getElementById('stages-box'); document.getElementById('stages-box').style.display='block';
stagesBox.style.display='block'; document.getElementById('stages-box').innerHTML='';
stagesBox.innerHTML='';
const params={};
document.querySelectorAll('#params-form [name^="p_"]').forEach(el=>{
let v=el.value;
const dt=el.dataset.type||'';
if(dt==='array'||dt.startsWith('array')) v=JSON.stringify([v]);
if(dt==='map'||dt==='map-fixed') v=v||'{}';
params[el.name.replace('p_','')]=v;
});
try{ try{
const r=await fetch('/api/test',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({ const r=await fetch('/api/test',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({
@@ -219,28 +228,43 @@ async function runTest(){
svcOperationId:selectedOp.opId, svcOperationId:selectedOp.opId,
params, params,
instanceUid:selectedInst||'', instanceUid:selectedInst||'',
displayName:document.getElementById('param-displayname')?.value||('autotest-1') displayName:document.getElementById('param-displayname')?.value||'autotest-1'
})}); })});
const d=await r.json(); const d=await r.json();
const cls=d.status==='OK'?'badge badge-success':'badge'; if(d.status==='FAIL'){document.getElementById('test-status').innerHTML=` <span class="badge">FAIL</span> ${d.error||''}`;btn.disabled=false;return;}
document.getElementById('test-status').innerHTML=` <span class="${cls}">${d.status}</span> ${d.error||''} ${d.duration||''}s`; // start polling
const opUid=d.opUid;
// Показать стадии pollTimer=setInterval(async()=>{
if(d.stages&&d.stages.length){ const sr=await fetch('/api/test/status/'+opUid);
let sh='<div style="font-size:11px;font-weight:600;color:var(--muted);margin-top:4px;">Этапы</div>'; const sd=await sr.json();
d.stages.forEach(s=>{ showStages(sd.stages||[]);
const ok=s.isSuccessful; if(sd.status!=='RUNNING'){
const icon=ok===true?'✅':ok===false?'❌':'⏳'; stopPoll();
sh+=`<div style="font-size:11px;padding:2px 0;">${icon} ${s.stage}${(s.duration||0).toFixed(1)}s</div>`; const cls=sd.status==='OK'?'badge-success':'badge';
}); document.getElementById('test-status').innerHTML=` <span class="badge ${cls}">${sd.status}</span> ${sd.error||''} ${sd.duration||''}s`;
stagesBox.innerHTML=sh; btn.disabled=false;
} if(sd.status==='OK'&&selectedOp.opName==='create') await selectService(SVC_ID);
}
if(d.status==='OK'&&selectedOp.opName==='create'){await selectService(SVC_ID);} },2000);
}catch(e){ }catch(e){
document.getElementById('test-status').textContent=' Ошибка: '+e.message; document.getElementById('test-status').textContent=' Ошибка: '+e.message;
btn.disabled=false;
} }
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 ok=s.isSuccessful;
const icon=ok===true?'✅':ok===false?'❌':'⏳';
html+=`<div style="font-size:11px;padding:2px 0;">${icon} ${s.stage}${(s.duration||0).toFixed(1)}s</div>`;
});
document.getElementById('stages-box').innerHTML=html;
}
function stopPoll(){
if(pollTimer){clearInterval(pollTimer);pollTimer=null;}
} }
</script> </script>
</body> </body>