Async ops + progressive stages + buttons + confirm, v1.0.42
This commit is contained in:
+54
-52
@@ -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)
|
||||
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")
|
||||
|
||||
# modify/suspend/delete/resume: с параметрами
|
||||
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"),
|
||||
|
||||
Reference in New Issue
Block a user