Full Terraform logic: svcOperationId, /run, dtFinish, stages in UI, v1.0.41
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 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.40"
|
VERSION = "1.0.41"
|
||||||
|
|
||||||
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")
|
||||||
|
|||||||
+105
-52
@@ -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."""
|
||||||
import threading, time
|
import time
|
||||||
|
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
svc_id = data["serviceId"]
|
svc_id = data["serviceId"]
|
||||||
@@ -91,72 +91,125 @@ 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()
|
||||||
|
|
||||||
result = {"status": "RUNNING", "error": None, "instanceUid": None, "duration": 0}
|
|
||||||
t0 = time.time()
|
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:
|
||||||
|
return jsonify({"status": "FAIL", "error": "Не удалось получить instanceUid"}), 500
|
||||||
|
|
||||||
# Шаг 2: создать операцию, задать параметры, запустить
|
# 2. POST /instanceOperations → opUid
|
||||||
if instance_uid:
|
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 op_uid:
|
return jsonify({"status": "FAIL", "error": "Не удалось получить opUid"}), 500
|
||||||
for pid, pval in params.items():
|
|
||||||
client.post("/instanceOperationCfsParams",
|
# 3. POST /instanceOperationCfsParams ×N
|
||||||
{"instanceOperationUid": op_uid, "svcOperationCfsParamId": int(pid), "paramValue": str(pval)})
|
for pid, pval in params.items():
|
||||||
client.post(f"/instanceOperations/{op_uid}/run")
|
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)
|
||||||
|
|
||||||
# wait
|
|
||||||
deadline = time.time() + 300
|
|
||||||
while time.time() < deadline:
|
|
||||||
insts = get_instances(client)
|
|
||||||
for i in insts:
|
|
||||||
if i.get("instanceUid") == instance_uid:
|
|
||||||
if not i.get("operationIsInProgress") and i.get("explainedStatus") not in ("creating",):
|
|
||||||
result["status"] = "OK"
|
|
||||||
result["instanceUid"] = instance_uid
|
|
||||||
result["duration"] = round(time.time() - t0, 1)
|
|
||||||
tracker_add(instance_uid, svc_id, display_name)
|
|
||||||
return jsonify(result)
|
|
||||||
time.sleep(5)
|
|
||||||
result["status"] = "TIMEOUT"
|
|
||||||
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
|
||||||
# все операции: {instanceUid, operation}
|
|
||||||
op_payload = {"instanceUid": instance_uid, "operation": op_name}
|
|
||||||
if params:
|
|
||||||
op_payload["cfsParams"] = [{"svcOperationCfsParamId": int(k), "paramValue": str(v)} for k, v in params.items()]
|
|
||||||
client.post("/instanceOperations", op_payload)
|
|
||||||
|
|
||||||
deadline = time.time() + 300
|
# redeploy: без параметров, сразу /run
|
||||||
while time.time() < deadline:
|
if op_name == "redeploy":
|
||||||
insts = get_instances(client)
|
op_payload = {"instanceUid": instance_uid, "svcOperationId": svc_op_id, "operation": op_name}
|
||||||
for i in insts:
|
op_resp = client.post("/instanceOperations", op_payload)
|
||||||
if i.get("instanceUid") == instance_uid:
|
op_uid = _find_uid(op_resp) or _uid_from_location(op_resp.get("_location", ""))
|
||||||
if not i.get("operationIsInProgress"):
|
if not op_uid:
|
||||||
result["status"] = "OK"
|
return jsonify({"status": "FAIL", "error": "Не удалось получить opUid"}), 500
|
||||||
result["instanceUid"] = instance_uid
|
client.post(f"/instanceOperations/{op_uid}/run")
|
||||||
result["duration"] = round(time.time() - t0, 1)
|
result = _wait_op(client, op_uid, t0)
|
||||||
if op_name == "delete":
|
result["instanceUid"] = instance_uid
|
||||||
tracker_remove(instance_uid)
|
return jsonify(result)
|
||||||
return jsonify(result)
|
|
||||||
time.sleep(5)
|
# modify/suspend/delete/resume: с параметрами
|
||||||
result["status"] = "TIMEOUT"
|
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)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
import traceback
|
import traceback
|
||||||
result["status"] = "FAIL"
|
return jsonify({
|
||||||
result["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),
|
||||||
|
})
|
||||||
|
|
||||||
result["instanceUid"] = instance_uid
|
|
||||||
result["duration"] = round(time.time() - t0, 1)
|
def _wait_op(client, op_uid, t0):
|
||||||
return jsonify(result)
|
"""Поллинг операции до dtFinish — 1:1 с waitForOperationFinish."""
|
||||||
|
import time
|
||||||
|
deadline = time.time() + 300
|
||||||
|
while time.time() < deadline:
|
||||||
|
try:
|
||||||
|
data = client.get(f"/instanceOperations/{op_uid}?fields=dtFinish,isSuccessful,errorLog,isInProgress,duration,stages")
|
||||||
|
except Exception:
|
||||||
|
time.sleep(5)
|
||||||
|
continue
|
||||||
|
op = data.get("instanceOperation", {})
|
||||||
|
dt_finish = op.get("dtFinish")
|
||||||
|
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", [])}
|
||||||
|
time.sleep(5)
|
||||||
|
return {"status": "TIMEOUT", "duration": round(time.time() - t0, 1)}
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route("/api/test/status/<op_uid>")
|
||||||
|
def api_test_status(op_uid):
|
||||||
|
"""Получить текущий статус операции (для поллинга с UI)."""
|
||||||
|
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({
|
||||||
|
"done": done,
|
||||||
|
"isSuccessful": op.get("isSuccessful"),
|
||||||
|
"isInProgress": op.get("isInProgress"),
|
||||||
|
"duration": op.get("duration"),
|
||||||
|
"stages": op.get("stages", []),
|
||||||
|
"errorLog": op.get("errorLog"),
|
||||||
|
})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({"error": str(e)}), 500
|
||||||
|
|
||||||
|
|
||||||
def _find_uid(resp):
|
def _find_uid(resp):
|
||||||
|
|||||||
@@ -91,6 +91,7 @@
|
|||||||
<button class="btn btn-primary btn-sm" onclick="runTest()" id="btn-test" style="display:none;">Запустить тест</button>
|
<button class="btn btn-primary btn-sm" onclick="runTest()" id="btn-test" style="display:none;">Запустить тест</button>
|
||||||
<span id="test-status" style="font-size:11px;margin-left:8px;"></span>
|
<span id="test-status" style="font-size:11px;margin-left:8px;"></span>
|
||||||
</div>
|
</div>
|
||||||
|
<div id="stages-box" style="display:none;padding:0 8px 8px;max-height:200px;overflow-y:auto;"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -198,6 +199,9 @@ async function runTest(){
|
|||||||
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');
|
||||||
|
stagesBox.style.display='block';
|
||||||
|
stagesBox.innerHTML='';
|
||||||
|
|
||||||
const params={};
|
const params={};
|
||||||
document.querySelectorAll('#params-form [name^="p_"]').forEach(el=>{
|
document.querySelectorAll('#params-form [name^="p_"]').forEach(el=>{
|
||||||
@@ -220,7 +224,19 @@ async function runTest(){
|
|||||||
const d=await r.json();
|
const d=await r.json();
|
||||||
const cls=d.status==='OK'?'badge badge-success':'badge';
|
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`;
|
document.getElementById('test-status').innerHTML=` <span class="${cls}">${d.status}</span> ${d.error||''} ${d.duration||''}s`;
|
||||||
if(d.status==='OK'){await selectService(SVC_ID);}
|
|
||||||
|
// Показать стадии
|
||||||
|
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==='OK'&&selectedOp.opName==='create'){await selectService(SVC_ID);}
|
||||||
}catch(e){
|
}catch(e){
|
||||||
document.getElementById('test-status').textContent=' Ошибка: '+e.message;
|
document.getElementById('test-status').textContent=' Ошибка: '+e.message;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user