v1.0.54: fix 4 audit bugs — _client auto-detect, _find_uid by key, tracker_add before params, flock LOCK_NB
This commit is contained in:
@@ -0,0 +1,73 @@
|
|||||||
|
# История разработки app-autotest
|
||||||
|
|
||||||
|
## v1.0.54 (27.07.2026) — Аудит #3: 4 бага исправлено
|
||||||
|
|
||||||
|
### Баг #1: `_client()` не автоопределял стенд (КРИТИЧЕСКИЙ)
|
||||||
|
- **Где:** `api_test.py:_client()` — использовал `current_app.config["NUBES_API_ENDPOINT"]` (raw env var)
|
||||||
|
- **Симптом:** main.py автоопределял стенд для главной, но POST /api/test падал с 401 если токен от другого стенда
|
||||||
|
- **Исправление:** `detect_endpoint()` вынесен в `api/http_client.py`, используется в `_client()`
|
||||||
|
- **Как пропустили:** анализировал main.py и api_test.py в изоляции, не сравнил
|
||||||
|
|
||||||
|
### Баг #2: `_find_uid()` возвращал не тот UUID (КРИТИЧЕСКИЙ)
|
||||||
|
- **Где:** `api_test.py:_find_uid()` — итерировал по ВСЕМ значениям dict, искал 36-символьную строку
|
||||||
|
- **Симптом:** `/instanceOperations` возвращает оба `instanceUid` + `instanceOperationUid`, функция брала первый попавшийся → `run` шёл на неправильный URL
|
||||||
|
- **Исправление:** ищет по конкретным ключам: `instanceOperationUid` → `instanceUid` → `uid` → `Uid`
|
||||||
|
- **Как пропустили:** не проверил реальный формат ответа API
|
||||||
|
|
||||||
|
### Баг #3: Сироты при ошибке params (СРЕДНИЙ)
|
||||||
|
- **Где:** `api_test.py`: порядок — `POST /instances` → `POST /instanceOperations` → params loop → `tracker_add`
|
||||||
|
- **Симптом:** если params падает — инстанс и операция созданы в Nubes, трекер пуст → сироты
|
||||||
|
- **Исправление:** `tracker_add` вызывается ДО params loop, сразу после получения `instanceUid`
|
||||||
|
- **Как пропустили:** не трассировал линейно порядок вызовов
|
||||||
|
|
||||||
|
### Баг #4: `flock` без таймаута (НИЗКИЙ)
|
||||||
|
- **Где:** `tracker.py:_locked_read/_write` — `fcntl.flock(fd, LOCK_EX)` без LOCK_NB
|
||||||
|
- **Симптом:** при зависшем процессе с локом все воркеры блокируются навсегда
|
||||||
|
- **Исправление:** `_acquire_lock()` с `LOCK_EX | LOCK_NB` + retry до 2 секунд
|
||||||
|
- **Как пропустили:** новый код flock не перечитал с нуля после добавления
|
||||||
|
|
||||||
|
### Архитектурное: `detect_endpoint` вынесен в http_client.py
|
||||||
|
- Раньше был в main.py → недоступен для api_test.py
|
||||||
|
- Теперь в `api/http_client.py` → оба модуля используют
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## v1.0.53 (27.07.2026) — Файловый трекер с fcntl.flock
|
||||||
|
- In-memory dict заменён на `/tmp/instances.json` с `fcntl.LOCK_EX`
|
||||||
|
- Multi-worker gunicorn: все воркеры читают/пишут один файл под локом
|
||||||
|
|
||||||
|
## v1.0.52 (27.07.2026) — `_tmpl()` helper
|
||||||
|
- Все переменные шаблона передаются во всех трёх return-путях index()
|
||||||
|
- Исправлен UndefinedError при «Выйти»
|
||||||
|
|
||||||
|
## v1.0.51 (27.07.2026) — Автоопределение стенда + UnboundLocalError
|
||||||
|
- `detect_endpoint()` в main.py: пробует токен против dev и test API
|
||||||
|
- `instance_groups = {}` инициализирован до if
|
||||||
|
- `_finish_op` обёрнут в полный try/except
|
||||||
|
|
||||||
|
## v1.0.50 (27.07.2026) — showStages + api_operations fix
|
||||||
|
- `showStages()`: dtFinish вместо isSuccessful для ⏳/✅/❌
|
||||||
|
- `api_operations()`: не фильтровать "not created", добавлять tracked-сирот
|
||||||
|
|
||||||
|
## v1.0.49 (27.07.2026) — In-memory tracker + refreshInstances
|
||||||
|
- Трекер: in-memory dict вместо файла `/tmp/instances.json`
|
||||||
|
- `refreshInstances()` добавляет новые инстансы в DOM (не только бейджи)
|
||||||
|
- `selectService()` заменён на `refreshInstances()` после OK
|
||||||
|
|
||||||
|
## v1.0.48 (27.07.2026) — tracker_add синхронно
|
||||||
|
- `tracker_add` в `api_test()` до `threading.Thread`
|
||||||
|
- Лог `is_ok` в `_finish_op`
|
||||||
|
- Flexbox-кнопки горизонтально
|
||||||
|
|
||||||
|
## v1.0.47 (27.07.2026) — displayName fix
|
||||||
|
- displayName захватывается до очистки формы
|
||||||
|
- tracker_add до _op_results[OK]
|
||||||
|
- autotest-1 в _INITIAL
|
||||||
|
|
||||||
|
## v1.0.46 (27.07.2026) — _finish_op signature
|
||||||
|
- Добавлены op_name, svc_op_id в _finish_op()
|
||||||
|
|
||||||
|
## v1.0.45 и ранее
|
||||||
|
- Базовый CREATE/MODIFY/SUSPEND/DELETE/RESUME/REDEPLOY
|
||||||
|
- UI с этапами, поллинг, params форма
|
||||||
|
- Множественные баги CREATE flow (документированы в DOCS/api-create-flow.md)
|
||||||
@@ -1,5 +1,23 @@
|
|||||||
import requests
|
import requests
|
||||||
|
|
||||||
|
STANDS = [
|
||||||
|
"https://lk-api-gateway-dev.ngcloud.ru/api/v1/svc",
|
||||||
|
"https://lk-api-gateway-test.ngcloud.ru/api/v1/svc",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def detect_endpoint(token):
|
||||||
|
"""Пробуем токен против dev и test стендов, возвращаем рабочий URL."""
|
||||||
|
for ep in STANDS:
|
||||||
|
try:
|
||||||
|
c = HttpClient(ep, token)
|
||||||
|
data = c.get("/instances", params={"pageSize": 1, "page": 1})
|
||||||
|
if data.get("results") is not None:
|
||||||
|
return ep
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
class HttpClient:
|
class HttpClient:
|
||||||
def __init__(self, endpoint, token):
|
def __init__(self, endpoint, token):
|
||||||
|
|||||||
+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.53"
|
VERSION = "1.0.54"
|
||||||
|
|
||||||
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")
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
import fcntl
|
import fcntl
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import time
|
||||||
|
|
||||||
_PATH = "/tmp/instances.json"
|
_PATH = "/tmp/instances.json"
|
||||||
|
|
||||||
@@ -13,6 +14,19 @@ _INITIAL = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _acquire_lock(fd):
|
||||||
|
"""LOCK_EX с таймаутом 2 секунды (LOCK_NB + retry)."""
|
||||||
|
deadline = time.time() + 2
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
|
return True
|
||||||
|
except BlockingIOError:
|
||||||
|
if time.time() >= deadline:
|
||||||
|
return False
|
||||||
|
time.sleep(0.05)
|
||||||
|
|
||||||
|
|
||||||
def _locked_read():
|
def _locked_read():
|
||||||
"""Читает файл под эксклюзивной блокировкой, seed при отсутствии."""
|
"""Читает файл под эксклюзивной блокировкой, seed при отсутствии."""
|
||||||
try:
|
try:
|
||||||
@@ -20,7 +34,8 @@ def _locked_read():
|
|||||||
except OSError:
|
except OSError:
|
||||||
return dict(_INITIAL)
|
return dict(_INITIAL)
|
||||||
try:
|
try:
|
||||||
fcntl.flock(fd, fcntl.LOCK_EX)
|
if not _acquire_lock(fd):
|
||||||
|
return dict(_INITIAL)
|
||||||
try:
|
try:
|
||||||
data = os.read(fd, 65536)
|
data = os.read(fd, 65536)
|
||||||
if data:
|
if data:
|
||||||
@@ -45,7 +60,8 @@ def _locked_write(data):
|
|||||||
except OSError:
|
except OSError:
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
fcntl.flock(fd, fcntl.LOCK_EX)
|
if not _acquire_lock(fd):
|
||||||
|
return
|
||||||
os.lseek(fd, 0, 0)
|
os.lseek(fd, 0, 0)
|
||||||
os.ftruncate(fd, 0)
|
os.ftruncate(fd, 0)
|
||||||
os.write(fd, json.dumps(data, indent=2).encode("utf-8"))
|
os.write(fd, json.dumps(data, indent=2).encode("utf-8"))
|
||||||
|
|||||||
+14
-10
@@ -1,6 +1,6 @@
|
|||||||
from flask import Blueprint, current_app, jsonify, request
|
from flask import Blueprint, current_app, jsonify, request
|
||||||
|
|
||||||
from api.http_client import HttpClient
|
from api.http_client import HttpClient, detect_endpoint
|
||||||
from operations.get_services import get_services, get_service_detail
|
from operations.get_services import get_services, get_service_detail
|
||||||
from operations.get_instances import get_instances
|
from operations.get_instances import get_instances
|
||||||
from operations.tracker import add as tracker_add, list_all as tracker_list
|
from operations.tracker import add as tracker_add, list_all as tracker_list
|
||||||
@@ -11,7 +11,8 @@ bp = Blueprint("api_test", __name__)
|
|||||||
|
|
||||||
def _client():
|
def _client():
|
||||||
token = request.cookies.get("token") or current_app.config["NUBES_API_TOKEN"]
|
token = request.cookies.get("token") or current_app.config["NUBES_API_TOKEN"]
|
||||||
return HttpClient(current_app.config["NUBES_API_ENDPOINT"], token)
|
endpoint = detect_endpoint(token) or current_app.config["NUBES_API_ENDPOINT"]
|
||||||
|
return HttpClient(endpoint, token)
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/api/services")
|
@bp.route("/api/services")
|
||||||
@@ -118,12 +119,8 @@ 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
|
||||||
|
|
||||||
for pid, pval in params.items():
|
# Записать в трекер СРАЗУ после получения instanceUid, до params/run
|
||||||
client.post("/instanceOperationCfsParams",
|
# (если params упадут — инстанс уже отслежен, сирот не будет)
|
||||||
{"instanceOperationUid": op_uid, "svcOperationCfsParamId": int(pid), "paramValue": str(pval)})
|
|
||||||
client.post(f"/instanceOperations/{op_uid}/run")
|
|
||||||
|
|
||||||
# Записать в трекер СРАЗУ, до фонового потока (поток может умереть под gunicorn)
|
|
||||||
try:
|
try:
|
||||||
tracker_add(instance_uid, svc_id, display_name)
|
tracker_add(instance_uid, svc_id, display_name)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -131,6 +128,11 @@ def api_test():
|
|||||||
print(f"[TRACKER ERROR] add failed: {e}", flush=True)
|
print(f"[TRACKER ERROR] add failed: {e}", flush=True)
|
||||||
traceback.print_exc()
|
traceback.print_exc()
|
||||||
|
|
||||||
|
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")
|
||||||
|
|
||||||
# фоном ждать завершения
|
# фоном ждать завершения
|
||||||
threading.Thread(target=_finish_op, args=(client, op_uid, instance_uid, svc_id, display_name, op_name, svc_op_id, True), daemon=True).start()
|
threading.Thread(target=_finish_op, args=(client, op_uid, instance_uid, svc_id, display_name, op_name, svc_op_id, True), daemon=True).start()
|
||||||
return jsonify({"status": "RUNNING", "opUid": op_uid, "instanceUid": instance_uid})
|
return jsonify({"status": "RUNNING", "opUid": op_uid, "instanceUid": instance_uid})
|
||||||
@@ -239,9 +241,11 @@ def api_test_status(op_uid):
|
|||||||
|
|
||||||
|
|
||||||
def _find_uid(resp):
|
def _find_uid(resp):
|
||||||
|
"""Извлечь instanceUid или instanceOperationUid из ответа API."""
|
||||||
if isinstance(resp, dict):
|
if isinstance(resp, dict):
|
||||||
for v in resp.values():
|
for key in ("instanceOperationUid", "instanceUid", "uid", "Uid"):
|
||||||
if isinstance(v, str) and len(v) == 36 and v.count("-") == 4:
|
v = resp.get(key)
|
||||||
|
if isinstance(v, str) and v:
|
||||||
return v
|
return v
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|||||||
+2
-20
@@ -1,6 +1,6 @@
|
|||||||
from flask import Blueprint, current_app, render_template, request, make_response, jsonify
|
from flask import Blueprint, current_app, render_template, request, make_response, jsonify
|
||||||
|
|
||||||
from api.http_client import HttpClient
|
from api.http_client import HttpClient, detect_endpoint
|
||||||
from operations.get_instances import get_organization, get_instances
|
from operations.get_instances import get_organization, get_instances
|
||||||
from operations.get_services import get_services, get_service_detail
|
from operations.get_services import get_services, get_service_detail
|
||||||
from operations.tracker import list_all as tracker_list
|
from operations.tracker import list_all as tracker_list
|
||||||
@@ -8,24 +8,6 @@ from runner import load_config
|
|||||||
|
|
||||||
bp = Blueprint("main", __name__)
|
bp = Blueprint("main", __name__)
|
||||||
|
|
||||||
STANDS = [
|
|
||||||
"https://lk-api-gateway-dev.ngcloud.ru/api/v1/svc",
|
|
||||||
"https://lk-api-gateway-test.ngcloud.ru/api/v1/svc",
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def _detect_endpoint(token):
|
|
||||||
"""Пробуем токен против dev и test стендов, возвращаем рабочий URL."""
|
|
||||||
for ep in STANDS:
|
|
||||||
try:
|
|
||||||
c = HttpClient(ep, token)
|
|
||||||
data = c.get("/instances", params={"pageSize": 1, "page": 1})
|
|
||||||
if data.get("results") is not None:
|
|
||||||
return ep
|
|
||||||
except Exception:
|
|
||||||
continue
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _mask(s):
|
def _mask(s):
|
||||||
if not s or len(s) < 8:
|
if not s or len(s) < 8:
|
||||||
@@ -113,7 +95,7 @@ def index():
|
|||||||
instance_groups = {}
|
instance_groups = {}
|
||||||
config = {}
|
config = {}
|
||||||
if active_token:
|
if active_token:
|
||||||
endpoint = _detect_endpoint(active_token)
|
endpoint = detect_endpoint(active_token)
|
||||||
if endpoint:
|
if endpoint:
|
||||||
try:
|
try:
|
||||||
client = HttpClient(endpoint, active_token)
|
client = HttpClient(endpoint, active_token)
|
||||||
|
|||||||
Reference in New Issue
Block a user