control-api: reduce SQLite disk writes; add diagnostic mode

Disk writes:
- SQLite pragmas in DSN: wal_autocheckpoint=10000, journal_size_limit=64MB, cache_size=64MB
- migration 0013: drop redundant idx_checks_registry_cycle
- results batched: UpsertChecksIfOpen in one transaction; agent flushes every 5s and before complete
- heartbeat kept in memory, persisted on state change or every 60s; startup grace for stale sweeps

Diagnostic mode:
- POST /api/v1/admin/diagnostics/attach|detach, GET /api/v1/admin/diagnostics
- migration 0014: diagnostic_holds; validator state "diagnostic"
- held addresses are not queued, held validators skip sweeps, port release and delete

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ayurishchevandClaude Opus 5.5 committed 2026-11-03 07:01:24 +03:00
1 parent d0ab6b94f9
commit 55d383bd34
41 files changed
+1214 -94

No files matched your search

+3 -1
View File
@@ -48,7 +48,7 @@ docker compose up -d --build # весь стенд на одной
**Остальные компоненты** **Остальные компоненты**
| Компонент | Ключи | | Компонент | Ключи |
|---|---| |---|---|
| `validator-agent` | `validator_id`, `control_api_url`, `control_api_token_env` (`CONTROL_API_AGENT_TOKEN`), `poll_interval_seconds`, `self_check.*` (таймаут, `methods` — `ip_echo`/`control_api`, `ip_echo_urls`), `checks.*` (таймауты HTTPS/ICMP, число ICMP-пакетов, `https_attempts`, `https_retry_delay_seconds`, `traceroute.*`, `ssh.*`) | | `validator-agent` | `validator_id`, `control_api_url`, `control_api_token_env` (`CONTROL_API_AGENT_TOKEN`), `poll_interval_seconds`, `self_check.*` (таймаут, `methods` — `ip_echo`/`control_api`, `ip_echo_urls`), `checks.*` (таймауты HTTPS/ICMP, число ICMP-пакетов, `https_attempts`, `https_retry_delay_seconds`, `results_flush_seconds`, `traceroute.*`, `ssh.*`) |
| `prober` | `site_id`, `control_api_url`, `control_api_token_env` (`CONTROL_API_AGENT_TOKEN`), `poll_interval_seconds`, `checks.*` (таймауты TCP/ICMP, число ICMP-пакетов) | | `prober` | `site_id`, `control_api_url`, `control_api_token_env` (`CONTROL_API_AGENT_TOKEN`), `poll_interval_seconds`, `checks.*` (таймауты TCP/ICMP, число ICMP-пакетов) |
| `admin-dashboard` | `server.listen_addr` (`:8090`), `control_api.base_url`, `control_api.timeout_seconds`, `control_api.token_env` (`ADMIN_DASHBOARD_CONTROL_API_TOKEN`), `auth.username_env` / `password_env` / `session_secret_env` (`ADMIN_DASHBOARD_USERNAME` / `_PASSWORD` / `_SESSION_SECRET`), `auth.session_ttl_minutes` (480), `overview.last_completed_count` (20), `overview.poll_interval_seconds` (5) | | `admin-dashboard` | `server.listen_addr` (`:8090`), `control_api.base_url`, `control_api.timeout_seconds`, `control_api.token_env` (`ADMIN_DASHBOARD_CONTROL_API_TOKEN`), `auth.username_env` / `password_env` / `session_secret_env` (`ADMIN_DASHBOARD_USERNAME` / `_PASSWORD` / `_SESSION_SECRET`), `auth.session_ttl_minutes` (480), `overview.last_completed_count` (20), `overview.poll_interval_seconds` (5) |
@@ -212,6 +212,8 @@ scripts/run-local-e2e.sh # сквозной прог
| Дата | Веха | Документ | | Дата | Веха | Документ |
|---|---|---| |---|---|---|
| 2026-11-03 | Диагностический режим: `POST /admin/diagnostics/attach` / `detach`, `GET /admin/diagnostics` — привязка адресов к валидаторам (состояние `diagnostic`) до явной отвязки; миграция `0014` | [план](docs/changes/2026-11-03_00-28_diagnostic-mode-plan.md) · [итог](docs/changes/2026-11-03_00-28_diagnostic-mode-summary.md) · [API](docs/API.md) |
| 2026-11-03 | Меньше записи control-api на диск: прагмы SQLite (`wal_autocheckpoint`, `cache_size`), удалён лишний индекс `checks` (миграция `0013`), результаты пачкой одной транзакцией (агент — раз в `results_flush_seconds`), heartbeat в памяти с записью в БД раз в 60 с | [план](docs/changes/2026-11-03_00-19_control-api-disk-write-reduction-plan.md) · [итог](docs/changes/2026-11-03_00-19_control-api-disk-write-reduction-summary.md) |
| 2026-11-02 | Доставка `validator-agent` из реестра `artreg.rxmsk.ru/civ-agent`: валидатор скачивает готовый образ по digest вместо git-клона и сборки на хосте; скрипт публикации `scripts/publish-agent-image.sh` | [план](docs/changes/2026-11-02_23-54_ansible-agent-from-registry-plan.md) · [итог](docs/changes/2026-11-02_23-54_ansible-agent-from-registry-summary.md) · [Ansible](deploy/ansible/README.md) | | 2026-11-02 | Доставка `validator-agent` из реестра `artreg.rxmsk.ru/civ-agent`: валидатор скачивает готовый образ по digest вместо git-клона и сборки на хосте; скрипт публикации `scripts/publish-agent-image.sh` | [план](docs/changes/2026-11-02_23-54_ansible-agent-from-registry-plan.md) · [итог](docs/changes/2026-11-02_23-54_ansible-agent-from-registry-summary.md) · [Ansible](deploy/ansible/README.md) |
| 2026-11-02 | Пересобран `bin/validator-agent`; ansible-роль доставки проверяет новые переменные env-файла (предупреждение) и после запуска — наличие `traceroute` и новых параметров в конфиге агента | [план](docs/changes/2026-11-02_22-40_ansible-agent-traceroute-rollout-plan.md) · [итог](docs/changes/2026-11-02_22-40_ansible-agent-traceroute-rollout-summary.md) · [Ansible](deploy/ansible/README.md) | | 2026-11-02 | Пересобран `bin/validator-agent`; ansible-роль доставки проверяет новые переменные env-файла (предупреждение) и после запуска — наличие `traceroute` и новых параметров в конфиге агента | [план](docs/changes/2026-11-02_22-40_ansible-agent-traceroute-rollout-plan.md) · [итог](docs/changes/2026-11-02_22-40_ansible-agent-traceroute-rollout-summary.md) · [Ansible](deploy/ansible/README.md) |
| 2026-11-02 | Исходящий HTTPS: до 3 попыток на цель; при провале всех — асинхронная трассировка `traceroute -4 -n` (опрос статуса раз в 5 с), подробный вывод в журнал событий адреса (`traceroute_result`) | [план](docs/changes/2026-11-02_22-21_https-retry-traceroute-plan.md) · [итог](docs/changes/2026-11-02_22-21_https-retry-traceroute-summary.md) | | 2026-11-02 | Исходящий HTTPS: до 3 попыток на цель; при провале всех — асинхронная трассировка `traceroute -4 -n` (опрос статуса раз в 5 с), подробный вывод в журнал событий адреса (`traceroute_result`) | [план](docs/changes/2026-11-02_22-21_https-retry-traceroute-plan.md) · [итог](docs/changes/2026-11-02_22-21_https-retry-traceroute-summary.md) |
+3
View File
@@ -42,6 +42,9 @@ checks:
# Attempts per HTTPS URL (first + retries) and pause between them. # Attempts per HTTPS URL (first + retries) and pause between them.
https_attempts: 3 https_attempts: 3
https_retry_delay_seconds: 2 https_retry_delay_seconds: 2
# Check results are sent to control-api in batches this often (and always
# before the address is reported complete).
results_flush_seconds: 5
# Background traceroute (IPv4) after an HTTPS check fails on all attempts; # Background traceroute (IPv4) after an HTTPS check fails on all attempts;
# result goes to the address event log as "traceroute_result". # result goes to the address event log as "traceroute_result".
traceroute: traceroute:
+1 -1
View File
@@ -102,7 +102,7 @@ ansible-playbook playbooks/deploy-validator-agent.yml -e image_tag=pre-tracerout
`VALIDATOR_AGENT_CONTROL_API_URL`, `CONTROL_API_AGENT_TOKEN`, `VALIDATOR_AGENT_SELF_CHECK_METHODS`, `VALIDATOR_AGENT_CONTROL_API_URL`, `CONTROL_API_AGENT_TOKEN`, `VALIDATOR_AGENT_SELF_CHECK_METHODS`,
`VALIDATOR_AGENT_SELF_CHECK_TIMEOUT_SECONDS`, `VALIDATOR_AGENT_POLL_INTERVAL_SECONDS`, `VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS`, `VALIDATOR_AGENT_SELF_CHECK_TIMEOUT_SECONDS`, `VALIDATOR_AGENT_POLL_INTERVAL_SECONDS`, `VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS`,
`VALIDATOR_AGENT_ICMP_TIMEOUT_SECONDS`, `VALIDATOR_AGENT_ICMP_COUNT`, `VALIDATOR_AGENT_SSH_ENABLED`, `VALIDATOR_AGENT_SSH_TIMEOUT_SECONDS`, `VALIDATOR_AGENT_ICMP_TIMEOUT_SECONDS`, `VALIDATOR_AGENT_ICMP_COUNT`, `VALIDATOR_AGENT_SSH_ENABLED`, `VALIDATOR_AGENT_SSH_TIMEOUT_SECONDS`,
повтор HTTPS и трассировка: `VALIDATOR_AGENT_HTTPS_ATTEMPTS`, `VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS`, `VALIDATOR_AGENT_TRACEROUTE_ENABLED`, повтор HTTPS и трассировка: `VALIDATOR_AGENT_HTTPS_ATTEMPTS`, `VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS`, `VALIDATOR_AGENT_RESULTS_FLUSH_SECONDS`, `VALIDATOR_AGENT_TRACEROUTE_ENABLED`,
`VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS`, `VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS`, `VALIDATOR_AGENT_TRACEROUTE_POLL_INTERVAL_SECONDS` `VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS`, `VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS`, `VALIDATOR_AGENT_TRACEROUTE_POLL_INTERVAL_SECONDS`
(если не заданы — значения по умолчанию из entrypoint). (если не заданы — значения по умолчанию из entrypoint).
Смена только env-файла не требует изменения кода: достаточно запустить сценарий (контейнер пересоздаётся с новыми значениями). Смена только env-файла не требует изменения кода: достаточно запустить сценарий (контейнер пересоздаётся с новыми значениями).
+1
View File
@@ -25,6 +25,7 @@ VALIDATOR_AGENT_POLL_INTERVAL_SECONDS=5
VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS=10 VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS=10
VALIDATOR_AGENT_HTTPS_ATTEMPTS=3 VALIDATOR_AGENT_HTTPS_ATTEMPTS=3
VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS=2 VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS=2
VALIDATOR_AGENT_RESULTS_FLUSH_SECONDS=5
VALIDATOR_AGENT_TRACEROUTE_ENABLED=true VALIDATOR_AGENT_TRACEROUTE_ENABLED=true
VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS=90 VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS=90
VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS=30 VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS=30
@@ -58,6 +58,7 @@
new_env_vars: new_env_vars:
- VALIDATOR_AGENT_HTTPS_ATTEMPTS - VALIDATOR_AGENT_HTTPS_ATTEMPTS
- VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS - VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS
- VALIDATOR_AGENT_RESULTS_FLUSH_SECONDS
- VALIDATOR_AGENT_TRACEROUTE_ENABLED - VALIDATOR_AGENT_TRACEROUTE_ENABLED
- VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS - VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS
- VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS - VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS
+1
View File
@@ -104,6 +104,7 @@ services:
VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS: "${VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS:-10}" VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS: "${VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS:-10}"
VALIDATOR_AGENT_HTTPS_ATTEMPTS: "${VALIDATOR_AGENT_HTTPS_ATTEMPTS:-3}" VALIDATOR_AGENT_HTTPS_ATTEMPTS: "${VALIDATOR_AGENT_HTTPS_ATTEMPTS:-3}"
VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS: "${VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS:-2}" VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS: "${VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS:-2}"
VALIDATOR_AGENT_RESULTS_FLUSH_SECONDS: "${VALIDATOR_AGENT_RESULTS_FLUSH_SECONDS:-5}"
VALIDATOR_AGENT_TRACEROUTE_ENABLED: "${VALIDATOR_AGENT_TRACEROUTE_ENABLED:-true}" VALIDATOR_AGENT_TRACEROUTE_ENABLED: "${VALIDATOR_AGENT_TRACEROUTE_ENABLED:-true}"
VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS: "${VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS:-90}" VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS: "${VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS:-90}"
VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS: "${VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS:-30}" VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS: "${VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS:-30}"
@@ -10,6 +10,7 @@ export VALIDATOR_AGENT_SELF_CHECK_METHODS="${VALIDATOR_AGENT_SELF_CHECK_METHODS:
export VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS="${VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS:-10}" export VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS="${VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS:-10}"
export VALIDATOR_AGENT_HTTPS_ATTEMPTS="${VALIDATOR_AGENT_HTTPS_ATTEMPTS:-3}" export VALIDATOR_AGENT_HTTPS_ATTEMPTS="${VALIDATOR_AGENT_HTTPS_ATTEMPTS:-3}"
export VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS="${VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS:-2}" export VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS="${VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS:-2}"
export VALIDATOR_AGENT_RESULTS_FLUSH_SECONDS="${VALIDATOR_AGENT_RESULTS_FLUSH_SECONDS:-5}"
export VALIDATOR_AGENT_TRACEROUTE_ENABLED="${VALIDATOR_AGENT_TRACEROUTE_ENABLED:-true}" export VALIDATOR_AGENT_TRACEROUTE_ENABLED="${VALIDATOR_AGENT_TRACEROUTE_ENABLED:-true}"
export VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS="${VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS:-90}" export VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS="${VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS:-90}"
export VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS="${VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS:-30}" export VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS="${VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS:-30}"
@@ -23,7 +24,7 @@ export VALIDATOR_AGENT_SSH_TIMEOUT_SECONDS="${VALIDATOR_AGENT_SSH_TIMEOUT_SECOND
# NOT templated into the YAML: the binary reads them straight from this # NOT templated into the YAML: the binary reads them straight from this
# container's environment (names default in the config loader), so secrets # container's environment (names default in the config loader), so secrets
# never land in a file inside the container. # never land in a file inside the container.
envsubst '${VALIDATOR_AGENT_VALIDATOR_ID} ${VALIDATOR_AGENT_CONTROL_API_URL} ${VALIDATOR_AGENT_POLL_INTERVAL_SECONDS} ${VALIDATOR_AGENT_SELF_CHECK_TIMEOUT_SECONDS} ${VALIDATOR_AGENT_SELF_CHECK_METHODS} ${VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS} ${VALIDATOR_AGENT_HTTPS_ATTEMPTS} ${VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS} ${VALIDATOR_AGENT_TRACEROUTE_ENABLED} ${VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS} ${VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS} ${VALIDATOR_AGENT_TRACEROUTE_POLL_INTERVAL_SECONDS} ${VALIDATOR_AGENT_ICMP_TIMEOUT_SECONDS} ${VALIDATOR_AGENT_ICMP_COUNT} ${VALIDATOR_AGENT_SSH_ENABLED} ${VALIDATOR_AGENT_SSH_TIMEOUT_SECONDS}' \ envsubst '${VALIDATOR_AGENT_VALIDATOR_ID} ${VALIDATOR_AGENT_CONTROL_API_URL} ${VALIDATOR_AGENT_POLL_INTERVAL_SECONDS} ${VALIDATOR_AGENT_SELF_CHECK_TIMEOUT_SECONDS} ${VALIDATOR_AGENT_SELF_CHECK_METHODS} ${VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS} ${VALIDATOR_AGENT_HTTPS_ATTEMPTS} ${VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS} ${VALIDATOR_AGENT_RESULTS_FLUSH_SECONDS} ${VALIDATOR_AGENT_TRACEROUTE_ENABLED} ${VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS} ${VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS} ${VALIDATOR_AGENT_TRACEROUTE_POLL_INTERVAL_SECONDS} ${VALIDATOR_AGENT_ICMP_TIMEOUT_SECONDS} ${VALIDATOR_AGENT_ICMP_COUNT} ${VALIDATOR_AGENT_SSH_ENABLED} ${VALIDATOR_AGENT_SSH_TIMEOUT_SECONDS}' \
< /etc/validator-agent/validator-agent.yaml.tmpl > /etc/validator-agent/validator-agent.yaml < /etc/validator-agent/validator-agent.yaml.tmpl > /etc/validator-agent/validator-agent.yaml
exec /usr/local/bin/validator-agent -config /etc/validator-agent/validator-agent.yaml exec /usr/local/bin/validator-agent -config /etc/validator-agent/validator-agent.yaml
@@ -10,6 +10,7 @@ checks:
https_timeout_seconds: ${VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS} https_timeout_seconds: ${VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS}
https_attempts: ${VALIDATOR_AGENT_HTTPS_ATTEMPTS} https_attempts: ${VALIDATOR_AGENT_HTTPS_ATTEMPTS}
https_retry_delay_seconds: ${VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS} https_retry_delay_seconds: ${VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS}
results_flush_seconds: ${VALIDATOR_AGENT_RESULTS_FLUSH_SECONDS}
traceroute: traceroute:
enabled: ${VALIDATOR_AGENT_TRACEROUTE_ENABLED} enabled: ${VALIDATOR_AGENT_TRACEROUTE_ENABLED}
timeout_seconds: ${VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS} timeout_seconds: ${VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS}
+25
View File
@@ -999,6 +999,31 @@ curl -s -X POST "$BASE/api/v1/admin/ips" -d '{"addresses":["203.0.113.10"]}' #
curl -s -X POST "$BASE/api/v1/admin/ips/203.0.113.10/cancel" curl -s -X POST "$BASE/api/v1/admin/ips/203.0.113.10/cancel"
``` ```
## Диагностический режим
Оператор привязывает floating IP к валидатору и держит привязку, пока сам её не снимет. Адрес на диагностике не проверяется, валидатор переходит в состояние `diagnostic` и не получает адресов из очереди. Привязка хранится в БД и переживает перезапуск control-api. Все вызовы требуют admin-токен.
### `POST /api/v1/admin/diagnostics/attach`
Тело: `{"items":[{"address":"37.139.32.23","validator_id":"vkiplab-v1"},{"address":"37.139.32.53"}],"note":"трассировка TCP 443"}`.
`validator_id` необязателен: без него берётся свободный (`idle`) валидатор с портом. Ответ `200`:
`{"results":[{"address":"...","status":"attached","validator_id":"...","fip_id":"..."},{"address":"...","status":"rejected","reason":"..."}]}`.
Частичный успех допустим. Причины `rejected`: floating IP не найден; привязан к чужому порту; адрес в активной проверке
(`assigning_fip`, `awaiting_self_check`, `checking`, `aggregating`); адрес уже на диагностике; валидатор не найден или не `idle`;
свободных валидаторов нет; ошибка облака (привязка откатывается).
### `POST /api/v1/admin/diagnostics/detach`
Тело: `{"addresses":["37.139.32.23"]}` или `{"all":true}`. Floating IP отвязывается, валидатор возвращается в `idle`.
Ответ: `{"results":[{"address":"...","status":"detached","validator_id":"...","fip_id":"..."},{"address":"...","status":"rejected","reason":"..."}]}`.
Адрес, уже свободный в облаке, не ошибка. При ошибке облака привязка остаётся, вызов можно повторить.
### `GET /api/v1/admin/diagnostics`
Список удерживаемых адресов: `[{"address","validator_id","fip_id","note","created_at"}]`.
События: `diagnostic_attached`, `diagnostic_detached` (payload: `address`, `validator_id`, `fip_id`, `note`).
## Модель состояний и связь методов с ней ## Модель состояний и связь методов с ней
``` ```
@@ -0,0 +1,77 @@
# План: снижение записи control-api на диск (пункты 2–5 анализа)
## Исходные данные (замер 2026-11-03 под боевым тестом)
- База `control-api.db` занимает 530 МБ и лежит на LVM RAID1 из двух HDD (`/opt/lvraid`).
- control-api пишет около 210 КБ/с, это примерно 60% записи на RAID. На каждом HDD около 50 мелких записей в секунду, загрузка 22–25%, iowait до 15%.
- За минуту добавляется около 180 строк `checks` и 65 строк `events`, то есть примерно 50 КБ записи на строку.
- Причины:
- на каждую строку меняются 5–7 страниц таблицы и индексов;
- каждый результат пишется отдельной транзакцией;
- heartbeat 20 агентов раз в 5 с даёт 4 коммита в секунду;
- при WAL около 4 МБ перенос в базу (checkpoint) идёт почти непрерывно.
## Пункт 2. Настройки SQLite
`internal/db/db.go`:
- **`wal_autocheckpoint=10000`** (около 40 МБ WAL вместо 4 МБ). Перенос в базу идёт реже, и одна и та же «горячая» страница индекса попадает в базу один раз за перенос, а не много раз.
- **`journal_size_limit=67108864`** (64 МБ). После переноса файл WAL усекается и не растёт бесконечно.
- **`cache_size=-65536`** (64 МБ вместо 2 МБ). Меньше повторных чтений страниц через ОС, в том числе при открытом дашборде.
- Прагмы переносятся в DSN (`_pragma=...`), чтобы применяться к каждому новому соединению, а не только к первому.
- Значения — константы в коде, без новых параметров конфига.
## Пункт 3. Лишний индекс
- **Миграция `0013_drop_redundant_checks_index.sql`:** `DROP INDEX IF EXISTS idx_checks_registry_cycle`. Колонки `(registry_id, cycle_id)` уже стоят первыми в UNIQUE-индексе `checks`, и запросы по ним используют его.
- **Проверка:** перед удалением на копии боевой базы сравнить `EXPLAIN QUERY PLAN` для запросов с `registry_id=? AND cycle_id=?` до и после.
- Удаление индекса выполняется быстро, место освобождается внутри файла (размер файла не уменьшается).
## Пункт 4. Результаты пачкой
- **control-api:**
- новый метод `DB.UpsertChecksIfOpen(ctx, []Check)` записывает все результаты одного запроса в одной транзакции;
- `handleAgentResults` и `handleProberResults` переходят на него;
- логика `IfOpen` (результат после вердикта отбрасывается, событие `result_dropped`) не меняется;
- старые агенты, присылающие по одному результату, продолжают работать.
- **validator-agent:**
- результаты копятся в буфере и отправляются раз в 5 с (`checks.results_flush_seconds`, по умолчанию 5), а также перед `complete`;
- при падении агента теряется не больше 5 с результатов: недостающая проверка и так считается провалом, адрес перепроверяется;
- образ агента публикуется в `artreg` и выкатывается ролью.
## Пункт 5. Heartbeat без записи на каждый сигнал
Сейчас каждый heartbeat (агенты и проберы, раз в 5 с) обновляет строку в БД.
- В оркестраторе в памяти хранится время последнего сигнала по каждому валидатору и площадке.
- В БД heartbeat пишется только в двух случаях:
1. нужна смена состояния (`unreachable` → `idle`/`assigned`);
2. с последней записи прошло 60 с (`heartbeat_persist_seconds`, константа). Это нужно, чтобы после перезапуска было время, от которого считать.
- **Поиск зависших** (`SweepStaleHeartbeats` и `SweepStaleSiteHeartbeats`) берёт время из памяти, а если его нет — из БД. После старта control-api первые `heartbeat_timeout_seconds` поиск не выполняется: агенты успевают прислать сигнал, и никто не будет ложно помечен `unreachable`.
- **Admin API** (`/admin/validators`, `/admin/sites`) отдаёт `last_heartbeat_at` из памяти, если оно свежее. Дашборд показывает точное время, как сейчас.
- **Ответ на heartbeat неизвестного валидатора** (404) не меняется: существование проверяется чтением, без записи.
Ожидаемо коммитов от heartbeat станет примерно в 12 раз меньше (с 4/с до ~0,35/с).
## Ожидаемый эффект
- Коммитов в секунду станет в разы меньше: результаты идут пачками, heartbeat почти не пишет.
- При каждом переносе WAL в базу будет меньше случайных записей на HDD.
- Точная цифра — замер на стенде после выкатки (тем же способом: `/proc/<pid>/io`, `/proc/diskstats`).
## Тесты (минимум)
- `UpsertChecksIfOpen`: пачка из нескольких результатов записывается; результат для адреса после вердикта отбрасывается.
- Heartbeat: повторный сигнал в пределах 60 с не пишет в БД, а смена `unreachable` → `idle` пишет.
- Существующие тесты `db`, `httpapi`, `orchestrator`, `agentcore` проходят.
## Выкатка (после окончания боевого теста, по команде пользователя)
1. Резервная копия БД (`sqlite3 ... ".backup"`), прогон миграции на копии.
2. Пересборка `bin/control-api` и `bin/validator-agent`, обновление `SHA256SUMS`.
3. Образ `civ-capi` (с тегом отката) и перезапуск control-api при пустой очереди.
4. `scripts/publish-agent-image.sh` и выкатка агентов ролью. Агенты можно выкатить позже, сервер совместим со старыми.
## Риски
- WAL до 40–64 МБ: при аварийном выключении восстановление займёт чуть дольше. Данные не теряются: WAL переносится в базу при следующем открытии.
- Если control-api падает, теряется время heartbeat, хранившееся только в памяти (не больше 60 с). Отсрочка поиска зависших после старта это покрывает.
@@ -0,0 +1,24 @@
# Итог: снижение записи control-api на диск
План: [2026-11-03_00-19_control-api-disk-write-reduction-plan.md](2026-11-03_00-19_control-api-disk-write-reduction-plan.md). Реализовано вместе с [диагностическим режимом](2026-11-03_00-28_diagnostic-mode-summary.md).
## Что сделано
- **Настройки SQLite** (`internal/db/db.go`): прагмы перенесены в DSN (применяются к каждому соединению): `wal_autocheckpoint=10000`, `journal_size_limit=64 МБ`, `cache_size=64 МБ`, плюс прежние `WAL`, `synchronous=NORMAL`, `foreign_keys`, `busy_timeout`.
- **Лишний индекс**: миграция `0013_drop_redundant_checks_index.sql` удаляет `idx_checks_registry_cycle`. На копии боевой БД `EXPLAIN QUERY PLAN` всех запросов по `registry_id`/`cycle_id` после удаления использует `sqlite_autoindex_checks_1`.
- **Результаты пачкой**: `DB.UpsertChecksIfOpen` пишет все результаты запроса одной транзакцией; используют агент и пробер. Агент копит результаты и отправляет раз в `checks.results_flush_seconds` (5 с, `VALIDATOR_AGENT_RESULTS_FLUSH_SECONDS`) и перед `complete`.
- **Heartbeat** (`internal/orchestrator/heartbeat.go`): время последнего сигнала в памяти; в БД — при смене состояния или раз в 60 с. Поиск зависших берёт более позднее из памяти и БД, первые `heartbeat_timeout_seconds` после старта не выполняется. Admin API отдаёт время из памяти.
## Изменения поведения
- Пачка результатов с неизвестным `ip_id` целиком отклоняется (404), раньше результаты до него успевали записаться.
- При неудачной отправке пачки агент её теряет (как и раньше одиночный результат); недостающие проверки считаются провалом.
## Проверка
- `go build`, `go vet`, `go test ./internal/...` — без ошибок. Новые тесты: пачка результатов (с отброшенной строкой), ограничение записи heartbeat.
- Эффект на диск будет измерен на стенде после выкатки (`/proc/<pid>/io`, `/proc/diskstats`).
## Выкатка
control-api (миграции `0013`, `0014` при первом старте; перед этим резервная копия БД) и validator-agent (новый образ в artreg). Агентов можно обновить позже — сервер совместим со старыми.
@@ -0,0 +1,71 @@
# План: диагностический режим в control-api
## Цель
Оператор выбирает один или несколько floating IP, control-api привязывает их к валидаторам и держит привязку, пока оператор сам её не снимет. На валидаторе в это время можно вручную разбираться с сетью: traceroute в разных режимах, curl, tcpdump. Привязка и отвязка выполняются отдельными вызовами.
## Поведение
- Адрес на диагностике привязан к порту валидатора, проверки по нему не запускаются.
- Валидатор на диагностике переходит в новое состояние `diagnostic`. Оркестратор не выдаёт ему адреса из очереди, а агент получает пустое задание и простаивает.
- Привязка живёт до явной отвязки и переживает перезапуск control-api: хранится в БД. Автоматического таймаута нет.
- Остальные валидаторы продолжают обычную работу, в том числе автоцикл.
## API (admin-токен)
| Вызов | Что делает |
|---|---|
| `POST /api/v1/admin/diagnostics/attach` | Тело `{"items":[{"address":"37.139.32.23","validator_id":"vkiplab-v1"},{"address":"37.139.32.53"}],"note":"трассировка TCP 443"}`. `validator_id` необязателен: без него берётся свободный (`idle`) валидатор. Ответ по каждому адресу: `attached` (с валидатором) или `rejected` (с причиной). Частичный успех допустим. |
| `POST /api/v1/admin/diagnostics/detach` | Тело `{"addresses":["37.139.32.23"]}` или `{"all":true}`. Floating IP отвязывается, валидатор возвращается в `idle`. Ответ по каждому адресу. |
| `GET /api/v1/admin/diagnostics` | Список удерживаемых адресов: адрес, валидатор, `fip_id`, с какого времени, заметка. |
### Когда адрес не привязывается (`rejected`)
- floating IP не найден в проекте;
- floating IP уже привязан к чужому порту;
- адрес сейчас в активной проверке (`assigning_fip`, `awaiting_self_check`, `checking`, `aggregating`);
- адрес уже на диагностике;
- указанный валидатор не найден, занят или недоступен (не `idle`);
- свободных валидаторов не осталось.
## Реализация
1. **Миграция:** таблица `diagnostic_holds` (`address` UNIQUE, `validator_id` UNIQUE, `fip_id`, `note`, `created_at`). Номер миграции — следующий свободный на момент реализации.
2. **БД** (`internal/db`):
- захват валидатора: в одной транзакции проверяется, что он в состоянии `idle`, он переводится в `diagnostic` и создаётся запись;
- освобождение: запись удаляется, валидатор переходит в `idle`;
- список записей.
3. **Оркестратор** (`internal/orchestrator`):
- `DiagnosticAttach`:
- проверки из списка `rejected`;
- захват валидатора;
- `AssociateFloatingIP` в облаке. При ошибке захват откатывается, валидатор возвращается в `idle`;
- событие `diagnostic_attached`.
- `DiagnosticDetach`: `DisassociateFloatingIP`, освобождение валидатора, событие `diagnostic_detached`. Если в облаке адрес уже отвязан, это не ошибка: запись всё равно удаляется.
- `DiagnosticList`.
4. **Защита удерживаемых адресов от остальной логики:**
- `ClaimNextQueued` не выдаёт адрес, который на диагностике. Если автоцикл поставит его в очередь, он дождётся отвязки.
- `releaseValidatorPorts` (вызывается из «очистить всё», удаления и отмены адресов, в том числе в автоцикле) не трогает порты валидаторов в состоянии `diagnostic`.
- `SweepStaleHeartbeats` не переводит валидатор `diagnostic` в `unreachable`. Иначе первый же heartbeat вернул бы его в `idle`, и привязка потерялась бы.
- `ReconcileValidators` и `Heartbeat` состояние `diagnostic` уже не меняют. Это нужно проверить тестом.
- Скан floating IP уже пропускает адреса, привязанные к какому-либо порту: удерживаемый адрес в очередь не попадёт.
5. **HTTP** (`internal/httpapi`): три обработчика, маршруты с доступом `accessAdmin`, описание в `docs/API.md`.
## Не входит в эту доработку
- Раздел в admin-dashboard (выбор адресов, кнопки «привязать» и «отвязать»). Это можно сделать следующим шагом.
- Запуск диагностических команд на валидаторе через control-api. Команды выполняются вручную по SSH.
## Тесты (минимум)
- Привязка и отвязка на mock-облаке: валидатор `idle` → `diagnostic` → `idle`, адрес не выдаётся из очереди, пока привязан.
- Отказ: занятый валидатор, адрес в активной проверке, ошибка облака (захват откатывается).
- `SweepStaleHeartbeats` и `releaseValidatorPorts` не трогают валидатор `diagnostic`.
## Выкатка
Пересборка `bin/control-api` и образа `civ-capi`, перезапуск при пустой очереди после окончания боевого теста, по команде пользователя. Агента и проберы менять не нужно.
## Связь с другими планами
План снижения записи на диск (`2026-11-03_00-19_control-api-disk-write-reduction-plan.md`) тоже добавляет миграцию и меняет heartbeat. Если делать оба, номера миграций и правки `SweepStaleHeartbeats` согласуются при реализации.
@@ -0,0 +1,32 @@
# Итог: диагностический режим в control-api
План: [2026-11-03_00-28_diagnostic-mode-plan.md](2026-11-03_00-28_diagnostic-mode-plan.md)
## Что сделано
- **API** (admin-токен, описание в `docs/API.md`):
- `POST /api/v1/admin/diagnostics/attach` — привязать адреса к валидаторам (указанным или свободным), ответ по каждому адресу: `attached` / `rejected` с причиной;
- `POST /api/v1/admin/diagnostics/detach` — отвязать адреса или все (`{"all":true}`);
- `GET /api/v1/admin/diagnostics` — удерживаемые адреса.
- **Хранение**: миграция `0014_diagnostic_holds.sql`; привязка переживает перезапуск control-api, снимается только явно.
- **Валидатор** на диагностике — в состоянии `diagnostic`: заданий не получает, не переводится в `unreachable`, его порты не освобождаются при «очистить всё» и удалении адресов, удалить такой валидатор нельзя.
- **Адрес** на диагностике не выдаётся из очереди.
- **Отказы**: нет floating IP, привязан к чужому порту, адрес в активной проверке, уже на диагностике, валидатор не найден/занят, нет свободных валидаторов. Ошибка облака откатывает захват валидатора.
- **События** `diagnostic_attached` / `diagnostic_detached`; в дашборде — бейдж состояния `diagnostic`.
## Проверка
`go test ./internal/...` — без ошибок. Новые тесты: привязка/отвязка (адрес не выдаётся из очереди, heartbeat и сверка не меняют `diagnostic`), отказы, откат при ошибке облака, поиск зависших и освобождение портов не трогают такой валидатор.
## Пример
```bash
curl -H "Authorization: Bearer $ADMIN" -X POST http://localhost:8081/api/v1/admin/diagnostics/attach \
-d '{"items":[{"address":"37.139.32.23","validator_id":"vkiplab-v1"}],"note":"traceroute TCP 443"}'
curl -H "Authorization: Bearer $ADMIN" -X POST http://localhost:8081/api/v1/admin/diagnostics/detach \
-d '{"addresses":["37.139.32.23"]}'
```
## Не входит
Раздел в admin-dashboard для привязки/отвязки.
+41 -5
View File
@@ -402,8 +402,42 @@ func fetchIPEcho(ctx context.Context, url string) (string, error) {
} }
func (a *Agent) runChecks(ctx context.Context, assignment assignmentResp) { func (a *Agent) runChecks(ctx context.Context, assignment assignmentResp) {
var results []checkResultDTO
var traces sync.WaitGroup var traces sync.WaitGroup
// Results are sent in batches every results_flush_seconds and before
// complete, instead of one request (and one control-api commit) each.
var (
bufMu sync.Mutex
buf []checkResultDTO
)
flush := func() {
bufMu.Lock()
batch := buf
buf = nil
bufMu.Unlock()
if len(batch) > 0 {
a.postResults(ctx, batch)
}
}
stopFlush := make(chan struct{})
var flusher sync.WaitGroup
flusher.Add(1)
go func() {
defer flusher.Done()
every := time.Duration(a.cfg.Checks.ResultsFlushSeconds) * time.Second
if every <= 0 {
every = 5 * time.Second
}
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-t.C:
flush()
case <-stopFlush:
return
}
}
}()
for _, ct := range assignment.CheckConfig { for _, ct := range assignment.CheckConfig {
for _, target := range ct.Targets { for _, target := range ct.Targets {
var fn func(context.Context) checkrunner.Result var fn func(context.Context) checkrunner.Result
@@ -432,14 +466,13 @@ func (a *Agent) runChecks(ctx context.Context, assignment assignmentResp) {
// loopback-only local e2e harness) would collide on the // loopback-only local e2e harness) would collide on the
// checks table's UNIQUE(ip_id, attempt, source, type, // checks table's UNIQUE(ip_id, attempt, source, type,
// target) key and silently overwrite each other. // target) key and silently overwrite each other.
results = append(results, checkResultDTO{ bufMu.Lock()
buf = append(buf, checkResultDTO{
IPID: assignment.IPID, CheckType: res.CheckType, Target: target, IPID: assignment.IPID, CheckType: res.CheckType, Target: target,
Success: res.Success, LatencyMS: res.LatencyMS, Detail: res.Detail, Success: res.Success, LatencyMS: res.LatencyMS, Detail: res.Detail,
CheckedAt: res.CheckedAt.Format(time.RFC3339Nano), CheckedAt: res.CheckedAt.Format(time.RFC3339Nano),
}) })
// Report progressively rather than batching until the end, so bufMu.Unlock()
// a crash mid-run doesn't lose already-completed check results.
a.postResults(ctx, []checkResultDTO{results[len(results)-1]})
if ct.Type == "https" && !res.Success && a.cfg.Checks.Traceroute.IsEnabled() { if ct.Type == "https" && !res.Success && a.cfg.Checks.Traceroute.IsEnabled() {
traces.Add(1) traces.Add(1)
@@ -455,6 +488,9 @@ func (a *Agent) runChecks(ctx context.Context, assignment assignmentResp) {
// detaches the floating IP and the trace would leave from another address. // detaches the floating IP and the trace would leave from another address.
traces.Wait() traces.Wait()
close(stopFlush)
flusher.Wait()
flush()
a.postComplete(ctx, assignment.IPID) a.postComplete(ctx, assignment.IPID)
a.lastHandledIPID = assignment.IPID a.lastHandledIPID = assignment.IPID
} }
+7
View File
@@ -270,6 +270,10 @@ type AgentChecks struct {
HTTPSAttempts int `yaml:"https_attempts"` HTTPSAttempts int `yaml:"https_attempts"`
HTTPSRetryDelaySeconds int `yaml:"https_retry_delay_seconds"` HTTPSRetryDelaySeconds int `yaml:"https_retry_delay_seconds"`
// ResultsFlushSeconds is how often buffered check results are sent to
// control-api (they are always sent before the completion signal).
ResultsFlushSeconds int `yaml:"results_flush_seconds"`
Traceroute TracerouteCfg `yaml:"traceroute"` Traceroute TracerouteCfg `yaml:"traceroute"`
} }
@@ -330,6 +334,9 @@ func LoadValidatorAgent(path string) (*ValidatorAgent, error) {
if c.Checks.HTTPSRetryDelaySeconds <= 0 { if c.Checks.HTTPSRetryDelaySeconds <= 0 {
c.Checks.HTTPSRetryDelaySeconds = 2 c.Checks.HTTPSRetryDelaySeconds = 2
} }
if c.Checks.ResultsFlushSeconds <= 0 {
c.Checks.ResultsFlushSeconds = 5
}
if c.Checks.Traceroute.TimeoutSeconds <= 0 { if c.Checks.Traceroute.TimeoutSeconds <= 0 {
c.Checks.Traceroute.TimeoutSeconds = 90 c.Checks.Traceroute.TimeoutSeconds = 90
} }
+2
View File
@@ -60,6 +60,8 @@ func validatorBadge(state string) Badge {
return Badge{"pill-danger", "unreachable"} return Badge{"pill-danger", "unreachable"}
case "unregistered": case "unregistered":
return Badge{"pill-neutral", "unregistered"} return Badge{"pill-neutral", "unregistered"}
case "diagnostic":
return Badge{"pill-warning", "diagnostic"}
default: default:
return Badge{"pill-info", state} // assigned / checking return Badge{"pill-info", state} // assigned / checking
} }
+35 -12
View File
@@ -8,6 +8,7 @@ import (
"database/sql" "database/sql"
_ "embed" _ "embed"
"fmt" "fmt"
"strings"
"time" "time"
_ "modernc.org/sqlite" _ "modernc.org/sqlite"
@@ -49,6 +50,12 @@ var checkRunsSchema string
//go:embed migrations/0012_self_check_failures.sql //go:embed migrations/0012_self_check_failures.sql
var selfCheckFailuresSchema string var selfCheckFailuresSchema string
//go:embed migrations/0013_drop_redundant_checks_index.sql
var dropChecksIndexSchema string
//go:embed migrations/0014_diagnostic_holds.sql
var diagnosticHoldsSchema string
// migrations is the ordered list of schema versions. Each entry's SQL is // migrations is the ordered list of schema versions. Each entry's SQL is
// applied, in order, for any version greater than the database's current // applied, in order, for any version greater than the database's current
// PRAGMA user_version — so a fresh database walks the whole list and an // PRAGMA user_version — so a fresh database walks the whole list and an
@@ -69,6 +76,28 @@ var migrations = []struct {
{10, verdictIntegritySchema}, {10, verdictIntegritySchema},
{11, checkRunsSchema}, {11, checkRunsSchema},
{12, selfCheckFailuresSchema}, {12, selfCheckFailuresSchema},
{13, dropChecksIndexSchema},
{14, diagnosticHoldsSchema},
}
// connPragmas are applied to every new connection. A larger WAL checkpoint
// interval and cache cut random writes on the HDD-backed volume.
var connPragmas = []string{
"busy_timeout(5000)",
"journal_mode(WAL)",
"synchronous(NORMAL)",
"foreign_keys(ON)",
"wal_autocheckpoint(10000)",
"journal_size_limit(67108864)",
"cache_size(-65536)",
}
func dsn(path string) string {
q := make([]string, len(connPragmas))
for i, p := range connPragmas {
q[i] = "_pragma=" + p
}
return path + "?" + strings.Join(q, "&")
} }
type DB struct { type DB struct {
@@ -79,24 +108,18 @@ type DB struct {
// pragmas suited to a single-writer WAL workload, and runs any pending // pragmas suited to a single-writer WAL workload, and runs any pending
// schema migrations. // schema migrations.
func Open(ctx context.Context, path string) (*DB, error) { func Open(ctx context.Context, path string) (*DB, error) {
sqlDB, err := sql.Open("sqlite", path+"?_pragma=busy_timeout(5000)") sqlDB, err := sql.Open("sqlite", dsn(path))
if err != nil { if err != nil {
return nil, fmt.Errorf("open sqlite: %w", err) return nil, fmt.Errorf("open sqlite: %w", err)
} }
// Control API is the sole writer; one connection avoids SQLITE_BUSY // Control API is the sole writer; one connection avoids SQLITE_BUSY
// entirely for writes while still allowing concurrent reads via WAL. // entirely for writes while still allowing concurrent reads via WAL.
sqlDB.SetMaxOpenConns(1) sqlDB.SetMaxOpenConns(1)
// Pragmas are in the DSN, so they apply to every new connection; this
for _, pragma := range []string{ // ping opens the first one and reports a bad pragma early.
"PRAGMA journal_mode=WAL", if err := sqlDB.PingContext(ctx); err != nil {
"PRAGMA synchronous=NORMAL", sqlDB.Close()
"PRAGMA foreign_keys=ON", return nil, fmt.Errorf("open sqlite: %w", err)
"PRAGMA busy_timeout=5000",
} {
if _, err := sqlDB.ExecContext(ctx, pragma); err != nil {
sqlDB.Close()
return nil, fmt.Errorf("apply pragma %q: %w", pragma, err)
}
} }
d := &DB{DB: sqlDB} d := &DB{DB: sqlDB}
@@ -0,0 +1,4 @@
-- (registry_id, cycle_id) are the first columns of the UNIQUE index on
-- checks, which serves every lookup by them; the extra index only costs
-- writes (see docs/changes/2026-11-03_00-19_control-api-disk-write-reduction-plan.md).
DROP INDEX IF EXISTS idx_checks_registry_cycle;
@@ -0,0 +1,11 @@
-- Addresses held on a validator for manual diagnostics (see
-- docs/changes/2026-11-03_00-28_diagnostic-mode-plan.md). A hold lives until
-- an explicit detach. No foreign keys on purpose, like the other history tables.
CREATE TABLE diagnostic_holds (
id INTEGER PRIMARY KEY AUTOINCREMENT,
address TEXT NOT NULL UNIQUE,
validator_id TEXT NOT NULL UNIQUE,
fip_id TEXT NOT NULL DEFAULT '',
note TEXT NOT NULL DEFAULT '',
created_at TIMESTAMP NOT NULL
);
+3
View File
@@ -14,6 +14,9 @@ const (
ValidatorAssigned = "assigned" ValidatorAssigned = "assigned"
ValidatorChecking = "checking" ValidatorChecking = "checking"
ValidatorUnreachable = "unreachable" ValidatorUnreachable = "unreachable"
// ValidatorDiagnostic: the validator holds an address for manual
// diagnostics (see diagnostic_holds) and takes no queue work.
ValidatorDiagnostic = "diagnostic"
// Site (prober) availability states — no assigned/checking equivalent, // Site (prober) availability states — no assigned/checking equivalent,
// since a prober isn't bound to one IP at a time. // since a prober isn't bound to one IP at a time.
+33 -1
View File
@@ -28,8 +28,40 @@ func (d *DB) UpsertCheck(ctx context.Context, c Check) error {
// false (and writes nothing) when the result was dropped. The state test and // false (and writes nothing) when the result was dropped. The state test and
// the write are one statement, so they cannot interleave with SetAggregating. // the write are one statement, so they cannot interleave with SetAggregating.
func (d *DB) UpsertCheckIfOpen(ctx context.Context, c Check) (bool, error) { func (d *DB) UpsertCheckIfOpen(ctx context.Context, c Check) (bool, error) {
return upsertCheckIfOpen(ctx, d, c)
}
// UpsertChecksIfOpen stores a batch of results in one transaction, applying
// the UpsertCheckIfOpen rule to each. written[i] reports whether checks[i] was
// stored (false: dropped).
func (d *DB) UpsertChecksIfOpen(ctx context.Context, checks []Check) ([]bool, error) {
written := make([]bool, len(checks))
if len(checks) == 0 {
return written, nil
}
tx, err := d.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
defer tx.Rollback()
for i, c := range checks {
if written[i], err = upsertCheckIfOpen(ctx, tx, c); err != nil {
return nil, err
}
}
if err := tx.Commit(); err != nil {
return nil, err
}
return written, nil
}
type execer interface {
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}
func upsertCheckIfOpen(ctx context.Context, x execer, c Check) (bool, error) {
now := timeToDB(Now()) now := timeToDB(Now())
res, err := d.ExecContext(ctx, ` res, err := x.ExecContext(ctx, `
INSERT INTO checks (registry_id, cycle_id, ip_id, ip_address, attempt_number, validator_id, INSERT INTO checks (registry_id, cycle_id, ip_id, ip_address, attempt_number, validator_id,
source, check_type, target, success, latency_ms, detail, checked_at, created_at, recorded_at, run_id) source, check_type, target, success, latency_ms, detail, checked_at, created_at, recorded_at, run_id)
SELECT q.registry_id, q.cycle_id, q.id, ?, q.attempt_number, COALESCE(NULLIF(?, ''), q.owner_validator_id, ''), SELECT q.registry_id, q.cycle_id, q.id, ?, q.attempt_number, COALESCE(NULLIF(?, ''), q.owner_validator_id, ''),
+112
View File
@@ -0,0 +1,112 @@
package db
import (
"context"
"database/sql"
"fmt"
"time"
)
// DiagnosticHold is an address held on a validator for manual diagnostics.
type DiagnosticHold struct {
Address string `json:"address"`
ValidatorID string `json:"validator_id"`
FIPID string `json:"fip_id"`
Note string `json:"note"`
CreatedAt time.Time `json:"created_at"`
}
// ClaimDiagnostic moves an idle validator to the diagnostic state and records
// the hold, in one transaction. ErrNotFound: no such validator; ErrBusy: the
// validator is not idle; ErrConflict: the address or validator is already held.
func (d *DB) ClaimDiagnostic(ctx context.Context, validatorID, address, fipID, note string) error {
tx, err := d.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
now := timeToDB(Now())
res, err := tx.ExecContext(ctx, `
UPDATE validators SET state=?, updated_at=?
WHERE validator_id=? AND state=? AND current_ip_id IS NULL
`, ValidatorDiagnostic, now, validatorID, ValidatorIdle)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n != 1 {
var one int
err := tx.QueryRowContext(ctx, `SELECT 1 FROM validators WHERE validator_id=?`, validatorID).Scan(&one)
if err == sql.ErrNoRows {
return fmt.Errorf("validator %q: %w", validatorID, ErrNotFound)
}
if err != nil {
return err
}
return fmt.Errorf("validator %q is not idle: %w", validatorID, ErrBusy)
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO diagnostic_holds (address, validator_id, fip_id, note, created_at) VALUES (?, ?, ?, ?, ?)
`, address, validatorID, fipID, note, now); err != nil {
return fmt.Errorf("address %q or validator %q is already held: %w", address, validatorID, ErrConflict)
}
return tx.Commit()
}
// ReleaseDiagnostic deletes the hold of an address and returns the validator
// to idle. ErrNotFound if the address is not held.
func (d *DB) ReleaseDiagnostic(ctx context.Context, address string) (*DiagnosticHold, error) {
tx, err := d.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
defer tx.Rollback()
h, err := scanHold(tx.QueryRowContext(ctx, holdSelect+` WHERE address=?`, address))
if err == sql.ErrNoRows {
return nil, fmt.Errorf("address %q is not on diagnostic: %w", address, ErrNotFound)
}
if err != nil {
return nil, err
}
if _, err := tx.ExecContext(ctx, `DELETE FROM diagnostic_holds WHERE address=?`, address); err != nil {
return nil, err
}
if _, err := tx.ExecContext(ctx, `
UPDATE validators SET state=?, updated_at=? WHERE validator_id=? AND state=?
`, ValidatorIdle, timeToDB(Now()), h.ValidatorID, ValidatorDiagnostic); err != nil {
return nil, err
}
return h, tx.Commit()
}
const holdSelect = `SELECT address, validator_id, fip_id, note, created_at FROM diagnostic_holds`
func scanHold(row rowScanner) (*DiagnosticHold, error) {
var h DiagnosticHold
var created string
if err := row.Scan(&h.Address, &h.ValidatorID, &h.FIPID, &h.Note, &created); err != nil {
return nil, err
}
var err error
if h.CreatedAt, err = dbToTime(created); err != nil {
return nil, err
}
return &h, nil
}
// ListDiagnosticHolds returns all holds, oldest first.
func (d *DB) ListDiagnosticHolds(ctx context.Context) ([]DiagnosticHold, error) {
rows, err := d.QueryContext(ctx, holdSelect+` ORDER BY id`)
if err != nil {
return nil, err
}
defer rows.Close()
out := []DiagnosticHold{}
for rows.Next() {
h, err := scanHold(rows)
if err != nil {
return nil, err
}
out = append(out, *h)
}
return out, rows.Err()
}
+3 -1
View File
@@ -86,7 +86,9 @@ func (d *DB) ClaimNextQueued(ctx context.Context, validatorID string, leaseTTL t
var item IPQueueItem var item IPQueueItem
err = tx.QueryRowContext(ctx, ` err = tx.QueryRowContext(ctx, `
SELECT q.id, q.ip_address, q.sequence, q.attempt_number, q.retry_count SELECT q.id, q.ip_address, q.sequence, q.attempt_number, q.retry_count
FROM ip_queue q WHERE q.state=? AND NOT EXISTS ( FROM ip_queue q WHERE q.state=?
AND NOT EXISTS (SELECT 1 FROM diagnostic_holds h WHERE h.address=q.ip_address)
AND NOT EXISTS (
SELECT 1 FROM ip_self_check_failures f SELECT 1 FROM ip_self_check_failures f
WHERE f.registry_id=q.registry_id AND f.validator_id=? AND f.cycle_id>=q.sc_round_start_cycle) WHERE f.registry_id=q.registry_id AND f.validator_id=? AND f.cycle_id>=q.sc_round_start_cycle)
ORDER BY q.sequence LIMIT 1 ORDER BY q.sequence LIMIT 1
+1 -1
View File
@@ -501,7 +501,7 @@ func registryLevelsQuery(ids []any, sl registrySlice) (string, []any) {
// sums: the recorded checks of each address's newest cycle (the same cycle // sums: the recorded checks of each address's newest cycle (the same cycle
// whose time is LastCheckedAt), counted per level and per check family. It // whose time is LastCheckedAt), counted per level and per check family. It
// runs one grouped query per chunk of addresses, not one per address, over // runs one grouped query per chunk of addresses, not one per address, over
// idx_checks_registry_cycle. With sl.RunID the cycle is the address's one in // the unique checks index (registry_id, cycle_id, ...). With sl.RunID the cycle is the address's one in
// that run (over idx_checks_run) and sl.Level and sl.Family leave only the // that run (over idx_checks_run) and sl.Level and sl.Family leave only the
// matching checks, so the levels and types outside them stay empty. Checks // matching checks, so the levels and types outside them stay empty. Checks
// whose source is neither egress nor an inbound site are not counted. The // whose source is neither egress nor an inbound site are not counted. The
+1 -1
View File
@@ -391,7 +391,7 @@ func TestMigration0011BuildsRunsFromExistingData(t *testing.T) {
} }
var ver int var ver int
d.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&ver) d.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&ver)
if ver != 12 { if ver != 14 {
t.Errorf("user_version = %d", ver) t.Errorf("user_version = %d", ver)
} }
} }
+2 -2
View File
@@ -353,11 +353,11 @@ func TestMigration0009Indexes(t *testing.T) {
// TestRegistryLevelsQueryUsesIndex guards against a full scan of checks: the // TestRegistryLevelsQueryUsesIndex guards against a full scan of checks: the
// per-address MAX(cycle_id) and the join back must go through // per-address MAX(cycle_id) and the join back must go through
// idx_checks_registry_cycle, the run's slice through idx_checks_run. // the unique checks index, the run's slice through idx_checks_run.
func TestRegistryLevelsQueryUsesIndex(t *testing.T) { func TestRegistryLevelsQueryUsesIndex(t *testing.T) {
d, ctx := newTestDB(t) d, ctx := newTestDB(t)
for sl, index := range map[registrySlice]string{ for sl, index := range map[registrySlice]string{
{}: "idx_checks_registry_cycle", {}: "sqlite_autoindex_checks_1",
{RunID: 1, Level: LevelIngress, Family: "tls"}: "idx_checks_run", {RunID: 1, Level: LevelIngress, Family: "tls"}: "idx_checks_run",
} { } {
q, args := registryLevelsQuery([]any{1, 2, 3}, sl) q, args := registryLevelsQuery([]any{1, 2, 3}, sl)
+7
View File
@@ -259,6 +259,13 @@ func (d *DB) DeleteValidator(ctx context.Context, validatorID string) error {
if err != nil { if err != nil {
return err return err
} }
var held int
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM diagnostic_holds WHERE validator_id=?`, validatorID).Scan(&held); err != nil {
return err
}
if held > 0 {
return fmt.Errorf("validator %q is on diagnostic: %w", validatorID, ErrBusy)
}
if currentIPID.Valid { if currentIPID.Valid {
return fmt.Errorf("validator %q owns ip_id %d: %w", validatorID, currentIPID.Int64, ErrBusy) return fmt.Errorf("validator %q owns ip_id %d: %w", validatorID, currentIPID.Int64, ErrBusy)
} }
+26 -1
View File
@@ -240,7 +240,32 @@ func TestMigration0010MarksRowsAfterVerdict(t *testing.T) {
t.Errorf("ssh: after_verdict=%d recorded=%s created=%s", a, rec, cr) t.Errorf("ssh: after_verdict=%d recorded=%s created=%s", a, rec, cr)
} }
var ver int var ver int
if err := d.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&ver); err != nil || ver != 12 { if err := d.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&ver); err != nil || ver != 14 {
t.Errorf("user_version=%d err=%v", ver, err) t.Errorf("user_version=%d err=%v", ver, err)
} }
} }
// A batch is written in one transaction; a row for a finished address is
// dropped without affecting the others.
func TestUpsertChecksIfOpenBatch(t *testing.T) {
d, ctx := newTestDB(t)
open := checkingIP(t, d, "1.2.3.4")
done := checkingIP(t, d, "5.6.7.8")
if _, err := d.ExecContext(ctx, `UPDATE ip_queue SET state='done' WHERE id=?`, done.ID); err != nil {
t.Fatal(err)
}
written, err := d.UpsertChecksIfOpen(ctx, []Check{
checkOf(open, "icmp", true), checkOf(open, "ssh", false), checkOf(done, "icmp", true),
})
if err != nil {
t.Fatal(err)
}
if len(written) != 3 || !written[0] || !written[1] || written[2] {
t.Fatalf("written = %v, want [true true false]", written)
}
var n int
d.QueryRowContext(ctx, `SELECT COUNT(*) FROM checks`).Scan(&n)
if n != 2 {
t.Fatalf("%d rows stored, want 2", n)
}
}
+2 -2
View File
@@ -97,8 +97,8 @@ func TestRouteTableIsClassified(t *testing.T) {
t.Fatalf("admin route %q is %s, want admin", rt.Pattern, rt.Access) t.Fatalf("admin route %q is %s, want admin", rt.Pattern, rt.Access)
} }
} }
if counts["admin"] != 46 || counts["agent"] != 5 || counts["open"] != 8 { if counts["admin"] != 49 || counts["agent"] != 5 || counts["open"] != 8 {
t.Fatalf("access counts = %v, want admin=46 agent=5 open=8", counts) t.Fatalf("access counts = %v, want admin=49 agent=5 open=8", counts)
} }
} }
+3
View File
@@ -203,6 +203,9 @@ func (s *Server) handleAdminValidators(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, err.Error()) writeError(w, http.StatusInternalServerError, err.Error())
return return
} }
for i := range validators {
s.Orch.OverlayValidatorHeartbeat(&validators[i])
}
writeJSON(w, http.StatusOK, validators) writeJSON(w, http.StatusOK, validators)
} }
+13 -9
View File
@@ -42,7 +42,7 @@ func (s *Server) handleAgentHeartbeat(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id") id := r.PathValue("id")
var req heartbeatRequest var req heartbeatRequest
_ = readJSON(r, &req) // heartbeat body is informational only; tolerate empty/missing _ = readJSON(r, &req) // heartbeat body is informational only; tolerate empty/missing
if err := s.DB.Heartbeat(r.Context(), id); err != nil { if err := s.Orch.ValidatorHeartbeat(r.Context(), id); err != nil {
writeError(w, http.StatusNotFound, "unknown validator: "+id) writeError(w, http.StatusNotFound, "unknown validator: "+id)
return return
} }
@@ -149,7 +149,7 @@ func (s *Server) handleAgentResults(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "invalid body: "+err.Error()) writeError(w, http.StatusBadRequest, "invalid body: "+err.Error())
return return
} }
dropped := map[int64]int{} checks := make([]db.Check, 0, len(req.Results))
for _, res := range req.Results { for _, res := range req.Results {
item, err := s.DB.GetIP(r.Context(), res.IPID) item, err := s.DB.GetIP(r.Context(), res.IPID)
if err != nil { if err != nil {
@@ -160,17 +160,21 @@ func (s *Server) handleAgentResults(w http.ResponseWriter, r *http.Request) {
if err != nil { if err != nil {
checkedAt = db.Now() checkedAt = db.Now()
} }
written, err := s.Orch.RecordCheckIfOpen(r.Context(), db.Check{ checks = append(checks, db.Check{
IPID: item.ID, IPAddress: item.IPAddress, AttemptNumber: item.AttemptNumber, IPID: item.ID, IPAddress: item.IPAddress, AttemptNumber: item.AttemptNumber,
ValidatorID: id, Source: db.SourceEgress, CheckType: res.CheckType, Target: res.Target, ValidatorID: id, Source: db.SourceEgress, CheckType: res.CheckType, Target: res.Target,
Success: res.Success, LatencyMS: res.LatencyMS, Detail: res.Detail, CheckedAt: checkedAt, Success: res.Success, LatencyMS: res.LatencyMS, Detail: res.Detail, CheckedAt: checkedAt,
}) })
if err != nil { }
writeError(w, http.StatusInternalServerError, err.Error()) written, err := s.Orch.RecordChecksIfOpen(r.Context(), checks)
return if err != nil {
} writeError(w, http.StatusInternalServerError, err.Error())
if !written { return
dropped[item.ID]++ }
dropped := map[int64]int{}
for i, ok := range written {
if !ok {
dropped[checks[i].IPID]++
} }
} }
writeJSON(w, http.StatusOK, s.reportDropped(r.Context(), "validator-agent", id, db.SourceEgress, dropped)) writeJSON(w, http.StatusOK, s.reportDropped(r.Context(), "validator-agent", id, db.SourceEgress, dropped))
+2
View File
@@ -18,6 +18,7 @@ func (s *Server) handleConfigListValidators(w http.ResponseWriter, r *http.Reque
} }
out := make([]validatorDTO, len(validators)) out := make([]validatorDTO, len(validators))
for i, v := range validators { for i, v := range validators {
s.Orch.OverlayValidatorHeartbeat(&v)
out[i] = validatorDTO{ out[i] = validatorDTO{
ValidatorID: v.ValidatorID, Hostname: v.Hostname, OSPortID: v.OSPortID, ValidatorID: v.ValidatorID, Hostname: v.Hostname, OSPortID: v.OSPortID,
State: v.State, LastHeartbeatAt: v.LastHeartbeatAt, State: v.State, LastHeartbeatAt: v.LastHeartbeatAt,
@@ -76,6 +77,7 @@ func (s *Server) handleConfigListSites(w http.ResponseWriter, r *http.Request) {
} }
out := make([]siteDTO, len(sites)) out := make([]siteDTO, len(sites))
for i, site := range sites { for i, site := range sites {
s.Orch.OverlaySiteHeartbeat(&site)
out[i] = siteDTO{ out[i] = siteDTO{
Index: site.Index, SiteID: site.SiteID, Hostname: site.Hostname, Index: site.Index, SiteID: site.SiteID, Hostname: site.Hostname,
State: site.State, LastHeartbeatAt: site.LastHeartbeatAt, State: site.State, LastHeartbeatAt: site.LastHeartbeatAt,
+1
View File
@@ -46,6 +46,7 @@ func newConfigTestHarness(t *testing.T) (*fakeClient, *db.DB, *orchestrator.Orch
log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
orch := orchestrator.New(d, mock, cfg, log) orch := orchestrator.New(d, mock, cfg, log)
orch.EndStartupGrace()
// A background scan must never outlive the database it writes to. // A background scan must never outlive the database it writes to.
t.Cleanup(func() { orch.CancelScan() }) t.Cleanup(func() { orch.CancelScan() })
srv := New(d, orch, log) srv := New(d, orch, log)
+69
View File
@@ -0,0 +1,69 @@
package httpapi
import (
"net/http"
"strings"
"cloudipvalidator/internal/orchestrator"
)
type diagnosticAttachRequest struct {
Items []struct {
Address string `json:"address"`
ValidatorID string `json:"validator_id"`
} `json:"items"`
Note string `json:"note"`
}
type diagnosticDetachRequest struct {
Addresses []string `json:"addresses"`
All bool `json:"all"`
}
type diagnosticResultsResponse struct {
Results []orchestrator.DiagnosticResult `json:"results"`
}
func (s *Server) handleAdminDiagnosticAttach(w http.ResponseWriter, r *http.Request) {
var req diagnosticAttachRequest
if err := readJSON(r, &req); err != nil {
writeError(w, http.StatusBadRequest, "invalid body: "+err.Error())
return
}
if len(req.Items) == 0 {
writeError(w, http.StatusBadRequest, "items must not be empty")
return
}
items := make([]orchestrator.DiagnosticItem, len(req.Items))
for i, it := range req.Items {
addr := strings.TrimSpace(it.Address)
if addr == "" {
writeError(w, http.StatusBadRequest, "address must not be empty")
return
}
items[i] = orchestrator.DiagnosticItem{Address: addr, ValidatorID: strings.TrimSpace(it.ValidatorID)}
}
writeJSON(w, http.StatusOK, diagnosticResultsResponse{Results: s.Orch.DiagnosticAttach(r.Context(), items, req.Note)})
}
func (s *Server) handleAdminDiagnosticDetach(w http.ResponseWriter, r *http.Request) {
var req diagnosticDetachRequest
if err := readJSON(r, &req); err != nil {
writeError(w, http.StatusBadRequest, "invalid body: "+err.Error())
return
}
if !req.All && len(req.Addresses) == 0 {
writeError(w, http.StatusBadRequest, "addresses or all=true is required")
return
}
writeJSON(w, http.StatusOK, diagnosticResultsResponse{Results: s.Orch.DiagnosticDetach(r.Context(), req.Addresses, req.All)})
}
func (s *Server) handleAdminDiagnosticList(w http.ResponseWriter, r *http.Request) {
holds, err := s.Orch.DiagnosticList(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
writeJSON(w, http.StatusOK, holds)
}
+17 -14
View File
@@ -36,7 +36,7 @@ func (s *Server) handleProberHeartbeat(w http.ResponseWriter, r *http.Request) {
siteID := r.PathValue("site_id") siteID := r.PathValue("site_id")
var req heartbeatRequest var req heartbeatRequest
_ = readJSON(r, &req) // heartbeat body is informational only; tolerate empty/missing _ = readJSON(r, &req) // heartbeat body is informational only; tolerate empty/missing
if err := s.DB.SiteHeartbeat(r.Context(), siteID); err != nil { if err := s.Orch.SiteHeartbeat(r.Context(), siteID); err != nil {
writeError(w, http.StatusNotFound, "unknown site_id: "+siteID) writeError(w, http.StatusNotFound, "unknown site_id: "+siteID)
return return
} }
@@ -97,8 +97,7 @@ func (s *Server) handleProberResults(w http.ResponseWriter, r *http.Request) {
return return
} }
completed := map[int64]bool{} checks := make([]db.Check, 0, len(req.Results))
dropped := map[int64]int{}
for _, res := range req.Results { for _, res := range req.Results {
item, err := s.DB.GetIP(r.Context(), res.IPID) item, err := s.DB.GetIP(r.Context(), res.IPID)
if err != nil { if err != nil {
@@ -109,21 +108,25 @@ func (s *Server) handleProberResults(w http.ResponseWriter, r *http.Request) {
if err != nil { if err != nil {
checkedAt = db.Now() checkedAt = db.Now()
} }
written, err := s.Orch.RecordCheckIfOpen(r.Context(), db.Check{ checks = append(checks, db.Check{
IPID: item.ID, IPAddress: item.IPAddress, AttemptNumber: item.AttemptNumber, IPID: item.ID, IPAddress: item.IPAddress, AttemptNumber: item.AttemptNumber,
Source: db.InboundSource(siteIndex), CheckType: res.CheckType, Target: res.IPAddress, Source: db.InboundSource(siteIndex), CheckType: res.CheckType, Target: res.IPAddress,
Success: res.Success, LatencyMS: res.LatencyMS, Detail: res.Detail, CheckedAt: checkedAt, Success: res.Success, LatencyMS: res.LatencyMS, Detail: res.Detail, CheckedAt: checkedAt,
}) })
if err != nil { }
writeError(w, http.StatusInternalServerError, err.Error()) written, err := s.Orch.RecordChecksIfOpen(r.Context(), checks)
return if err != nil {
} writeError(w, http.StatusInternalServerError, err.Error())
if !written { return
dropped[item.ID]++ }
continue completed := map[int64]bool{}
} dropped := map[int64]int{}
if res.Complete { for i, ok := range written {
completed[res.IPID] = true switch {
case !ok:
dropped[checks[i].IPID]++
case req.Results[i].Complete:
completed[checks[i].IPID] = true
} }
} }
for ipID := range completed { for ipID := range completed {
+3
View File
@@ -59,6 +59,9 @@ func (s *Server) routeTable() []route {
{"POST /api/v1/admin/ips/delete", s.handleAdminDeleteIPs, accessAdmin}, {"POST /api/v1/admin/ips/delete", s.handleAdminDeleteIPs, accessAdmin},
{"POST /api/v1/admin/ips/clear", s.handleAdminClearQueue, accessAdmin}, {"POST /api/v1/admin/ips/clear", s.handleAdminClearQueue, accessAdmin},
{"GET /api/v1/admin/validators", s.handleAdminValidators, accessAdmin}, {"GET /api/v1/admin/validators", s.handleAdminValidators, accessAdmin},
{"POST /api/v1/admin/diagnostics/attach", s.handleAdminDiagnosticAttach, accessAdmin},
{"POST /api/v1/admin/diagnostics/detach", s.handleAdminDiagnosticDetach, accessAdmin},
{"GET /api/v1/admin/diagnostics", s.handleAdminDiagnosticList, accessAdmin},
{"GET /api/v1/admin/auto-cycle", s.handleAdminGetAutoCycle, accessAdmin}, {"GET /api/v1/admin/auto-cycle", s.handleAdminGetAutoCycle, accessAdmin},
{"PUT /api/v1/admin/auto-cycle", s.handleAdminPutAutoCycle, accessAdmin}, {"PUT /api/v1/admin/auto-cycle", s.handleAdminPutAutoCycle, accessAdmin},
{"POST /api/v1/admin/auto-cycle/start", s.handleAdminStartAutoCycle, accessAdmin}, {"POST /api/v1/admin/auto-cycle/start", s.handleAdminStartAutoCycle, accessAdmin},
+187
View File
@@ -0,0 +1,187 @@
package orchestrator
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"cloudipvalidator/internal/db"
"cloudipvalidator/internal/openstack"
)
// Diagnostic hold results (per address).
const (
DiagAttached = "attached"
DiagDetached = "detached"
DiagRejected = "rejected"
)
// DiagnosticItem is one address to attach; ValidatorID is optional (an idle
// validator is picked when empty).
type DiagnosticItem struct {
Address string
ValidatorID string
}
// DiagnosticResult is the outcome for one address.
type DiagnosticResult struct {
Address string `json:"address"`
Status string `json:"status"`
ValidatorID string `json:"validator_id,omitempty"`
FIPID string `json:"fip_id,omitempty"`
Reason string `json:"reason,omitempty"`
}
func rejected(address, reason string) DiagnosticResult {
return DiagnosticResult{Address: address, Status: DiagRejected, Reason: reason}
}
// activeQueueStates are the states in which an address is being checked.
var activeQueueStates = map[string]bool{
db.IPAssigningFIP: true, db.IPAwaitingSelfCheck: true, db.IPChecking: true, db.IPAggregating: true,
}
// DiagnosticAttach binds each address to a validator's port and holds it
// there until DiagnosticDetach. Partial success is normal: every address gets
// its own result.
func (o *Orchestrator) DiagnosticAttach(ctx context.Context, items []DiagnosticItem, note string) []DiagnosticResult {
out := make([]DiagnosticResult, 0, len(items))
for _, it := range items {
out = append(out, o.diagnosticAttachOne(ctx, it, note))
}
return out
}
func (o *Orchestrator) diagnosticAttachOne(ctx context.Context, it DiagnosticItem, note string) DiagnosticResult {
addr := it.Address
holds, err := o.DB.ListDiagnosticHolds(ctx)
if err != nil {
return rejected(addr, "internal error: "+err.Error())
}
for _, h := range holds {
if h.Address == addr {
return rejected(addr, "address is already on diagnostic")
}
}
if item, err := o.DB.GetIPByAddress(ctx, addr); err == nil && activeQueueStates[item.State] {
return rejected(addr, "address is being checked ("+item.State+")")
}
fip, err := o.OS.GetFloatingIPByAddress(ctx, addr)
if err != nil {
if openstack.IsNotFound(err) {
return rejected(addr, "floating ip not found in the project")
}
return rejected(addr, "cloud lookup failed: "+err.Error())
}
v, reason := o.pickDiagnosticValidator(ctx, it.ValidatorID)
if v == nil {
return rejected(addr, reason)
}
if fip.PortID != "" && fip.PortID != v.OSPortID {
return rejected(addr, "floating ip is attached to another port")
}
if err := o.DB.ClaimDiagnostic(ctx, v.ValidatorID, addr, fip.ID, note); err != nil {
return rejected(addr, "validator "+v.ValidatorID+" cannot be claimed: "+err.Error())
}
if err := o.OS.AssociateFloatingIP(ctx, fip.ID, v.OSPortID); err != nil {
if _, rerr := o.DB.ReleaseDiagnostic(ctx, addr); rerr != nil {
o.Log.Error("roll back diagnostic hold", "ip", addr, "err", rerr)
}
return rejected(addr, "associate floating ip: "+err.Error())
}
o.diagnosticEvent(ctx, "diagnostic_attached", addr, v.ValidatorID, fip.ID, note)
o.Log.Info("diagnostic hold attached", "ip", addr, "validator", v.ValidatorID)
return DiagnosticResult{Address: addr, Status: DiagAttached, ValidatorID: v.ValidatorID, FIPID: fip.ID}
}
// pickDiagnosticValidator returns the requested validator if it is idle, or
// the first idle one with a port when none is requested.
func (o *Orchestrator) pickDiagnosticValidator(ctx context.Context, id string) (*db.Validator, string) {
if id != "" {
v, err := o.DB.GetValidator(ctx, id)
if errors.Is(err, sql.ErrNoRows) {
return nil, "validator not found"
}
if err != nil {
return nil, "internal error: " + err.Error()
}
if v.State != db.ValidatorIdle {
return nil, fmt.Sprintf("validator is not idle (%s)", v.State)
}
if v.OSPortID == "" {
return nil, "validator has no port"
}
return v, ""
}
idle, err := o.DB.ListIdleValidators(ctx)
if err != nil {
return nil, "internal error: " + err.Error()
}
for i := range idle {
if idle[i].OSPortID != "" {
return &idle[i], ""
}
}
return nil, "no idle validators left"
}
// DiagnosticDetach unbinds the given addresses (all holds when all is true)
// and returns their validators to idle. A floating ip that is already free in
// the cloud is not an error; a cloud failure keeps the hold so it can be retried.
func (o *Orchestrator) DiagnosticDetach(ctx context.Context, addresses []string, all bool) []DiagnosticResult {
holds, err := o.DB.ListDiagnosticHolds(ctx)
if err != nil {
return []DiagnosticResult{rejected("", "internal error: "+err.Error())}
}
byAddr := make(map[string]db.DiagnosticHold, len(holds))
for _, h := range holds {
byAddr[h.Address] = h
if all {
addresses = append(addresses, h.Address)
}
}
out := make([]DiagnosticResult, 0, len(addresses))
for _, addr := range addresses {
h, ok := byAddr[addr]
if !ok {
out = append(out, rejected(addr, "address is not on diagnostic"))
continue
}
fipID := h.FIPID
if fip, err := o.OS.GetFloatingIPByAddress(ctx, addr); err == nil {
fipID = fip.ID
if fip.PortID != "" {
if err := o.OS.DisassociateFloatingIP(ctx, fipID); err != nil {
out = append(out, rejected(addr, "disassociate floating ip: "+err.Error()))
continue
}
}
} else if !openstack.IsNotFound(err) {
out = append(out, rejected(addr, "cloud lookup failed: "+err.Error()))
continue
}
if _, err := o.DB.ReleaseDiagnostic(ctx, addr); err != nil {
out = append(out, rejected(addr, "release: "+err.Error()))
continue
}
o.diagnosticEvent(ctx, "diagnostic_detached", addr, h.ValidatorID, fipID, h.Note)
o.Log.Info("diagnostic hold detached", "ip", addr, "validator", h.ValidatorID)
out = append(out, DiagnosticResult{Address: addr, Status: DiagDetached, ValidatorID: h.ValidatorID, FIPID: fipID})
}
return out
}
// DiagnosticList returns the current holds.
func (o *Orchestrator) DiagnosticList(ctx context.Context) ([]db.DiagnosticHold, error) {
return o.DB.ListDiagnosticHolds(ctx)
}
func (o *Orchestrator) diagnosticEvent(ctx context.Context, typ, addr, validatorID, fipID, note string) {
payload, _ := json.Marshal(map[string]string{
"address": addr, "validator_id": validatorID, "fip_id": fipID, "note": note,
})
o.event(ctx, "control-api", validatorID, nil, typ, string(payload))
}
+191
View File
@@ -0,0 +1,191 @@
package orchestrator
import (
"context"
"errors"
"testing"
"time"
"cloudipvalidator/internal/db"
"cloudipvalidator/internal/openstack"
)
func diagSetup(t *testing.T) (*Orchestrator, *db.DB, context.Context, *openstack.MockClient) {
t.Helper()
ctx := context.Background()
o, d, mock := newTestOrchestrator(t, 180)
mock.Seed("fip-a", "1.1.1.1", "svc")
mock.Seed("fip-b", "2.2.2.2", "svc")
_ = d.RegisterValidator(ctx, "validator-1", "host", "port-1", "v")
_ = d.RegisterValidator(ctx, "validator-2", "host", "port-2", "v")
return o, d, ctx, mock
}
func validatorState(t *testing.T, d *db.DB, id string) string {
t.Helper()
v, err := d.GetValidator(context.Background(), id)
if err != nil {
t.Fatal(err)
}
return v.State
}
func TestDiagnosticAttachDetach(t *testing.T) {
o, d, ctx, _ := diagSetup(t)
if err := d.SeedQueue(ctx, []string{"1.1.1.1"}); err != nil {
t.Fatal(err)
}
res := o.DiagnosticAttach(ctx, []DiagnosticItem{{Address: "1.1.1.1", ValidatorID: "validator-1"}}, "trace")
if len(res) != 1 || res[0].Status != DiagAttached || res[0].ValidatorID != "validator-1" {
t.Fatalf("attach: %+v", res)
}
if s := validatorState(t, d, "validator-1"); s != db.ValidatorDiagnostic {
t.Fatalf("state = %s, want diagnostic", s)
}
if fips, _ := o.OS.ListFloatingIPsByPort(ctx, "port-1"); len(fips) != 1 {
t.Fatalf("fips on port-1 = %v", fips)
}
// The held address is queued but never handed out; the other validator stays idle.
o.Tick(ctx)
if ip, _ := d.GetIPByAddress(ctx, "1.1.1.1"); ip.State != db.IPQueued {
t.Fatalf("held address state = %s, want queued", ip.State)
}
// Reconcile and heartbeat leave the diagnostic state alone.
if err := o.ValidatorHeartbeat(ctx, "validator-1"); err != nil {
t.Fatal(err)
}
if s := validatorState(t, d, "validator-1"); s != db.ValidatorDiagnostic {
t.Fatalf("after heartbeat/reconcile state = %s", s)
}
if list, _ := o.DiagnosticList(ctx); len(list) != 1 || list[0].Note != "trace" {
t.Fatalf("list: %+v", list)
}
res = o.DiagnosticDetach(ctx, nil, true)
if len(res) != 1 || res[0].Status != DiagDetached {
t.Fatalf("detach: %+v", res)
}
if s := validatorState(t, d, "validator-1"); s != db.ValidatorIdle {
t.Fatalf("state = %s, want idle", s)
}
if fips, _ := o.OS.ListFloatingIPsByPort(ctx, "port-1"); len(fips) != 0 {
t.Fatalf("fip still attached: %v", fips)
}
o.Tick(ctx)
if ip, _ := d.GetIPByAddress(ctx, "1.1.1.1"); ip.State == db.IPQueued {
t.Fatal("released address was not claimed")
}
}
func TestDiagnosticRejections(t *testing.T) {
o, d, ctx, _ := diagSetup(t)
// Busy validator.
if _, err := d.ExecContext(ctx, `UPDATE validators SET state='assigned' WHERE validator_id='validator-1'`); err != nil {
t.Fatal(err)
}
res := o.DiagnosticAttach(ctx, []DiagnosticItem{{Address: "1.1.1.1", ValidatorID: "validator-1"}}, "")
if res[0].Status != DiagRejected {
t.Fatalf("busy validator: %+v", res)
}
// Unknown address and a cloud error roll back the claim.
res = o.DiagnosticAttach(ctx, []DiagnosticItem{{Address: "9.9.9.9"}}, "")
if res[0].Status != DiagRejected {
t.Fatalf("unknown fip: %+v", res)
}
}
func TestDiagnosticCloudErrorRollsBack(t *testing.T) {
o, d, ctx, mock := diagSetup(t)
mock.AssociateFailures = map[string]error{"fip-a": errors.New("neutron down")}
res := o.DiagnosticAttach(ctx, []DiagnosticItem{{Address: "1.1.1.1", ValidatorID: "validator-1"}}, "")
if res[0].Status != DiagRejected {
t.Fatalf("attach: %+v", res)
}
if s := validatorState(t, d, "validator-1"); s != db.ValidatorIdle {
t.Fatalf("state = %s, want idle after rollback", s)
}
if list, _ := o.DiagnosticList(ctx); len(list) != 0 {
t.Fatalf("hold left behind: %+v", list)
}
}
func TestSweepAndReleasePortsSkipDiagnosticValidator(t *testing.T) {
o, d, ctx, _ := diagSetup(t)
if err := d.SeedQueue(ctx, []string{"1.1.1.1"}); err != nil {
t.Fatal(err)
}
if res := o.DiagnosticAttach(ctx, []DiagnosticItem{{Address: "1.1.1.1", ValidatorID: "validator-1"}}, ""); res[0].Status != DiagAttached {
t.Fatalf("attach: %+v", res)
}
old := db.Now().Add(-time.Hour).UTC().Format(time.RFC3339Nano)
if _, err := d.ExecContext(ctx, `UPDATE validators SET last_heartbeat_at=?`, old); err != nil {
t.Fatal(err)
}
o.EndStartupGrace()
if err := o.SweepStaleHeartbeats(ctx); err != nil {
t.Fatal(err)
}
if s := validatorState(t, d, "validator-1"); s != db.ValidatorDiagnostic {
t.Fatalf("sweep changed diagnostic validator to %s", s)
}
if s := validatorState(t, d, "validator-2"); s != db.ValidatorUnreachable {
t.Fatalf("validator-2 = %s, want unreachable", s)
}
vs := o.validatorsByID(ctx, "validator-1")
o.releaseValidatorPorts(ctx, vs)
if fips, _ := o.OS.ListFloatingIPsByPort(ctx, "port-1"); len(fips) != 1 {
t.Fatalf("releaseValidatorPorts detached a held fip: %v", fips)
}
}
func TestHeartbeatPersistThrottle(t *testing.T) {
o, d, ctx, _ := diagSetup(t)
stored := func() string {
var s string
d.QueryRowContext(ctx, `SELECT COALESCE(last_heartbeat_at,'') FROM validators WHERE validator_id='validator-1'`).Scan(&s)
return s
}
if err := o.ValidatorHeartbeat(ctx, "validator-1"); err != nil {
t.Fatal(err)
}
first := stored()
if first == "" {
t.Fatal("first heartbeat was not written")
}
time.Sleep(5 * time.Millisecond)
if err := o.ValidatorHeartbeat(ctx, "validator-1"); err != nil {
t.Fatal(err)
}
if stored() != first {
t.Fatal("second heartbeat within the interval was written to the database")
}
// Memory is newer, and the admin overlay shows it.
v, _ := d.GetValidator(ctx, "validator-1")
o.OverlayValidatorHeartbeat(v)
if !v.LastHeartbeatAt.After(mustParse(t, first)) {
t.Fatal("overlay did not show the in-memory heartbeat")
}
// A state change is written at once.
_ = d.MarkValidatorUnreachable(ctx, "validator-1")
if err := o.ValidatorHeartbeat(ctx, "validator-1"); err != nil {
t.Fatal(err)
}
if s := validatorState(t, d, "validator-1"); s != db.ValidatorIdle {
t.Fatalf("state = %s, want idle", s)
}
if err := o.ValidatorHeartbeat(ctx, "nobody"); err == nil {
t.Fatal("unknown validator must fail")
}
}
func mustParse(t *testing.T, s string) time.Time {
t.Helper()
tm, err := time.Parse(time.RFC3339Nano, s)
if err != nil {
t.Fatal(err)
}
return tm
}
+181
View File
@@ -0,0 +1,181 @@
package orchestrator
import (
"context"
"database/sql"
"fmt"
"sync"
"time"
"cloudipvalidator/internal/db"
)
// heartbeatPersistInterval is how often a steady heartbeat is written to the
// database. Between writes the last signal lives in memory only.
const heartbeatPersistInterval = 60 * time.Second
// heartbeatState keeps the last signal of every validator and site in memory,
// so a heartbeat does not cost a database commit.
type heartbeatState struct {
mu sync.Mutex
startedAt time.Time
seen map[string]time.Time // key "v:<id>" or "s:<id>": last signal
persisted map[string]time.Time // key: last database write
}
// touch records a signal now and reports whether it must be written to the
// database (forced by a state change, or the last write is old enough).
func (h *heartbeatState) touch(key string, force bool) bool {
now := time.Now()
h.mu.Lock()
defer h.mu.Unlock()
if h.seen == nil {
h.seen = map[string]time.Time{}
h.persisted = map[string]time.Time{}
}
h.seen[key] = now
if last, ok := h.persisted[key]; !force && ok && now.Sub(last) < heartbeatPersistInterval {
return false
}
h.persisted[key] = now
return true
}
func (h *heartbeatState) lastSeen(key string) (time.Time, bool) {
h.mu.Lock()
defer h.mu.Unlock()
t, ok := h.seen[key]
return t, ok
}
// newest returns the later of the in-memory signal and the stored one.
func (h *heartbeatState) newest(key string, stored *time.Time) *time.Time {
t, ok := h.lastSeen(key)
if !ok {
return stored
}
t = t.UTC().Truncate(time.Millisecond)
if stored != nil && !t.After(*stored) {
return stored
}
return &t
}
// ValidatorHeartbeat handles a validator's sign of life. It returns
// sql.ErrNoRows for an unknown validator. The database is written only when
// the validator is unreachable (state change) or the last write is older than
// heartbeatPersistInterval.
func (o *Orchestrator) ValidatorHeartbeat(ctx context.Context, id string) error {
v, err := o.DB.GetValidator(ctx, id)
if err != nil {
return err
}
if !o.hb.touch("v:"+id, v.State == db.ValidatorUnreachable) {
return nil
}
return o.DB.Heartbeat(ctx, id)
}
// SiteHeartbeat is ValidatorHeartbeat for prober sites.
func (o *Orchestrator) SiteHeartbeat(ctx context.Context, siteID string) error {
state, err := o.siteState(ctx, siteID)
if err != nil {
return err
}
if !o.hb.touch("s:"+siteID, state == db.SiteUnreachable) {
return nil
}
return o.DB.SiteHeartbeat(ctx, siteID)
}
func (o *Orchestrator) siteState(ctx context.Context, siteID string) (string, error) {
sites, err := o.DB.ListSites(ctx)
if err != nil {
return "", err
}
for _, s := range sites {
if s.SiteID == siteID {
return s.State, nil
}
}
return "", sql.ErrNoRows
}
// OverlayValidatorHeartbeat replaces v.LastHeartbeatAt with the in-memory
// value when it is newer.
func (o *Orchestrator) OverlayValidatorHeartbeat(v *db.Validator) {
v.LastHeartbeatAt = o.hb.newest("v:"+v.ValidatorID, v.LastHeartbeatAt)
}
// OverlaySiteHeartbeat is OverlayValidatorHeartbeat for sites.
func (o *Orchestrator) OverlaySiteHeartbeat(s *db.Site) {
s.LastHeartbeatAt = o.hb.newest("s:"+s.SiteID, s.LastHeartbeatAt)
}
// EndStartupGrace ends the post-start sweep delay early (for tests).
func (o *Orchestrator) EndStartupGrace() { o.hb.startedAt = time.Time{} }
// inStartupGrace is true during the first HeartbeatTimeoutSeconds after
// start: agents have not had time to report in memory yet.
func (o *Orchestrator) inStartupGrace() bool {
return time.Since(o.hb.startedAt) < time.Duration(o.Cfg.HeartbeatTimeoutSeconds)*time.Second
}
// SweepStaleHeartbeats marks validators unreachable if they haven't
// heartbeated within HeartbeatTimeoutSeconds (the later of the in-memory and
// stored signal counts). It does not itself reclaim their in-flight IP — that
// happens independently via lease expiry. Validators on a diagnostic hold are
// never touched, and nothing is marked in the startup grace period.
func (o *Orchestrator) SweepStaleHeartbeats(ctx context.Context) error {
if o.inStartupGrace() {
return nil
}
cutoff := db.Now().Add(-time.Duration(o.Cfg.HeartbeatTimeoutSeconds) * time.Second)
all, err := o.DB.ListValidators(ctx)
if err != nil {
return err
}
for _, v := range all {
if v.State == db.ValidatorUnreachable || v.State == db.ValidatorDiagnostic {
continue
}
last := o.hb.newest("v:"+v.ValidatorID, v.LastHeartbeatAt)
if last == nil || !last.Before(cutoff) {
continue
}
if err := o.DB.MarkValidatorUnreachable(ctx, v.ValidatorID); err != nil {
o.Log.Error("mark validator unreachable", "validator", v.ValidatorID, "err", err)
continue
}
o.event(ctx, "control-api", "", nil, "validator_unreachable", fmt.Sprintf(`{"validator_id":%q}`, v.ValidatorID))
}
return nil
}
// SweepStaleSiteHeartbeats marks prober sites unreachable if they haven't
// heartbeated within HeartbeatTimeoutSeconds — mirrors SweepStaleHeartbeats.
func (o *Orchestrator) SweepStaleSiteHeartbeats(ctx context.Context) error {
if o.inStartupGrace() {
return nil
}
cutoff := db.Now().Add(-time.Duration(o.Cfg.HeartbeatTimeoutSeconds) * time.Second)
all, err := o.DB.ListSites(ctx)
if err != nil {
return err
}
for _, s := range all {
if s.State == db.SiteUnreachable {
continue
}
last := o.hb.newest("s:"+s.SiteID, s.LastHeartbeatAt)
if last == nil || !last.Before(cutoff) {
continue
}
if err := o.DB.MarkSiteUnreachable(ctx, s.SiteID); err != nil {
o.Log.Error("mark site unreachable", "site_id", s.SiteID, "err", err)
continue
}
o.event(ctx, "control-api", "", nil, "site_unreachable", fmt.Sprintf(`{"site_id":%q}`, s.SiteID))
}
return nil
}
+12 -42
View File
@@ -62,6 +62,9 @@ type Orchestrator struct {
// next Tick does not start the same work twice. // next Tick does not start the same work twice.
inflight sync.Map inflight sync.Map
wg sync.WaitGroup wg sync.WaitGroup
// hb is the in-memory heartbeat state (see heartbeat.go).
hb heartbeatState
} }
// Wait blocks until all background work started by Tick has finished. // Wait blocks until all background work started by Tick has finished.
@@ -99,6 +102,7 @@ func New(d *db.DB, osClient openstack.FloatingIPClient, cfg *config.ControlAPI,
Log: log, Log: log,
ScanPageSize: cfg.OpenStack.ListPageSize, ScanPageSize: cfg.OpenStack.ListPageSize,
hb: heartbeatState{startedAt: time.Now()},
} }
} }
@@ -395,6 +399,12 @@ func (o *Orchestrator) RecordCheckIfOpen(ctx context.Context, c db.Check) (bool,
return o.DB.UpsertCheckIfOpen(ctx, c) return o.DB.UpsertCheckIfOpen(ctx, c)
} }
// RecordChecksIfOpen is RecordCheckIfOpen for a batch, written in one
// transaction; written[i] reports whether checks[i] was stored.
func (o *Orchestrator) RecordChecksIfOpen(ctx context.Context, checks []db.Check) ([]bool, error) {
return o.DB.UpsertChecksIfOpen(ctx, checks)
}
// RecordCheck is RecordCheckIfOpen for callers that do not need to know // RecordCheck is RecordCheckIfOpen for callers that do not need to know
// whether the result was dropped. // whether the result was dropped.
func (o *Orchestrator) RecordCheck(ctx context.Context, c db.Check) error { func (o *Orchestrator) RecordCheck(ctx context.Context, c db.Check) error {
@@ -419,8 +429,8 @@ func (o *Orchestrator) MarkSiteComplete(ctx context.Context, ipID int64, siteInd
func (o *Orchestrator) releaseValidatorPorts(ctx context.Context, validators []db.Validator) { func (o *Orchestrator) releaseValidatorPorts(ctx context.Context, validators []db.Validator) {
var wg sync.WaitGroup var wg sync.WaitGroup
for _, v := range validators { for _, v := range validators {
if v.OSPortID == "" { if v.OSPortID == "" || v.State == db.ValidatorDiagnostic {
continue continue // a diagnostic hold keeps its floating ip attached
} }
wg.Add(1) wg.Add(1)
go func(v db.Validator) { go func(v db.Validator) {
@@ -893,46 +903,6 @@ func (o *Orchestrator) sweepExpiredLeases(ctx context.Context) error {
return nil return nil
} }
// sweepStaleHeartbeats marks validators unreachable if they haven't
// heartbeated within HeartbeatTimeoutSeconds. It does not itself reclaim
// their in-flight IP — that happens independently via lease expiry, so a
// validator that stops heartbeating but whose lease hasn't yet expired
// still finishes its current check window if it recovers in time.
func (o *Orchestrator) SweepStaleHeartbeats(ctx context.Context) error {
cutoff := db.Now().Add(-time.Duration(o.Cfg.HeartbeatTimeoutSeconds) * time.Second)
stale, err := o.DB.ListStaleHeartbeats(ctx, cutoff)
if err != nil {
return err
}
for _, v := range stale {
if err := o.DB.MarkValidatorUnreachable(ctx, v.ValidatorID); err != nil {
o.Log.Error("mark validator unreachable", "validator", v.ValidatorID, "err", err)
continue
}
o.event(ctx, "control-api", "", nil, "validator_unreachable", fmt.Sprintf(`{"validator_id":%q}`, v.ValidatorID))
}
return nil
}
// SweepStaleSiteHeartbeats marks prober sites unreachable if they haven't
// heartbeated within HeartbeatTimeoutSeconds — mirrors SweepStaleHeartbeats
// exactly, for sites instead of validators.
func (o *Orchestrator) SweepStaleSiteHeartbeats(ctx context.Context) error {
cutoff := db.Now().Add(-time.Duration(o.Cfg.HeartbeatTimeoutSeconds) * time.Second)
stale, err := o.DB.ListStaleSiteHeartbeats(ctx, cutoff)
if err != nil {
return err
}
for _, s := range stale {
if err := o.DB.MarkSiteUnreachable(ctx, s.SiteID); err != nil {
o.Log.Error("mark site unreachable", "site_id", s.SiteID, "err", err)
continue
}
o.event(ctx, "control-api", "", nil, "site_unreachable", fmt.Sprintf(`{"site_id":%q}`, s.SiteID))
}
return nil
}
// RecordEvent is the exported entry point httpapi uses to log // RecordEvent is the exported entry point httpapi uses to log
// agent/prober-reported audit events (config_received, fip_changed, // agent/prober-reported audit events (config_received, fip_changed,
// error, etc.) through the same path as internally generated events // error, etc.) through the same path as internally generated events
@@ -42,6 +42,9 @@ checks:
# Attempts per HTTPS URL (first + retries) and pause between them. # Attempts per HTTPS URL (first + retries) and pause between them.
https_attempts: 3 https_attempts: 3
https_retry_delay_seconds: 2 https_retry_delay_seconds: 2
# Check results are sent to control-api in batches this often (and always
# before the address is reported complete).
results_flush_seconds: 5
# Background traceroute (IPv4) after an HTTPS check fails on all attempts; # Background traceroute (IPv4) after an HTTPS check fails on all attempts;
# result goes to the address event log as "traceroute_result". # result goes to the address event log as "traceroute_result".
traceroute: traceroute: