Prod upgrade fixes: profiler compatibility with new FastAPI, pinned dependencies

- profiler: Literal instead of Query(enum=...) (broke on FastAPI 0.162)
- pin fastapi/starlette/uvicorn/pydantic for the profiler, upper bounds for APP_CORE
- health check: show the service log when an HTTP check fails
- update.sh: the "before" version comes from deploy.state
- migrate.py: hint about OVPMON_*_DB_PATH when the default database is missing
- docs: --source --no-pull mode, dependency pinning, PIP_CONSTRAINT
- tests: new test for the section parameter, fixed test_server_process.py

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ayurishchevandClaude Sonnet 5.5 committed 2026-11-13 00:03:39 +03:00
1 parent 1bbf9b7cc1
commit 79c950f8f7
14 files changed
+156 -38

No files matched your search

+3
View File
@@ -37,6 +37,9 @@ def main(argv=None):
if st.too_new:
raise migrations._too_new_error(st)
print(f"Database: {db_path}" + ("" if st.exists else " (does not exist yet)"))
if not st.exists and not args.db:
print("Hint: the default database was used; for an installed system set OVPMON_OPENVPN_MONITOR_DB_PATH "
"(see /etc/ovpmon/env) or pass --db PATH")
if args.check:
print(f"Schema version: {st.current} (latest known: {migrations.latest_version()})")
if not st.pending:
+6 -7
View File
@@ -1,7 +1,6 @@
Flask>=3.0.0
Flask-Cors>=4.0.0
PyJWT>=2.10.0
pyotp>=2.9.0
qrcode>=7.4.2
bcrypt>=4.2.0
Flask>=3.0.0,<4
Flask-Cors>=4.0.0,<7
PyJWT>=2.10.0,<3
pyotp>=2.9.0,<3
qrcode>=7.4.2,<9
bcrypt>=4.2.0,<6
+3
View File
@@ -37,6 +37,9 @@ def main(argv=None):
if st.too_new:
raise migrations._too_new_error(st)
print(f"Database: {db_path}" + ("" if st.exists else " (does not exist yet)"))
if not st.exists and not args.db:
print("Hint: the default database was used; for an installed system set OVPMON_PROFILER_DB_PATH "
"(see /etc/ovpmon/env) or pass --db PATH")
if args.check:
print(f"Schema version: {st.current} (latest known: {migrations.latest_version()})")
if not st.pending:
+4 -2
View File
@@ -1,5 +1,7 @@
fastapi
uvicorn
fastapi==0.143.3
starlette==1.8.0
uvicorn==0.54.0
pydantic==2.14.1
sqlalchemy
psutil
python-multipart
+3 -1
View File
@@ -1,3 +1,5 @@
from typing import Literal, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from database import get_db
@@ -13,7 +15,7 @@ router = APIRouter(dependencies=[Depends(verify_token)])
@router.get("/config", response_model=ConfigResponse)
def get_config(
section: str = Query(None, enum=["server", "pki"]),
section: Optional[Literal["server", "pki"]] = Query(None),
db: Session = Depends(get_db)
):
response = ConfigResponse()
+21
View File
@@ -0,0 +1,21 @@
import os
import tempfile
# The DB path must be set before database.py is imported (via main)
_tmp = tempfile.TemporaryDirectory()
os.environ["OVPMON_PROFILER_DB_PATH"] = os.path.join(_tmp.name, "test.db")
from fastapi.testclient import TestClient
from main import app
from utils.auth import verify_token
app.dependency_overrides[verify_token] = lambda: {"sub": "test"}
client = TestClient(app)
def test_config_section_values():
r = client.get("/api/config", params={"section": "server"})
assert r.status_code == 200 and r.json()["server"] and not r.json().get("pki")
assert client.get("/api/config", params={"section": "pki"}).status_code == 200
assert client.get("/api/config").status_code == 200
assert client.get("/api/config", params={"section": "bogus"}).status_code == 422
+14 -20
View File
@@ -1,33 +1,27 @@
import os
import tempfile
# The DB path must be set before database.py is imported (via main)
_tmp = tempfile.TemporaryDirectory()
os.environ["OVPMON_PROFILER_DB_PATH"] = os.path.join(_tmp.name, "test.db")
from fastapi.testclient import TestClient
from main import app
import sys
import os
# Add project root to sys.path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from utils.auth import verify_token
app.dependency_overrides[verify_token] = lambda: {"sub": "test"}
client = TestClient(app)
def test_get_stats():
response = client.get("/server/process/stats")
print(f"Stats response status: {response.status_code}")
print(f"Stats response body: {response.json()}")
response = client.get("/api/server/process/stats")
assert response.status_code == 200
data = response.json()
assert "pid" in data
assert "cpu_percent" in data
assert "memory_mb" in data
def test_control_invalid():
response = client.post("/server/process/invalid_action")
print(f"Invalid action response: {response.status_code}")
assert response.status_code == 400
if __name__ == "__main__":
print("Running API tests...")
try:
test_get_stats()
test_control_invalid()
print("Tests passed!")
except Exception as e:
print(f"Tests failed: {e}")
def test_control_invalid():
response = client.post("/api/server/process/invalid_action")
assert response.status_code == 400
@@ -0,0 +1,36 @@
# Суммаризация: доработки по итогам обновления ПРОД (2026-11-12)
План: [2026-11-12_Prod_Upgrade_Fixes_PLAN.md](2026-11-12_Prod_Upgrade_Fixes_PLAN.md). Источник: `prod_upgrade_findings.md`.
## Что сделано
| Шаг | Изменение | Файлы |
|-----|-----------|-------|
| 1 | `Query(None, enum=[...])` → `Optional[Literal["server", "pki"]] = Query(None)`; тест значений параметра (200 / 422) | `APP_PROFILER/routers/system.py`, `APP_PROFILER/test_config_section.py` |
| 2 | Закреплены `fastapi==0.143.3`, `starlette==1.8.0`, `uvicorn==0.54.0`, `pydantic==2.14.1`; в `APP_CORE` добавлены верхние границы по мажору | `APP_PROFILER/requirements.txt`, `APP_CORE/requirements.txt` |
| 3 | При отказе `wait_http` выводится лог связанных сервисов (API → свой сервис, nginx-проверки → все) | `deploy/native/lib.sh` |
| 4 | `OLD_VERSION`: `deploy.state` → `<prefix>/VERSION` → `unknown` | `deploy/native/update.sh` |
| 5 | `migrate.py`: подсказка `Hint:` про `OVPMON_*_DB_PATH`, если БД не найдена и `--db` не задан; коды возврата не менялись | `APP_CORE/migrate.py`, `APP_PROFILER/migrate.py` |
| 6 | Документация: `--source --no-pull`, фиксация зависимостей, `PIP_CONSTRAINT` | `DOCS/Deployment/System_Services/Operations.md`, `README.md`, `DOCS/Changes/README.md` |
| + | Починены два устаревших теста `test_server_process.py` (см. ниже) | `APP_PROFILER/test_server_process.py` |
## Проверка (ревью после субагента)
- Дифф сверен с планом: все шаги выполнены, лишних изменений нет. Имена переменных БД сверены с `APP_CORE/db.py` и `install.sh`.
- `bash -n` для `lib.sh` и `update.sh`: без ошибок.
- Тесты в `venv` проекта: `APP_CORE` 19 passed; `APP_PROFILER` 25 passed (после правки ниже).
- Тесты `APP_PROFILER` в чистом окружении с закреплённым набором (fastapi 0.143.3, starlette 1.8.0, uvicorn 0.54.0, pydantic 2.14.1): те же результаты до правки тестов. Закреплённый набор ставится и работает.
## Починка двух падавших тестов
`test_server_process.py::test_get_stats` и `::test_control_invalid` падали с 404 и до нашего изменения. Причина в самих тестах: они ходили на `/server/process/...` без префикса `/api` (роутер подключён с ним с первого коммита) и без подмены `verify_token` (иначе 401). Приложение работает правильно (на `/api/...` с токеном: 200 и 400). Исправлено: добавлен префикс `/api`, подмена `verify_token` и временная БД по образцу `test_pki_guard.py`; убран мёртвый блок `__main__` и `print`. Тест `stats` проверяет только форму ответа.
## Не проверено
- Вывод лога сервиса при реальном отказе health-check и расчёт `OLD_VERSION` на хосте с `deploy.state`: проверены только синтаксис и чтение кода, на живой установке не запускались.
- Верхние границы в `APP_CORE/requirements.txt` (`Flask-Cors<7`, `qrcode<9`, `bcrypt<6`) выбраны по текущим мажорам; сверить с набором на ПРОД.
## Вне объёма
- Команда «показать diff и применить» для ручных установок.
- Расследование повторов `Client disconnected` в логе gatherer.
@@ -0,0 +1,36 @@
# План: доработки по результатам обновления ПРОД (2026-11-12)
Источник: `prod_upgrade_findings.md`. Статус: **ожидает утверждения**.
## Проверка находок по коду
| # | Находка | Статус в коде | Решение |
|---|---------|---------------|---------|
| 1 | `Query(..., enum=...)` падает на новом FastAPI; зависимости без версий | Подтверждено: единственное место `APP_PROFILER/routers/system.py:16`; `APP_PROFILER/requirements.txt` без версий, `APP_CORE` только `>=` | Исправить |
| 2 | Health-check не показывает причину отказа | Лог выводится только если сервис не `active`; при ошибке HTTP (`wait_http`) лога нет | Исправить |
| 3 | `OLD_VERSION == NEW_VERSION` в итоге | `OLD_VERSION` берётся из `$PREFIX/VERSION`, а не из `deploy.state` | Исправить + описать режим `--source --no-pull` в документации |
| 4a | `migrate.py --check` код 2 без окружения | Не ошибка: код 2 = «есть неприменённые миграции» (БД по умолчанию не существует) | Только понятное сообщение, когда БД не найдена |
| 4b | Нужен GNU tar | Уже есть: `check_gnu_tar` в `update.sh:271` | Не требуется |
| 4c | Ручная установка: diff шаблонов | Отдельная функция (новая команда) | Вне объёма, отдельное изменение |
| 4d | Повтор `Client disconnected` каждые ~20 с | Не расследовалось | Вне объёма, отдельное расследование |
## Шаги
1. **Совместимость профайлера.** `routers/system.py`: `Query(None, enum=[...])` → `Literal["server", "pki"]` (с сохранением значения по умолчанию `None`). Один тест на значения параметра (допустимое / недопустимое → 422).
2. **Фиксация зависимостей.**
- `APP_PROFILER/requirements.txt`: `fastapi==0.143.3`, `starlette==1.8.0`, `uvicorn==0.54.0`, `pydantic==2.14.1` (рабочий набор с ПРОД); остальные пакеты без изменений.
- `APP_CORE/requirements.txt`: добавить верхние границы по мажорной версии (`Flask>=3.0.0,<4` и т. д.).
- Прогнать тесты в `venv` на зафиксированном наборе.
3. **Диагностика health-check** (`deploy/native/lib.sh`): при отказе `wait_http` выводить `show_service_log` для сервиса, к которому относится проверка (monitoring API → `ovpmon-api`, profiler API → `ovpmon-profiler`; для nginx-проверок — все сервисы).
4. **Версия «до»** (`deploy/native/update.sh`): `OLD_VERSION` брать из `OVPMON_VERSION` в `deploy.state`, при отсутствии — из `$PREFIX/VERSION`.
5. **`migrate.py`** (оба компонента): если БД не существует и `--db` не задан, добавить в вывод подсказку про `OVPMON_*_DB_PATH` / `/etc/ovpmon/env`. Код возврата не меняется.
6. **Документация.** В `DOCS/Deployment` описать режим `--source --no-pull` (состояние git-каталога установки, `git reset --hard origin/main` с сохранением живого `config.ini`), фиксацию зависимостей и `PIP_CONSTRAINT`. Обновить `README.md` и `DOCS/Changes/README.md`.
## Исполнение
Код пишет субагент (Sonnet 5.5, Medium Effort) после утверждения плана. По завершении — файл `2026-11-12_Prod_Upgrade_Fixes.md` (суммаризация).
## Риски
- Закреплённые версии устареют: обновлять осознанно, проверкой тестами. Для Docker-образов набор тот же, пересборка подтянет его.
- Изменение `Literal` меняет схему OpenAPI (enum остаётся, формат корректнее).
+1
View File
@@ -30,3 +30,4 @@ Every change has a plan (`*_PLAN.md`) before it and a summary of what was done a
| 2026-10-07 | Backup: бейджи Type, Status и Last result в таблице Destinations выровнены по верхнему краю строки (`align-top`), дата остаётся под бейджем | [plan](2026-10-07_Backup_Badges_Align_PLAN.md) · [change](2026-10-07_Backup_Badges_Align.md) |
| 2026-10-07 | Скорость (Mbps) на графиках за период больше суток: средняя скорость корзины из байтов агрегатных таблиц вместо нулей (история клиента и Analytics), подписи «RX/TX Mbps (avg)» | [plan](2026-10-07_Aggregated_Speed_PLAN.md) · [change](2026-10-07_Aggregated_Speed.md) |
| 2026-11-12 | Clients: несколько сессий одного пользователя видны в UI: бейдж «×N», «N devices» вместо адреса, раскрывающийся список сессий, KPI Active Sessions; `/api/v1/stats` отдаёт `sessions_count` и `sessions` | [plan](2026-11-12_Multi_Session_UI_PLAN.md) · [change](2026-11-12_Multi_Session_UI.md) |
| 2026-11-12 | Доработки по итогам обновления ПРОД: `Literal` вместо `Query(enum=)` в профайлере (совместимость с новым FastAPI), фиксация зависимостей, лог сервиса при отказе health-check, версия «до» из `deploy.state`, подсказка в `migrate.py`, документация `--source --no-pull` | [plan](2026-11-12_Prod_Upgrade_Fixes_PLAN.md) · [change](2026-11-12_Prod_Upgrade_Fixes.md) |
@@ -102,6 +102,18 @@ How the code is restored: the current (new or half-swapped) code directories are
`update.sh --rollback` does the same by hand from the newest `COMPLETE` backup after a confirmation, with one difference: PKI and client profiles come from the backup too (one consistent set with the databases), and the current state is saved first to `<time>-pre-restore`. Use it when an update succeeded but the new version misbehaves. Data created after that backup is lost (it is in the `-pre-restore` copy).
## Updating with `--source ... --no-pull` (install directory is a git checkout)
When the install directory is a git checkout and the new version is brought in by hand (`--source <checkout> --no-pull`), keep in mind:
- `--no-pull` skips `git pull`: the sources must already be at the wanted commit. `deploy.state` records the version that was installed by the scripts; the git checkout of the install directory can differ from it (for example after a manual `git pull` or local commits). The "before" version in the update log is taken from `OVPMON_VERSION` in `deploy.state`, then from `<prefix>/VERSION`.
- To bring a diverged checkout to the published state: `git fetch origin && git reset --hard origin/main`. This discards local changes of tracked files, including the **live `config.ini`** of both components. Save them first (`cp APP_CORE/config.ini APP_PROFILER/config.ini` to a safe place) and put them back after the reset; the update keeps `config.ini` and writes the shipped one as `config.ini.dist` when it differs.
- The update runs the migrations as a separate step; `python migrate.py --check` outside the service environment looks at the default database path, which may not exist (exit code 2 = pending migrations). Load `/etc/ovpmon/env` first or pass `--db PATH` (variables `OVPMON_OPENVPN_MONITOR_DB_PATH` and `OVPMON_PROFILER_DB_PATH`).
### Dependency versions
`APP_PROFILER/requirements.txt` pins `fastapi`, `starlette`, `uvicorn` and `pydantic` to the tested set (an unpinned install pulled a newer FastAPI that broke the API); `APP_CORE/requirements.txt` has an upper bound by major version for each package. Update the pins deliberately and run the tests on the new set. To hold back any package without editing the files, give `pip` a constraints file: `PIP_CONSTRAINT=/etc/ovpmon/constraints.txt deploy/native/update.sh ...` (the variable is read by every `pip install` of the scripts, the environment is inherited).
## Existing installations (adoption)
A host that was set up by hand (the layout of the old guide: code in `/opt/OpenVPN-Monitoring-Simple`, `/etc/ovpmon/env`, init scripts or units, helper and doas rules) can be updated with `update.sh`: it has no state file, so it is adopted and recorded after the first successful update. Files that these scripts do not manage are **left as they are**: init scripts, units, an nginx site and a doas file that do not carry the marker line `managed by ovpmon deploy/native` and differ from the shipped ones are only reported. The helper is replaced (the new one behaves like the old one without `helper.conf`), `helper.conf` is written when missing, and `OVPMON_RUNTIME`, `OVPMON_OPENVPN_SERVICE` and `OVPMON_OPENVPN_CONFIG` are added to the environment file only when absent. If the install directory is a git checkout (the source is the install directory), `git pull` changes the live files, therefore a rollback is armed from phase 2.
+2
View File
@@ -23,6 +23,8 @@ Nginx is the only public entry point. More: [Overview](DOCS/General/Overview.md)
2. The script prints the URL and the **administrator password once** (no default account exists).
3. Follow [First steps](DOCS/Deployment/First_Steps.md): secure the account, initialize the PKI, configure and start the VPN server, create the first client.
Update notes (2026-11-12): profiler dependencies are pinned (`fastapi`, `starlette`, `uvicorn`, `pydantic`), the health check prints the service log on failure, `update.sh` takes the "before" version from `deploy.state`, `migrate.py` hints at `OVPMON_*_DB_PATH`; `--source --no-pull` and `PIP_CONSTRAINT`: [Operations](DOCS/Deployment/System_Services/Operations.md).
Optional: NAT, MSS clamping and TTL for the VPN clients on system-service hosts: `deploy/native/firewall.sh --dry-run` ([Firewall](DOCS/Deployment/System_Services/Firewall.md)).
## Documentation
+10 -7
View File
@@ -983,10 +983,12 @@ nginx_apply() { # test the configuration, reload or start nginx
# ---------------------------------------------------------------------------------------------
http_code() { curl -sk -o /dev/null -w '%{http_code}' --max-time 5 "$@" 2>/dev/null || true; }
# wait_http LABEL URL REGEX: waits until the HTTP status matches REGEX (e.g. '200' or '401|403')
# wait_http LABEL URL REGEX [SERVICE...]: waits until the HTTP status matches REGEX (e.g. '200' or '401|403').
# On failure the log of the given services is shown (to find the reason)
wait_http() {
local label url re w code
local label url re w code s
label="$1"; url="$2"; re="$3"
shift 3 || true
w=0
while :; do
code=$(http_code "$url")
@@ -996,6 +998,7 @@ wait_http() {
fi
if [ "$w" -ge "$HEALTH_TIMEOUT" ]; then
log " $label: no good answer after ${HEALTH_TIMEOUT}s (last HTTP status '$code', wanted $re): $url" >&2
for s in "$@"; do show_service_log "$s"; done
return 1
fi
sleep 2
@@ -1012,12 +1015,12 @@ health_check() {
if svc_active "$s"; then log " $s: $(svc_state_word "$s")"; else log " $s: NOT running" >&2; show_service_log "$s"; bad=1; fi
done
[ "$bad" = 0 ] || return 1
wait_http "monitoring API" "http://127.0.0.1:5001/" '[1-5][0-9][0-9]' || bad=1
wait_http "profiler API" "http://127.0.0.1:8000/" '200' || bad=1
wait_http "monitoring API" "http://127.0.0.1:5001/" '[1-5][0-9][0-9]' ovpmon-api || bad=1
wait_http "profiler API" "http://127.0.0.1:8000/" '200' ovpmon-profiler || bad=1
if [ -n "${1:-}" ]; then
wait_http "UI (nginx)" "https://127.0.0.1:$1/" '200' || bad=1
wait_http "monitoring API through nginx" "https://127.0.0.1:$1/api/v1/user/me" '401|403' || bad=1
wait_http "profiler API through nginx" "https://127.0.0.1:$1/profiles-api/config" '401|403' || bad=1
wait_http "UI (nginx)" "https://127.0.0.1:$1/" '200' $SERVICES || bad=1
wait_http "monitoring API through nginx" "https://127.0.0.1:$1/api/v1/user/me" '401|403' $SERVICES || bad=1
wait_http "profiler API through nginx" "https://127.0.0.1:$1/profiles-api/config" '401|403' $SERVICES || bad=1
fi
[ "$bad" = 0 ] || return 1
log "all health checks passed"
+5 -1
View File
@@ -279,7 +279,11 @@ main() {
else
warn "no state file ($STATE_FILE): this installation was not made by install.sh; it is adopted and recorded after a successful update. Files that these scripts do not manage (init scripts, nginx site, doas file) are left as they are"
fi
OLD_VERSION=$(cat "$PREFIX/VERSION" 2>/dev/null || echo "unknown")
# The version "before": deploy.state first (VERSION in a git-based install directory may already be the new one)
OLD_VERSION=""
[ ! -f "$STATE_FILE" ] || OLD_VERSION=$(state_get OVPMON_VERSION 2>/dev/null || true)
[ -n "$OLD_VERSION" ] || OLD_VERSION=$(cat "$PREFIX/VERSION" 2>/dev/null || true)
[ -n "$OLD_VERSION" ] || OLD_VERSION="unknown"
for _f in APP_CORE/openvpn_api_v3.py APP_CORE/openvpn_gatherer_v3.py APP_CORE/migrate.py APP_CORE/requirements.txt \
APP_PROFILER/main.py APP_PROFILER/migrate.py APP_PROFILER/requirements.txt \