Async ops + progressive stages + buttons + confirm, v1.0.42
This commit is contained in:
+1
-1
@@ -6,7 +6,7 @@ from routes.main import bp as main_bp
|
||||
from routes.api import bp as api_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.config["NUBES_API_ENDPOINT"] = os.getenv("NUBES_API_ENDPOINT", "https://lk-api-gateway-dev.ngcloud.ru/api/v1/svc")
|
||||
|
||||
+45
-43
@@ -79,8 +79,8 @@ def api_params(op_id):
|
||||
|
||||
@bp.route("/api/test", methods=["POST"])
|
||||
def api_test():
|
||||
"""Запустить одну операцию — логика 1:1 с Terraform."""
|
||||
import time
|
||||
"""Запустить операцию — возвращает opUid сразу, выполнение в фоне."""
|
||||
import threading, time
|
||||
|
||||
data = request.get_json()
|
||||
svc_id = data["serviceId"]
|
||||
@@ -91,45 +91,34 @@ def api_test():
|
||||
display_name = data.get("displayName", f"autotest-{svc_id}")
|
||||
|
||||
client = _client()
|
||||
t0 = time.time()
|
||||
|
||||
try:
|
||||
if op_name == "create":
|
||||
# 1. POST /instances → instanceUid
|
||||
payload = {"serviceId": svc_id, "displayName": display_name, "descr": ""}
|
||||
resp = client.post("/instances", payload)
|
||||
instance_uid = resp.get("instanceUid") or _find_uid(resp) or _uid_from_location(resp.get("_location", ""))
|
||||
if not instance_uid:
|
||||
return jsonify({"status": "FAIL", "error": "Не удалось получить instanceUid"}), 500
|
||||
|
||||
# 2. POST /instanceOperations → opUid
|
||||
op_payload = {"instanceUid": instance_uid, "operation": "create"}
|
||||
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
|
||||
|
||||
# 3. POST /instanceOperationCfsParams ×N
|
||||
for pid, pval in params.items():
|
||||
client.post("/instanceOperationCfsParams",
|
||||
{"instanceOperationUid": op_uid, "svcOperationCfsParamId": int(pid), "paramValue": str(pval)})
|
||||
|
||||
# 4. POST /run
|
||||
client.post(f"/instanceOperations/{op_uid}/run")
|
||||
|
||||
# 5. waitForOperationFinish (dtFinish-based)
|
||||
result = _wait_op(client, op_uid, t0)
|
||||
if result["status"] == "OK":
|
||||
tracker_add(instance_uid, svc_id, display_name)
|
||||
result["instanceUid"] = instance_uid
|
||||
return jsonify(result)
|
||||
# фоном ждать завершения
|
||||
threading.Thread(target=_finish_op, args=(client, op_uid, instance_uid, svc_id, display_name, True), daemon=True).start()
|
||||
return jsonify({"status": "RUNNING", "opUid": op_uid, "instanceUid": instance_uid})
|
||||
|
||||
else:
|
||||
# modify / suspend / delete / resume / redeploy
|
||||
if not instance_uid:
|
||||
return jsonify({"status": "FAIL", "error": "Нет instanceUid"}), 400
|
||||
|
||||
# redeploy: без параметров, сразу /run
|
||||
if op_name == "redeploy":
|
||||
op_payload = {"instanceUid": instance_uid, "svcOperationId": svc_op_id, "operation": op_name}
|
||||
op_resp = client.post("/instanceOperations", op_payload)
|
||||
@@ -137,43 +126,36 @@ def api_test():
|
||||
if not op_uid:
|
||||
return jsonify({"status": "FAIL", "error": "Не удалось получить opUid"}), 500
|
||||
client.post(f"/instanceOperations/{op_uid}/run")
|
||||
result = _wait_op(client, op_uid, t0)
|
||||
result["instanceUid"] = instance_uid
|
||||
return jsonify(result)
|
||||
|
||||
# modify/suspend/delete/resume: с параметрами
|
||||
else:
|
||||
op_payload = {"instanceUid": instance_uid, "svcOperationId": svc_op_id, "operation": op_name}
|
||||
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")
|
||||
|
||||
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)
|
||||
# фоном ждать завершения
|
||||
is_delete = (op_name == "delete")
|
||||
threading.Thread(target=_finish_op, args=(client, op_uid, instance_uid, svc_id, display_name, False, is_delete), daemon=True).start()
|
||||
return jsonify({"status": "RUNNING", "opUid": op_uid, "instanceUid": instance_uid})
|
||||
|
||||
except Exception as e:
|
||||
import traceback
|
||||
return jsonify({
|
||||
"status": "FAIL",
|
||||
"error": str(e) + " | " + traceback.format_exc()[-200:],
|
||||
"instanceUid": instance_uid,
|
||||
"duration": round(time.time() - t0, 1),
|
||||
})
|
||||
return jsonify({"status": "FAIL", "error": str(e) + " | " + traceback.format_exc()[-200:]})
|
||||
|
||||
|
||||
def _wait_op(client, op_uid, t0):
|
||||
"""Поллинг операции до dtFinish — 1:1 с waitForOperationFinish."""
|
||||
# Результаты фоновых операций: opUid → {status, error, stages, duration}
|
||||
_op_results = {}
|
||||
|
||||
|
||||
def _finish_op(client, op_uid, instance_uid, svc_id, display_name, is_create, is_delete=False):
|
||||
"""Фоном ждать dtFinish и сохранить результат."""
|
||||
import time
|
||||
deadline = time.time() + 300
|
||||
t0 = time.time()
|
||||
deadline = t0 + 300
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
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
|
||||
op = data.get("instanceOperation", {})
|
||||
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():
|
||||
is_ok = op.get("isSuccessful")
|
||||
if not is_ok:
|
||||
err = op.get("errorLog") or "неизвестная ошибка"
|
||||
return {"status": "FAIL", "error": str(err), "duration": round(time.time() - t0, 1), "stages": op.get("stages", [])}
|
||||
return {"status": "OK", "duration": round(time.time() - t0, 1), "stages": op.get("stages", [])}
|
||||
err = op.get("errorLog") or ""
|
||||
_op_results[op_uid] = {
|
||||
"status": "OK" if is_ok else "FAIL",
|
||||
"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)
|
||||
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>")
|
||||
def api_test_status(op_uid):
|
||||
"""Получить текущий статус операции (для поллинга с UI)."""
|
||||
"""Получить текущий статус операции (поллинг с UI)."""
|
||||
# сначала проверяем фоновый трекер
|
||||
if op_uid in _op_results:
|
||||
return jsonify(_op_results[op_uid])
|
||||
# иначе спрашиваем API напрямую
|
||||
try:
|
||||
data = _client().get(f"/instanceOperations/{op_uid}?fields=dtFinish,isSuccessful,errorLog,isInProgress,duration,stages")
|
||||
op = data.get("instanceOperation", {})
|
||||
dt_finish = op.get("dtFinish")
|
||||
done = bool(dt_finish and str(dt_finish).strip())
|
||||
return jsonify({
|
||||
"status": "OK" if (done and op.get("isSuccessful")) else ("FAIL" if done else "RUNNING"),
|
||||
"done": done,
|
||||
"isSuccessful": op.get("isSuccessful"),
|
||||
"isInProgress": op.get("isInProgress"),
|
||||
|
||||
+76
-52
@@ -97,16 +97,15 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let svcInstances=[], selectedInst=null, selectedOp=null;
|
||||
let svcInstances=[], selectedInst=null, selectedOp=null, pollTimer=null;
|
||||
const SVC_ID=1;
|
||||
|
||||
// Загрузка при старте
|
||||
selectService(SVC_ID);
|
||||
|
||||
async function selectService(svcId){
|
||||
selectedInst=null; selectedOp=null;
|
||||
selectedInst=null; selectedOp=null; stopPoll();
|
||||
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 d=await r.json();
|
||||
@@ -121,7 +120,6 @@ async function selectService(svcId){
|
||||
</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()">
|
||||
<span style="flex:1;color:var(--brand-primary);">+ Создать новый инстанс</span>
|
||||
</div>`;
|
||||
@@ -129,16 +127,12 @@ async function selectService(svcId){
|
||||
}
|
||||
|
||||
async function toggleInstance(iuid){
|
||||
selectedInst=iuid;
|
||||
selectedInst=iuid; stopPoll();
|
||||
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);
|
||||
if(opsEl.classList.contains('open')){
|
||||
opsEl.classList.remove('open');
|
||||
document.getElementById('params-card').style.display='none';
|
||||
return;
|
||||
}
|
||||
// Закрыть все
|
||||
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/'+SVC_ID);
|
||||
@@ -146,33 +140,44 @@ async function toggleInstance(iuid){
|
||||
const ops=d.operations.filter(o=>o.operation!=='reconcile'&&o.operation!=='create');
|
||||
opsEl.innerHTML=ops.map(o=>
|
||||
`<div class="inst-item" style="margin-left:0;">
|
||||
<span style="flex:1;">${o.operation}</span>
|
||||
<button class="btn btn-primary btn-sm" onclick="startOperation(${o.svcOperationId},'${o.operation}')">Тест</button>
|
||||
<button class="btn btn-sm" onclick="runOp('${o.operation}',${o.svcOperationId})">${o.operation}</button>
|
||||
</div>`
|
||||
).join('');
|
||||
opsEl.classList.add('open');
|
||||
}
|
||||
|
||||
function startCreate(){
|
||||
selectedInst=null;
|
||||
selectedInst=null; stopPoll();
|
||||
document.querySelectorAll('[data-iuid]').forEach(e=>e.classList.remove('active'));
|
||||
document.querySelectorAll('.inst-ops').forEach(e=>e.classList.remove('open'));
|
||||
loadParams(18,'create'); // svcOperationId for create = 18
|
||||
showParams(18,'create');
|
||||
}
|
||||
|
||||
function startOperation(opId,opName){
|
||||
loadParams(opId,opName);
|
||||
function runOp(opName,opId){
|
||||
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};
|
||||
document.getElementById('params-card').style.display='block';
|
||||
document.getElementById('btn-test').style.display='inline-flex';
|
||||
document.getElementById('stages-box').style.display='none';
|
||||
document.getElementById('test-status').textContent='';
|
||||
|
||||
const r=await fetch('/api/params/'+opId);
|
||||
const params=await r.json();
|
||||
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=>{
|
||||
@@ -191,26 +196,30 @@ async function loadParams(opId,opName){
|
||||
}
|
||||
return `<div class="param-row"><label class="${labelCls}">${p.name}</label>${input}</div>`;
|
||||
}).join('');
|
||||
document.getElementById('test-status').textContent='';
|
||||
}
|
||||
|
||||
async function runTest(){
|
||||
if(!selectedOp) return;
|
||||
const btn=document.getElementById('btn-test');
|
||||
btn.disabled=true;
|
||||
document.getElementById('test-status').textContent=' ⏳ выполняется...';
|
||||
const stagesBox=document.getElementById('stages-box');
|
||||
stagesBox.style.display='block';
|
||||
stagesBox.innerHTML='';
|
||||
|
||||
const params={};
|
||||
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||'{}';
|
||||
params[el.name.replace('p_','')]=v;
|
||||
pp[el.name.replace('p_','')]=v;
|
||||
});
|
||||
executeOp(pp);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function executeOp(params){
|
||||
stopPoll();
|
||||
const btn=document.getElementById('btn-test');
|
||||
btn.disabled=true;
|
||||
document.getElementById('test-status').textContent=' ⏳ выполняется...';
|
||||
document.getElementById('stages-box').style.display='block';
|
||||
document.getElementById('stages-box').innerHTML='';
|
||||
|
||||
try{
|
||||
const r=await fetch('/api/test',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({
|
||||
@@ -219,29 +228,44 @@ async function runTest(){
|
||||
svcOperationId:selectedOp.opId,
|
||||
params,
|
||||
instanceUid:selectedInst||'',
|
||||
displayName:document.getElementById('param-displayname')?.value||('autotest-1')
|
||||
displayName:document.getElementById('param-displayname')?.value||'autotest-1'
|
||||
})});
|
||||
const d=await r.json();
|
||||
const cls=d.status==='OK'?'badge badge-success':'badge';
|
||||
document.getElementById('test-status').innerHTML=` <span class="${cls}">${d.status}</span> ${d.error||''} ${d.duration||''}s`;
|
||||
|
||||
// Показать стадии
|
||||
if(d.stages&&d.stages.length){
|
||||
let sh='<div style="font-size:11px;font-weight:600;color:var(--muted);margin-top:4px;">Этапы</div>';
|
||||
d.stages.forEach(s=>{
|
||||
const ok=s.isSuccessful;
|
||||
const icon=ok===true?'✅':ok===false?'❌':'⏳';
|
||||
sh+=`<div style="font-size:11px;padding:2px 0;">${icon} ${s.stage} — ${(s.duration||0).toFixed(1)}s</div>`;
|
||||
});
|
||||
stagesBox.innerHTML=sh;
|
||||
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;
|
||||
pollTimer=setInterval(async()=>{
|
||||
const sr=await fetch('/api/test/status/'+opUid);
|
||||
const sd=await sr.json();
|
||||
showStages(sd.stages||[]);
|
||||
if(sd.status!=='RUNNING'){
|
||||
stopPoll();
|
||||
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`;
|
||||
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){
|
||||
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 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>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user