Compare commits
6
Commits
1366ecbdea
...
068c10ea1c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
068c10ea1c | ||
|
|
2f038f8362 | ||
|
|
e95b5eb7d5 | ||
|
|
b7669c9e41 | ||
|
|
864208238f | ||
|
|
db73409e8f |
No files matched your search
@@ -32,8 +32,8 @@ docker compose up -d --build # весь стенд на одной
|
|||||||
| `openstack.auth_method` | `token` (готовый токен проекта из `OS_TOKEN`, сам не обновляется) или `password` (логин/пароль Keystone, токен перевыпускается автоматически) |
|
| `openstack.auth_method` | `token` (готовый токен проекта из `OS_TOKEN`, сам не обновляется) или `password` (логин/пароль Keystone, токен перевыпускается автоматически) |
|
||||||
| `openstack.*_env` | Имена переменных окружения: `OS_AUTH_URL`, `OS_PROJECT_ID`, `OS_REGION_NAME`, `OS_INTERFACE`, `OS_TOKEN` либо `OS_USERNAME`/`OS_USER_DOMAIN_NAME`/`OS_PASSWORD` |
|
| `openstack.*_env` | Имена переменных окружения: `OS_AUTH_URL`, `OS_PROJECT_ID`, `OS_REGION_NAME`, `OS_INTERFACE`, `OS_TOKEN` либо `OS_USERNAME`/`OS_USER_DOMAIN_NAME`/`OS_PASSWORD` |
|
||||||
| `orchestrator.poll_interval_seconds` | Период такта оркестратора (5) |
|
| `orchestrator.poll_interval_seconds` | Период такта оркестратора (5) |
|
||||||
| `orchestrator.self_check_timeout_seconds`, `max_self_check_retries` | Ожидание self-check валидатора (60) и число его повторов (3) |
|
| `orchestrator.self_check_timeout_seconds`, `max_self_check_retries` | Ожидание self-check валидатора (60). `max_self_check_retries` **устарело** и не используется: потолок провалов self-check задаётся настройкой `self_check_max_attempts` (по умолчанию 5, `/settings`) |
|
||||||
| `orchestrator.checking_window_seconds` | Сколько ждать результаты проверок, прежде чем подвести итог (120) |
|
| `orchestrator.checking_window_seconds` | Сколько ждать результаты проверок, прежде чем подвести итог; отсчёт от начала проверки (120) |
|
||||||
| `orchestrator.lease_ttl_seconds`, `max_retries` | Лизинг адреса за валидатором (180) и число возвратов в очередь при его истечении (3) |
|
| `orchestrator.lease_ttl_seconds`, `max_retries` | Лизинг адреса за валидатором (180) и число возвратов в очередь при его истечении (3) |
|
||||||
| `orchestrator.heartbeat_timeout_seconds` | После скольких секунд тишины валидатор или площадка считаются потерянными (30) |
|
| `orchestrator.heartbeat_timeout_seconds` | После скольких секунд тишины валидатор или площадка считаются потерянными (30) |
|
||||||
| `orchestrator.fip_settle_seconds` | Только начальное значение: пауза между привязкой FIP и self-check; далее управляется на лету. Должно выполняться `fip_settle_seconds + self_check_timeout_seconds < lease_ttl_seconds` |
|
| `orchestrator.fip_settle_seconds` | Только начальное значение: пауза между привязкой FIP и self-check; далее управляется на лету. Должно выполняться `fip_settle_seconds + self_check_timeout_seconds < lease_ttl_seconds` |
|
||||||
@@ -97,9 +97,14 @@ docs/ документация и планы доработок
|
|||||||
|
|
||||||
**Итоговый результат**
|
**Итоговый результат**
|
||||||
- `pass` — прошли все проверки: исходящие и все настроенные площадки по всем портам и ICMP. `partial` — часть прошла, часть нет. `fail` — не прошла ни одна проверка или адрес не дошёл до проверок (self-check не подтвердился). `cancelled` — остановлено оператором.
|
- `pass` — прошли все проверки: исходящие и все настроенные площадки по всем портам и ICMP. `partial` — часть прошла, часть нет. `fail` — не прошла ни одна проверка или адрес не дошёл до проверок (self-check не подтвердился). `cancelled` — остановлено оператором.
|
||||||
- Итог подводится, когда отчитались валидатор и все настроенные площадки либо истекло `checking_window_seconds`. Молчание источника — провал (`aggregation.missing_counts_as_fail`).
|
- Итог подводится, когда отчитались валидатор и все настроенные площадки либо истекло `checking_window_seconds` (отсчёт от начала проверки). Молчание источника — провал (`aggregation.missing_counts_as_fail`).
|
||||||
|
- Проверки фиксируются в момент вердикта: результат после него не сохраняется (событие `result_dropped`), каждая площадка зондирует адрес один раз за попытку. Вердикт всегда совпадает с сохранёнными проверками.
|
||||||
- Площадки опциональны: с пустым списком `sites` итог строится только по egress-проверкам.
|
- Площадки опциональны: с пустым списком `sites` итог строится только по egress-проверкам.
|
||||||
|
|
||||||
|
**Запуски и аналитика**
|
||||||
|
- Запуск — одна партия проверок: открывается, когда адрес попадает в пустую или обработанную очередь, принимает всё, что добавлено или перепроверено, пока открыт, и завершается, когда у всех его адресов есть итог. Перепроверка после завершения открывает новый запуск; результаты запусков не пересекаются.
|
||||||
|
- Страница «Аналитика» показывает один завершённый запуск по фактическим проверкам: показатели, причины `partial`, подсети (список — в настройках), цели и типы проверок, площадки, классы ошибок, валидаторы; списки адресов выгружаются в CSV.
|
||||||
|
|
||||||
**Реестр**
|
**Реестр**
|
||||||
- Запись реестра создаётся при первой постановке адреса и не удаляется: она переживает удаление из очереди и повторное добавление.
|
- Запись реестра создаётся при первой постановке адреса и не удаляется: она переживает удаление из очереди и повторное добавление.
|
||||||
- История проверок хранится по циклам; `history_retention_cycles` ограничивает глубину (0 — без ограничения), сама запись реестра остаётся.
|
- История проверок хранится по циклам; `history_retention_cycles` ограничивает глубину (0 — без ограничения), сама запись реестра остаётся.
|
||||||
@@ -121,7 +126,8 @@ docs/ документация и планы доработок
|
|||||||
| Валидатор | `POST /agents/register`, `POST /agents/{id}/heartbeat`, `GET /agents/{id}/assignment`, `GET /agents/{id}/observed-ip`, `POST /agents/{id}/self-check\|events\|results\|complete` |
|
| Валидатор | `POST /agents/register`, `POST /agents/{id}/heartbeat`, `GET /agents/{id}/assignment`, `GET /agents/{id}/observed-ip`, `POST /agents/{id}/self-check\|events\|results\|complete` |
|
||||||
| Пробер | `POST /probers/register`, `POST /probers/{site_id}/heartbeat`, `GET /probers/{site_id}/assignments`, `POST /probers/{site_id}/results` |
|
| Пробер | `POST /probers/register`, `POST /probers/{site_id}/heartbeat`, `GET /probers/{site_id}/assignments`, `POST /probers/{site_id}/results` |
|
||||||
| Очередь | `GET /admin/status`, `GET\|POST /admin/ips` (`limit/offset/state/q/result/order` — постранично), `GET /admin/ips/{ip}`, `POST /admin/ips/{ip}/cancel`, `DELETE /admin/ips/{ip}`, `POST /admin/ips/delete\|clear`, `POST\|GET /admin/ips/scan` (фоновый скан: `202`, `dry_run`, `wait`; статус и прогресс) |
|
| Очередь | `GET /admin/status`, `GET\|POST /admin/ips` (`limit/offset/state/q/result/order` — постранично), `GET /admin/ips/{ip}`, `POST /admin/ips/{ip}/cancel`, `DELETE /admin/ips/{ip}`, `POST /admin/ips/delete\|clear`, `POST\|GET /admin/ips/scan` (фоновый скан: `202`, `dry_run`, `wait`; статус и прогресс) |
|
||||||
| Реестр | `GET /admin/registry` (`limit/offset/q/last_result` — постранично), `GET /admin/registry/{ip}` |
|
| Реестр | `GET /admin/registry` (`limit/offset/q/last_result/run/subnet` — постранично; в строке — уровни `egress`/`ingress` с разбивкой по типам), `GET /admin/registry/{ip}` |
|
||||||
|
| Аналитика | `GET /admin/analytics/runs`, `GET /admin/analytics/runs/{id}`, `GET /admin/analytics/runs/{id}/lists/{kind}` (JSON или `?format=csv`), `GET`/`PUT /admin/config/subnets` |
|
||||||
| Автоцикл | `GET\|PUT /admin/auto-cycle`, `POST /admin/auto-cycle/start\|stop` |
|
| Автоцикл | `GET\|PUT /admin/auto-cycle`, `POST /admin/auto-cycle/start\|stop` |
|
||||||
| Конфигурация | `/admin/config/validators`, `/sites`, `/targets`, `/check-types`, `GET\|PUT /admin/config/orchestrator`, `GET\|PUT /admin/config/inbound-checks` |
|
| Конфигурация | `/admin/config/validators`, `/sites`, `/targets`, `/check-types`, `GET\|PUT /admin/config/orchestrator`, `GET\|PUT /admin/config/inbound-checks` |
|
||||||
| Служебное | `GET /admin/validators`, `GET /healthz` |
|
| Служебное | `GET /admin/validators`, `GET /healthz` |
|
||||||
@@ -160,9 +166,10 @@ docs/ документация и планы доработок
|
|||||||
|---|---|
|
|---|---|
|
||||||
| `/overview` | Счётчики и прогресс («Готово D из T», оценка времени), «в работе», «в очереди: Q», «последние завершённые», поиск по IP и фильтр по статусу, индикатор скана и автоцикла; работает на счётчиках и ограниченных списках, поэтому быстрый и при тысячах адресов |
|
| `/overview` | Счётчики и прогресс («Готово D из T», оценка времени), «в работе», «в очереди: Q», «последние завершённые», поиск по IP и фильтр по статусу, индикатор скана и автоцикла; работает на счётчиках и ограниченных списках, поэтому быстрый и при тысячах адресов |
|
||||||
| `/ips`, `/ips/{ip}` | Очередь **постранично** с поиском и фильтром на сервере: добавление адресов, «Сканировать Floating IP» (панель прогресса) и «Пробное сканирование», перепроверка, отмена, удаление (страница или «все N по фильтру», «Очистить всё»); детали и события адреса |
|
| `/ips`, `/ips/{ip}` | Очередь **постранично** с поиском и фильтром на сервере: добавление адресов, «Сканировать Floating IP» (панель прогресса) и «Пробное сканирование», перепроверка, отмена, удаление (страница или «все N по фильтру», «Очистить всё»); детали и события адреса |
|
||||||
| `/registry`, `/registry/{ip}` | Реестр всех адресов (постранично) и полная история проверок адреса; поиск, фильтр и страница сохраняются в адресной строке |
|
| `/registry`, `/registry/{ip}` | Реестр всех адресов (постранично) и полная история проверок адреса; поиск, фильтр и страница сохраняются в адресной строке. Последний результат разделён на уровни Egress и Ingress: «успешно из всего» по каждому и по типам проверок (icmp, ssh, tcp, https…) |
|
||||||
|
| `/analytics` | Аналитика одного завершённого запуска: показатели, причины `partial`, подсети, провалы по целям и типам проверок, ingress по площадкам, классы ошибок, валидаторы; выбор запуска; списки адресов с выгрузкой в CSV |
|
||||||
| `/validators`, `/sites`, `/targets`, `/check-types` | Управление валидаторами, внешними площадками, группами целей и типами проверок |
|
| `/validators`, `/sites`, `/targets`, `/check-types` | Управление валидаторами, внешними площадками, группами целей и типами проверок |
|
||||||
| `/settings` | Панель «Автоматический цикл», пауза перед self-check, глубина истории, TCP-порты и ICMP для inbound-проверок |
|
| `/settings` | Панель «Автоматический цикл», пауза перед self-check, потолок провалов self-check на адрес, глубина истории, TCP-порты и ICMP для inbound-проверок |
|
||||||
- Порядок блоков на `/overview` фиксирован: статистика → фильтр → таблицы; поллится только блок таблиц, поэтому набранный в фильтре текст не сбрасывается.
|
- Порядок блоков на `/overview` фиксирован: статистика → фильтр → таблицы; поллится только блок таблиц, поэтому набранный в фильтре текст не сбрасывается.
|
||||||
- Ошибки control-api показываются баннером; при недоступном API страница остаётся рабочей.
|
- Ошибки control-api показываются баннером; при недоступном API страница остаётся рабочей.
|
||||||
- Тёмная и светлая темы, переключатель в шапке.
|
- Тёмная и светлая темы, переключатель в шапке.
|
||||||
@@ -201,6 +208,12 @@ scripts/run-local-e2e.sh # сквозной прог
|
|||||||
|
|
||||||
| Дата | Веха | Документ |
|
| Дата | Веха | Документ |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
|
| 2026-10-04 | Аналитика: сравнение двух запусков (`/analytics/compare`): новые, выбывшие и изменившиеся адреса, динамика по семи индикаторам, матрица переходов вердикта; API `analytics/compare` | [план](docs/changes/2026-10-04_10-08_analytics-run-compare-plan.md) · [итог](docs/changes/2026-10-04_10-08_analytics-run-compare-summary.md) |
|
||||||
|
| 2026-10-04 | Аналитика: карточки `pass`, `partial`, `fail` открывают список адресов с этим вердиктом и выгрузку в CSV (`lists/verdict_*`) | [план](docs/changes/2026-10-04_09-55_analytics-verdict-indicators-plan.md) · [итог](docs/changes/2026-10-04_09-55_analytics-verdict-indicators-summary.md) |
|
||||||
|
| 2026-10-04 | Повтор после сбоя self-check — на другом валидаторе: валидатор, проваливший self-check, этому адресу больше не выдаётся; потолок провалов `self_check_max_attempts` (по умолчанию 5, миграция `0012`); поле `self_check_failed_on` | [план](docs/changes/2026-10-04_08-01_self-check-exclude-validator-plan.md) · [итог](docs/changes/2026-10-04_08-01_self-check-exclude-validator-summary.md) |
|
||||||
|
| 2026-10-03 | Раздел «Аналитика»: запуски проверки (миграция `0011`), показатели и списки адресов по запуску, подсети, CSV; сайдбар: связь с control-api и выход наверху, группы разделов; фильтры реестра по запуску и подсети | [план](docs/changes/2026-10-03_16-39_analytics-section-plan.md) · [итог](docs/changes/2026-10-03_18-41_analytics-section-summary.md) · [макет](docs/mockups/analytics-mockup.html) · [USAGE](docs/USAGE.md#аналитика-запусков) · [API](docs/API.md#аналитика-запусков) |
|
||||||
|
| 2026-10-03 | Вердикт без опоздавших результатов: проверки фиксируются в момент вердикта, площадка зондирует адрес один раз за попытку, окно проверки считается от её начала, время записи по часам сервера (`checks.recorded_at`) | [план](docs/changes/2026-10-03_17-21_verdict-no-late-results-plan.md) · [итог](docs/changes/2026-10-03_17-21_verdict-no-late-results-summary.md) · [API](docs/API.md#результаты-после-вердикта) · [USAGE](docs/USAGE.md#просмотр-деталей-и-истории-по-конкретному-адресу) |
|
||||||
|
| 2026-10-03 | Реестр: последний результат по уровням Egress и Ingress, «успешно из всего» и разбивка по типам проверок (поля `egress`, `ingress`, `last_cycle_id` в `GET /admin/registry`) | [план](docs/changes/2026-10-03_16-24_registry-egress-ingress-levels-plan.md) · [итог](docs/changes/2026-10-03_16-24_registry-egress-ingress-levels-summary.md) · [USAGE](docs/USAGE.md#реестр-адресов-и-глубина-истории) · [API](docs/API.md#get-apiv1adminregistry) |
|
||||||
| 2026-10-02 | Валидатор не получает второй адрес при потере heartbeat (иначе адреса уходили в `fail` без проверок); heartbeat агента в отдельном потоке; быстрая очистка очереди, не зависящая от соединения клиента | [план](docs/changes/2026-10-02_09-02_orchestrator-validator-state-and-clear-plan.md) · [анализ инцидента](analysis/2026-10-02_08-56_1026-addresses_mass-check-analysis.md) · [USAGE](docs/USAGE.md#управление-валидаторами) |
|
| 2026-10-02 | Валидатор не получает второй адрес при потере heartbeat (иначе адреса уходили в `fail` без проверок); heartbeat агента в отдельном потоке; быстрая очистка очереди, не зависящая от соединения клиента | [план](docs/changes/2026-10-02_09-02_orchestrator-validator-state-and-clear-plan.md) · [анализ инцидента](analysis/2026-10-02_08-56_1026-addresses_mass-check-analysis.md) · [USAGE](docs/USAGE.md#управление-валидаторами) |
|
||||||
| 2026-10-02 | Самопроверка через ручку control-api (`self_check.methods`, способ `control_api` рядом с IP-echo); отвязка Floating IP при провале self-check | [план](docs/changes/2026-10-02_03-06_self-check-control-api-plan.md) · [API](docs/API.md#get-apiv1agentsidobserved-ip) |
|
| 2026-10-02 | Самопроверка через ручку control-api (`self_check.methods`, способ `control_api` рядом с IP-echo); отвязка Floating IP при провале self-check | [план](docs/changes/2026-10-02_03-06_self-check-control-api-plan.md) · [API](docs/API.md#get-apiv1agentsidobserved-ip) |
|
||||||
| 2026-10-01 | Скан Floating IP при тысячах адресов: фоновый постраничный скан с прогрессом, фаза `scanning` в автоцикле, постраничные `/ips` и `/registry`, «Обзор» на счётчиках | [план](docs/changes/2026-10-01_18-19_fip-scan-at-scale-plan.md) · [ревью и тесты](docs/changes/2026-10-01_18-59_fip-scan-at-scale-review.md) · [USAGE](docs/USAGE.md#сканирование-floating-ip-из-openstack) · [API](docs/API.md#post-apiv1adminipsscan) |
|
| 2026-10-01 | Скан Floating IP при тысячах адресов: фоновый постраничный скан с прогрессом, фаза `scanning` в автоцикле, постраничные `/ips` и `/registry`, «Обзор» на счётчиках | [план](docs/changes/2026-10-01_18-19_fip-scan-at-scale-plan.md) · [ревью и тесты](docs/changes/2026-10-01_18-59_fip-scan-at-scale-review.md) · [USAGE](docs/USAGE.md#сканирование-floating-ip-из-openstack) · [API](docs/API.md#post-apiv1adminipsscan) |
|
||||||
|
|||||||
+2
-2
@@ -1,4 +1,4 @@
|
|||||||
9447699d9eed4b9fb5d417769fc868986a10357ec633ec3742883b3002aaafc3 control-api
|
2f4fa432060fb70c744ab5f593d3f12bbf39f5f6587b4fb6a445c60218d25831 control-api
|
||||||
9fb6608b84143f7c4f318f3cc92dcd9f95c7831d627b23d67cce5a5908ced704 validator-agent
|
9fb6608b84143f7c4f318f3cc92dcd9f95c7831d627b23d67cce5a5908ced704 validator-agent
|
||||||
3e9e14dbb361ee76aaad7c1da6864b3ea111e0ed151403f904b12485631bbf75 prober
|
3e9e14dbb361ee76aaad7c1da6864b3ea111e0ed151403f904b12485631bbf75 prober
|
||||||
d72234688eb1954dbff420ca1c8e83b83ceab561b18a0336af0f73fe4d9ac8be admin-dashboard
|
76db6c2dedaa89b7ba8253287a8289c7d72034f5371bcc714a55f3ab257f66ff admin-dashboard
|
||||||
Binary file not shown.
Binary file not shown.
+10
-5
@@ -12,8 +12,8 @@
|
|||||||
|
|
||||||
| Группа | Таблицы | Можно чистить |
|
| Группа | Таблицы | Можно чистить |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Данные прогона | `ip_queue` (очередь), `ip_registry` (реестр адресов), `checks` (реестр проверок), `ip_site_checks` (признаки площадок по адресам в работе), `events` (журнал событий) | да |
|
| Данные прогона | `ip_queue` (очередь), `ip_registry` (реестр адресов), `checks` (реестр проверок), `ip_site_checks` (признаки площадок по адресам в работе), `check_runs` и `run_results` (запуски и итоги адресов в них), `ip_self_check_failures` (история сбоев self-check по адресам), `events` (журнал событий) | да |
|
||||||
| Настройки (не трогать) | `validators`, `sites`, `target_groups` (цели), `check_types`, `inbound_checks_settings`, `settings`, `auto_cycle` | **нет** |
|
| Настройки (не трогать) | `validators`, `sites`, `target_groups` (цели), `check_types`, `inbound_checks_settings`, `settings`, `auto_cycle`, `subnets` (список подсетей для аналитики) | **нет** |
|
||||||
| Служебное | `sqlite_sequence` (нумерация записей), `PRAGMA user_version` (версия схемы) | нумерацию можно сбросить, версию не менять |
|
| Служебное | `sqlite_sequence` (нумерация записей), `PRAGMA user_version` (версия схемы) | нумерацию можно сбросить, версию не менять |
|
||||||
|
|
||||||
Связи (внешние ключи): `checks`, `events`, `ip_site_checks` ссылаются на `ip_queue`; `checks`, `events`, `ip_queue` — на `ip_registry`;
|
Связи (внешние ключи): `checks`, `events`, `ip_site_checks` ссылаются на `ip_queue`; `checks`, `events`, `ip_queue` — на `ip_registry`;
|
||||||
@@ -86,7 +86,7 @@ UNION ALL SELECT 'sites', COUNT(*) FROM sites;"
|
|||||||
|
|
||||||
### 3.1. Полный сброс данных прогона (перед новым полным прогоном)
|
### 3.1. Полный сброс данных прогона (перед новым полным прогоном)
|
||||||
|
|
||||||
Очищает очередь, реестр адресов, реестр проверок, журнал событий. Валидаторы, площадки, цели, типы проверок и все настройки остаются.
|
Очищает очередь, реестр адресов, реестр проверок, историю сбоев self-check, журнал событий. Валидаторы, площадки, цели, типы проверок и все настройки остаются.
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
PRAGMA foreign_keys = ON;
|
PRAGMA foreign_keys = ON;
|
||||||
@@ -96,12 +96,15 @@ UPDATE validators SET current_ip_id = NULL WHERE current_ip_id IS NOT NULL;
|
|||||||
UPDATE validators SET state = 'idle' WHERE state = 'assigned';
|
UPDATE validators SET state = 'idle' WHERE state = 'assigned';
|
||||||
-- порядок важен: сначала зависимые таблицы
|
-- порядок важен: сначала зависимые таблицы
|
||||||
DELETE FROM ip_site_checks;
|
DELETE FROM ip_site_checks;
|
||||||
|
DELETE FROM run_results;
|
||||||
|
DELETE FROM check_runs;
|
||||||
DELETE FROM checks;
|
DELETE FROM checks;
|
||||||
|
DELETE FROM ip_self_check_failures;
|
||||||
DELETE FROM events;
|
DELETE FROM events;
|
||||||
DELETE FROM ip_queue;
|
DELETE FROM ip_queue;
|
||||||
DELETE FROM ip_registry;
|
DELETE FROM ip_registry;
|
||||||
-- нумерация снова с 1 (необязательно)
|
-- нумерация снова с 1 (необязательно)
|
||||||
DELETE FROM sqlite_sequence WHERE name IN ('ip_registry', 'checks', 'ip_queue', 'events');
|
DELETE FROM sqlite_sequence WHERE name IN ('ip_registry', 'checks', 'ip_queue', 'events', 'check_runs', 'ip_self_check_failures');
|
||||||
COMMIT;
|
COMMIT;
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -155,7 +158,7 @@ WHERE cycle_id <= (SELECT MAX(c2.cycle_id) FROM checks c2 WHERE c2.registry_id =
|
|||||||
|
|
||||||
### 3.4. Удалить конкретные адреса целиком
|
### 3.4. Удалить конкретные адреса целиком
|
||||||
|
|
||||||
Удаляет адрес из очереди и реестра вместе со всей его историей (проверки и события). Список адресов подставьте в первую команду
|
Удаляет адрес из очереди и реестра вместе со всей его историей (проверки, сбои self-check и события). Список адресов подставьте в первую команду
|
||||||
`CREATE TEMP TABLE doomed_reg`. Адрес, который сейчас проверяется, удалять этим способом нельзя: используйте API (раздел 5).
|
`CREATE TEMP TABLE doomed_reg`. Адрес, который сейчас проверяется, удалять этим способом нельзя: используйте API (раздел 5).
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
@@ -167,7 +170,9 @@ CREATE TEMP TABLE doomed_ip AS
|
|||||||
SELECT id FROM ip_queue WHERE registry_id IN (SELECT id FROM doomed_reg);
|
SELECT id FROM ip_queue WHERE registry_id IN (SELECT id FROM doomed_reg);
|
||||||
UPDATE validators SET current_ip_id = NULL WHERE current_ip_id IN (SELECT id FROM doomed_ip);
|
UPDATE validators SET current_ip_id = NULL WHERE current_ip_id IN (SELECT id FROM doomed_ip);
|
||||||
DELETE FROM ip_site_checks WHERE ip_id IN (SELECT id FROM doomed_ip);
|
DELETE FROM ip_site_checks WHERE ip_id IN (SELECT id FROM doomed_ip);
|
||||||
|
DELETE FROM run_results WHERE registry_id IN (SELECT id FROM doomed_reg);
|
||||||
DELETE FROM checks WHERE registry_id IN (SELECT id FROM doomed_reg);
|
DELETE FROM checks WHERE registry_id IN (SELECT id FROM doomed_reg);
|
||||||
|
DELETE FROM ip_self_check_failures WHERE registry_id IN (SELECT id FROM doomed_reg);
|
||||||
DELETE FROM events WHERE registry_id IN (SELECT id FROM doomed_reg) OR ip_id IN (SELECT id FROM doomed_ip);
|
DELETE FROM events WHERE registry_id IN (SELECT id FROM doomed_reg) OR ip_id IN (SELECT id FROM doomed_ip);
|
||||||
DELETE FROM ip_queue WHERE id IN (SELECT id FROM doomed_ip);
|
DELETE FROM ip_queue WHERE id IN (SELECT id FROM doomed_ip);
|
||||||
DELETE FROM ip_registry WHERE id IN (SELECT id FROM doomed_reg);
|
DELETE FROM ip_registry WHERE id IN (SELECT id FROM doomed_reg);
|
||||||
|
|||||||
+166
-12
@@ -198,8 +198,13 @@ self-check способом `control_api` (`self_check.methods` в
|
|||||||
```
|
```
|
||||||
|
|
||||||
Ответ: `{"ok": true}`. При `success: false` control-api сам решает —
|
Ответ: `{"ok": true}`. При `success: false` control-api сам решает —
|
||||||
повторить попытку назначения FIP или пометить IP как `failed` (после
|
вернуть адрес в очередь или пометить IP как `failed`. Сбой записывается в
|
||||||
исчерпания `orchestrator.max_self_check_retries`).
|
историю адреса; повтор **не отдаётся этому валидатору** (он остаётся в
|
||||||
|
работе и берёт остальные адреса). Итог `fail` ставится, когда число
|
||||||
|
проваленных self-check у адреса достигло потолка `self_check_max_attempts`
|
||||||
|
(по умолчанию 5, см. [«Настройки оркестратора»](#настройки-оркестратора-apiv1adminconfigorchestrator));
|
||||||
|
`orchestrator.max_self_check_retries` не используется. Сбой привязки FIP и
|
||||||
|
истечение лизинга идут по `max_retries`, как раньше.
|
||||||
|
|
||||||
### `POST /api/v1/agents/{id}/events`
|
### `POST /api/v1/agents/{id}/events`
|
||||||
|
|
||||||
@@ -218,6 +223,19 @@ self-check способом `control_api` (`self_check.methods` в
|
|||||||
|
|
||||||
Ответ: `{"ok": true}`.
|
Ответ: `{"ok": true}`.
|
||||||
|
|
||||||
|
### Результаты после вердикта
|
||||||
|
|
||||||
|
Проверки фиксируются в момент вердикта: `POST /agents/{id}/results` и
|
||||||
|
`POST /probers/{site_id}/results` принимают результат только пока адрес
|
||||||
|
проверяется (состояния до `aggregating`) и только для его текущей попытки.
|
||||||
|
Результат, пришедший после начала агрегации или после вердикта, а также
|
||||||
|
результат прежней попытки не сохраняется и не меняет сохранённые проверки.
|
||||||
|
Ответ остаётся `200`, чтобы отправитель не повторял запрос:
|
||||||
|
`{"ok": true, "ignored": N}`, где `N` — число отброшенных проверок. На каждый
|
||||||
|
такой запрос по адресу пишется событие `result_dropped`
|
||||||
|
(`{"source": "egress"|"inbound-site-N", "dropped": N}`). Благодаря этому вердикт
|
||||||
|
всегда совпадает с сохранёнными проверками и пересчитывается из них.
|
||||||
|
|
||||||
### `POST /api/v1/agents/{id}/results`
|
### `POST /api/v1/agents/{id}/results`
|
||||||
|
|
||||||
Отчёт о результатах исходящих (egress) проверок. Можно отправлять по
|
Отчёт о результатах исходящих (egress) проверок. Можно отправлять по
|
||||||
@@ -286,13 +304,17 @@ USAGE.md про состояния площадки).
|
|||||||
|
|
||||||
Запрос: тело не требуется.
|
Запрос: тело не требуется.
|
||||||
|
|
||||||
Ответ: `{"ok": true}`. `404`, если `site_id` не сконфигурирован.
|
Ответ: `{"ok": true}`, либо `{"ok": true, "ignored": N}`, если часть результатов
|
||||||
|
отброшена (см. «Результаты после вердикта» ниже). `404`, если `site_id` не сконфигурирован.
|
||||||
|
|
||||||
### `GET /api/v1/probers/{site_id}/assignments`
|
### `GET /api/v1/probers/{site_id}/assignments`
|
||||||
|
|
||||||
Список всех IP, которые сейчас находятся в состоянии `checking` — то есть
|
Список IP в состоянии `checking`, которые эта площадка ещё не зондировала
|
||||||
всё, что нужно прозондировать на этом цикле опроса (валидаторов может
|
в текущей попытке (валидаторов может работать несколько параллельно,
|
||||||
работать несколько параллельно, поэтому список, а не один IP).
|
поэтому список, а не один IP). Адрес выдаётся площадке, пока она не
|
||||||
|
пришлёт для него результат с `complete: true`; после этого этой площадке он
|
||||||
|
больше не выдаётся (другим площадкам выдаётся). Новая попытка (повтор после
|
||||||
|
сбоя) выдаёт адрес снова. Так каждая площадка зондирует адрес один раз за попытку.
|
||||||
|
|
||||||
Ответ:
|
Ответ:
|
||||||
```json
|
```json
|
||||||
@@ -398,10 +420,14 @@ IP на данном проходе". До этого момента control-api
|
|||||||
{
|
{
|
||||||
"ip": { "ID": 42, "IPAddress": "203.0.113.10", "State": "done", "OverallResult": "pass", "...": "..." },
|
"ip": { "ID": 42, "IPAddress": "203.0.113.10", "State": "done", "OverallResult": "pass", "...": "..." },
|
||||||
"checks": [ {"Source": "egress", "CheckType": "https", "Target": "https://github.com", "Success": true, "...": "..."} ],
|
"checks": [ {"Source": "egress", "CheckType": "https", "Target": "https://github.com", "Success": true, "...": "..."} ],
|
||||||
"events": [ {"EventType": "fip_associated", "OccurredAt": "...", "...": "..."} ]
|
"events": [ {"EventType": "fip_associated", "OccurredAt": "...", "...": "..."} ],
|
||||||
|
"self_check_failed_on": ["vkiplab-v17"]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`self_check_failed_on` — валидаторы, у которых self-check на этом адресе не
|
||||||
|
прошёл в текущем запуске (по алфавиту; `[]`, если сбоев не было).
|
||||||
|
|
||||||
> Обратите внимание: вложенные объекты `ip`/`checks`/`events` сериализуются
|
> Обратите внимание: вложенные объекты `ip`/`checks`/`events` сериализуются
|
||||||
> без переопределения имён полей (используются имена Go-структур, например
|
> без переопределения имён полей (используются имена Go-структур, например
|
||||||
> `IPAddress`, `State`, `Success`) — в отличие от методов для
|
> `IPAddress`, `State`, `Success`) — в отличие от методов для
|
||||||
@@ -659,7 +685,16 @@ curl -s -X POST http://<control-api>:8080/api/v1/admin/auto-cycle/stop
|
|||||||
"last_result": "pass",
|
"last_result": "pass",
|
||||||
"last_checked_at": "2026-02-01T09:05:00Z",
|
"last_checked_at": "2026-02-01T09:05:00Z",
|
||||||
"in_queue": true,
|
"in_queue": true,
|
||||||
"current_state": "done"
|
"current_state": "done",
|
||||||
|
"last_cycle_id": 4,
|
||||||
|
"egress": {"total": 5, "ok": 5, "by_type": [
|
||||||
|
{"type": "https", "total": 3, "ok": 3},
|
||||||
|
{"type": "icmp", "total": 2, "ok": 2}
|
||||||
|
]},
|
||||||
|
"ingress": {"total": 4, "ok": 3, "by_type": [
|
||||||
|
{"type": "icmp", "total": 1, "ok": 1},
|
||||||
|
{"type": "tcp", "total": 3, "ok": 2}
|
||||||
|
]}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
```
|
```
|
||||||
@@ -667,6 +702,22 @@ curl -s -X POST http://<control-api>:8080/api/v1/admin/auto-cycle/stop
|
|||||||
`in_queue`/`current_state` отражают, есть ли у адреса сейчас живая строка в
|
`in_queue`/`current_state` отражают, есть ли у адреса сейчас живая строка в
|
||||||
`ip_queue`, а не только в реестре.
|
`ip_queue`, а не только в реестре.
|
||||||
|
|
||||||
|
**Уровни `egress` и `ingress`.** Результат последнего цикла (`last_cycle_id` —
|
||||||
|
наибольший цикл с записанными проверками, `0` — проверок нет), разделённый
|
||||||
|
на выходные проверки валидатора (`egress`) и входные проверки пробера со всех
|
||||||
|
площадок (`ingress`). В каждом уровне: `total` — сколько проверок записано,
|
||||||
|
`ok` — сколько успешных, `by_type` — то же по типам, по алфавиту. Тип — это
|
||||||
|
`check_type` до первого дефиса: `tcp-22` и `tcp-443` дают `tcp`, `tls-443` —
|
||||||
|
`tls`; `https`, `icmp`, `ssh` остаются как есть, новый тип проверки появляется
|
||||||
|
в `by_type` сам. Без проверок на уровне: `{"total": 0, "ok": 0, "by_type": []}`.
|
||||||
|
Счёт идёт по записанным проверкам, а `last_result` учитывает ещё и недостающие
|
||||||
|
результаты, поэтому при неполном наборе вердикт может быть хуже, чем «`ok` из
|
||||||
|
`total`».
|
||||||
|
|
||||||
|
Фильтры постраничного режима (только вместе с `limit`): `run` — только адреса,
|
||||||
|
у которых есть результат в этом запуске (см. [«Аналитика запусков»](#аналитика-запусков)); `subnet` — только
|
||||||
|
адреса внутри подсети (CIDR, например `203.0.113.0/24`). Неверный `run` или `subnet` — `400`.
|
||||||
|
|
||||||
### `GET /api/v1/admin/registry/{ip}`
|
### `GET /api/v1/admin/registry/{ip}`
|
||||||
|
|
||||||
Реестровая запись по одному адресу плюс вся сохранённая история проверок
|
Реестровая запись по одному адресу плюс вся сохранённая история проверок
|
||||||
@@ -680,10 +731,14 @@ curl -s -X POST http://<control-api>:8080/api/v1/admin/auto-cycle/stop
|
|||||||
"checks": [
|
"checks": [
|
||||||
{"CycleID": 4, "Source": "egress", "CheckType": "https", "Success": true, "...": "..."},
|
{"CycleID": 4, "Source": "egress", "CheckType": "https", "Success": true, "...": "..."},
|
||||||
{"CycleID": 3, "Source": "egress", "CheckType": "https", "Success": false, "...": "..."}
|
{"CycleID": 3, "Source": "egress", "CheckType": "https", "Success": false, "...": "..."}
|
||||||
]
|
],
|
||||||
|
"self_check_failed_on": ["vkiplab-v17"]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`self_check_failed_on` — валидаторы, у которых self-check на этом адресе не
|
||||||
|
прошёл, по всем запускам (по алфавиту; `[]`, если сбоев не было).
|
||||||
|
|
||||||
`404`, если адрес никогда не ставился на проверку.
|
`404`, если адрес никогда не ставился на проверку.
|
||||||
|
|
||||||
**Глубина хранения.** Сколько последних циклов на адрес хранится в
|
**Глубина хранения.** Сколько последних циклов на адрес хранится в
|
||||||
@@ -755,7 +810,7 @@ curl -s -X POST "$BASE/api/v1/admin/ips/clear"
|
|||||||
|
|
||||||
### Настройки оркестратора: `/api/v1/admin/config/orchestrator`
|
### Настройки оркестратора: `/api/v1/admin/config/orchestrator`
|
||||||
|
|
||||||
Два параметра:
|
Три параметра:
|
||||||
|
|
||||||
- `fip_settle_seconds` — пауза между привязкой Floating IP к валидатору и
|
- `fip_settle_seconds` — пауза между привязкой Floating IP к валидатору и
|
||||||
моментом, когда self-check по этому адресу становится доступен агенту
|
моментом, когда self-check по этому адресу становится доступен агенту
|
||||||
@@ -769,11 +824,19 @@ curl -s -X POST "$BASE/api/v1/admin/ips/clear"
|
|||||||
на адрес в реестре (`GET /api/v1/admin/registry/{ip}`, см.
|
на адрес в реестре (`GET /api/v1/admin/registry/{ip}`, см.
|
||||||
[«Реестр адресов»](#реестр-адресов-и-история-проверок)). `0` — без
|
[«Реестр адресов»](#реестр-адресов-и-история-проверок)). `0` — без
|
||||||
ограничения (поведение по умолчанию).
|
ограничения (поведение по умолчанию).
|
||||||
|
- `self_check_max_attempts` — потолок провалов self-check на один адрес
|
||||||
|
(1…50, по умолчанию 5). Когда у адреса провалено столько self-check,
|
||||||
|
он получает итог `fail`. Не зависит от числа валидаторов. Валидатор,
|
||||||
|
проваливший self-check на адресе, этому адресу больше не выдаётся (на
|
||||||
|
остальные адреса это не влияет); если все рабочие валидаторы уже
|
||||||
|
провалили адрес, исключения сбрасываются и повторы продолжаются до
|
||||||
|
потолка. Значение действует на следующих повторах без перезапуска.
|
||||||
|
В `PUT` поле необязательно: если не передано, не меняется.
|
||||||
|
|
||||||
| Метод | Путь | Тело | Успех | Ошибки |
|
| Метод | Путь | Тело | Успех | Ошибки |
|
||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
| GET | `/api/v1/admin/config/orchestrator` | — | `{"fip_settle_seconds":N,"history_retention_cycles":M}` | |
|
| GET | `/api/v1/admin/config/orchestrator` | — | `{"fip_settle_seconds":N,"history_retention_cycles":M,"self_check_max_attempts":K}` | |
|
||||||
| PUT | `/api/v1/admin/config/orchestrator` | `{"fip_settle_seconds":N,"history_retention_cycles":M}` | `200` | `400`, если `N < 0` или `M < 0`, или если `fip_settle_seconds + self_check_timeout_seconds >= lease_ttl_seconds` (пауза не должна съедать весь лизинг адреса — иначе self-check не успеет пройти до истечения `lease_ttl_seconds`, и адрес будет вечно возвращаться в очередь) |
|
| PUT | `/api/v1/admin/config/orchestrator` | `{"fip_settle_seconds":N,"history_retention_cycles":M,"self_check_max_attempts":K}` | `200` | `400`, если `N < 0`, `M < 0` или `K` вне 1…50, или если `fip_settle_seconds + self_check_timeout_seconds >= lease_ttl_seconds` (пауза не должна съедать весь лизинг адреса — иначе self-check не успеет пройти до истечения `lease_ttl_seconds`, и адрес будет вечно возвращаться в очередь) |
|
||||||
|
|
||||||
Как и остальные разделы этой группы, YAML-поле `orchestrator.
|
Как и остальные разделы этой группы, YAML-поле `orchestrator.
|
||||||
fip_settle_seconds` в `control-api.yaml` — только одноразовый bootstrap
|
fip_settle_seconds` в `control-api.yaml` — только одноразовый bootstrap
|
||||||
@@ -955,3 +1018,94 @@ curl -s "$BASE/api/v1/admin/ips/203.0.113.10" | python3 -m json.tool
|
|||||||
|
|
||||||
Для полностью автоматизированного локального прогона (без ручных curl)
|
Для полностью автоматизированного локального прогона (без ручных curl)
|
||||||
см. `scripts/run-local-e2e.sh` и [docs/LOCAL_E2E.md](LOCAL_E2E.md).
|
см. `scripts/run-local-e2e.sh` и [docs/LOCAL_E2E.md](LOCAL_E2E.md).
|
||||||
|
|
||||||
|
## Аналитика запусков
|
||||||
|
|
||||||
|
Запуск — одна «партия» проверок. Он открывается, когда адрес попадает в пустую (или полностью обработанную)
|
||||||
|
очередь; пока он открыт, в него входят все добавленные и перепроверяемые адреса. Запуск завершается, когда все его
|
||||||
|
адреса получили итог (`done`, `failed`, `occupied`) либо удалены из очереди. Перепроверка после завершения запуска
|
||||||
|
открывает **новый** запуск, прежний не меняется. Тип запуска: `auto` (скан автоцикла) или `manual`. Для одного адреса
|
||||||
|
в запуске хранится результат его последнего цикла. Для данных, накопленных до появления запусков, запуски выделены по
|
||||||
|
паузам: циклы, которые заканчиваются с промежутком меньше часа, образуют один запуск.
|
||||||
|
|
||||||
|
### `GET /api/v1/admin/analytics/runs`
|
||||||
|
|
||||||
|
Список запусков, новые первыми, для выбора на странице «Аналитика».
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{"id": 2, "kind": "manual", "state": "open", "started_at": "2026-10-03T15:30:00Z", "finalized_at": null,
|
||||||
|
"addresses": 120, "pass": 40, "partial": 80, "fail": 0, "cancelled": 0, "total": 200, "pending": 80},
|
||||||
|
{"id": 1, "kind": "manual", "state": "finalized", "started_at": "2026-10-02T13:46:45Z", "finalized_at": "2026-10-02T22:28:54Z",
|
||||||
|
"addresses": 6440, "pass": 1962, "partial": 4478, "fail": 0, "cancelled": 0, "total": 6440, "pending": 0}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
`addresses` — адреса с итогом, `total` — все адреса запуска в очереди, `pending` — ещё в работе.
|
||||||
|
|
||||||
|
### `GET /api/v1/admin/analytics/runs/{id}`
|
||||||
|
|
||||||
|
Все показатели страницы по одному **завершённому** запуску; открытый запуск — `409`, неизвестный — `404`.
|
||||||
|
Считаются проверки последнего цикла каждого адреса в запуске, в том числе пришедшие позже вердикта (как факты).
|
||||||
|
Результат кэшируется, пока данные запуска и список подсетей не менялись.
|
||||||
|
|
||||||
|
| Блок | Содержимое |
|
||||||
|
|---|---|
|
||||||
|
| `run` | `id`, `kind`, `state`, `started_at`, `finalized_at`, `duration_seconds`, `rechecked` (адресов с несколькими циклами в запуске) |
|
||||||
|
| `summary` | `addresses`, `pass`, `partial`, `fail`, `cancelled`; `egress_ok`, `ingress_ok` (адреса, у которых все записанные проверки уровня успешны); `egress_https_any_failed` и `egress_https_all_failed` (хотя бы одна / все https-проверки провалены), `egress_https_all_targets_failed` (все цели полного набора); `ingress_ssh_any_failed`, `ingress_ssh_all_failed`; `addresses_per_minute` |
|
||||||
|
| `reasons` | причины `partial`, каждый адрес один раз: «Только egress», «Ingress и egress», «Egress и неполный набор», «Ingress, egress и неполный набор», «Только неполный набор», «Только ingress»; нулевые не выдаются |
|
||||||
|
| `quality` | `late_failed_checks_at_pass`, `late_failed_addresses_at_pass`, `ingress_failed_checks`, `ingress_failed_late`, `incomplete_addresses`, `pass_with_failed_addresses`, `pass_by_facts` |
|
||||||
|
| `subnets` | по подсети: `cidr`, `label`, `addresses`, `pass`, `egress_ok`, `ingress_ok` (без списка подсетей — группы по /24; адрес вне списка — «прочие») |
|
||||||
|
| `targets` | `types` (семейства egress-проверок), `targets` (хосты, по убыванию провалов https), `failed` (по типу: число адресов с провалом на каждую цель) |
|
||||||
|
| `matrix` | по типу: строки «подсеть × цель» для подсетей с `partial` (`partial`, `percent` по целям) |
|
||||||
|
| `sites` | `types` и строки площадок: `total` и `ok` проверок по типу |
|
||||||
|
| `errors` | классы ошибок проваленных ingress-проверок («SSH: таймаут», «ICMP: нет ответа», …) со счётчиками |
|
||||||
|
| `validators` | по валидатору: `total`, `ok` https-проверок egress |
|
||||||
|
|
||||||
|
Тип проверки — это `check_type` до первого дефиса: `tcp-22` и `tcp-443` дают `tcp`.
|
||||||
|
|
||||||
|
### `GET /api/v1/admin/analytics/runs/{id}/lists/{kind}`
|
||||||
|
|
||||||
|
Таблица адресов за показателем или классом ошибки: `{"kind", "class", "columns": [...], "rows": [[...]]}`.
|
||||||
|
`kind`: `verdict_pass`, `verdict_partial`, `verdict_fail`, `egress_https_any`, `egress_https_all`, `ingress_ssh_any`, `ingress_ssh_all` или `error` (с `?class=SSH: таймаут`;
|
||||||
|
без класса и неизвестный `kind` — `404`). С `?format=csv` — файл CSV (UTF-8 с BOM, `Content-Disposition: attachment`,
|
||||||
|
имя вида `ingress_ssh_all_run1.csv`). Для `verdict_*` — адреса запуска с этим вердиктом (без `cancelled`, по числовому порядку; число строк равно `summary.pass`/`partial`/`fail`): адрес, подсеть, валидатор (по https-проверкам, «—», если их нет), `Egress` и `Ingress` («успешно из всех», «—» без проверок), «Проверок в цикле» (записано из ожидаемых) и у `partial` ещё «Причина» (как в блоке `reasons`). Для `error` строка — одна проваленная проверка: адрес, подсеть, площадка,
|
||||||
|
валидатор, вердикт адреса, статус («провал, в вердикте» или «провал, после вердикта»).
|
||||||
|
|
||||||
|
### `GET /api/v1/admin/analytics/compare?base=A&target=B`
|
||||||
|
|
||||||
|
Сравнение двух завершённых запусков: `base` — старый (A), `target` — новый (B). Адрес — это IP; адрес с итогом
|
||||||
|
`cancelled` в запуск не входит (их число — в `cancelled`). Ответ:
|
||||||
|
|
||||||
|
| Поле | Содержимое |
|
||||||
|
|---|---|
|
||||||
|
| `runs` | `base` и `target`: сведения о запуске и `addresses` |
|
||||||
|
| `groups` | `new` (есть в B, нет в A), `left` (были в A, нет в B), `common` (в обоих), `changed`, `same`; `common = changed + same` |
|
||||||
|
| `indicators` | по семи индикаторам (`verdict_pass`, `verdict_partial`, `verdict_fail`, `egress_https_any`, `egress_https_all`, `ingress_ssh_any`, `ingress_ssh_all`): `base`, `target`, `delta`, `new`, `left`, `entered`, `exited`; `delta = new − left + entered − exited` |
|
||||||
|
| `transitions` | `verdicts`, `matrix[из][в]` вердиктов общих адресов, `new` и `left` — новые/выбывшие по вердикту |
|
||||||
|
| `cancelled` | отменённые адреса в `base` и `target` |
|
||||||
|
|
||||||
|
Общий адрес **изменился**, если его принадлежность хотя бы к одному из семи индикаторов в A и B разная (другой набор
|
||||||
|
проваленных целей или площадок при тех же индикаторах — не изменение). `400` — нет или неверные `base`/`target` либо
|
||||||
|
они совпадают, `404` — запуска нет, `409` — запуск ещё идёт.
|
||||||
|
|
||||||
|
### `GET /api/v1/admin/analytics/compare/lists/{group}?base=A&target=B`
|
||||||
|
|
||||||
|
Таблица адресов группы `new`, `left`, `common`, `changed`, `same`, `entered` или `exited`. Фильтры: `indicator` (ключ
|
||||||
|
индикатора; для `entered` и `exited` обязателен; для `new`/`left` — адрес входит в индикатор в своём запуске, для
|
||||||
|
`common`/`changed`/`same` — хотя бы в одном из запусков), `from` и `to` вместе (вердикт в A и в B; только для общих групп).
|
||||||
|
Неизвестные группа, индикатор или фильтр — `404`. Столбцы `new` и `left`: адрес, подсеть, вердикт, Egress, Ingress,
|
||||||
|
индикаторы. Остальные группы: адрес, подсеть, вердикт, Egress и Ingress в виде `A → B` и «Что изменилось» (вердикт,
|
||||||
|
вход в индикаторы и выход из них, добавленные и убранные цели https и площадки ssh, смена валидатора; у группы без
|
||||||
|
изменений — «без изменений»). С `?format=csv` — файл CSV (UTF-8 с BOM), имя `compare_<group>[_<indicator>][_<from>-<to>]_run<A>-<B>.csv`.
|
||||||
|
|
||||||
|
### `GET /api/v1/admin/config/subnets`, `PUT /api/v1/admin/config/subnets`
|
||||||
|
|
||||||
|
Список подсетей, по которым группируются адреса на странице «Аналитика». `PUT` заменяет список целиком:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"subnets": [{"cidr": "83.166.248.0/21", "label": "москва"}, {"cidr": "10.0.0.0/8"}]}
|
||||||
|
```
|
||||||
|
|
||||||
|
CIDR приводится к канонической записи (`10.1.2.3/24` → `10.1.2.0/24`), повторы схлопываются; неверный CIDR — `400`,
|
||||||
|
список остаётся прежним. Адрес относится к самой узкой подходящей подсети.
|
||||||
+9
-3
@@ -46,18 +46,24 @@ admin-dashboard -config /etc/cloud-ip-validator/admin-dashboard.yaml
|
|||||||
|
|
||||||
## Страницы и что на них можно делать
|
## Страницы и что на них можно делать
|
||||||
|
|
||||||
|
Сайдбар слева: вверху логотип, под ним блок сессии (состояние связи с `control-api` — зелёный индикатор, красный
|
||||||
|
«нет связи» при сбое, переключатель темы, при включённом входе имя пользователя и кнопка «Выйти»), ниже разделы в двух
|
||||||
|
группах: «Мониторинг» (Обзор, Очередь IP, Реестр, Аналитика) и «Настройка» (Валидаторы, Площадки, Цели, Типы проверок,
|
||||||
|
Настройки).
|
||||||
|
|
||||||
| Страница | Назначение |
|
| Страница | Назначение |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `/overview` | Сводная статистика: счётчики по состояниям, «текущая проверка» (live-снимок всех IP не в терминальном состоянии) и «последние N завершённых» (по умолчанию 20, `overview.last_completed_count`) с разбивкой pass/partial/fail/cancelled. Обновляется каждые `overview.poll_interval_seconds` секунд без перезагрузки страницы. Поиск по IP и фильтр по статусу (`pass`/`partial`/`fail`/`cancelled`) над обеими таблицами — набранное/выбранное не сбрасывается очередным обновлением. Пока включён [автоматический цикл](USAGE.md#автоматический-цикл-проверок), под счётчиками показывается индикатор «Автоцикл активен» с текущей фазой и временем следующего запуска; управляется цикл на `/settings`. |
|
| `/overview` | Сводная статистика: счётчики по состояниям, «текущая проверка» (live-снимок всех IP не в терминальном состоянии) и «последние N завершённых» (по умолчанию 20, `overview.last_completed_count`) с разбивкой pass/partial/fail/cancelled. Обновляется каждые `overview.poll_interval_seconds` секунд без перезагрузки страницы. Поиск по IP и фильтр по статусу (`pass`/`partial`/`fail`/`cancelled`) над обеими таблицами — набранное/выбранное не сбрасывается очередным обновлением. Пока включён [автоматический цикл](USAGE.md#автоматический-цикл-проверок), под счётчиками показывается индикатор «Автоцикл активен» с текущей фазой и временем следующего запуска; управляется цикл на `/settings`. |
|
||||||
| `/ips` | Очередь **постранично** (по 50 адресов; 25/50/100/200) с поиском по IP и фильтром по состоянию/итогу на сервере; кнопка «Сканировать Floating IP» запускает фоновое сканирование с панелью прогресса, «Пробное сканирование» ничего не ставит в очередь (подробности — «Очередь из тысяч адресов» ниже). Форма сверху принимает список адресов (по одному на строке или через запятую) и отправляет их в `POST /api/v1/admin/ips` — **один и тот же вызов** добавляет новые адреса и принудительно перезапускает уже завершённые (см. ниже). Кнопка «Сканировать Floating IP» делает то же самое автоматически: находит в проекте OpenStack все свободные (не привязанные к порту) Floating IP и сразу ставит их в очередь (`POST /api/v1/admin/ips/scan`, см. [API.md](API.md#post-apiv1adminipsscan)) — то же сканирование можно включить по расписанию через `orchestrator.fip_scan_interval_seconds`. У каждого адреса — кнопка «Перепроверить» (для `done`/`failed`) или «Отменить» (для активных состояний), и всегда — «Удалить» (безвозвратно убирает адрес из очереди, но не из реестра — см. ниже). Чекбоксы у строк + кнопка «Удалить выбранные» удаляют список одним вызовом; «Очистить всё» удаляет вообще всё, включая активные проверки — обе операции требуют явного подтверждения. Пока не истекла настроенная на `/settings` пауза (`fip_settle_seconds`), только что привязавший Floating IP адрес показывает отдельный бейдж «прогрев FIP» вместо обычного статуса. Если на момент попытки привязки Floating IP оказался уже занят другим портом (дрейф состояния облака или ошибочно переданный адрес), цикл проверки для него не запускается — адрес показывает отдельный бейдж «занят» (отличный от «fail») и строку `fip_occupied` в списке событий на его странице; кнопка «Перепроверить» ставит его в очередь заново. |
|
| `/ips` | Очередь **постранично** (по 50 адресов; 25/50/100/200) с поиском по IP и фильтром по состоянию/итогу на сервере; кнопка «Сканировать Floating IP» запускает фоновое сканирование с панелью прогресса, «Пробное сканирование» ничего не ставит в очередь (подробности — «Очередь из тысяч адресов» ниже). Форма сверху принимает список адресов (по одному на строке или через запятую) и отправляет их в `POST /api/v1/admin/ips` — **один и тот же вызов** добавляет новые адреса и принудительно перезапускает уже завершённые (см. ниже). Кнопка «Сканировать Floating IP» делает то же самое автоматически: находит в проекте OpenStack все свободные (не привязанные к порту) Floating IP и сразу ставит их в очередь (`POST /api/v1/admin/ips/scan`, см. [API.md](API.md#post-apiv1adminipsscan)) — то же сканирование можно включить по расписанию через `orchestrator.fip_scan_interval_seconds`. У каждого адреса — кнопка «Перепроверить» (для `done`/`failed`) или «Отменить» (для активных состояний), и всегда — «Удалить» (безвозвратно убирает адрес из очереди, но не из реестра — см. ниже). Чекбоксы у строк + кнопка «Удалить выбранные» удаляют список одним вызовом; «Очистить всё» удаляет вообще всё, включая активные проверки — обе операции требуют явного подтверждения. Пока не истекла настроенная на `/settings` пауза (`fip_settle_seconds`), только что привязавший Floating IP адрес показывает отдельный бейдж «прогрев FIP» вместо обычного статуса. Если на момент попытки привязки Floating IP оказался уже занят другим портом (дрейф состояния облака или ошибочно переданный адрес), цикл проверки для него не запускается — адрес показывает отдельный бейдж «занят» (отличный от «fail») и строку `fip_occupied` в списке событий на его странице; кнопка «Перепроверить» ставит его в очередь заново. |
|
||||||
| `/ips/{ip}` | Детали одного адреса, пока он в очереди: все проверки текущей попытки и вся история событий, плюс ссылка на полную историю в реестре (см. ниже). |
|
| `/ips/{ip}` | Детали одного адреса, пока он в очереди: все проверки текущей попытки и вся история событий, плюс ссылка на полную историю в реестре (см. ниже). |
|
||||||
| `/registry` | **Реестр** — все адреса, когда-либо поставленные на проверку, независимо от того, стоят ли они сейчас в очереди. Переживает удаление адреса из `/ips` и повторное добавление того же адреса позже (см. «Реестр адресов» ниже). Поиск по IP и фильтр по статусу — то же самое, что на `/overview`, плюс отражается в адресной строке (`?q=&status=`), так что отфильтрованную ссылку можно сохранить/переслать. |
|
| `/registry` | **Реестр** — все адреса, когда-либо поставленные на проверку, независимо от того, стоят ли они сейчас в очереди. Переживает удаление адреса из `/ips` и повторное добавление того же адреса позже (см. «Реестр адресов» ниже). Поиск по IP и фильтр по статусу — то же самое, что на `/overview`, плюс отражается в адресной строке (`?q=&status=`), так что отфильтрованную ссылку можно сохранить/переслать. В колонке «Последний результат» под вердиктом — уровни **Egress** и **Ingress** в виде «N из M» с разбивкой по типам проверок (`https`, `icmp`, `ssh`, `tcp`, `tls`…), см. [USAGE.md](USAGE.md#реестр-адресов-и-глубина-истории). |
|
||||||
| `/registry/{ip}` | Полная сохранённая история проверок одного адреса по всем циклам (не только текущему) — в отличие от `/ips/{ip}`, которая показывает только текущую попытку. |
|
| `/registry/{ip}` | Полная сохранённая история проверок одного адреса по всем циклам (не только текущему) — в отличие от `/ips/{ip}`, которая показывает только текущую попытку. |
|
||||||
|
| `/analytics` | **Аналитика** одного завершённого запуска (`?run=ID`, по умолчанию последний): выбор запуска (идущий виден, но недоступен), показатели, причины `partial`, качество данных, подсети, egress по целям (по типу проверки, тепловая карта «подсеть × цель»), ingress по площадкам, классы ошибок, валидаторы. Карточки `pass`/`partial`/`fail`, карточки провалов `https`/`ssh` и классы ошибок открывают список адресов с выгрузкой в CSV. Кнопка «Сравнить с другим запуском» ведёт на `/analytics/compare?base=A&target=B`: сравнение двух запусков (новые, выбывшие и изменившиеся адреса, динамика по семи индикаторам, матрица переходов вердикта; числа открывают списки с CSV). Подробности — [USAGE.md](USAGE.md#аналитика-запусков). |
|
||||||
| `/validators` | Список валидаторов + создание/изменение `os_port_id`/удаление. |
|
| `/validators` | Список валидаторов + создание/изменение `os_port_id`/удаление. |
|
||||||
| `/sites` | Площадки — число слотов не ограничено, форма сверху добавляет новый слот, назначить/сменить/освободить `site_id` в каждой строке; колонка «Статус» показывает бейдж подключения пробера (`unregistered`/`idle`/`unreachable`, по аналогии с `/validators`), см. [USAGE.md](USAGE.md#состояния-площадки). |
|
| `/sites` | Площадки — число слотов не ограничено, форма сверху добавляет новый слот, назначить/сменить/освободить `site_id` в каждой строке; колонка «Статус» показывает бейдж подключения пробера (`unregistered`/`idle`/`unreachable`, по аналогии с `/validators`), см. [USAGE.md](USAGE.md#состояния-площадки). |
|
||||||
| `/targets` | Группы целей для egress-проверок — создание/редактирование/удаление. |
|
| `/targets` | Группы целей для egress-проверок — создание/редактирование/удаление. |
|
||||||
| `/check-types` | Типы проверок (`https`/`icmp`/`ssh`/...), включение/выключение, привязка к группам целей. |
|
| `/check-types` | Типы проверок (`https`/`icmp`/`ssh`/...), включение/выключение, привязка к группам целей. |
|
||||||
| `/settings` | Четыре блока. Первый — панель **«Автоматический цикл»**: статус и фаза, время последнего/следующего запуска, результат последнего цикла, поля «Интервал между циклами (мин)» и «Максимальная длительность проверки (мин, 0 = без лимита)» с кнопкой «Сохранить» и кнопка «Включить»/«Выключить» (показывается та, что сейчас применима). Значения вводятся в минутах (допустимы дробные), в control-api уходят секундами; минимум интервала — 1 минута (`60` с), нарушение приходит предупреждением в баннере. Подробности — [USAGE.md](USAGE.md#автоматический-цикл-проверок), API — [API.md](API.md#автоматический-цикл-проверок). Далее три формы: `fip_settle_seconds` — пауза (в секундах) между привязкой Floating IP и началом self-check («прогрев» дата-плейна OpenStack, см. [USAGE.md](USAGE.md#пауза-перед-self-check-fip_settle_seconds)); `history_retention_cycles` — сколько последних циклов проверки хранить на адрес в реестре (0 — без ограничения); и типы проверок пробера — TCP-порты (через запятую) + чекбокс ICMP, общие для всех площадок (см. [USAGE.md](USAGE.md#управление-типами-проверок-пробера)). |
|
| `/settings` | Четыре блока. Первый — панель **«Автоматический цикл»**: статус и фаза, время последнего/следующего запуска, результат последнего цикла, поля «Интервал между циклами (мин)» и «Максимальная длительность проверки (мин, 0 = без лимита)» с кнопкой «Сохранить» и кнопка «Включить»/«Выключить» (показывается та, что сейчас применима). Значения вводятся в минутах (допустимы дробные), в control-api уходят секундами; минимум интервала — 1 минута (`60` с), нарушение приходит предупреждением в баннере. Подробности — [USAGE.md](USAGE.md#автоматический-цикл-проверок), API — [API.md](API.md#автоматический-цикл-проверок). Далее формы: `fip_settle_seconds` — пауза (в секундах) между привязкой Floating IP и началом self-check («прогрев» дата-плейна OpenStack, см. [USAGE.md](USAGE.md#пауза-перед-self-check-fip_settle_seconds)); `self_check_max_attempts` — «Потолок провалов self-check на адрес» (1…50, по умолчанию 5; повторы идут на других валидаторах, см. [USAGE.md](USAGE.md#повтор-после-сбоя-self-check)); `history_retention_cycles` — сколько последних циклов проверки хранить на адрес в реестре (0 — без ограничения); и типы проверок пробера — TCP-порты (через запятую) + чекбокс ICMP, общие для всех площадок (см. [USAGE.md](USAGE.md#управление-типами-проверок-пробера)). |
|
||||||
|
|
||||||
### «В работе», «в очереди» и «последняя завершённая» проверка
|
### «В работе», «в очереди» и «последняя завершённая» проверка
|
||||||
|
|
||||||
@@ -179,7 +185,7 @@ auto-refresh на `/ips`, см. git-историю). Опрашивается т
|
|||||||
Без сессии обычный запрос получает редирект `303` на `/login?next=…` (после входа — возврат на исходную страницу; `next` принимается только как
|
Без сессии обычный запрос получает редирект `303` на `/login?next=…` (после входа — возврат на исходную страницу; `next` принимается только как
|
||||||
относительный путь на этом же сайте).
|
относительный путь на этом же сайте).
|
||||||
- **Сессия** хранится в cookie `session` (подпись HMAC-SHA256, `HttpOnly`, `SameSite=Strict`, `Secure` при HTTPS), состояния на сервере нет —
|
- **Сессия** хранится в cookie `session` (подпись HMAC-SHA256, `HttpOnly`, `SameSite=Strict`, `Secure` при HTTPS), состояния на сервере нет —
|
||||||
дашборд остаётся stateless. Срок — `auth.session_ttl_minutes` (по умолчанию 480 минут). Кнопка «Выйти» (внизу сайдбара) стирает cookie в браузере;
|
дашборд остаётся stateless. Срок — `auth.session_ttl_minutes` (по умолчанию 480 минут). Кнопка «Выйти» (вверху сайдбара) стирает cookie в браузере;
|
||||||
скопированная cookie остаётся валидной до истечения срока. Сбросить все сессии сразу — сменить `ADMIN_DASHBOARD_SESSION_SECRET` и перезапустить дашборд.
|
скопированная cookie остаётся валидной до истечения срока. Сбросить все сессии сразу — сменить `ADMIN_DASHBOARD_SESSION_SECRET` и перезапустить дашборд.
|
||||||
- **Фоновое обновление.** Когда сессия истекла, htmx-запросы (опрос `/overview/fragment`) получают `401` с `HX-Redirect: /login` — браузер
|
- **Фоновое обновление.** Когда сессия истекла, htmx-запросы (опрос `/overview/fragment`) получают `401` с `HX-Redirect: /login` — браузер
|
||||||
уходит на страницу входа целиком, а не подставляет её внутрь фрагмента.
|
уходит на страницу входа целиком, а не подставляет её внутрь фрагмента.
|
||||||
|
|||||||
+2
-1
@@ -226,7 +226,8 @@ flowchart TB
|
|||||||
только все ожидаемые флаги выставлены — либо истекло время ожидания
|
только все ожидаемые флаги выставлены — либо истекло время ожидания
|
||||||
(`checking_window_seconds`) — фоновая агрегация суммирует все строки
|
(`checking_window_seconds`) — фоновая агрегация суммирует все строки
|
||||||
`checks` по текущей попытке и записывает итог (`pass`/`partial`/`fail`)
|
`checks` по текущей попытке и записывает итог (`pass`/`partial`/`fail`)
|
||||||
обратно в `ip_queue`. Оператор в любой момент читает уже накопленные
|
обратно в `ip_queue`. С началом агрегации запись проверок по адресу
|
||||||
|
закрыта: опоздавшие результаты отбрасываются (событие `result_dropped`). Оператор в любой момент читает уже накопленные
|
||||||
данные через административные `GET`-методы, не дожидаясь завершения
|
данные через административные `GET`-методы, не дожидаясь завершения
|
||||||
проверки — подробнее о значениях полей см.
|
проверки — подробнее о значениях полей см.
|
||||||
[USAGE.md](USAGE.md#значения-полей-ip).
|
[USAGE.md](USAGE.md#значения-полей-ip).
|
||||||
|
|||||||
+109
-3
@@ -24,6 +24,7 @@
|
|||||||
- [Как читать итоговый результат (pass/partial/fail)](#как-читать-итоговый-результат-passpartialfail)
|
- [Как читать итоговый результат (pass/partial/fail)](#как-читать-итоговый-результат-passpartialfail)
|
||||||
- [Просмотр деталей и истории по конкретному адресу](#просмотр-деталей-и-истории-по-конкретному-адресу)
|
- [Просмотр деталей и истории по конкретному адресу](#просмотр-деталей-и-истории-по-конкретному-адресу)
|
||||||
- [Реестр адресов и глубина истории](#реестр-адресов-и-глубина-истории)
|
- [Реестр адресов и глубина истории](#реестр-адресов-и-глубина-истории)
|
||||||
|
- [Аналитика запусков](#аналитика-запусков)
|
||||||
- [Управление валидаторами](#управление-валидаторами)
|
- [Управление валидаторами](#управление-валидаторами)
|
||||||
- [Управление площадками (проберами)](#управление-площадками-проберами)
|
- [Управление площадками (проберами)](#управление-площадками-проберами)
|
||||||
- [Управление типами проверок пробера](#управление-типами-проверок-пробера)
|
- [Управление типами проверок пробера](#управление-типами-проверок-пробера)
|
||||||
@@ -32,6 +33,7 @@
|
|||||||
- [Принудительная остановка проверки](#принудительная-остановка-проверки)
|
- [Принудительная остановка проверки](#принудительная-остановка-проверки)
|
||||||
- [Удаление адресов из очереди](#удаление-адресов-из-очереди)
|
- [Удаление адресов из очереди](#удаление-адресов-из-очереди)
|
||||||
- [Пауза перед self-check (fip_settle_seconds)](#пауза-перед-self-check-fip_settle_seconds)
|
- [Пауза перед self-check (fip_settle_seconds)](#пауза-перед-self-check-fip_settle_seconds)
|
||||||
|
- [Повтор после сбоя self-check](#повтор-после-сбоя-self-check)
|
||||||
- [Частые проблемы и что с ними делать](#частые-проблемы-и-что-с-ними-делать)
|
- [Частые проблемы и что с ними делать](#частые-проблемы-и-что-с-ними-делать)
|
||||||
|
|
||||||
## Как устроена работа с системой
|
## Как устроена работа с системой
|
||||||
@@ -305,8 +307,9 @@ curl -s http://<control-api>:8080/api/v1/admin/ips \
|
|||||||
оператора: годится ли адрес для данного случая использования.
|
оператора: годится ли адрес для данного случая использования.
|
||||||
- **`fail`** — либо ни одна проверка не прошла, либо адрес вообще не
|
- **`fail`** — либо ни одна проверка не прошла, либо адрес вообще не
|
||||||
дошёл до стадии проверок (например, self-check не подтвердился —
|
дошёл до стадии проверок (например, self-check не подтвердился —
|
||||||
трафик валидатора не пошёл через назначенный FIP — и попытки
|
трафик валидатора не пошёл через назначенный FIP — и число провалов
|
||||||
исчерпались). Смотрите `events` по этому адресу (см. ниже), чтобы
|
достигло потолка `self_check_max_attempts`, см.
|
||||||
|
[«Повтор после сбоя self-check»](#повтор-после-сбоя-self-check)). Смотрите `events` по этому адресу (см. ниже), чтобы
|
||||||
понять, на каком шаге и почему.
|
понять, на каком шаге и почему.
|
||||||
- **`cancelled`** — проверку остановил оператор через `POST
|
- **`cancelled`** — проверку остановил оператор через `POST
|
||||||
/api/v1/admin/ips/{ip}/cancel` (`State` при этом — `failed`), а не
|
/api/v1/admin/ips/{ip}/cancel` (`State` при этом — `failed`), а не
|
||||||
@@ -331,7 +334,19 @@ curl -s http://<control-api>:8080/api/v1/admin/ips \
|
|||||||
Отсутствие ответа от источника (площадка не прислала результат до
|
Отсутствие ответа от источника (площадка не прислала результат до
|
||||||
истечения `checking_window_seconds`) засчитывается как провал — это
|
истечения `checking_window_seconds`) засчитывается как провал — это
|
||||||
управляется настройкой `aggregation.missing_counts_as_fail` в конфиге
|
управляется настройкой `aggregation.missing_counts_as_fail` в конфиге
|
||||||
control-api (по умолчанию включено).
|
control-api (по умолчанию включено). Окно `checking_window_seconds`
|
||||||
|
отсчитывается от начала проверки (состояние `checking`), а не от выдачи
|
||||||
|
адреса валидатору, поэтому привязка Floating IP, пауза `fip_settle_seconds`
|
||||||
|
и self-check в окно не входят.
|
||||||
|
|
||||||
|
**Вердикт и проверки не расходятся.** Проверки фиксируются в момент
|
||||||
|
вердикта: результат, пришедший после него (опоздавший), не сохраняется и не
|
||||||
|
меняет проверки адреса — Floating IP к этому времени уже отвязан, и такая
|
||||||
|
проверка ничего не доказывает. Каждая площадка зондирует адрес один раз за
|
||||||
|
попытку. Отброшенные результаты видны как события `result_dropped` у адреса;
|
||||||
|
в нормальном прогоне их нет или единицы. Недостающий результат (источник не
|
||||||
|
прислал его вовсе) по-прежнему считается провалом, вердикт тогда не выше
|
||||||
|
`partial`.
|
||||||
|
|
||||||
## Просмотр деталей и истории по конкретному адресу
|
## Просмотр деталей и истории по конкретному адресу
|
||||||
|
|
||||||
@@ -385,6 +400,18 @@ curl -s http://<control-api>:8080/api/v1/admin/registry/203.0.113.10 | python3 -
|
|||||||
`/overview`, плюс он отражается в адресной строке (`?q=&status=`), так что
|
`/overview`, плюс он отражается в адресной строке (`?q=&status=`), так что
|
||||||
отфильтрованную ссылку можно сохранить или переслать.
|
отфильтрованную ссылку можно сохранить или переслать.
|
||||||
|
|
||||||
|
В колонке «Последний результат» под вердиктом (`pass`/`partial`/`fail`)
|
||||||
|
показаны два уровня последнего цикла: **Egress** (выходные проверки
|
||||||
|
валидатора) и **Ingress** (входные проверки пробера со всех площадок) в виде
|
||||||
|
«успешно из всего», например `Egress 5 из 5`, `Ingress 3 из 4`. Под каждым
|
||||||
|
уровнем — то же по типам проверок (`https 3 из 3`, `icmp 2 из 2`, `tcp 2 из 3`);
|
||||||
|
порты объединены в тип (`tcp-22` и `tcp-443` — один `tcp`), новый тип
|
||||||
|
проверки появится в списке сам. Цвет: зелёный — все успешны, красный — ни одной,
|
||||||
|
жёлтый — часть. Считаются записанные проверки цикла; вердикт учитывает ещё и
|
||||||
|
недостающие результаты, поэтому при неполном наборе он может быть хуже, чем
|
||||||
|
видно по счётчикам (подсказка при наведении). Те же данные — в
|
||||||
|
`GET /api/v1/admin/registry` ([API.md](API.md#get-apiv1adminregistry)).
|
||||||
|
|
||||||
**Глубина хранения.** Чтобы история не росла бесконечно на адресах,
|
**Глубина хранения.** Чтобы история не росла бесконечно на адресах,
|
||||||
которые перепроверяют очень часто, можно ограничить, сколько последних
|
которые перепроверяют очень часто, можно ограничить, сколько последних
|
||||||
циклов проверки хранить на каждый адрес — `history_retention_cycles` на
|
циклов проверки хранить на каждый адрес — `history_retention_cycles` на
|
||||||
@@ -395,6 +422,53 @@ curl -s http://<control-api>:8080/api/v1/admin/registry/203.0.113.10 | python3 -
|
|||||||
существует, когда впервые встречен, сколько всего было циклов) не
|
существует, когда впервые встречен, сколько всего было циклов) не
|
||||||
удаляется никогда.
|
удаляется никогда.
|
||||||
|
|
||||||
|
## Аналитика запусков
|
||||||
|
|
||||||
|
Страница `/analytics` в дашборде показывает результаты **одного завершённого запуска проверки**: итоги, причины
|
||||||
|
`partial`, подсети, провалы по целям, ingress по площадкам, классы ошибок, валидаторы и качество данных. Данные
|
||||||
|
других запусков на странице не участвуют, поэтому результаты разных прогонов не пересекаются.
|
||||||
|
|
||||||
|
**Что такое запуск.** Запуск открывается, когда адрес попадает в пустую (или полностью обработанную) очередь, а
|
||||||
|
скан автоцикла помечает его как `авто`. Пока он открыт, в него входят все добавленные и перепроверяемые адреса.
|
||||||
|
Когда у всех адресов запуска есть итог, запуск завершается и появляется в списке. Перепроверка после этого
|
||||||
|
открывает **новый** запуск; результаты прежнего остаются как были. Идущий запуск виден в списке, но недоступен
|
||||||
|
(«идёт, 120 из 800»). Запуски, накопленные до появления этой функции, выделены по паузам больше часа.
|
||||||
|
|
||||||
|
**Как читать числа.** Показатели считаются по фактическим проверкам последнего цикла каждого адреса, включая
|
||||||
|
пришедшие позже вердикта; вердикт системы показан рядом. `Egress OK` и `Ingress OK` — доли адресов, у которых все
|
||||||
|
записанные проверки уровня успешны. Блок «Качество данных» показывает, насколько вердикт расходится с проверками
|
||||||
|
(поздние результаты, неполный набор). После изменения «вердикт без опоздавших результатов» поздних результатов в новых
|
||||||
|
запусках быть не должно.
|
||||||
|
|
||||||
|
**Что можно открыть.** Карточки `pass`, `partial` и `fail` (список адресов с этим вердиктом: подсеть, валидатор, Egress и Ingress «успешно из всех», число проверок в цикле, у `partial` ещё причина; `fail` с нулём не кликается), карточки «Egress https: есть провалы / все провалены» и «Ingress ssh: есть провалы / все
|
||||||
|
провалены», а также каждая строка блока «Классы ошибок ingress» открывают окно со списком адресов (для класса ошибок
|
||||||
|
— с распределением по валидаторам и статусом каждой проверки). В окне кнопки «Скачать CSV» (файл от control-api,
|
||||||
|
UTF-8 с BOM, открывается в Excel) и «Копировать». Строка подсети и строка матрицы «подсеть × цель» ведут в «Реестр»
|
||||||
|
с фильтром по запуску и подсети (`/registry?run=…&subnet=…`).
|
||||||
|
|
||||||
|
**Сравнение запусков.** Страница `/analytics/compare` (кнопка «Сравнить с другим запуском» на `/analytics`) показывает
|
||||||
|
динамику между двумя завершёнными запусками: A (старый) и B (новый) выбираются из списков, «Поменять местами» меняет
|
||||||
|
их роли; по умолчанию B — последний запуск, A — предыдущий; выбор хранится в адресе страницы. Страница выделяет три
|
||||||
|
группы адресов: **новые** (есть в B, не было в A: пришли в проект), **выбывшие** (были в A, в B нет) и **изменившиеся**
|
||||||
|
(есть в обоих, но принадлежность к индикаторам разная; в списке столбец «Что изменилось»). Таблица «Динамика по
|
||||||
|
индикаторам» даёт по каждому из семи индикаторов (`pass`, `partial`, `fail`, «Egress https» и «Ingress ssh» — «есть
|
||||||
|
провалы» и «все провалены») значения в A и B, разность и её разложение: новые, выбывшие, вошли, вышли. «Переходы
|
||||||
|
вердикта» — матрица 3×3 по общим адресам. Все числа открывают список адресов с выгрузкой в CSV. Адреса с итогом
|
||||||
|
`cancelled` в сравнение не входят. Если запуски разного состава (например, перепроверка части адресов), новых и
|
||||||
|
выбывших будет много: это состав запусков, а не динамика. API — [API.md](API.md#get-apiv1adminanalyticscomparebasea-targetb).
|
||||||
|
|
||||||
|
**Подсети.** Список задаётся на `/settings` (блок «Подсети»): по одной в строке, CIDR и, через пробел, подпись. Адрес
|
||||||
|
относится к самой узкой подходящей подсети, остальные идут в строку «прочие». Пока список пуст, адреса
|
||||||
|
группируются по /24. То же через API: `PUT /api/v1/admin/config/subnets`.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s http://<control-api>:8080/api/v1/admin/analytics/runs | python3 -m json.tool
|
||||||
|
curl -s http://<control-api>:8080/api/v1/admin/analytics/runs/1 | python3 -m json.tool
|
||||||
|
curl -s -o egress.csv "http://<control-api>:8080/api/v1/admin/analytics/runs/1/lists/egress_https_all?format=csv"
|
||||||
|
```
|
||||||
|
|
||||||
|
Подробности и состав ответов — в [API.md](API.md#аналитика-запусков).
|
||||||
|
|
||||||
## Управление валидаторами
|
## Управление валидаторами
|
||||||
|
|
||||||
Список валидаторов и их текущее состояние:
|
Список валидаторов и их текущее состояние:
|
||||||
@@ -713,6 +787,37 @@ curl -s -X POST http://<control-api>:8080/api/v1/admin/ips/clear
|
|||||||
всё» — каждая с подтверждением, явно предупреждающим о необратимости
|
всё» — каждая с подтверждением, явно предупреждающим о необратимости
|
||||||
(см. [DASHBOARD.md](DASHBOARD.md)).
|
(см. [DASHBOARD.md](DASHBOARD.md)).
|
||||||
|
|
||||||
|
## Повтор после сбоя self-check
|
||||||
|
|
||||||
|
Если self-check адреса не прошёл на валидаторе N, адрес возвращается в
|
||||||
|
очередь, но **этому же валидатору больше не выдаётся**: повтор достаётся
|
||||||
|
другому. Правило действует только для этого адреса. Валидатор N не
|
||||||
|
блокируется и не помечается неисправным, он продолжает брать остальные
|
||||||
|
адреса. Так один временно неисправный валидатор (например, у него не
|
||||||
|
работает трансляция плавающего IP) не расходует все попытки адреса.
|
||||||
|
|
||||||
|
Итог `fail` ставится, когда число проваленных self-check у адреса достигло
|
||||||
|
потолка **«Потолок провалов self-check на адрес»** (`self_check_max_attempts`,
|
||||||
|
по умолчанию 5; `/settings` или `PUT /api/v1/admin/config/orchestrator`,
|
||||||
|
допустимо 1…50). Потолок не зависит от числа валидаторов и действует на
|
||||||
|
следующих повторах без перезапуска. Если все рабочие валидаторы
|
||||||
|
(`idle`, `assigned`, `checking`) уже провалили адрес, а потолок не достигнут
|
||||||
|
(валидаторов меньше потолка, в том числе один), исключения сбрасываются и
|
||||||
|
повторы продолжаются до потолка.
|
||||||
|
|
||||||
|
Исключение создаёт только проваленный self-check. Ошибка привязки
|
||||||
|
плавающего IP, потеря валидатора и истечение лизинга исключений не создают и
|
||||||
|
идут по `orchestrator.max_retries`, как раньше. Поле
|
||||||
|
`orchestrator.max_self_check_retries` в YAML больше не используется.
|
||||||
|
|
||||||
|
Ручная перепроверка или повторная постановка адреса начинает серию заново
|
||||||
|
(счётчик сбоев обнуляется). История сбоев хранится постоянно (таблица
|
||||||
|
`ip_self_check_failures`) и отдаётся в поле `self_check_failed_on` ответов
|
||||||
|
`GET /admin/ips/{ip}` и `GET /admin/registry/{ip}`; на страницах `/ips/{ip}` и
|
||||||
|
`/registry/{ip}` показана строка «Self-check не прошёл на: …». В журнале
|
||||||
|
событий при повторе появляется `validator_excluded`. Показ на странице
|
||||||
|
аналитики — отдельный следующий шаг.
|
||||||
|
|
||||||
## Пауза перед self-check (fip_settle_seconds)
|
## Пауза перед self-check (fip_settle_seconds)
|
||||||
|
|
||||||
Как только Floating IP привязывается к валидатору, control-api по
|
Как только Floating IP привязывается к валидатору, control-api по
|
||||||
@@ -772,6 +877,7 @@ https://api.ipify.org`) и логи `journalctl -u validator-agent` на пре
|
|||||||
|
|
||||||
**Адрес постоянно проваливает self-check (не зависает, а именно
|
**Адрес постоянно проваливает self-check (не зависает, а именно
|
||||||
возвращается в очередь снова и снова).**
|
возвращается в очередь снова и снова).**
|
||||||
|
См. также [«Повтор после сбоя self-check»](#повтор-после-сбоя-self-check): повторы идут на других валидаторах, а список «Self-check не прошёл на: …» показан на странице адреса.
|
||||||
Смотрите `events` по адресу (`GET /api/v1/admin/ips/{ip}`) — в детали
|
Смотрите `events` по адресу (`GET /api/v1/admin/ips/{ip}`) — в детали
|
||||||
события `self_check_result` будет указан обнаруженный исходящий адрес.
|
события `self_check_result` будет указан обнаруженный исходящий адрес.
|
||||||
Если он не совпадает с ожидаемым — вероятно, на ВМ-валидаторе есть другой
|
Если он не совпадает с ожидаемым — вероятно, на ВМ-валидаторе есть другой
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
# План: уровни Egress / Ingress в таблице «Реестр»
|
||||||
|
|
||||||
|
## Контекст
|
||||||
|
|
||||||
|
Колонка «Последний результат» в «Реестре» показывает одну пилюлю общего вердикта (pass / partial / fail / cancelled). Для аналитики этого мало: не видно, где именно сбой — на выходе (egress) или на входе (ingress) — и какой тип проверки упал.
|
||||||
|
|
||||||
|
Нужно разделить результат на два уровня и показать «успешно из всего» (например, «5 из 5») по каждому уровню, с разбивкой по типу проверки (icmp, ssh, tcp, https, tls и новые типы, когда появятся).
|
||||||
|
|
||||||
|
Решения пользователя:
|
||||||
|
- Пилюля общего вердикта остаётся, уровни добавляются под ней. Фильтр по вердикту не меняется.
|
||||||
|
- «Всего» = число записанных проверок последнего цикла (не ожидаемое по настройкам).
|
||||||
|
|
||||||
|
## Что уже есть (по графу и коду)
|
||||||
|
|
||||||
|
- Проверки лежат в `checks` (`internal/db/migrations/0007_ip_registry.sql:39-65`). Уровень задаёт `source`: `egress` или `inbound-site-N` (`internal/db/models.go:39,68-72`). Тип — в `check_type`: `https`, `icmp`, `ssh`, `tcp-<порт>`, `tls-<порт>`.
|
||||||
|
- Индекс `idx_checks_registry_cycle(registry_id, cycle_id)` уже есть. Миграция не нужна.
|
||||||
|
- Цепочка данных: `fillRegistrySummary` (`internal/db/queries_registry.go:199`) → `registrySummaryToDTO` (`internal/httpapi/handlers_registry.go:75`) → `registryDTO` (`internal/httpapi/dto_admin.go:87`) → клиент дашборда → `registryItem` (`internal/dashboard/dto.go:258`) → шаблон `internal/dashboard/templates/registry.html` (`registry_table`, строки 69–101).
|
||||||
|
- Дашборд ходит в БД только через HTTP control-api. Менять нужно оба слоя.
|
||||||
|
|
||||||
|
## Правила расчёта
|
||||||
|
|
||||||
|
- Цикл: максимальный `cycle_id` в `checks` для адреса (так же, как сейчас считается `LastCheckedAt`).
|
||||||
|
- Уровень: `source = 'egress'` → Egress; `source LIKE 'inbound-site-%'` → Ingress. Прочее игнорируется.
|
||||||
|
- Тип: часть `check_type` до первого `-` (`tcp-22`, `tcp-443` → `tcp`; `tls-443` → `tls`; `ssh`, `icmp`, `https` без изменений). Новый тип попадает в разбивку сам, без правок кода.
|
||||||
|
- Ingress: считаются проверки всех площадок вместе (площадок может быть любое число).
|
||||||
|
- Правило разбора живёт в одном месте: две функции в `internal/db/models.go` рядом с `InboundSource`: `CheckLevel(source)` и `CheckFamily(checkType)`.
|
||||||
|
- Группировка делается в Go, не в SQL: SQL отдаёт `GROUP BY registry_id, source, check_type`, и это не больше ~30 строк на адрес.
|
||||||
|
|
||||||
|
## Изменения
|
||||||
|
|
||||||
|
### 1. БД (`internal/db`)
|
||||||
|
- `models.go`: типы `TypeStat{Type, Total, OK}` и `LevelResult{Total, OK, ByType []TypeStat}` (по типам — в алфавитном порядке). Функции `CheckLevel`, `CheckFamily`.
|
||||||
|
- `queries_registry.go`: в `RegistrySummary` добавить `LastCycleID`, `Egress`, `Ingress`. Один пакетный запрос на страницу вместо запроса на каждый адрес:
|
||||||
|
```sql
|
||||||
|
SELECT c.registry_id, c.source, c.check_type, COUNT(*), SUM(c.success)
|
||||||
|
FROM checks c
|
||||||
|
JOIN (SELECT registry_id, MAX(cycle_id) AS cid FROM checks
|
||||||
|
WHERE registry_id IN (…) GROUP BY registry_id) m
|
||||||
|
ON m.registry_id = c.registry_id AND m.cid = c.cycle_id
|
||||||
|
GROUP BY c.registry_id, c.source, c.check_type
|
||||||
|
```
|
||||||
|
Новая функция заполняет сводки списком адресов (порциями по 500). Её вызывают `ListRegistryPage`, `ListRegistry` и `GetRegistryByAddress`. Это заодно убирает N+1 для новых полей.
|
||||||
|
- `lastResultCond` и `fillRegistrySummary` (вердикт) не меняются.
|
||||||
|
|
||||||
|
### 2. HTTP API (`internal/httpapi`)
|
||||||
|
- `dto_admin.go`: в `registryDTO` добавить `last_cycle_id`, `egress`, `ingress` как `{total, ok, by_type: [{type, total, ok}]}`. Изменение только добавляет поля, старые клиенты не ломаются.
|
||||||
|
- `handlers_registry.go`: `registrySummaryToDTO` заполняет новые поля.
|
||||||
|
- `docs/API.md` (раздел «Реестр адресов», ~645–668): новые поля и пример JSON.
|
||||||
|
|
||||||
|
### 3. Дашборд (`internal/dashboard`)
|
||||||
|
- `dto.go`: `registryItem` получает те же поля.
|
||||||
|
- `templates/registry.html`: в ячейке «Последний результат» сверху пилюля вердикта, ниже две строки:
|
||||||
|
`Egress 5 из 5` и `Ingress 3 из 4`, под каждой чипы по типам: `https 3 из 3`, `icmp 2 из 2`. Цвет: все успешны — зелёный, ни одной — красный, иначе жёлтый. Нет проверок — «—». В `title` ячейки: «по записанным проверкам цикла N; вердикт учитывает недостающие результаты». Сохранить `data-label` для мобильной раскладки.
|
||||||
|
- `static/dashboard.css` (~417–423): стили строки уровня и чипа по образцу `pill-*`.
|
||||||
|
- Страница деталей `registry_detail.html` не меняется (вне объёма).
|
||||||
|
|
||||||
|
### 4. Тесты
|
||||||
|
- `internal/db/queries_registry_test.go`: новые тесты — разбивка egress/ingress по типам; `tcp-22` и `tcp-443` сливаются в `tcp`; `tls`, `ssh`; новый тип (например `dns`) появляется в разбивке; адрес без проверок даёт нули; берётся последний цикл; работает после удаления строки очереди; несколько адресов в одном пакетном запросе. Добавить хелпер с ingress-проверками рядом с `finishWithChecks` (`queries_scale_test.go:24`).
|
||||||
|
- `internal/httpapi/handlers_scale_test.go` (`TestAdminRegistryPaginationFiltersAndCompat`): проверить новые поля в ответе.
|
||||||
|
- `internal/dashboard/handlers_test.go` (`TestRegistryPageAndDetail`): фикстура с уровнями, проверка вывода «5 из 5» и имён типов.
|
||||||
|
- `TestScaleSmoke6440` (`queries_scale_test.go:356`): добавить ingress-проверки в засев, лимит 10 с сохраняется.
|
||||||
|
|
||||||
|
## Порядок работы (по правилам проекта)
|
||||||
|
|
||||||
|
1. Скопировать этот план в `docs/changes/2026-10-03_<ЧЧ-ММ>_registry-egress-ingress-levels-plan.md`.
|
||||||
|
2. Реализовать п.1 → п.2 → п.3 → п.4.
|
||||||
|
3. Написать `docs/changes/…-summary.md` (что изменено).
|
||||||
|
4. Обновить `README.md` и `docs/API.md`/`docs/USAGE.md`, где описан реестр.
|
||||||
|
5. Обновить граф: `/graphify . --update`.
|
||||||
|
|
||||||
|
## Проверка
|
||||||
|
|
||||||
|
- `go build ./... && go vet ./... && go test ./...`
|
||||||
|
- `EXPLAIN QUERY PLAN` пакетного запроса: должен идти по `idx_checks_registry_cycle`, без полного перебора `checks`.
|
||||||
|
- Локальный стенд (`scripts/run-local-e2e.sh`, `docs/LOCAL_E2E.md`): прогнать цикл, открыть `/registry`, сверить «N из M» по уровням и типам с таблицей на странице деталей `/registry/<ip>`.
|
||||||
|
- Страница на 6440 адресов отвечает за время порядка прежних 0,12 с (допустим рост в разы, но не секунды).
|
||||||
|
|
||||||
|
## Ограничения и риски
|
||||||
|
|
||||||
|
- «N из M» считается по записанным проверкам. Если результатов не хватает, вердикт может быть хуже, чем «N из M» (например, все записанные успешны, а вердикт `partial`). Это показано подсказкой.
|
||||||
|
- Пока идёт цикл, счётчики отражают частично пришедшие проверки текущего цикла. Состояние цикла видно в колонке состояния.
|
||||||
|
- Фильтра и сортировки по уровням нет: сейчас вне объёма. Если понадобятся для аналитики, это отдельное изменение.
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# Реестр: уровни Egress и Ingress — итог
|
||||||
|
|
||||||
|
План: [2026-10-03_16-24_registry-egress-ingress-levels-plan.md](2026-10-03_16-24_registry-egress-ingress-levels-plan.md).
|
||||||
|
|
||||||
|
## Что сделано
|
||||||
|
|
||||||
|
В колонке «Последний результат» таблицы «Реестр» под вердиктом показаны два уровня последнего цикла:
|
||||||
|
**Egress** и **Ingress** в виде «успешно из всего» (например, «5 из 5»), а под каждым — то же по типам проверок
|
||||||
|
(`https`, `icmp`, `ssh`, `tcp`, `tls`; новый тип появляется сам).
|
||||||
|
|
||||||
|
## Правила
|
||||||
|
|
||||||
|
- Цикл — наибольший `cycle_id` с записанными проверками адреса.
|
||||||
|
- Уровень по `checks.source`: `egress` → Egress, `inbound-site-N` → Ingress (все площадки вместе). Прочие источники не считаются.
|
||||||
|
- Тип — `check_type` до первого дефиса: `tcp-22` и `tcp-443` → `tcp`.
|
||||||
|
- «Всего» — число записанных проверок. Вердикт (`last_result`) учитывает ещё и недостающие результаты, поэтому может быть хуже, чем «N из M». В таблице это отмечено подсказкой.
|
||||||
|
|
||||||
|
## Изменённые файлы
|
||||||
|
|
||||||
|
- `internal/db/models.go` — `CheckLevel`, `CheckFamily`, константы уровней.
|
||||||
|
- `internal/db/queries_registry.go` — `TypeStat`, `LevelResult`, поля `LastCycleID`/`Egress`/`Ingress` в `RegistrySummary`; `fillRegistryLevels` — один сгруппированный запрос на порцию до 500 адресов вместо запроса на адрес (используют `ListRegistry`, `ListRegistryPage`, `GetRegistryByAddress`). Миграция не нужна, запрос идёт по `idx_checks_registry_cycle`.
|
||||||
|
- `internal/httpapi/dto_admin.go`, `handlers_registry.go` — поля `last_cycle_id`, `egress`, `ingress` (только добавление, старые клиенты не ломаются).
|
||||||
|
- `internal/dashboard/dto.go`, `render.go` (функция шаблона `dict`), `templates/registry.html`, `static/dashboard.css` — отображение.
|
||||||
|
- Документация: `docs/API.md`, `docs/USAGE.md`, `docs/DASHBOARD.md`, `README.md`.
|
||||||
|
|
||||||
|
## Не менялось
|
||||||
|
|
||||||
|
Фильтр по вердикту (`lastResultCond`), расчёт `last_result`, страница деталей `/registry/{ip}`, схема БД.
|
||||||
|
|
||||||
|
## Тесты и проверка
|
||||||
|
|
||||||
|
- Новые: `internal/db/queries_registry_levels_test.go` (разбор уровней и типов, нулевые счётчики, последний цикл, несколько адресов, после удаления строки очереди), `TestRegistryLevelsQueryUsesIndex` (план запроса без полного перебора `checks`), `TestAdminRegistryLevels` (API), `TestRegistryPageShowsEgressIngressLevels` (дашборд).
|
||||||
|
- `TestScaleSmoke6440` дополнен проверками (30 на адрес): страница из 100 адресов — около 0,18 с.
|
||||||
|
- `go build ./... && go vet ./... && go test ./...` — без ошибок.
|
||||||
|
- Не проверено вручную на локальном стенде (`scripts/run-local-e2e.sh`) и в браузере: вид колонки на узком экране проверен только по разметке.
|
||||||
|
|
||||||
|
## Ограничения
|
||||||
|
|
||||||
|
- Пока цикл идёт, счётчики отражают частично пришедшие проверки.
|
||||||
|
- Фильтра и сортировки по уровням нет — отдельное изменение, если понадобится для аналитики.
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
# План: раздел «Аналитика»
|
||||||
|
|
||||||
|
Статус: план, код не менялся. Основа — прогон 6440 адресов (2026-10-02 13:47 – 22:29 UTC) и три отчёта в `analysis/`.
|
||||||
|
|
||||||
|
## 1. Зачем
|
||||||
|
|
||||||
|
Сейчас выводы по прогону получены ручными запросами к БД: срезы по подсетям, провалы по целям, ingress по площадкам, расхождение вердикта и проверок. Нужна страница, которая показывает то же самое постоянно, для любого прогона, без SQL.
|
||||||
|
|
||||||
|
Главное требование: переключать **отметку времени** — завершённый запуск проверки, — чтобы данные разных запусков не смешивались.
|
||||||
|
|
||||||
|
## 2. Ключевая находка: «запуска» в данных нет
|
||||||
|
|
||||||
|
`cycle_id` считается **на адрес** (`ip_registry.next_cycle`), а не на весь прогон. В БД сейчас: цикл 1 у 6431 адреса, циклы 2–4 у 9 перепроверенных. По `cycle_id` нельзя выбрать «прогон от 2 октября»: он ничего не группирует.
|
||||||
|
|
||||||
|
Группировка по времени тоже ненадёжна: прогон 6440 адресов шёл 8 ч 42 мин, а перепроверки внутри него шли в то же время.
|
||||||
|
|
||||||
|
Поэтому нужна новая сущность — **запуск** (`run`). Это единственное изменение схемы, без него переключатель невозможен.
|
||||||
|
|
||||||
|
## 3. Модель данных (миграция `0010`)
|
||||||
|
|
||||||
|
Новые таблицы:
|
||||||
|
|
||||||
|
- `check_runs(id, kind, started_at, finalized_at, state)`. `kind`: `auto` (автоцикл), `manual` (добавление, скан, перепроверка). `state`: `open` или `finalized`.
|
||||||
|
- `run_results(run_id, registry_id, ip_address, cycle_id, verdict, aggregated_at, expected_checks, recorded_at_aggregation)`. Одна строка на адрес в запуске. Нужна, потому что вердикт сейчас хранится только в `ip_queue.overall_result` и затирается при перепроверке.
|
||||||
|
- `subnets(cidr PRIMARY KEY, label)`. Список подсетей заказчика (45 шт.) не лежит ни в БД, ни в репозитории, его задаёт администратор.
|
||||||
|
|
||||||
|
Новые колонки: `run_id` в `ip_queue` и `checks`. Индекс `idx_checks_run(run_id, registry_id)`.
|
||||||
|
|
||||||
|
### Правила запуска
|
||||||
|
|
||||||
|
1. Новый запуск открывается, когда в очередь попадает адрес, а открытого запуска нет. Автоцикл открывает запуск явно в начале фазы.
|
||||||
|
2. Пока запуск открыт, все добавленные и перепроверяемые адреса входят в него.
|
||||||
|
3. Запуск **завершается**, когда все его строки очереди в конечном состоянии (`done`, `failed`, `occupied`, отмена). Тогда `finalized_at` = последняя агрегация.
|
||||||
|
4. Перепроверка после завершения открывает **новый** запуск. Поэтому старый запуск не меняется.
|
||||||
|
5. Если адрес перепроверен внутри открытого запуска, в аналитике берётся его последний цикл этого запуска.
|
||||||
|
6. Поздние результаты (пришли после агрегации, как у 50 адресов в анализе 6.5) остаются в своём запуске: `run_id` берётся из строки очереди при записи проверки. Их число показывается отдельно.
|
||||||
|
|
||||||
|
### Заполнение уже накопленных данных
|
||||||
|
|
||||||
|
Запуски выделяются по паузе: если между окончаниями соседних циклов больше 60 минут, начинается новый запуск. Максимальная пауза в текущей БД 0,8 минуты, поэтому получится **один запуск на 6440 адресов**, 9 перепроверок войдут в него. Вердикт берётся из `ip_queue.overall_result`, для прежних циклов без него считается по проверкам и помечается как расчётный.
|
||||||
|
|
||||||
|
## 4. API (control-api, только чтение)
|
||||||
|
|
||||||
|
- `GET /api/v1/admin/analytics/runs` — список запусков: id, тип, начало, конец, адресов, доли `pass/partial/fail`, состояние. Открытый запуск виден, но помечен как идущий.
|
||||||
|
- `GET /api/v1/admin/analytics/runs/{id}` — все блоки страницы одним ответом (десятки КБ):
|
||||||
|
- **summary**: адресов; вердикты; Egress OK и Ingress OK по фактическим проверкам; доли по типам проверок; индикаторы прикладного уровня: адреса, провалившие все egress-проверки https (на запуске 02.10: 307, из них по всем 5 целям 290), и адреса, провалившие все ingress-проверки ssh (7; хотя бы с одной площадки 222); длительность и скорость; число поздних результатов; число неполных наборов.
|
||||||
|
- **partial_reasons**: причины `partial` (только egress; ingress и egress; только ingress; неполный набор; только неполный набор).
|
||||||
|
- **subnets**: по каждой подсети — адресов, `pass`, Egress OK, Ingress OK.
|
||||||
|
- **targets**: egress по цели и типу проверки (процент провалов); матрица «подсеть × цель» для выбранного типа.
|
||||||
|
- **sites**: ingress по площадке и типу проверки.
|
||||||
|
- **validators**: доля провалов egress по валидаторам.
|
||||||
|
- **errors**: классы ошибок по уровню и типу (таймаут, нет маршрута, баннер SSH и др.), классификатор по `checks.detail`.
|
||||||
|
- **data_quality**: поздние результаты, неполные наборы, адреса, где вердикт расходится с проверками.
|
||||||
|
- `GET/PUT /api/v1/admin/config/subnets` — список подсетей (замена целиком, текстом по одной в строке).
|
||||||
|
|
||||||
|
Группировка по типу проверки везде одна и та же, правило `CheckFamily` из `internal/db/models.go` (tcp-22 и tcp-443 → `tcp`). Новый тип появляется в таблицах сам.
|
||||||
|
|
||||||
|
Адрес → подсеть определяется в Go по самому длинному совпавшему префиксу (SQLite не умеет работать с CIDR). Для 6440 адресов это миллисекунды.
|
||||||
|
|
||||||
|
Расчёт идёт одним проходом по `checks` запуска (~190 тыс. строк). Результат завершённого запуска кэшируется в памяти по `run_id` и `MAX(checks.id)` запуска, чтобы поздний результат сбросил кэш.
|
||||||
|
|
||||||
|
## 5. Макет страницы `/analytics?run=<id>`
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─ Аналитика ─────────────────────────────────────────────────────────────┐
|
||||||
|
│ Запуск: ◀ [ 02.10 13:47 → 22:29 · авто · 6440 адр · 30% pass ▾ ] ▶ │
|
||||||
|
│ (идущий запуск виден в списке, но недоступен: «идёт, 120 из 800») │
|
||||||
|
├──────────────────────────────────────────────────────────────────────────┤
|
||||||
|
│ [Адресов 6440] [pass 1962 · 30%] [partial 4478 · 70%] [fail 0] │
|
||||||
|
│ [Egress OK 31%] [Ingress OK 97%] [Длительность 8 ч 42 м] [Поздних 246] │
|
||||||
|
├──────────────────────────────────┬───────────────────────────────────────┤
|
||||||
|
│ Почему partial │ Данные: качество │
|
||||||
|
│ ▇▇▇▇▇▇▇▇▇▇▇▇ только egress 4146 │ Поздние результаты 246 (50 адр.)│
|
||||||
|
│ ▇ ingress+egress 157 │ Неполный набор 167 адресов │
|
||||||
|
│ ▇ egress+неполный набор 125 │ Вердикт ≠ проверки 50 адресов │
|
||||||
|
│ ▏ только ingress 8 │ │
|
||||||
|
├──────────────────────────────────┴───────────────────────────────────────┤
|
||||||
|
│ Подсети [сорт: хуже всего ▾] [показать все 43] │
|
||||||
|
│ подсеть адр. pass% Egress OK% Ingress OK% │
|
||||||
|
│ 161.104.108.0/23 45 ░░░░░ 0% ░░░░░ 0% ▇▇▇▇▇ 100% │
|
||||||
|
│ 83.166.248.0/21 659 ▇░░░░ 11% ▇░░░░ 12% ▇▇▇▇░ 91% →реестр│
|
||||||
|
├──────────────────────────────────────────────────────────────────────────┤
|
||||||
|
│ Egress по целям тип: [https] [icmp] [все] │
|
||||||
|
│ цель провал | подсеть × цель (тепловая карта) │
|
||||||
|
│ packages.ubuntu.com 60% | 83.166.248.0/21 ■■□■■ │
|
||||||
|
│ dl-cdn.alpinelinux.org 34% | 212.233.72.0/21 ■■□■■ │
|
||||||
|
├──────────────────────────────────────────────────────────────────────────┤
|
||||||
|
│ Ingress по площадкам площадка × тип (tcp/ssh/icmp) | классы ошибок │
|
||||||
|
├──────────────────────────────────────────────────────────────────────────┤
|
||||||
|
│ Валидаторы: полоса «доля провалов egress» по 20 валидаторам (≈33–38%) │
|
||||||
|
└──────────────────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
- Два индикатора прикладного уровня (Egress https и Ingress ssh: все провалены) кликабельны: клик открывает окно со списком адресов и кнопкой «Скачать CSV». В рабочей странице список берётся из `GET /admin/analytics/runs/{id}/addresses?list=egress_https_all_failed|ingress_ssh_all_failed` (CSV собирается на сервере, `Content-Disposition: attachment`, UTF-8 с BOM), чтобы не зависеть от размера страницы.
|
||||||
|
- Каждая строка блока «Классы ошибок ingress» кликабельна: окно показывает распределение проваленных проверок класса по валидаторам, вердикт адреса, статус проверки («в вердикте» или «после вердикта») и список с кнопкой «Скачать CSV». Эндпоинт: `GET /admin/analytics/runs/{id}/errors/{class}` (JSON и `?format=csv`).
|
||||||
|
- Выбор запуска хранится в адресной строке (`?run=`), ссылку можно переслать. По умолчанию — последний завершённый запуск.
|
||||||
|
- Каждый блок рассчитан только на выбранный запуск. Данных других запусков на странице нет.
|
||||||
|
- Строка подсети, ячейка матрицы и причина `partial` — ссылки в «Реестр» с фильтром, чтобы увидеть конкретные адреса. Для этого в `GET /admin/registry` и `/registry` добавляются параметры `run`, `subnet`, `target`, `reason`; страница «Реестр» тоже учитывает выбранный запуск.
|
||||||
|
- Рисование: HTML и встроенный SVG на сервере, без библиотек графиков (в дашборде их нет). Цвета и тепловая карта — по руководству навыка `dataviz`, с тёмной темой, как в остальном дашборде.
|
||||||
|
- Пункт «Аналитика» в боковом меню (`internal/dashboard/templates/layout.html`).
|
||||||
|
|
||||||
|
## 6. Файлы
|
||||||
|
|
||||||
|
- БД: `internal/db/migrations/0010_check_runs.sql`, `models.go`, `queries_runs.go`, правки `queries_ipqueue.go` (`SubmitIPs`, `FinishIP`, `CancelIP`, `ClearAllIPs`) и `queries_checks.go` (`UpsertCheck` ставит `run_id`).
|
||||||
|
- Оркестратор: `internal/orchestrator/orchestrator.go` — запись `run_results` при агрегации, завершение запуска; автоцикл открывает запуск.
|
||||||
|
- Аналитика: новый пакет `internal/analytics` (расчёт блоков, классификатор ошибок, подсети).
|
||||||
|
- API: `internal/httpapi/handlers_analytics.go`, `routes.go`, `docs/API.md`.
|
||||||
|
- Дашборд: `internal/dashboard/handlers_analytics.go`, `templates/analytics.html`, `static/dashboard.css`, пункт меню, форма списка подсетей на `/settings`.
|
||||||
|
|
||||||
|
## 7. Поставка тремя шагами
|
||||||
|
|
||||||
|
1. **Запуски**: миграция, правила, заполнение накопленных данных. Результат: в БД один запуск на 6440 адресов. Видимых изменений в UI нет.
|
||||||
|
2. **API аналитики**: расчёт и эндпоинты.
|
||||||
|
3. **Страница**: макет выше, фильтры в реестре.
|
||||||
|
|
||||||
|
Каждый шаг отдельно собирается, тестируется и выкатывается на стенд.
|
||||||
|
|
||||||
|
## 8. Проверка
|
||||||
|
|
||||||
|
- Контрольные числа: расчёт по запуску на копии боевой БД (`rxprod-compose/capi-db`) должен дать цифры отчётов `analysis/`: 6440 адресов, 1962 `pass` / 4478 `partial`; провал egress у 4437; провал HTTPS по `packages.ubuntu.com` у 3841; 290 адресов провалили все цели; ingress провален у 224; 50 `pass` с поздними провалами; 167 неполных наборов. Если цифры не сходятся, расчёт неверен.
|
||||||
|
- Миграция на копии боевой БД: ровно один запуск, `run_id` заполнен у всех `checks` и `ip_queue`, повторный запуск миграции безопасен.
|
||||||
|
- Тесты: изоляция запусков (два запуска с разными результатами у одного адреса не пересекаются); перепроверка после завершения открывает новый запуск, внутри открытого — нет; поздний результат попадает в свой запуск; идущий запуск не выбирается; новый тип проверки (`dns`) появляется в таблицах; подсети (самый длинный префикс, адрес вне списка → «прочие»).
|
||||||
|
- Нагрузка: страница на запуске 6440 адресов, расчёт до ~1 с, повторный запрос из кэша быстрее; `EXPLAIN QUERY PLAN` по `idx_checks_run`.
|
||||||
|
- Вручную на стенде: выбрать запуск, сверить ключевые числа с отчётами, пройти по ссылке из подсети в реестр.
|
||||||
|
|
||||||
|
## 9. Допущения и ограничения
|
||||||
|
|
||||||
|
- **Валидатор у ingress-проверок.** В `checks.validator_id` для проверок пробера пусто. Валидатор адреса в цикле берётся из события `fip_associated` (поле `validator_id` в payload) по `registry_id` и `cycle_id`. На запуске 02.10 все 950 проваленных ingress-проверок нашли валидатора. Надёжнее писать `validator_id` в ingress-проверку при приёме результата; это отдельное маленькое изменение шага 1.
|
||||||
|
- **Классификатор ошибок** работает по `checks.detail` и типу проверки; на запуске 02.10 он даёт 7 классов с суммой 950 (SSH: таймаут 327, ICMP: нет ответа 276, TCP-22: таймаут 260, SSH: баннер «Not allowed» 47, SSH: нет маршрута 18, ICMP: time exceeded 15, TCP-22: нет маршрута 7). Новые тексты ошибок попадают в класс «прочее» и видны в списке.
|
||||||
|
- **Новое наблюдение для блока «Качество данных».** 844 из 950 проваленных ingress-проверок (89%) записаны после агрегации вердикта (среди всех ingress-проверок после вердикта пришло 1430 из 76644, около 1,9%). То есть таймауты приходят позже вердикта систематически, а не случайно. В отчёте анализа 6.5 это видно только для 246 провалов у адресов `pass`.
|
||||||
|
|
||||||
|
- Список подсетей даёт администратор (форма на `/settings`). Пока он пуст, подсети группируются автоматически по `/24`.
|
||||||
|
- Порог 60 минут для заполнения накопленных данных — только для старых записей, настройкой не делается.
|
||||||
|
- Глубина истории (`history_retention_cycles` > 0) удаляет старые проверки, и аналитика старых запусков теряет детали. По умолчанию 0 (хранить всё). Вердикты в `run_results` остаются.
|
||||||
|
- Перед выкладкой миграции обязательна копия `rxprod-compose/capi-db/control-api.db`.
|
||||||
|
- Вне объёма (следующий этап): сравнение двух запусков, выгрузка в CSV, оповещения.
|
||||||
|
- Вердикт системы и фактические проверки считаются отдельно и показаны рядом (по анализу 6.5 они расходятся у 50 адресов), чтобы поздние результаты не скрывались.
|
||||||
|
|
||||||
|
## 10. Порядок по правилам проекта
|
||||||
|
|
||||||
|
План (этот файл) → реализация по шагам из п.7 → `…-summary.md` на каждый шаг → обновление `README.md` и `docs/` → обновление графа.
|
||||||
|
|
||||||
|
## 11. Уточнения при реализации (макет утверждён)
|
||||||
|
|
||||||
|
- Реализуется страница, точно повторяющая макет `docs/mockups/analytics-mockup.html`; отличия только там, где макет был заглушкой (данные, ссылки) или где этого требует рабочее приложение: время в подписях запусков — локальное время дашборда (как везде в нём), матрица «подсеть × цель» строится для любого типа проверки (в макете для `icmp` её не было), надпись про перепроверки показывается, только если они были.
|
||||||
|
- Решения по открытым вопросам плана приняты по умолчанию: перепроверка после завершения запуска открывает новый запуск; список подсетей хранится в БД (`subnets`) и задаётся на `/settings`, пока пуст — группы по /24.
|
||||||
|
- Миграция `0011` (запуски, `run_results`, `subnets`, `run_id` у `ip_queue` и `checks`, заполнение накопленных данных, валидатор у ingress-проверок). Раньше плана «Аналитика» выполнена миграция `0010` (вердикт без опоздавших результатов).
|
||||||
|
- Ссылки из подсетей ведут в «Реестр» с фильтрами `run` и `subnet` (добавлены в `GET /admin/registry` и `/registry`).
|
||||||
|
- **Сайдбар** (новое требование): убраны три точки возле логотипа; индикатор связи с control-api, переключатель темы и кнопка выхода подняты наверх в блок сессии под логотипом; индикатор краснеет («нет связи»), когда control-api недоступен; разделы разбиты на группы «Мониторинг» (Обзор, Очередь IP, Реестр, Аналитика) и «Настройка» (Валидаторы, Площадки, Цели, Типы проверок, Настройки); нижний блок сайдбара убран.
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
# План: вердикт без опоздавших результатов
|
||||||
|
|
||||||
|
Статус: план, код не менялся. Основа: код `internal/orchestrator`, `internal/probercore`, `internal/httpapi` и БД стенда (запуск 2026-10-02, 6440 адресов).
|
||||||
|
|
||||||
|
## 1. Требование
|
||||||
|
|
||||||
|
Вердикт адреса и его проверки должны совпадать. После вердикта результат не может появиться или измениться. Вердикт можно пересчитать из сохранённых проверок и получить то же значение.
|
||||||
|
|
||||||
|
## 2. Причины (проверены по коду и данным)
|
||||||
|
|
||||||
|
1. **Prober проверяет один адрес много раз.** `GET /probers/{site}/assignments` отдаёт все адреса в состоянии `checking`. Prober (`probercore.pollOnce`) обходит их при каждом опросе (каждые 5 с) и ничего не помнит о том, что адрес уже проверен. Пока адрес ждёт остальные площадки и egress, он проверяется снова и снова.
|
||||||
|
2. **Новый результат затирает старый.** Результаты пишутся через `UpsertCheck` с `ON CONFLICT DO UPDATE`. Строка живёт с первой записи, а значения берутся из последнего круга. В БД 61 406 из 76 644 ingress-строк (80%) перезаписаны позже первой записи более чем на 3 с. У egress перезаписей нет (агент проверяет один раз).
|
||||||
|
3. **Записи принимаются после вердикта.** `Orchestrator.RecordCheck` вызывает `UpsertCheck` без проверки состояния адреса. Итог на запуске 02.10:
|
||||||
|
- ingress: 1430 строк записаны после вердикта (844 проваленных и 586 успешных); из 844 проваленных 833 записаны уже после отвязки Floating IP, то есть проверяли адрес, который к валидатору уже не привязан;
|
||||||
|
- egress: 351 строка после вердикта (32 проваленных).
|
||||||
|
4. **Окно считается не с начала проверки.** `isReadyToAggregate` сравнивает `assigned_at` с порогом `checking_window_seconds` (120 с). `assigned_at` ставится при выдаче адреса валидатору, то есть окно включает привязку Floating IP, паузу `fip_settle_seconds` (30 с) и self-check (до 60 с). На сами проверки остаётся около 30 с. По окну агрегировано 509 адресов (8%), у них часть результатов не успела прийти.
|
||||||
|
5. **Время сравнивается чужими часами.** `checks.checked_at` ставит prober или агент на своей машине, а `aggregated_at` — control-api. При расхождении часов «после вердикта» определяется неверно.
|
||||||
|
|
||||||
|
Следствие: часть проваленных ingress-проверок в БД — не провалы адреса, а результат проверки уже отвязанного Floating IP. Отчёты по провалам ingress (в том числе таймаутам) за запуск 02.10 нужно читать с этой поправкой.
|
||||||
|
|
||||||
|
## 3. Решение
|
||||||
|
|
||||||
|
### A. Одна проверка адреса на площадку и попытку
|
||||||
|
`handleProberAssignments` не отдаёт адрес, для которого эта площадка уже отметила `complete` в `ip_site_checks` в текущей попытке. Новая попытка (повтор после сбоя) отдаёт адрес снова. Prober менять не нужно, пересобирается только `control-api`. Побочный эффект: нагрузка на prober и на сеть падает в разы.
|
||||||
|
|
||||||
|
### B. После вердикта запись закрыта
|
||||||
|
`UpsertCheck` пишет строку только если адрес в состоянии `checking` и номер попытки совпадает. Проверка выполняется в одном SQL-запросе (условие в `INSERT … SELECT … WHERE EXISTS`), без гонок.
|
||||||
|
- Отброшенный результат не пишется и не меняет существующую строку.
|
||||||
|
- Ответ агенту и prober остаётся `200 {"ok": true, "ignored": true}`, чтобы они не повторяли запрос.
|
||||||
|
- На каждую отброшенную пачку пишется одно событие `result_dropped` (источник, число проверок). Счётчик виден в аналитике; в норме он равен нулю или близок к нему.
|
||||||
|
|
||||||
|
### C. Окно проверки считается с начала проверки
|
||||||
|
Новая колонка `ip_queue.checking_started_at`, ставится в `SetChecking`. `isReadyToAggregate` сравнивает порог с ней, а не с `assigned_at`. Значение `checking_window_seconds` не меняется (120 с), но теперь это 120 с именно на проверки. Для строк без значения (старые данные) используется `assigned_at`.
|
||||||
|
|
||||||
|
### D. Время записи ставит сервер
|
||||||
|
Новая колонка `checks.recorded_at` — время последней записи по часам control-api; при перезаписи обновляется. Все сравнения «до/после вердикта» идут по ней, а не по `checked_at`. Для старых строк значение равно `created_at`.
|
||||||
|
|
||||||
|
### E. Вердикт воспроизводим
|
||||||
|
При агрегации в событие `aggregated` дописываются `egress_total`, `ingress_total`. Тест-инвариант: вердикт, пересчитанный по сохранённым проверкам адреса с учётом недостающих, равен `overall_result`.
|
||||||
|
|
||||||
|
### F. Недостающие результаты
|
||||||
|
Правило не меняется: недостающая проверка считается провалом, вердикт не выше `partial`. Благодаря C число таких адресов должно упасть. Остаток показывается отдельно («нет результата»), а не смешивается с провалами.
|
||||||
|
|
||||||
|
### G. Старые данные
|
||||||
|
В миграции `0010` колонка `checks.after_verdict` (0/1) для существующих строк: `1`, если `checked_at` позже `aggregated_at` строки очереди. Пересчитать затёртые результаты нельзя, поэтому в аналитике они помечаются как недостоверные и показываются отдельно (на запуске 02.10: 1430 ingress и 351 egress). После внедрения для новых данных значение всегда `0`.
|
||||||
|
|
||||||
|
Отвергнутый вариант: пересчитывать вердикт при опоздавших результатах. К этому моменту Floating IP уже отвязан, и такие результаты ничего не доказывают.
|
||||||
|
|
||||||
|
## 4. Файлы
|
||||||
|
|
||||||
|
- `internal/db/migrations/0010_verdict_integrity.sql` — колонки `ip_queue.checking_started_at`, `checks.recorded_at`, `checks.after_verdict`.
|
||||||
|
- `internal/db/queries_checks.go` — условная запись, признак «отброшено».
|
||||||
|
- `internal/db/queries_ipqueue.go` — `SetChecking`, выборка для prober без адресов с готовой площадкой.
|
||||||
|
- `internal/orchestrator/orchestrator.go` — `RecordCheck` возвращает признак, `isReadyToAggregate` по `checking_started_at`, поля в событии `aggregated`.
|
||||||
|
- `internal/httpapi/handlers_agent.go`, `handlers_prober.go` — ответ `ignored`, событие `result_dropped`.
|
||||||
|
- Документы: `docs/API.md` (ответы на запись результатов), `docs/USAGE.md`, `README.md`.
|
||||||
|
- Нумерация миграций: этот план идёт раньше плана аналитики (`…_analytics-section-plan.md`); аналитика получает `0011`.
|
||||||
|
|
||||||
|
## 5. Тесты
|
||||||
|
|
||||||
|
- Запись после вердикта игнорируется: строка не создана и не изменена; запись в состоянии `checking` проходит; запись старой попытки игнорируется.
|
||||||
|
- Повторная запись той же проверки внутри окна идемпотентна.
|
||||||
|
- `assignments`: после `complete` площадки адрес не возвращается ей, но возвращается остальным; после повтора попытки возвращается снова.
|
||||||
|
- Окно считается с `checking_started_at`: адрес, назначенный давно, но начавший проверку только что, не агрегируется по окну.
|
||||||
|
- Инвариант вердикта: для набора сценариев (все успешны, часть провалена, часть недостающих, ничего) вердикт равен пересчёту.
|
||||||
|
- Миграция на копии боевой БД: `after_verdict` = 1 для 1430 ingress и 351 egress строк запуска 02.10, остальное без изменений; повторный запуск безопасен.
|
||||||
|
|
||||||
|
## 6. Проверка на стенде
|
||||||
|
|
||||||
|
1. Копия `rxprod-compose/capi-db/control-api.db`, пересборка и перезапуск `control-api` (по процедуре из `docs/SETUP.md`). Prober и агенты не пересобираются.
|
||||||
|
2. Контрольный прогон на небольшой партии (например, 300 адресов).
|
||||||
|
3. Ожидаемый результат: ни одной строки `checks` с `recorded_at` позже `aggregated_at` (`after_verdict = 0`); нет перезаписанных ingress-строк (`recorded_at` равен первой записи); событий `result_dropped` нет или единицы; адресов с агрегацией по окну заметно меньше 8%.
|
||||||
|
4. Сравнение с запуском 02.10: доля проваленных ingress-проверок (таймауты ssh, tcp-22, icmp) должна уменьшиться, если часть прежних провалов была отвязанным Floating IP. Если не уменьшится, версия про отвязку неверна, и нужно искать другую причину.
|
||||||
|
|
||||||
|
## 7. Риски
|
||||||
|
|
||||||
|
- Отброшенные результаты теряются. Это сознательно: после вердикта Floating IP отвязан. Счётчик `result_dropped` показывает, насколько часто это случается.
|
||||||
|
- Уменьшение числа проверок prober меняет нагрузку на сеть площадок. Это ожидаемый эффект, а не риск, но стоит предупредить владельцев площадок.
|
||||||
|
- Новое окно (с начала проверки) может чуть увеличить длительность прогона на адресах, у которых действительно не пришли результаты. Значение окна настраивается.
|
||||||
|
|
||||||
|
## 8. Порядок по правилам проекта
|
||||||
|
|
||||||
|
План (этот файл) → реализация → `…-summary.md` → обновление `README.md` и `docs/` → пересборка стенда → контрольный прогон → обновление графа. Раздел «Аналитика» (план `2026-10-03_16-39`) строится после этого изменения: «Поздние результаты» там становятся контрольным показателем, который должен быть равен нулю.
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
# Вердикт без опоздавших результатов — итог
|
||||||
|
|
||||||
|
План: [2026-10-03_17-21_verdict-no-late-results-plan.md](2026-10-03_17-21_verdict-no-late-results-plan.md).
|
||||||
|
|
||||||
|
Статус: код и тесты готовы. На стенд не выкладывалось, контрольный прогон не проводился.
|
||||||
|
|
||||||
|
## Что сделано
|
||||||
|
|
||||||
|
1. **Один проход площадки на адрес.** `GET /probers/{site}/assignments` больше не отдаёт адрес, для которого эта площадка отметила `complete` в текущей попытке (`DB.ListCheckingForSite`). Другим площадкам адрес выдаётся, новая попытка выдаёт его снова. Prober не менялся.
|
||||||
|
2. **После вердикта запись закрыта.** `DB.UpsertCheckIfOpen` пишет проверку только если строка очереди существует, попытка совпадает с текущей и состояние не `aggregating`, `done`, `failed`, `occupied`. Проверка состояния и запись — один SQL-запрос. Отброшенный результат не создаёт и не меняет строк. Ответ `200 {"ok": true, "ignored": N}`; на каждый адрес пишется событие `result_dropped`. `UpsertCheck` и `Orchestrator.RecordCheck` оставлены как обёртки для существующих вызовов.
|
||||||
|
3. **Окно проверки с её начала.** Новая колонка `ip_queue.checking_started_at` (ставится в `SetChecking`, сбрасывается при повторе). `isReadyToAggregate` считает `checking_window_seconds` от неё, для старых строк — от `assigned_at`.
|
||||||
|
4. **Время записи по часам сервера.** Колонка `checks.recorded_at`, обновляется при каждой принятой записи.
|
||||||
|
5. **Вердикт воспроизводим.** Правило вынесено в чистую функцию `computeVerdict`; в событие `aggregated` добавлены `egress` и `ingress` (число проверок по уровням).
|
||||||
|
6. **Старые данные.** Миграция `0010_verdict_integrity.sql`: `recorded_at` = `created_at`, колонка `after_verdict` = 1 у строк, записанных после вердикта (`julianday(checked_at) > julianday(aggregated_at)`).
|
||||||
|
|
||||||
|
## Проверка на копии боевой БД (запуск 02.10, 141 005 проверок)
|
||||||
|
|
||||||
|
Миграция применилась за секунды, `user_version` = 10, `recorded_at` заполнен у всех строк. Помечено `after_verdict`:
|
||||||
|
|
||||||
|
| | всего | провалов | успешных |
|
||||||
|
|---|--:|--:|--:|
|
||||||
|
| ingress | 1430 | 844 | 586 |
|
||||||
|
| egress | 351 | 32 | 319 |
|
||||||
|
|
||||||
|
В плане было 1426 и 350: они считались сравнением строк времени, миграция сравнивает точнее.
|
||||||
|
|
||||||
|
## Тесты
|
||||||
|
|
||||||
|
- `internal/db/queries_verdict_integrity_test.go`: запись принимается, пока адрес проверяется, и идемпотентна; после начала агрегации и после вердикта не создаёт и не меняет строк; результат прежней попытки отбрасывается; `recorded_at` растёт, `created_at` нет; `ListCheckingForSite` (готовая площадка, другая площадка, новая попытка); `checking_started_at` ставится и сбрасывается; миграция 0010 на базе версии 9.
|
||||||
|
- `internal/orchestrator/verdict_integrity_test.go`: таблица `computeVerdict` (7 случаев); окно от начала проверки и запасной вариант `assigned_at`; полный цикл: после вердикта результат не принят, сохранённые проверки не изменились, вердикт равен пересчёту.
|
||||||
|
- `internal/httpapi/handlers_verdict_integrity_test.go`: площадка получает адрес до `complete`, после него нет, другая площадка получает; результаты prober и агента после вердикта дают `ignored`, строки не изменены, два события `result_dropped`.
|
||||||
|
- `go build ./... && go vet ./... && go test ./...` проходят.
|
||||||
|
|
||||||
|
## Что не проверено
|
||||||
|
|
||||||
|
- Работа на живом стенде и контрольный прогон. Гипотеза «часть прежних провалов ingress — проверка отвязанного Floating IP» подтвердится или нет только им: после изменения доля провалов ssh, tcp-22 и icmp должна упасть. Если не упадёт, причину нужно искать в другом месте.
|
||||||
|
- Нагрузка на сеть площадок изменится: prober теперь зондирует адрес один раз, а не при каждом опросе.
|
||||||
|
|
||||||
|
## Что дальше
|
||||||
|
|
||||||
|
Пересборка и перезапуск только `control-api` (prober и агенты без изменений), копия БД перед миграцией, контрольный прогон на небольшой партии (300 адресов). Раздел «Аналитика» строится после этого и получает миграцию `0011`.
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# Раздел «Аналитика» — итог
|
||||||
|
|
||||||
|
План: [2026-10-03_16-39_analytics-section-plan.md](2026-10-03_16-39_analytics-section-plan.md). Макет: [docs/mockups/analytics-mockup.html](../mockups/analytics-mockup.html).
|
||||||
|
|
||||||
|
Статус: код, тесты и документация готовы. На стенд не выложено (бинарники `bin/` не пересобирались), не закоммичено.
|
||||||
|
|
||||||
|
## Что сделано
|
||||||
|
|
||||||
|
**Запуски (миграция `0011`).** Новые таблицы `check_runs`, `run_results`, `subnets`; колонки `run_id` у `ip_queue` и `checks`. Запуск открывается, когда адрес попадает в пустую или полностью обработанную очередь (`SubmitIPsAs`, `SeedQueue`), принимает всё добавленное и перепроверенное, пока открыт, и завершается, когда у всех его адресов есть итог или они удалены (`finalizeRunsTx` в `FinishIPExpected`, `CancelIP`, `RequeueOrFail`, `MarkFIPOccupied`, удалении и очистке; плюс страховка в такте оркестратора). Скан автоцикла помечает запуск `auto`. Итог адреса (`run_results`) пишется при вердикте вместе с ожидаемым и записанным числом проверок. Ingress-проверка получает `validator_id` держателя адреса при записи. Накопленные данные размечены миграцией: запуски выделяются паузами больше часа, итоги берутся из очереди или считаются по проверкам (помечаются `verdict_derived`), валидатор ingress восстановлен из события `fip_associated`; живые строки очереди без запуска попадают в открытый запуск при открытии БД.
|
||||||
|
|
||||||
|
**Расчёт (`internal/analytics`).** Показатели считаются по фактам: все проверки последнего цикла каждого адреса запуска, в том числе пришедшие позже вердикта. Блоки: показатели, причины `partial`, качество данных, подсети, цели и матрица «подсеть × цель» по типам проверок, площадки, классы ошибок, валидаторы; списки адресов (4 индикатора и класс ошибки). Подсеть — самая узкая подходящая; без списка — /24.
|
||||||
|
|
||||||
|
**API.** `GET /admin/analytics/runs`, `/runs/{id}` (кэш по версии данных запуска и списку подсетей; открытый запуск — 409), `/runs/{id}/lists/{kind}` (JSON и `?format=csv`), `GET`/`PUT /admin/config/subnets`; фильтры `run` и `subnet` в `GET /admin/registry`.
|
||||||
|
|
||||||
|
**Страница `/analytics`.** Точно по макету: выбор запуска (идущий виден, недоступен), 12 карточек, причины `partial`, качество данных, подсети, egress по целям с вкладками по типу и тепловой картой, ingress по площадкам, классы ошибок, валидаторы; окна со списками адресов, подсказками и выгрузкой CSV (скачивание — с сервера, `Content-Disposition: attachment`). Стили `static/analytics.css` (классы с префиксом `an-`, не пересекаются со стилями дашборда), скрипт `static/analytics.js`. В `/settings` блок «Подсети». Из подсетей и матрицы — переход в «Реестр» с фильтром (`/registry?run=…&subnet=…`, плашка фильтра со сбросом).
|
||||||
|
|
||||||
|
**Сайдбар.** Убраны три точки у логотипа. Индикатор связи с control-api (краснеет «нет связи» при сбое), переключатель темы и кнопка «Выйти» подняты наверх, в блок сессии под логотипом. Разделы разбиты на «Мониторинг» (Обзор, Очередь IP, Реестр, Аналитика) и «Настройка». Нижний блок убран.
|
||||||
|
|
||||||
|
## Проверка
|
||||||
|
|
||||||
|
- `go build ./... && go vet ./... && go test ./...` проходят. Новые тесты: БД (жизненный цикл запуска, присоединение и новый запуск при перепроверке, очистка и удаление, отмена и провал по повторам, валидатор ingress, подсети, фильтры реестра, миграция `0011` на базе версии 10), `internal/analytics` (расчёт по синтетическим данным, подсети, классы ошибок, списки), API (отчёт, списки, CSV, кэш, подсети, фильтры, 409/404/400), дашборд (страница одного запуска и пустое состояние, прокси списков и CSV, сайдбар, индикатор связи, форма подсетей, drill-down в реестр).
|
||||||
|
- **Контрольные числа** на копии боевой БД (запуск 02.10, 6440 адресов) после миграции `0011` совпали с отчётами `analysis/`: 1962 `pass` / 4478 `partial`; Egress OK 2003, Ingress OK 6215; причины `partial` 4146 / 157 / 125 / 9 / 33 / 8; https: есть провалы 4409, все провалены 307 (по всем 5 целям 290); ssh: есть провалы 222, все провалены 7; провалы по целям 3841 / 2193 / 1872 / 1805 / 1728; первая строка матрицы 83.166.248.0/21: 81 / 57 / 51 / 86 / 46; классы ошибок 327 / 276 / 260 / 47 / 18 / 15 / 7; поздние провалы 246 у 50 адресов, 844 из 950 ingress-провалов после вердикта, неполный набор 167, `pass` по фактам 1912. Миграция на копии — около 8 с, расчёт отчёта — около 2,5 с.
|
||||||
|
- **В браузере** (headless Chrome, локальный control-api и дашборд на той же копии): страница на 1440 px и 390 px, без горизонтальной прокрутки на телефоне; окна списков (4 409 строк) и класса ошибок открываются, кнопки внутри окна видны, вкладки типов и матрица работают, CSV отдаётся файлом.
|
||||||
|
|
||||||
|
## Отличия от макета
|
||||||
|
|
||||||
|
- Время в подписях запусков — локальное время дашборда (в макете было UTC).
|
||||||
|
- Матрица «подсеть × цель» строится и для `icmp` (в макете для него её не было).
|
||||||
|
- Строка «Перепроверено внутри запуска» показывается, только если такие адреса есть (в БД стенда прежние циклы этих адресов уже удалены, поэтому 0).
|
||||||
|
- Карточки не переносят значение на вторую строку: минимальная ширина карточки 168 px, на телефоне шрифт значения меньше.
|
||||||
|
- Таблицы данных на телефоне прокручиваются вбок, а не превращаются в карточки, как остальные таблицы дашборда.
|
||||||
|
|
||||||
|
## Что не сделано и ограничения
|
||||||
|
|
||||||
|
- Выкладка на стенд: нужна пересборка `control-api` и `admin-dashboard` и миграция `0011` на боевой БД (копия БД перед ней обязательна; процедура — в памяти проекта и в `docs/SETUP.md`). После выкладки задать список подсетей клиента на `/settings` (45 подсетей из отчёта) — без него адреса группируются по /24.
|
||||||
|
- Подсказки при наведении не работают на сенсорных экранах и с клавиатуры (как и в макете).
|
||||||
|
- В сайдбаре на узком экране (меню-«бургер») новый блок сессии я не просматривал отдельно.
|
||||||
|
- Фильтр реестра по подсети ограничен адресами, попавшими в список подсетей: строка «прочие» без ссылки.
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
# План: повтор после сбоя self-check — на другом валидаторе
|
||||||
|
|
||||||
|
Статус: реализовано, см. [итог](2026-10-04_08-01_self-check-exclude-validator-summary.md).
|
||||||
|
|
||||||
|
## 1. Проблема
|
||||||
|
|
||||||
|
В запуске 2 два адреса получили `fail`: `89.208.220.90` и `89.208.221.74`. Оба раза self-check провалился четыре раза подряд на одном валидаторе `vkiplab-v17` (он выходил в сеть с общего адреса облака `109.120.182.224`, а не с плавающего IP), с интервалом около 70 секунд.
|
||||||
|
|
||||||
|
Причина в логике повтора: после сбоя адрес возвращается в начало очереди, а освободившийся `v17` берёт следующий адрес с наименьшим `sequence`, то есть тот же. Один временно неисправный валидатор расходует все попытки адреса. Сам адрес исправен: `89.208.216.141`, попавший на `v17` дважды, после перехода на `v13` прошёл проверки.
|
||||||
|
|
||||||
|
## 2. Требования и принятые решения
|
||||||
|
|
||||||
|
1. Адрес, не прошедший self-check на валидаторе N, при повторе **не отдаётся валидатору N**. Правило действует только для этого адреса.
|
||||||
|
2. Валидатор N остаётся в системе как был: не блокируется, не помечается неисправным, продолжает брать и проверять все остальные адреса.
|
||||||
|
3. **Итог `fail`** ставится, когда число проваленных self-check у адреса достигло **потолка**. Потолок не зависит от числа валидаторов. Это **настройка** `self_check_max_attempts`: она меняется в разделе настроек `/settings` и через API; **значение по умолчанию для текущего окружения — 5**. Исключение валидаторов (п.1) гарантирует, что первые попытки идут на разных валидаторах: адрес получает `fail` после 5 провалов на 5 разных валидаторах (а не на одном).
|
||||||
|
4. Исключение создаёт **только** проваленный self-check; на ошибки привязки плавающего IP, потерю валидатора и истечение аренды оно не распространяется.
|
||||||
|
5. Сведения «Self-check не прошёл на: …» сохраняются и отдаются в API для последующего показа на странице аналитики.
|
||||||
|
|
||||||
|
## 3. Решение
|
||||||
|
|
||||||
|
### 3.1. Данные (миграция `0012_self_check_failures.sql`)
|
||||||
|
|
||||||
|
- Таблица `ip_self_check_failures(registry_id, run_id, cycle_id, attempt_number, validator_id, failed_at, detail)`. Постоянная история сбоев self-check по адресу; не очищается при перепроверках, живёт вместе с реестром (не удаляется вместе со строкой очереди) и служит источником для аналитики.
|
||||||
|
- Колонки `ip_queue.sc_failures` (сколько self-check провалено в текущей серии попыток) и `ip_queue.sc_round_start_attempt` (номер попытки, с которой действуют исключения; «раунд»).
|
||||||
|
- Настройка `self_check_max_attempts` в таблице `settings`: миграция записывает **5** (допустимо 1…50), дальше значение меняется в `/settings` или через API. Поле `orchestrator.max_self_check_retries` в YAML для self-check больше не используется (остаётся в файле для совместимости, в документации помечается устаревшим).
|
||||||
|
|
||||||
|
Исключение для валидатора N на адресе действует, если в `ip_self_check_failures` есть сбой этого валидатора на этом адресе с `attempt_number >= sc_round_start_attempt`.
|
||||||
|
|
||||||
|
### 3.2. Обработка сбоя (`Orchestrator.SelfCheckResult`, ветка «не прошёл»)
|
||||||
|
|
||||||
|
После проверки, что адрес принадлежит этому валидатору и ждёт self-check, и отвязки плавающего IP (как сейчас):
|
||||||
|
|
||||||
|
1. Записать сбой в `ip_self_check_failures`, увеличить `sc_failures`.
|
||||||
|
2. Решение:
|
||||||
|
- **`sc_failures >= self_check_max_attempts`** → `fail` (причина «self-check не прошёл N раз», в событии перечислены валидаторы);
|
||||||
|
- иначе → вернуть адрес в очередь. Если среди рабочих валидаторов (`idle`, `assigned`, `checking`; `unreachable` и `unregistered` не считаются) не осталось ни одного без сбоя в текущем раунде, начинается новый раунд (`sc_round_start_attempt` = следующая попытка): исключения теряют силу, повтор идёт по обычным правилам. Так при числе валидаторов меньше потолка (в том числе при единственном) повторы продолжаются до потолка, а адрес не застревает в очереди.
|
||||||
|
|
||||||
|
Лимит `max_retries` и счётчик `retry_count` для self-check больше не используются: возврат в очередь после сбоя self-check не увеличивает `retry_count` и не может привести к `fail` по нему. Для остальных причин возврата (ошибка привязки, истечение аренды) всё остаётся как сейчас.
|
||||||
|
|
||||||
|
### 3.3. Выдача адресов (`DB.ClaimNextQueued`)
|
||||||
|
|
||||||
|
Валидатор получает ближайший по `sequence` адрес, **кроме** тех, где он исключён (по 3.1). Исключённый адрес остаётся в очереди для остальных валидаторов и очередь не блокирует. Запрос по-прежнему одной транзакцией.
|
||||||
|
|
||||||
|
### 3.4. Жизненный цикл
|
||||||
|
|
||||||
|
- Ручная перепроверка или повторная постановка адреса (`SubmitIPs`) начинает новую серию: `sc_failures = 0`, `sc_round_start_attempt` = текущая попытка.
|
||||||
|
- История в `ip_self_check_failures` остаётся.
|
||||||
|
- Удаление адреса и очистка очереди историю не трогают; `docs/ADMIN_CLEANUP.md` дополняется новой таблицей.
|
||||||
|
|
||||||
|
### 3.5. Данные для аналитики и видимость
|
||||||
|
|
||||||
|
- Событие `self_check_result` остаётся как сейчас; добавляется событие `validator_excluded` (`{"validator_id": …, "failures": N}`).
|
||||||
|
- `GET /admin/ips/{ip}` и `GET /admin/registry/{ip}` получают поле `self_check_failed_on` (список валидаторов, у которых self-check на этом адресе не прошёл; для реестра — по всем запускам, для запуска — фильтр по `run_id`).
|
||||||
|
- Строка «Self-check не прошёл на: v17, …» на странице адреса (`/ips/{ip}`, `/registry/{ip}`).
|
||||||
|
- **Отображение на странице аналитики не входит в эту доработку:** данные и API будут готовы, показ (колонка в списках адресов, блок «Self-check по валидаторам») делается следующим шагом отдельным планом.
|
||||||
|
|
||||||
|
### 3.6. Настройка в интерфейсе (`/settings`)
|
||||||
|
|
||||||
|
Изменения отражаются в разделе настроек явно:
|
||||||
|
- В форме с `fip_settle_seconds` и `history_retention_cycles` добавляется поле **«Потолок провалов self-check на адрес»** (`self_check_max_attempts`), целое число, по умолчанию 5, допустимо 1…50.
|
||||||
|
- Под полем пояснение: «Сколько раз self-check может не пройти у одного адреса, прежде чем адрес получит итог `fail`. Повторы идут на других валидаторах: валидатор, на котором адрес не прошёл self-check, этому адресу больше не выдаётся (на остальные адреса это не влияет)».
|
||||||
|
- Значение сохраняется той же кнопкой «Сохранить», действует на следующих повторах без перезапуска; неверное значение (не число, вне 1…50) показывается предупреждением в баннере, форма остаётся прежней.
|
||||||
|
- В API: `GET/PUT /admin/config/orchestrator` получает поле `self_check_max_attempts` (ошибка 400 при неверном значении).
|
||||||
|
- Описание поля добавляется в `docs/DASHBOARD.md` (строка `/settings`) и `docs/USAGE.md`.
|
||||||
|
|
||||||
|
## 4. Файлы
|
||||||
|
|
||||||
|
- БД: `internal/db/migrations/0012_self_check_failures.sql`, `db.go`, `queries_ipqueue.go` (`ClaimNextQueued`, запись сбоя, новый возврат в очередь без `retry_count`, принудительный `fail`, сброс серии в `SubmitIPsAs`), `queries_settings.go` (настройка), запрос истории для API.
|
||||||
|
- Оркестратор: `orchestrator.go` (`SelfCheckResult`), `config.go` (начальное значение настройки).
|
||||||
|
- API и дашборд: `handlers_admin.go`, `handlers_config.go`, DTO, `handlers_settings.go`, `settings.html`, `ip_detail.html`, `registry_detail.html`.
|
||||||
|
- Документы: `USAGE.md` («Как читать итоговый результат», повторы self-check, настройка), `API.md`, `ADMIN_CLEANUP.md`, `README.md`, итог `docs/changes/…-summary.md`.
|
||||||
|
|
||||||
|
## 5. Тесты
|
||||||
|
|
||||||
|
- **БД:** валидатор, на котором адрес исключён, пропускает его и берёт следующий; другой валидатор берёт исключённый адрес; исключения действуют только для этого адреса; новый раунд снимает исключения; перепостановка сбрасывает серию, но не историю; настройка (значения по умолчанию, границы).
|
||||||
|
- **Оркестратор (сценарий инцидента на трёх валидаторах):** v1 всегда проваливает self-check — адрес не возвращается на v1, проходит на v2, а v1 в это время берёт и проходит другие адреса; потолок: адрес, провалившийся `self_check_max_attempts` раз, получает `fail`, раньше — нет; при потолке меньше числа валидаторов `fail` наступает на потолке без перебора всех; при потолке больше числа валидаторов начинается новый раунд; единственный валидатор повторяет на себе до потолка; `unreachable` не считается валидатором; сбой привязки и истечение аренды исключений и счётчика self-check не создают и по-прежнему идут по `max_retries`; изменение настройки действует на следующем повторе.
|
||||||
|
- **API и дашборд:** поле `self_check_failed_on`; поле «Потолок провалов self-check на адрес» отображается в `/settings` со значением 5, сохраняется, неверные значения показывают предупреждение; поле в `GET/PUT /admin/config/orchestrator`; строка «Self-check не прошёл на: …» на странице адреса.
|
||||||
|
- Миграция `0012` на копии боевой БД (настройка равна 5), повторный запуск безопасен. Полный `go build ./... && go vet ./... && go test ./...`.
|
||||||
|
|
||||||
|
## 6. Выкладка и проверка
|
||||||
|
|
||||||
|
Пересборка и перезапуск `control-api` и `admin-dashboard` (меняется форма настроек и страница адреса); агенты и prober без изменений. Порядок: проверка пустой очереди, копия БД, тег отката образа, миграция `0012`. Сбой на стенде воспроизвести нельзя, поэтому проверка там — штатный небольшой прогон без зависших `queued`; логику повторов покрывает тест на трёх валидаторах.
|
||||||
|
|
||||||
|
## 7. Риски и последствия принятого решения
|
||||||
|
|
||||||
|
- **Время до `fail` у неисправного адреса** ограничено потолком: 5 попыток по ~70 секунд, около 6 минут вместо ~5 минут сейчас (4 попытки). Очередь и другие валидаторы это не блокирует.
|
||||||
|
- **Потолок меньше числа валидаторов.** Адрес, которому не повезло с 5 неисправными валидаторами подряд, получит `fail`, хотя на остальных 15 прошёл бы. Это сознательный компромисс в пользу ограниченного времени; потолок меняется в настройках.
|
||||||
|
- Адрес, исключённый на части валидаторов, может чуть дольше ждать подходящего валидатора.
|
||||||
|
- Если сбой общий (проблема облака для всех валидаторов), адрес в итоге получит `fail`; это верное поведение.
|
||||||
|
- Не решается: причина сбоя `v17` в облаке (трансляция плавающего IP) — её нужно смотреть в OpenStack.
|
||||||
|
|
||||||
|
## 8. Решения по согласованию (все приняты)
|
||||||
|
|
||||||
|
1. Потолок попыток задаётся независимо от числа валидаторов; значение меняется в меню настроек (`/settings`) и через API.
|
||||||
|
2. Значение по умолчанию для текущего окружения — 5.
|
||||||
|
3. Исключение действует только для проваленного self-check; на ошибки привязки не распространяется.
|
||||||
|
4. «Self-check не прошёл на: …» сохраняется и отдаётся в API; показ на странице аналитики — следующим шагом.
|
||||||
|
5. Изменения отражаются в разделе настроек UI (п.3.6).
|
||||||
|
|
||||||
|
Открытых вопросов нет. Жду команды начать реализацию.
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# Итог: повтор после сбоя self-check — на другом валидаторе
|
||||||
|
|
||||||
|
План: [2026-10-04_08-01_self-check-exclude-validator-plan.md](2026-10-04_08-01_self-check-exclude-validator-plan.md).
|
||||||
|
Статус: код написан и проверен (gofmt, build, vet, test, миграция на копии боевой БД); стенд **не пересобирался**.
|
||||||
|
|
||||||
|
## Что изменено
|
||||||
|
|
||||||
|
- **Миграция `0012_self_check_failures.sql`** (версия схемы 12): таблица `ip_self_check_failures` (история сбоев по адресу, по `registry_id`, без внешних ключей); колонки `ip_queue.sc_failures` и `ip_queue.sc_round_start_cycle`; настройка `settings.self_check_max_attempts` (`DEFAULT 5`, допустимо 1…50).
|
||||||
|
- **`db.ClaimNextQueued`** пропускает адреса, на которых этот валидатор провалил self-check в текущем раунде; адрес остаётся в очереди для других валидаторов.
|
||||||
|
- **`db.FailSelfCheck`** (одна транзакция): записывает сбой, увеличивает `sc_failures`; при `sc_failures >= потолка` — `fail`; иначе возвращает адрес в очередь без изменения `retry_count`; если рабочих валидаторов без сбоя в раунде не осталось — новый раунд. Позднее сообщение (адрес не у этого валидатора) — `ErrInvalidState`.
|
||||||
|
- **Оркестратор** (`SelfCheckResult` → `failSelfCheck`): потолок читается из настроек на каждом сбое. События: `retry_or_fail` (при `fail` — со списком валидаторов) и `validator_excluded`. `max_self_check_retries` не используется (поле в YAML осталось).
|
||||||
|
- **`SubmitIPsAs`/`SeedQueue`**: перепостановка начинает новую серию (`sc_failures = 0`, новый раунд); история остаётся.
|
||||||
|
- **API**: `GET/PUT /admin/config/orchestrator` — поле `self_check_max_attempts` (400 вне 1…50; в PUT необязательно); `self_check_failed_on` в `GET /admin/ips/{ip}` (фильтр по запуску) и `GET /admin/registry/{ip}` (все запуски).
|
||||||
|
- **Дашборд**: поле «Потолок провалов self-check на адрес» на `/settings`; строка «Self-check не прошёл на: …» на `/ips/{ip}` и `/registry/{ip}`.
|
||||||
|
- **Документы**: `USAGE.md` (новый раздел «Повтор после сбоя self-check»), `API.md`, `DASHBOARD.md`, `ADMIN_CLEANUP.md` (новая таблица в сценариях 3.1 и 3.4), `README.md`.
|
||||||
|
|
||||||
|
## Отступления от плана
|
||||||
|
|
||||||
|
1. Раунд хранится как `sc_round_start_cycle` (номер `cycle_id`), а не `sc_round_start_attempt`: `attempt_number` сбрасывается при удалении и повторном создании строки очереди, а история остаётся — новая строка получила бы чужие исключения. `cycle_id` по адресу не повторяется. Поведение для оператора то же.
|
||||||
|
2. Значение 5 задано `DEFAULT 5` колонки (покрывает и существующую строку `settings`, и чистую установку), `config.go` не менялся.
|
||||||
|
3. В `PUT` потолок необязателен — старые клиенты без поля не получают 400.
|
||||||
|
4. `validator_excluded` не пишется, если начался новый раунд (исключение сразу теряет силу).
|
||||||
|
|
||||||
|
## Проверки
|
||||||
|
|
||||||
|
- `gofmt -l` — пусто; `go build ./...`, `go vet ./...` — без ошибок; `go test ./...` — все пакеты `ok`. Две проверки версии схемы в старых тестах миграций (`TestMigration0010…`, `TestMigration0011…`) обновлены с 11 на 12.
|
||||||
|
- Новые тесты: БД (`queries_selfcheck_test.go`), оркестратор (сценарий на трёх валидаторах, потолок, один и два валидатора, смена настройки), API, дашборд.
|
||||||
|
- Миграция `0012` на копии боевой БД: версия 11 → 12, `self_check_max_attempts = 5`, повторное открытие без ошибок, таблица сбоев пуста.
|
||||||
|
|
||||||
|
## Выкладка
|
||||||
|
|
||||||
|
Не выполнена. Нужны пересборка и перезапуск `control-api` и `admin-dashboard` по процедуре (проверка пустой очереди, копия БД, тег отката `pre-self-check-exclude`, миграция `0012`); на стенде в очереди сейчас 6489 адресов `done`, `queued` нет.
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
# План: кликабельные индикаторы PASS, PARTIAL, FAIL в разделе «Аналитика»
|
||||||
|
|
||||||
|
Статус: реализовано, см. [итог](2026-10-04_09-55_analytics-verdict-indicators-summary.md).
|
||||||
|
|
||||||
|
## 1. Что нужно
|
||||||
|
|
||||||
|
Вверху страницы `/analytics` есть ряд индикаторов. Сейчас кликабельны только четыре «прикладных»: «Egress https: есть провалы / все провалены» и «Ingress ssh: есть провалы / все провалены» (открывают окно со списком адресов, есть «Скачать CSV» и «Копировать»). Нужно сделать кликабельными ещё три: **pass**, **partial**, **fail**. По клику открывается тот же диалог со списком адресов с этим вердиктом.
|
||||||
|
|
||||||
|
Остальные индикаторы («Адресов», «Egress OK», «Ingress OK», «Длительность», «Поздние результаты») остаются как есть: в задаче их нет.
|
||||||
|
|
||||||
|
## 2. Решение
|
||||||
|
|
||||||
|
Новые виды списков строятся по тому же механизму, что и существующие: control-api отдаёт таблицу (JSON или CSV), дашборд проксирует, JS открывает диалог. Новых маршрутов, миграций и новых данных не нужно: вердикт, число проверок и причина `partial` уже вычисляются в `analytics.Compute`.
|
||||||
|
|
||||||
|
### 2.1. control-api (`internal/analytics/lists.go`)
|
||||||
|
|
||||||
|
Три новых вида списка (`kind`): `verdict_pass`, `verdict_partial`, `verdict_fail`. В список входят адреса запуска с этим вердиктом; отменённые (`cancelled`) не входят, как и в остальных списках и в числах `summary`. Порядок — по числовому адресу (`an.sorted()`).
|
||||||
|
|
||||||
|
Столбцы:
|
||||||
|
|
||||||
|
| Вид | Столбцы |
|
||||||
|
|---|---|
|
||||||
|
| `verdict_pass` | Адрес, Подсеть, Валидатор, Egress, Ingress, Проверок в цикле |
|
||||||
|
| `verdict_partial` | Адрес, Подсеть, Валидатор, Egress, Ingress, Проверок в цикле, **Причина** |
|
||||||
|
| `verdict_fail` | Адрес, Подсеть, Валидатор, Egress, Ingress, Проверок в цикле |
|
||||||
|
|
||||||
|
- «Валидатор» — тот же, что в списках https (`ShortValidator`); пусто → «—».
|
||||||
|
- «Egress» и «Ingress» — «успешно из всех» по уровню (`8 из 10`); у уровня без проверок — «—».
|
||||||
|
- «Проверок в цикле» — сохранённых из ожидаемых (`stored из ExpectedChecks`; если ожидаемое неизвестно, только сохранённое). Позволяет сразу увидеть «неполный набор».
|
||||||
|
- «Причина» у `partial` — та же формулировка, что в блоке «Почему partial» (`reasonName`), поэтому строки списка совпадают со столбиками блока.
|
||||||
|
|
||||||
|
Название CSV: `verdict_pass_run<N>.csv` и т. д. (по общему правилу). Для остальных видов ничего не меняется. Неизвестный `kind` по-прежнему даёт `404`.
|
||||||
|
|
||||||
|
Инвариант: число строк списка равно числу на карточке (`summary.pass / partial / fail`).
|
||||||
|
|
||||||
|
### 2.2. Дашборд (`internal/dashboard/static/analytics.js`, `analytics.css`)
|
||||||
|
|
||||||
|
- В `renderKpis` у плиток `pass`, `partial`, `fail` в поле списка ставится соответствующий `kind`, плитка становится `<button class="an-kpi" data-list=…>` и получает «список →», как у прикладных. У `fail` при значении 0 плитка остаётся некликабельной (список пуст, сейчас там надпись «ни одной полностью проваленной»).
|
||||||
|
- В `LISTS` добавляются три записи: заголовок («Адреса с вердиктом pass» и т. д.), пояснение («Вердикт адреса за последний цикл запуска, выставленный системой при агрегации…»), подсказки к столбцам (что значит Egress/Ingress, «Проверок в цикле», «Причина»).
|
||||||
|
- Обработчик клика и диалог менять не нужно: `[data-list]` уже подхватывает любую плитку. Стили есть (`button.an-kpi`); `an-go` для плитки без тега «успех/частично/провал» ставится рядом с существующим тегом.
|
||||||
|
- Серверной части дашборда (`handlers_analytics.go`, прокси списка и CSV) менять не нужно: `kind` в пути произвольный.
|
||||||
|
|
||||||
|
### 2.3. Объём списка pass
|
||||||
|
|
||||||
|
В запуске на ~6400 адресов `pass` может быть несколько тысяч строк. Диалог сейчас показывает все строки. Оставляем так (таблица на несколько тысяч строк в браузере открывается нормально) и проверяем на реальном объёме при выкладке; если окно тормозит — отдельным шагом добавим показ первых N строк с пометкой «полный список — в CSV». Выгрузка в CSV и копирование всегда полные.
|
||||||
|
|
||||||
|
## 3. Файлы
|
||||||
|
|
||||||
|
- `internal/analytics/lists.go` — константы, столбцы и строки новых видов.
|
||||||
|
- `internal/analytics/analytics.go` — только если нужна вспомогательная функция для строки «Egress/Ingress» (иначе без изменений).
|
||||||
|
- `internal/httpapi/handlers_analytics.go` — только комментарий с перечнем видов.
|
||||||
|
- `internal/dashboard/static/analytics.js` — плитки и `LISTS`.
|
||||||
|
- Документы: `docs/API.md` (перечень `kind`), `docs/USAGE.md` («Что можно открыть»), `docs/DASHBOARD.md` (строка `/analytics`), `README.md` (веха), итог `docs/changes/…-summary.md`.
|
||||||
|
|
||||||
|
## 4. Тесты
|
||||||
|
|
||||||
|
- `analytics`: для набора с pass, partial, fail и cancelled — число строк каждого списка равно `summary`; отменённые не входят; порядок по адресу; столбцы и значения «Egress/Ingress/Проверок в цикле»; «Причина» совпадает с `reasons`; у неполного набора в «Проверок в цикле» меньше ожидаемого.
|
||||||
|
- `httpapi`: `GET …/lists/verdict_partial` отдаёт JSON, `?format=csv` — файл с именем `verdict_partial_run<N>.csv`; неизвестный вид — `404` (уже есть, расширить).
|
||||||
|
- `dashboard`: прокси списка пропускает новые виды; в отданных данных страницы плитки pass/partial/fail имеют ссылки (если страница это проверяет без JS — иначе проверка вручную, п. 5).
|
||||||
|
- Полный `gofmt -l`, `go build ./... && go vet ./... && go test ./...`.
|
||||||
|
|
||||||
|
## 5. Выкладка и проверка
|
||||||
|
|
||||||
|
Меняются `control-api` (список) и `admin-dashboard` (статика встроена в бинарник); агенты и prober без изменений, миграций нет. Порядок: проверка пустой очереди, тег отката образов, пересборка, перезапуск. Проверка на стенде: на последнем запуске открыть плитки pass, partial, fail, сверить число в заголовке диалога с числом на плитке, скачать CSV, проверить фильтрацию и подсказки; оценить скорость окна на списке pass.
|
||||||
|
|
||||||
|
## 6. Риски
|
||||||
|
|
||||||
|
- Большой список pass: см. 2.3.
|
||||||
|
- Вердикт — оценка системы при агрегации, а не по фактическим проверкам (см. «Качество данных»): у адреса pass могут быть поздние провалы. В пояснении диалога это указывается; столбцы Egress/Ingress показывают фактические проверки.
|
||||||
|
- Числа на плитках и в списках берутся из одного вычисления отчёта, поэтому расходиться не должны (инвариант в тесте).
|
||||||
|
|
||||||
|
## 7. Не входит в доработку
|
||||||
|
|
||||||
|
Кликабельность «Egress OK», «Ingress OK», «Адресов», «Поздних результатов»; фильтры и сортировка внутри диалога; ссылка из строки диалога в «Реестр».
|
||||||
|
|
||||||
|
Открытых вопросов нет. Жду команды начать реализацию.
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# Итог: кликабельные индикаторы pass, partial, fail в «Аналитике»
|
||||||
|
|
||||||
|
План: [2026-10-04_09-55_analytics-verdict-indicators-plan.md](2026-10-04_09-55_analytics-verdict-indicators-plan.md).
|
||||||
|
Статус: код написан и проверен (gofmt, build, vet, test, синтаксис JS); стенд **не пересобирался**.
|
||||||
|
|
||||||
|
## Что изменено
|
||||||
|
|
||||||
|
- **control-api** (`internal/analytics/lists.go`): виды списков `verdict_pass`, `verdict_partial`, `verdict_fail`. Строки: адреса запуска с этим вердиктом, без `cancelled`, по числовому порядку. Столбцы: Адрес, Подсеть, Валидатор, Egress, Ingress, «Проверок в цикле»; у `partial` ещё «Причина» (та же формула, что в блоке «Почему partial»). Число строк равно `summary.pass/partial/fail`.
|
||||||
|
- Метод `addr.incomplete()` (`analytics.go`): «неполный набор» считается одним кодом для списка и для отчёта; логика отчёта не менялась.
|
||||||
|
- **Дашборд** (`analytics.js`): плитки `pass`, `partial`, `fail` стали кнопками со списком и «список →»; `fail` с нулём остаётся некликабельной. В `LISTS` три записи с пояснением и подсказками к столбцам. Диалог, CSS и прокси дашборда не менялись.
|
||||||
|
- **Документы**: `API.md`, `USAGE.md`, `DASHBOARD.md`, `README.md`.
|
||||||
|
|
||||||
|
## Особенности
|
||||||
|
|
||||||
|
- «Валидатор» берётся по https-проверкам (как в списках https): у адреса без https-проверок он «—».
|
||||||
|
- «Проверок в цикле» при неизвестном ожидаемом числе (`-1`) — только записанное.
|
||||||
|
- Вердикт — оценка системы при агрегации; Egress/Ingress в списке показывают фактические проверки. Пояснение есть в диалоге.
|
||||||
|
|
||||||
|
## Проверки
|
||||||
|
|
||||||
|
- `gofmt -l` пусто (одно выравнивание в тесте поправлено), `go build ./...`, `go vet ./...`, `go test ./...` — все пакеты `ok`; синтаксис `analytics.js` проверен.
|
||||||
|
- Новые тесты: `TestVerdictLists` (инвариант «строк = summary», отмена, порядок, столбцы, «—», неполный набор, причина совпадает с `reasons`); `TestAnalyticsEndpoints` расширен (JSON, CSV `verdict_partial_run<N>.csv`, `404` на неизвестный вид).
|
||||||
|
- Не проверено: открытие диалога в браузере и скорость окна на списке pass (нужна выкладка).
|
||||||
|
|
||||||
|
## Выкладка
|
||||||
|
|
||||||
|
Не выполнена. Нужны пересборка и перезапуск `control-api` и `admin-dashboard` (статика встроена в бинарник); миграций нет.
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
# План: сравнение двух запусков в разделе «Аналитика»
|
||||||
|
|
||||||
|
Статус: реализовано, см. [итог](2026-10-04_10-08_analytics-run-compare-summary.md).
|
||||||
|
|
||||||
|
## 1. Что нужно
|
||||||
|
|
||||||
|
Администратор выбирает два завершённых запуска и видит динамику между ними по семи индикаторам страницы «Аналитика»: `pass`, `partial`, `fail`, «Egress https: есть провалы», «Egress https: все провалены», «Ingress ssh: есть провалы», «Ingress ssh: все провалены». Отдельно выделяются три группы адресов:
|
||||||
|
|
||||||
|
1. **Новые**: есть в новом запуске, в старом не было. Нужны, чтобы понять, какие адреса прибыли в проект и подключились к анализу.
|
||||||
|
2. **Изменившиеся**: есть в обоих запусках, но состояние по проверкам разное. Для них показывается подробная сводка, что именно изменилось.
|
||||||
|
3. **Выбывшие**: были в старом запуске, в новом их нет. Нужны, чтобы понять, какие адреса вышли из состава проекта.
|
||||||
|
|
||||||
|
Адреса, которые есть в обоих запусках и не изменились, только считаются (список доступен, но не выделяется).
|
||||||
|
|
||||||
|
## 2. Основные решения
|
||||||
|
|
||||||
|
- **Отдельная страница `/analytics/compare`**, а не режим текущей: страница одного запуска остаётся как есть («данные других запусков на странице не участвуют»). На `/analytics` добавляется кнопка «Сравнить с другим запуском», она ведёт на сравнение с текущим запуском в роли нового.
|
||||||
|
- **Выбор запусков.** Два списка: «Запуск A (старый)» и «Запуск B (новый)» и кнопка «Поменять местами». По умолчанию B — последний завершённый запуск, A — предыдущий. Порядок не навязывается: «новые» всегда означает «есть в B, нет в A». Доступны только завершённые запуски с адресами (как в текущем выборе). Одинаковые A и B — ошибка `400`.
|
||||||
|
- **Адрес — это IP.** В запуске он присутствует, если у него есть итог, отличный от `cancelled`. Отменённые адреса из сравнения исключаются (в обоих запусках), их число показывается примечанием, чтобы они не выглядели как «новые» или «выбывшие».
|
||||||
|
- **Состояние адреса** — принадлежность к семи индикаторам по последнему циклу адреса в запуске (те же правила, что в отчёте запуска; один адрес может входить в несколько, вердикт — ровно в один из трёх). Адрес **изменился**, если принадлежность хотя бы к одному индикатору в A и B разная. Адрес с теми же индикаторами, но другим набором проваленных целей или площадок считается неизменившимся (см. риски).
|
||||||
|
- **Расчёт на control-api** по двум уже существующим `Analysis` (кэш завершённых запусков переиспользуется). Новых таблиц, миграций и новых данных нет.
|
||||||
|
|
||||||
|
## 3. Решение
|
||||||
|
|
||||||
|
### 3.1. control-api (`internal/analytics/compare.go`, новый)
|
||||||
|
|
||||||
|
- Таблица семи индикаторов (ключ, название, предикат по адресу): ключи совпадают с видами списков `verdict_pass`, `verdict_partial`, `verdict_fail`, `egress_https_any`, `egress_https_all`, `ingress_ssh_any`, `ingress_ssh_all`. Предикаты повторяют условия `Compute`/`List`; тест проверяет, что число адресов по каждому индикатору в каждом запуске равно соответствующему полю `summary`.
|
||||||
|
- `Compare(a, b *Analysis) *Comparison`:
|
||||||
|
- группы: `new`, `left`, `common`, `changed`, `same` (числа; `common = changed + same`);
|
||||||
|
- по каждому индикатору: `base`, `target`, `delta`, `new` (новые адреса в индикаторе), `left` (выбывшие, были в индикаторе), `entered` (общие адреса, вошедшие в индикатор), `exited` (общие адреса, вышедшие из индикатора). Инвариант: `delta = new − left + entered − exited` (проверяется тестом);
|
||||||
|
- матрица переходов вердикта для общих адресов (3×3), плюс строка «нет в A» (новые) и столбец «нет в B» (выбывшие);
|
||||||
|
- число отменённых адресов в каждом запуске.
|
||||||
|
- `(*Comparison) List(group, filter)`: таблица адресов. Группы: `new`, `left`, `changed`, `same`, `entered`, `exited`. Фильтры: `indicator` (для `new`/`left` — адрес входит в индикатор в своём запуске; для `changed`/`same` — принадлежность этому индикатору; для `entered`/`exited` обязателен), `from`+`to` (вердикт в A и в B, для ячейки матрицы). Порядок — по числовому адресу. Неверная группа или индикатор — ошибка (`404`).
|
||||||
|
- Столбцы списков:
|
||||||
|
- `new`: Адрес, Подсеть, Вердикт, Egress, Ingress, Индикаторы (в B);
|
||||||
|
- `left`: те же столбцы по запуску A;
|
||||||
|
- `changed`, `entered`, `exited`, `same`: Адрес, Подсеть, Вердикт (A → B), Egress (A → B), Ingress (A → B), **Что изменилось**. «Что изменилось» — текст по шагам: «вердикт partial → pass», «вошёл в: Egress https: все провалены», «вышел из: Ingress ssh: есть провалы», «https: провалены цели +a.test −b.test», «ssh: площадки −rxmsk», «валидатор v3 → v12». У `same` — «без изменений».
|
||||||
|
- Для текста нужны из `addr` уже имеющиеся поля (`https.failedTargets`, `ssh.sites`, `https.validator`, статистики egress/ingress); новых вычислений в `Compute` нет.
|
||||||
|
|
||||||
|
### 3.2. API (`internal/httpapi/handlers_analytics.go`)
|
||||||
|
|
||||||
|
- `GET /api/v1/admin/analytics/compare?base=A&target=B` → отчёт сравнения (`runs`: сведения об обоих запусках, `groups`, `indicators`, `transitions`, `cancelled`).
|
||||||
|
- `GET /api/v1/admin/analytics/compare/lists/{group}?base=A&target=B[&indicator=…][&from=…&to=…][&format=csv]` → таблица или CSV (UTF-8 с BOM; имя `compare_<group>[_<indicator>]_run<A>-<B>.csv`).
|
||||||
|
- Ошибки: `400` (нет или неверные id, `base = target`), `404` (запуска нет, неизвестная группа/индикатор), `409` (запуск ещё идёт).
|
||||||
|
- Загрузка `Analysis` по id выносится из `analysisFor` в общую функцию, чтобы сравнение и страница одного запуска пользовались одним кэшем.
|
||||||
|
|
||||||
|
### 3.3. Дашборд
|
||||||
|
|
||||||
|
- Страница `/analytics/compare?base=A&target=B` (`handlers_analytics.go`, `templates/analytics_compare.html`, `static/analytics-compare.js`), прокси списков и CSV: `/analytics/compare/lists/{group}` и `/analytics/compare/csv/{group}`. Состояние страницы целиком в адресе (можно отправить ссылку).
|
||||||
|
- Содержимое страницы сверху вниз:
|
||||||
|
1. Выбор A и B, «Поменять местами», «Сравнить»; под ним примечание: даты, тип и размер обоих запусков, число отменённых.
|
||||||
|
2. Карточки: «Новые», «Выбывшие», «Общие», «Изменились», «Без изменений». Кликабельны, открывают диалог со списком.
|
||||||
|
3. «Динамика по индикаторам»: строка на индикатор, столбцы A, B, Δ (рост `pass` и падение остальных — зелёным, обратное — красным), Новые, Выбывшие, Вошли, Вышли. Ненулевые числа кликабельны (список с соответствующими `group` и `indicator`).
|
||||||
|
4. «Переходы вердикта»: матрица 3×3 по общим адресам + «нет в A» / «нет в B»; ячейки кликабельны.
|
||||||
|
5. Диалог со списком, «Скачать CSV», «Копировать» — тот же, что на странице запуска.
|
||||||
|
- Код диалога (открытие, заполнение, CSV, копирование, подсказки) выносится из `analytics.js` в общий `analytics-dialog.js`, разметка диалога — в общий шаблон; страница одного запуска переходит на него без изменения поведения.
|
||||||
|
- На `/analytics` добавляется кнопка «Сравнить с другим запуском».
|
||||||
|
|
||||||
|
## 4. Файлы
|
||||||
|
|
||||||
|
- `internal/analytics/compare.go` (новый), `internal/analytics/compare_test.go` (новый).
|
||||||
|
- `internal/httpapi/handlers_analytics.go` (общий загрузчик, два новых обработчика), `routes`.
|
||||||
|
- `internal/dashboard`: `handlers_analytics.go` (страница и прокси), `client.go`, `routes.go`, `templates/analytics_compare.html`, `templates/analytics.html` (кнопка, общий диалог), `static/analytics.js`, `static/analytics-dialog.js` (новый), `static/analytics-compare.js` (новый), `static/analytics.css`.
|
||||||
|
- Документы: `docs/API.md`, `docs/USAGE.md` («Аналитика запусков»), `docs/DASHBOARD.md`, `README.md`, итог `docs/changes/…-summary.md`.
|
||||||
|
|
||||||
|
## 5. Тесты
|
||||||
|
|
||||||
|
- `analytics`: два запуска с новыми, выбывшими, изменившимися и неизменившимися адресами, с отменёнными; числа групп; инвариант `delta = new − left + entered − exited` по каждому индикатору; число адресов по индикатору равно `summary` каждого запуска; матрица переходов; списки каждой группы и фильтры (`indicator`, `from`/`to`); текст «Что изменилось» (вердикт, вход/выход из индикатора, цели, площадки, валидатор); порядок по адресу; пустые группы.
|
||||||
|
- `httpapi`: отчёт и списки (JSON, CSV с именем файла), `400` на одинаковые и неверные id, `404` на неизвестные запуск/группу/индикатор, `409` на незавершённый запуск.
|
||||||
|
- `dashboard`: страница с запуском по умолчанию, с явным `base`/`target`, предупреждение на неверные id, прокси списка и CSV; страница одного запуска после выноса диалога по-прежнему отдаёт данные и скрипты.
|
||||||
|
- `gofmt -l`, `go build ./... && go vet ./... && go test ./...`, проверка синтаксиса JS.
|
||||||
|
|
||||||
|
## 6. Выкладка и проверка
|
||||||
|
|
||||||
|
Меняются `control-api` и `admin-dashboard` (статика встроена); агенты, prober, миграции без изменений. Порядок: проверка пустой очереди, тег отката образов, пересборка, перезапуск. Проверка на стенде: сравнение запусков 1 и 2 через API (сумма групп равна числу адресов, инвариант по индикаторам), затем страница в браузере: выбор запусков, обмен местами, открытие диалогов из карточек, таблицы и матрицы, CSV, а также что страница одного запуска работает как раньше.
|
||||||
|
|
||||||
|
## 7. Риски
|
||||||
|
|
||||||
|
- **Что считается изменением.** Только принадлежность к семи индикаторам. Адрес, который остался в «Egress https: есть провалы», но у которого поменялись проваленные цели, попадает в «без изменений»; в списке `same` его сводка «без изменений» это не показывает. Если такие случаи важны, следующим шагом можно считать изменением и смену наборов целей и площадок.
|
||||||
|
- **Размер списков.** Группа новых или `same` может содержать тысячи строк (диалог показывает все, как и другие списки); CSV полный.
|
||||||
|
- **Разный состав запусков.** Если запуск 1 был частичным (например, перепроверка), то в сравнении будет много «новых» и «выбывших»: это отражает состав запусков, а не динамику. Размеры обоих запусков показаны в примечании над таблицами.
|
||||||
|
- Вердикт — оценка системы при агрегации, а не итог всех проверок (см. «Качество данных»); сравнение вердикта это не меняет, столбцы Egress и Ingress показывают фактические проверки.
|
||||||
|
- Вынос кода диалога затрагивает работающую страницу; закрывается тестами и ручной проверкой п. 6.
|
||||||
|
|
||||||
|
## 8. Не входит в доработку
|
||||||
|
|
||||||
|
Сравнение более чем двух запусков, графики динамики по времени, разбивка новых и выбывших по подсетям, сравнение по другим показателям (классы ошибок, площадки, валидаторы), автоматический выбор «интересных» пар запусков.
|
||||||
|
|
||||||
|
Открытых вопросов нет. Жду команды начать реализацию.
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# Итог: сравнение двух запусков в разделе «Аналитика»
|
||||||
|
|
||||||
|
План: [2026-10-04_10-08_analytics-run-compare-plan.md](2026-10-04_10-08_analytics-run-compare-plan.md).
|
||||||
|
Статус: код написан и проверен (gofmt, build, vet, test, синтаксис JS); стенд **не пересобирался**.
|
||||||
|
|
||||||
|
## Что изменено
|
||||||
|
|
||||||
|
- **control-api** (`internal/analytics/compare.go`): таблица семи индикаторов (ключи совпадают с видами списков), `Compare(base, target)` — группы `new`, `left`, `common`, `changed`, `same`, разложение каждого индикатора (`delta = new − left + entered − exited`), матрица переходов вердикта, число отменённых. `List(group, filter)` с фильтрами `indicator`, `from`/`to` и столбцом «Что изменилось».
|
||||||
|
- **API**: `GET /admin/analytics/compare` и `GET /admin/analytics/compare/lists/{group}` (JSON и CSV); `400` — неверные или одинаковые id, `404` — нет запуска, группы, индикатора или фильтра, `409` — запуск идёт. Загрузка отчёта запуска вынесена в общую функцию, кэш общий.
|
||||||
|
- **Дашборд**: страница `/analytics/compare` (выбор A и B, «Поменять местами», карточки групп, «Динамика по индикаторам», «Переходы вердикта», диалог со списком и CSV); прокси списков и CSV; кнопка «Сравнить с другим запуском» на `/analytics`.
|
||||||
|
- **Общий диалог**: код списков вынесен в `static/analytics-dialog.js`, разметка — в шаблон `analytics_dialog.html`; страница одного запуска перешла на него.
|
||||||
|
- **Документы**: `API.md`, `USAGE.md`, `DASHBOARD.md`, `README.md`.
|
||||||
|
|
||||||
|
## Отклонения от плана
|
||||||
|
|
||||||
|
1. Добавлена группа `common` (карточка «Общие» и ячейки матрицы открывают список через неё).
|
||||||
|
2. Фильтр `indicator` для `changed`/`same`/`common` — «хотя бы в одном из запусков».
|
||||||
|
3. Неверные `from`/`to` дают `404`, как другие неверные виды списков; к имени CSV добавляется суффикс `_<from>-<to>`.
|
||||||
|
4. Разметка диалога вынесена в отдельный шаблон.
|
||||||
|
|
||||||
|
## Особенности
|
||||||
|
|
||||||
|
- Адрес, оставшийся в тех же индикаторах, но с другим набором проваленных целей или площадок, считается неизменившимся (`same`).
|
||||||
|
- Дубли IP внутри запуска не обрабатываются (в реестре IP уникален).
|
||||||
|
|
||||||
|
## Проверки
|
||||||
|
|
||||||
|
- `gofmt -l` пусто; `go build ./...`, `go vet ./...`, `go test ./...` — все пакеты `ok`; `node --check` для трёх JS-файлов.
|
||||||
|
- Исправлено при ревью: в тесте дашборда число с неразрывным пробелом (`6 440`); в `TestRouteTableIsClassified` число admin-маршрутов 39 → 41.
|
||||||
|
- Новые тесты: инварианты сравнения (числа индикаторов равны `summary`, разложение `delta`, сумма групп и матрицы), все группы и фильтры, тексты «Что изменилось», API (отчёт, списки, CSV, коды ошибок), дашборд (пара по умолчанию, предупреждения, прокси, страница одного запуска после выноса диалога).
|
||||||
|
- Не проверено: страницы в браузере (диалог на `/analytics`, «Поменять местами», клики по матрице) и сравнение на данных стенда.
|
||||||
|
|
||||||
|
## Выкладка
|
||||||
|
|
||||||
|
Не выполнена. Нужны пересборка и перезапуск `control-api` и `admin-dashboard`; миграций нет.
|
||||||
@@ -0,0 +1,498 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Аналитика запусков</title>
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600&family=JetBrains+Mono:wght@500;700&display=swap">
|
||||||
|
<style>
|
||||||
|
/* Layout: sidebar shell like the real dashboard; one scrolling page, summary first, detail below.
|
||||||
|
Tokens are the dashboard's own (internal/dashboard/static/dashboard.css); heat ramp = one blue hue, validated sequential steps. */
|
||||||
|
:root {
|
||||||
|
--bg: #EEF1F5; --surface: #FFFFFF; --surface-alt: #E4E9F0;
|
||||||
|
--border: #CBD3DE; --border-soft: #DCE2EA;
|
||||||
|
--text: #12161F; --text-muted: #566073; --text-faint: #8992A3;
|
||||||
|
--accent: #2F5FE0; --accent-strong: #1F45B0; --accent-soft: #E1E9FC;
|
||||||
|
--success: #157F45; --success-soft: #DFF3E7;
|
||||||
|
--warning: #9A6400; --warning-soft: #F8EDD4;
|
||||||
|
--danger: #B4291D; --danger-soft: #FADEDA;
|
||||||
|
--neutral: #5B6576; --neutral-soft: #E4E8EE;
|
||||||
|
--bar: #3987e5; --bar-track: #E4E9F0;
|
||||||
|
--h1:#cde2fb; --h2:#9ec5f4; --h3:#6da7ec; --h4:#3987e5; --h5:#256abf; --h6:#184f95; --h7:#0d366b;
|
||||||
|
--hi1:#12161F; --hi2:#12161F; --hi3:#12161F; --hi4:#FFFFFF; --hi5:#FFFFFF; --hi6:#FFFFFF; --hi7:#FFFFFF;
|
||||||
|
--radius: 4px; --shadow: 0 1px 2px rgba(12,18,30,.06), 0 1px 1px rgba(12,18,30,.05);
|
||||||
|
--font-ui: "IBM Plex Sans", -apple-system, "Segoe UI", sans-serif;
|
||||||
|
--font-mono: "JetBrains Mono", ui-monospace, Consolas, monospace;
|
||||||
|
}
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root:not([data-theme="light"]) {
|
||||||
|
--bg:#0A0D13; --surface:#10141C; --surface-alt:#161B25; --border:#262E3B; --border-soft:#1D2430;
|
||||||
|
--text:#E7ECF5; --text-muted:#8D97AC; --text-faint:#626D82;
|
||||||
|
--accent:#5C8CFF; --accent-strong:#82A6FF; --accent-soft:#182140;
|
||||||
|
--success:#3DDC8A; --success-soft:#10261C; --warning:#F0B429; --warning-soft:#2B2210;
|
||||||
|
--danger:#FF6B5E; --danger-soft:#2C1613; --neutral:#A3ACBE; --neutral-soft:#1B212B;
|
||||||
|
--bar:#5C8CFF; --bar-track:#1D2430;
|
||||||
|
--h1:#0d366b; --h2:#104281; --h3:#184f95; --h4:#256abf; --h5:#3987e5; --h6:#6da7ec; --h7:#9ec5f4;
|
||||||
|
--hi1:#B8C9E8; --hi2:#C3D6F5; --hi3:#E7ECF5; --hi4:#FFFFFF; --hi5:#0A0D13; --hi6:#0A0D13; --hi7:#0A0D13;
|
||||||
|
--shadow: 0 1px 2px rgba(0,0,0,.4); color-scheme: dark;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
:root[data-theme="dark"] {
|
||||||
|
--bg:#0A0D13; --surface:#10141C; --surface-alt:#161B25; --border:#262E3B; --border-soft:#1D2430;
|
||||||
|
--text:#E7ECF5; --text-muted:#8D97AC; --text-faint:#626D82;
|
||||||
|
--accent:#5C8CFF; --accent-strong:#82A6FF; --accent-soft:#182140;
|
||||||
|
--success:#3DDC8A; --success-soft:#10261C; --warning:#F0B429; --warning-soft:#2B2210;
|
||||||
|
--danger:#FF6B5E; --danger-soft:#2C1613; --neutral:#A3ACBE; --neutral-soft:#1B212B;
|
||||||
|
--bar:#5C8CFF; --bar-track:#1D2430;
|
||||||
|
--h1:#0d366b; --h2:#104281; --h3:#184f95; --h4:#256abf; --h5:#3987e5; --h6:#6da7ec; --h7:#9ec5f4;
|
||||||
|
--hi1:#B8C9E8; --hi2:#C3D6F5; --hi3:#E7ECF5; --hi4:#FFFFFF; --hi5:#0A0D13; --hi6:#0A0D13; --hi7:#0A0D13;
|
||||||
|
--shadow: 0 1px 2px rgba(0,0,0,.4); color-scheme: dark;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
body { background: var(--bg); color: var(--text); font: 14px/1.5 var(--font-ui); }
|
||||||
|
.shell { display: grid; grid-template-columns: 208px minmax(0,1fr); min-height: 100vh; }
|
||||||
|
.side { background: var(--surface); border-right: 1px solid var(--border); padding: 16px 12px; display: flex; flex-direction: column; gap: 4px; position: sticky; top: 0; height: 100vh; }
|
||||||
|
.brand { font: 700 13px var(--font-mono); letter-spacing: .02em; padding: 4px 8px 14px; }
|
||||||
|
.nav a { display: block; padding: 7px 10px; border-radius: var(--radius); color: var(--text-muted); font: 500 12.5px var(--font-mono); text-decoration: none; }
|
||||||
|
.nav a.on { background: var(--accent-soft); color: var(--accent-strong); }
|
||||||
|
.nav a:focus-visible, button:focus-visible, select:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||||
|
main { min-width: 0; padding: 20px 24px 40px; display: grid; gap: 16px; align-content: start; }
|
||||||
|
.mock { background: var(--warning-soft); color: var(--warning); border: 1px solid var(--warning); border-radius: var(--radius); padding: 8px 12px; font-size: 12.5px; }
|
||||||
|
h1 { font: 700 18px var(--font-mono); margin: 0; }
|
||||||
|
h2 { font: 700 12px var(--font-mono); text-transform: uppercase; letter-spacing: .06em; color: var(--text-muted); margin: 0; }
|
||||||
|
.sub { color: var(--text-muted); font-size: 12.5px; margin: 0; }
|
||||||
|
.panel { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); padding: 14px 16px; display: grid; gap: 12px; min-width: 0; align-content: start; }
|
||||||
|
.head { display: flex; flex-wrap: wrap; gap: 6px 12px; align-items: baseline; justify-content: space-between; }
|
||||||
|
.runbar { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }
|
||||||
|
.runbar label { font: 700 12px var(--font-mono); color: var(--text-muted); text-transform: uppercase; letter-spacing: .06em; }
|
||||||
|
select, .btn { font: 500 13px var(--font-mono); background: var(--surface); color: var(--text); border: 1px solid var(--border); border-radius: var(--radius); padding: 7px 10px; }
|
||||||
|
select { min-width: 0; max-width: 100%; flex: 1 1 340px; }
|
||||||
|
.btn { cursor: pointer; } .btn:hover { background: var(--surface-alt); }
|
||||||
|
.btn[disabled] { opacity: .4; cursor: default; }
|
||||||
|
.tabs { display: inline-flex; gap: 0; }
|
||||||
|
.tabs button { font: 500 12px var(--font-mono); background: var(--surface); color: var(--text-muted); border: 1px solid var(--border); padding: 5px 12px; cursor: pointer; }
|
||||||
|
.tabs button + button { border-left: 0; }
|
||||||
|
.tabs button:first-child { border-radius: var(--radius) 0 0 var(--radius); } .tabs button:last-child { border-radius: 0 var(--radius) var(--radius) 0; }
|
||||||
|
.tabs button[aria-pressed="true"] { background: var(--accent-soft); color: var(--accent-strong); border-color: var(--accent); }
|
||||||
|
.kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; }
|
||||||
|
.kpi { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 12px 14px; display: grid; gap: 2px; box-shadow: var(--shadow); }
|
||||||
|
.kpi .k { font: 700 11px var(--font-mono); text-transform: uppercase; letter-spacing: .06em; color: var(--text-muted); }
|
||||||
|
.kpi .v { font: 700 26px var(--font-mono); font-variant-numeric: tabular-nums; }
|
||||||
|
.kpi .d { font-size: 12px; color: var(--text-muted); }
|
||||||
|
.tag { display: inline-flex; align-items: center; gap: 5px; font: 700 10.5px var(--font-mono); text-transform: uppercase; letter-spacing: .03em; padding: 2px 7px; border-radius: 2px; }
|
||||||
|
.tag::before { content: ""; width: 5px; height: 5px; background: currentColor; border-radius: 1px; }
|
||||||
|
.t-ok { background: var(--success-soft); color: var(--success); } .t-warn { background: var(--warning-soft); color: var(--warning); } .t-bad { background: var(--danger-soft); color: var(--danger); } .t-n { background: var(--neutral-soft); color: var(--neutral); }
|
||||||
|
.cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 420px), 1fr)); gap: 16px; }
|
||||||
|
.rows { display: grid; gap: 7px; }
|
||||||
|
.bar-row { display: grid; grid-template-columns: minmax(110px, 38%) minmax(0,1fr) auto; gap: 10px; align-items: center; font-size: 13px; }
|
||||||
|
.bar-row .n { overflow-wrap: anywhere; }
|
||||||
|
.track { height: 12px; background: var(--bar-track); border-radius: 2px; position: relative; }
|
||||||
|
.fill { height: 100%; background: var(--bar); border-radius: 0 4px 4px 0; }
|
||||||
|
.num { font: 500 12.5px var(--font-mono); font-variant-numeric: tabular-nums; text-align: right; white-space: nowrap; }
|
||||||
|
.scroll { overflow-x: auto; }
|
||||||
|
table { border-collapse: collapse; width: 100%; font-size: 13px; }
|
||||||
|
th .hint { cursor: help; color: var(--accent-strong); margin-left: 3px; }
|
||||||
|
th { font: 700 11px var(--font-mono); text-transform: uppercase; letter-spacing: .05em; color: var(--text-muted); text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--border); white-space: nowrap; }
|
||||||
|
th.r, td.r { text-align: right; }
|
||||||
|
td { padding: 6px 8px; border-bottom: 1px solid var(--border-soft); vertical-align: middle; }
|
||||||
|
td.a { font-family: var(--font-mono); font-size: 12.5px; white-space: nowrap; }
|
||||||
|
td.a a { color: var(--accent-strong); text-decoration: none; } td.a a:hover { text-decoration: underline; }
|
||||||
|
.pb { display: grid; grid-template-columns: 70px 40px; gap: 6px; align-items: center; justify-content: end; }
|
||||||
|
.pb .track { height: 8px; }
|
||||||
|
.heat td.c { padding: 2px; }
|
||||||
|
.cell { display: block; min-width: 76px; text-align: center; font: 500 12px var(--font-mono); font-variant-numeric: tabular-nums; padding: 7px 4px; border-radius: 2px; cursor: default; }
|
||||||
|
.h1{background:var(--h1);color:var(--hi1)} .h2{background:var(--h2);color:var(--hi2)} .h3{background:var(--h3);color:var(--hi3)} .h4{background:var(--h4);color:var(--hi4)} .h5{background:var(--h5);color:var(--hi5)} .h6{background:var(--h6);color:var(--hi6)} .h7{background:var(--h7);color:var(--hi7)}
|
||||||
|
.legend { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; font-size: 12px; color: var(--text-muted); }
|
||||||
|
.legend i { display: inline-block; width: 28px; height: 10px; border-radius: 2px; }
|
||||||
|
.vals { display: flex; align-items: flex-end; gap: 4px; height: 120px; border-bottom: 1px solid var(--border); position: relative; }
|
||||||
|
.vals .col { flex: 1 1 0; min-width: 0; background: var(--bar); border-radius: 3px 3px 0 0; }
|
||||||
|
.vals .avg { position: absolute; left: 0; right: 0; border-top: 1px dashed var(--text-muted); }
|
||||||
|
.vlab { display: flex; justify-content: space-between; font: 500 11px var(--font-mono); color: var(--text-faint); }
|
||||||
|
.dq { display: grid; gap: 8px; }
|
||||||
|
.dq .row { display: flex; gap: 10px; justify-content: space-between; align-items: baseline; border-bottom: 1px solid var(--border-soft); padding-bottom: 6px; font-size: 13px; }
|
||||||
|
.dq .row span:last-child { font: 700 13px var(--font-mono); white-space: nowrap; }
|
||||||
|
.note { font-size: 12px; color: var(--text-muted); }
|
||||||
|
button.kpi { font: inherit; color: inherit; text-align: left; cursor: pointer; width: 100%; }
|
||||||
|
button.kpi:hover { border-color: var(--accent); }
|
||||||
|
button.kpi:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||||
|
.kpi .go { font: 700 11px var(--font-mono); color: var(--accent-strong); }
|
||||||
|
dialog { width: min(760px, calc(100% - 32px)); max-height: calc(100vh - 32px); max-height: calc(100dvh - 32px); padding: 0; overflow: hidden; border: 1px solid var(--border); border-radius: 6px; background: var(--surface); color: var(--text); box-shadow: 0 16px 40px rgba(0,0,0,.35); }
|
||||||
|
dialog[open] { display: flex; flex-direction: column; }
|
||||||
|
dialog::backdrop { background: rgba(10,14,20,.5); }
|
||||||
|
.dlg { display: flex; flex-direction: column; gap: 12px; padding: 16px; min-height: 0; flex: 1 1 auto; max-height: calc(100vh - 34px); max-height: calc(100dvh - 34px); }
|
||||||
|
.dlg h3 { font: 700 15px var(--font-mono); margin: 0; overflow-wrap: anywhere; flex: 0 0 auto; }
|
||||||
|
.dlg .note { flex: 0 0 auto; max-height: 6.5em; overflow: auto; margin: 0; }
|
||||||
|
.dlg .dist { flex: 0 0 auto; }
|
||||||
|
.dlg .list { flex: 0 1 auto; min-height: 96px; overflow: auto; border: 1px solid var(--border-soft); border-radius: var(--radius); }
|
||||||
|
.dlg table { font-size: 12.5px; } .dlg th { position: sticky; top: 0; background: var(--surface); }
|
||||||
|
.dlg .foot { flex: 0 0 auto; display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; padding-top: 4px; border-top: 1px solid var(--border-soft); }
|
||||||
|
.dlg .foot .acts { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||||
|
@media (max-width: 520px) { .dlg { padding: 12px; gap: 10px; } .dlg .foot .acts { width: 100%; } .dlg .foot .acts .btn { flex: 1 1 auto; } }
|
||||||
|
@media (max-height: 540px) { .dlg .dist { display: none; } }
|
||||||
|
@media (max-height: 640px) { .dist .cols20 { height: 44px; } .dlg .note { max-height: 3em; } .dlg .dist .chips { display: none; } }
|
||||||
|
.btn.primary { background: var(--accent); color: #fff; border-color: var(--accent); }
|
||||||
|
.btn.primary:hover { background: var(--accent-strong); }
|
||||||
|
button.bar-row { font: inherit; color: inherit; text-align: left; width: 100%; background: none; border: 0; border-radius: var(--radius); padding: 3px 4px; margin: -3px -4px; cursor: pointer; }
|
||||||
|
button.bar-row:hover { background: var(--surface-alt); }
|
||||||
|
button.bar-row:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
|
||||||
|
.dist { display: grid; gap: 8px; }
|
||||||
|
.dist .chips { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||||
|
.dist .cols20 { display: grid; grid-template-columns: repeat(20, minmax(0, 1fr)); gap: 3px; align-items: end; height: 84px; border-bottom: 1px solid var(--border); }
|
||||||
|
.dist .cols20 div { background: var(--bar); border-radius: 2px 2px 0 0; min-height: 1px; }
|
||||||
|
.dist .lab20 { display: grid; grid-template-columns: repeat(20, minmax(0, 1fr)); gap: 3px; font: 500 9.5px var(--font-mono); color: var(--text-faint); text-align: center; }
|
||||||
|
#tip { position: fixed; z-index: 10; pointer-events: none; background: var(--text); color: var(--bg); font: 500 12px/1.4 var(--font-mono); padding: 6px 9px; border-radius: 4px; max-width: min(360px, calc(100vw - 24px)); white-space: normal; opacity: 0; transition: opacity .08s; }
|
||||||
|
@media (max-width: 860px) {
|
||||||
|
.shell { grid-template-columns: minmax(0,1fr); }
|
||||||
|
.side { position: static; height: auto; flex-direction: row; flex-wrap: wrap; align-items: center; border-right: 0; border-bottom: 1px solid var(--border); padding: 10px 16px; }
|
||||||
|
.brand { padding: 0 10px 0 0; } .nav { display: flex; flex-wrap: wrap; gap: 2px; }
|
||||||
|
main { padding: 16px; }
|
||||||
|
}
|
||||||
|
@media (prefers-reduced-motion: reduce) { #tip { transition: none; } }
|
||||||
|
</style>
|
||||||
|
|
||||||
|
</head><body style="margin:0">
|
||||||
|
<div class="shell">
|
||||||
|
<aside class="side">
|
||||||
|
<div class="brand">CLOUD IP VALIDATOR</div>
|
||||||
|
<nav class="nav" aria-label="Разделы">
|
||||||
|
<a href="#" onclick="return false">Обзор</a>
|
||||||
|
<a href="#" onclick="return false">Очередь</a>
|
||||||
|
<a href="#" onclick="return false">Реестр</a>
|
||||||
|
<a href="#" class="on" aria-current="page" onclick="return false">Аналитика</a>
|
||||||
|
<a href="#" onclick="return false">Валидаторы</a>
|
||||||
|
<a href="#" onclick="return false">Настройки</a>
|
||||||
|
</nav>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<main>
|
||||||
|
<div class="mock" role="note"><b>Макет.</b> Запуск от 02.10 построен на реальных числах из отчётов <code>analysis/</code> (6440 адресов). Два других запуска и идущий — <b>демонстрационные</b>, нужны только для проверки переключателя.</div>
|
||||||
|
|
||||||
|
<div class="head">
|
||||||
|
<h1>Аналитика</h1>
|
||||||
|
<p class="sub">Один выбранный запуск. Данные других запусков на странице не участвуют.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="panel" aria-label="Выбор запуска">
|
||||||
|
<div class="runbar">
|
||||||
|
<label for="run">Запуск</label>
|
||||||
|
<button class="btn" id="prev" aria-label="Предыдущий запуск">◀</button>
|
||||||
|
<select id="run"></select>
|
||||||
|
<button class="btn" id="next" aria-label="Следующий запуск">▶</button>
|
||||||
|
</div>
|
||||||
|
<p class="note" id="runnote"></p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="kpis" id="kpis"></div>
|
||||||
|
|
||||||
|
<div class="cols">
|
||||||
|
<section class="panel" aria-labelledby="h-reasons">
|
||||||
|
<h2 id="h-reasons">Почему partial</h2>
|
||||||
|
<div class="rows" id="reasons"></div>
|
||||||
|
<p class="note">Адрес считается один раз, по главной причине. Всё, где есть egress, учитывается как egress.</p>
|
||||||
|
</section>
|
||||||
|
<section class="panel" aria-labelledby="h-dq">
|
||||||
|
<h2 id="h-dq">Качество данных</h2>
|
||||||
|
<div class="dq" id="dq"></div>
|
||||||
|
<p class="note">Вердикт ставится при агрегации. Результаты, пришедшие позже, остаются в этом же запуске, но в вердикт не входят.</p>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="panel" aria-labelledby="h-sub">
|
||||||
|
<div class="head">
|
||||||
|
<h2 id="h-sub">Подсети</h2>
|
||||||
|
<div class="runbar">
|
||||||
|
<div class="tabs" role="group" aria-label="Сортировка подсетей">
|
||||||
|
<button type="button" data-sort="worst" aria-pressed="true">хуже всего</button>
|
||||||
|
<button type="button" data-sort="size" aria-pressed="false">больше адресов</button>
|
||||||
|
</div>
|
||||||
|
<button class="btn" id="allsub" type="button"></button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="scroll"><table id="subtbl"></table></div>
|
||||||
|
<p class="note">Строка ведёт в «Реестр» с фильтром по запуску и подсети.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" aria-labelledby="h-eg">
|
||||||
|
<div class="head">
|
||||||
|
<h2 id="h-eg">Egress по целям</h2>
|
||||||
|
<div class="tabs" role="group" aria-label="Тип проверки">
|
||||||
|
<button type="button" data-type="https" aria-pressed="true">https</button>
|
||||||
|
<button type="button" data-type="icmp" aria-pressed="false">icmp</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="rows" id="targets"></div>
|
||||||
|
<div id="matrixwrap">
|
||||||
|
<div class="head"><h2 style="margin-top:6px">Подсеть × цель</h2>
|
||||||
|
<div class="legend" id="hlegend"></div></div>
|
||||||
|
<div class="scroll"><table class="heat" id="matrix"></table></div>
|
||||||
|
</div>
|
||||||
|
<p class="note" id="matrixnote"></p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="cols">
|
||||||
|
<section class="panel" aria-labelledby="h-in">
|
||||||
|
<h2 id="h-in">Ingress по площадкам</h2>
|
||||||
|
<div class="scroll"><table id="sites"></table></div>
|
||||||
|
</section>
|
||||||
|
<section class="panel" aria-labelledby="h-err">
|
||||||
|
<h2 id="h-err">Классы ошибок ingress</h2>
|
||||||
|
<div class="rows" id="errs"></div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="panel" aria-labelledby="h-val">
|
||||||
|
<h2 id="h-val">Валидаторы: доля провалов egress https</h2>
|
||||||
|
<div class="vals" id="vals" role="img" aria-label="Доля проваленных https-проверок по 20 валидаторам"></div>
|
||||||
|
<div class="vlab"><span>validator 1</span><span id="vavg"></span><span>validator 20</span></div>
|
||||||
|
<p class="note">Ровная полоса значит: проблема зависит от подсети адреса, а не от валидатора.</p>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
<dialog id="dlg" aria-labelledby="dlg-title">
|
||||||
|
<div class="dlg">
|
||||||
|
<h3 id="dlg-title"></h3>
|
||||||
|
<p class="note" id="dlg-note"></p>
|
||||||
|
<div class="dist" id="dlg-dist" hidden></div>
|
||||||
|
<div class="list"><table id="dlg-tbl"></table></div>
|
||||||
|
<div class="foot">
|
||||||
|
<span class="note" id="dlg-msg" role="status"></span>
|
||||||
|
<div class="acts">
|
||||||
|
<button class="btn" type="button" id="dlg-copy">Копировать</button>
|
||||||
|
<button class="btn primary" type="button" id="dlg-csv">Скачать CSV</button>
|
||||||
|
<button class="btn" type="button" id="dlg-close" autofocus>Закрыть</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</dialog>
|
||||||
|
<div id="tip" role="tooltip"></div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const REAL = {"subnets": [{"c": "37.139.32.0/22", "n": 327, "p": 240, "e": 240, "i": 327}, {"c": "185.130.112.0/22", "n": 360, "p": 169, "e": 169, "i": 360}, {"c": "161.104.104.0/22", "n": 452, "p": 124, "e": 124, "i": 452}, {"c": "87.239.104.0/21", "n": 369, "p": 115, "e": 115, "i": 365}, {"c": "212.233.72.0/21", "n": 471, "p": 105, "e": 105, "i": 460}, {"c": "212.111.84.0/22", "n": 218, "p": 102, "e": 102, "i": 215}, {"c": "146.185.240.0/22", "n": 197, "p": 81, "e": 81, "i": 190}, {"c": "83.166.248.0/21", "n": 659, "p": 71, "e": 82, "i": 598}, {"c": "89.208.196.0/22", "n": 165, "p": 60, "e": 60, "i": 164}, {"c": "89.208.84.0/22", "n": 151, "p": 58, "e": 60, "i": 140}, {"c": "213.219.212.0/22", "n": 84, "p": 53, "e": 53, "i": 84}, {"c": "91.219.226.0/23", "n": 106, "p": 52, "e": 53, "i": 93}, {"c": "89.208.208.0/22", "n": 157, "p": 50, "e": 50, "i": 157}, {"c": "37.139.40.0/22", "n": 108, "p": 50, "e": 50, "i": 108}, {"c": "90.156.216.0/22", "n": 110, "p": 46, "e": 46, "i": 110}, {"c": "79.137.174.0/23", "n": 117, "p": 43, "e": 43, "i": 117}, {"c": "185.86.144.0/22", "n": 105, "p": 43, "e": 43, "i": 105}, {"c": "212.233.88.0/21", "n": 237, "p": 42, "e": 45, "i": 230}, {"c": "95.163.208.0/22", "n": 210, "p": 41, "e": 41, "i": 210}, {"c": "217.16.24.0/22", "n": 79, "p": 39, "e": 53, "i": 70}, {"c": "95.163.212.0/22", "n": 118, "p": 35, "e": 35, "i": 118}, {"c": "90.156.212.0/22", "n": 236, "p": 32, "e": 32, "i": 235}, {"c": "84.23.52.0/22", "n": 154, "p": 32, "e": 32, "i": 154}, {"c": "85.192.32.0/22", "n": 75, "p": 31, "e": 31, "i": 74}, {"c": "212.233.120.0/22", "n": 131, "p": 30, "e": 30, "i": 126}, {"c": "83.166.232.0/21", "n": 263, "p": 29, "e": 30, "i": 227}, {"c": "185.241.192.0/22", "n": 90, "p": 25, "e": 25, "i": 85}, {"c": "94.139.244.0/22", "n": 69, "p": 25, "e": 26, "i": 69}, {"c": "217.16.16.0/21", "n": 32, "p": 23, "e": 27, "i": 20}, {"c": "5.188.140.0/22", "n": 22, "p": 22, "e": 22, "i": 22}, {"c": "217.16.28.0/22", "n": 28, "p": 18, "e": 18, "i": 28}, {"c": "89.208.216.0/24", "n": 34, "p": 17, "e": 17, "i": 34}, {"c": "109.120.188.0/22", "n": 14, "p": 11, "e": 11, "i": 14}, {"c": "89.208.220.0/22", "n": 144, "p": 10, "e": 10, "i": 144}, {"c": "95.163.182.0/23", "n": 132, "p": 10, "e": 11, "i": 117}, {"c": "212.233.96.0/22", "n": 13, "p": 6, "e": 6, "i": 13}, {"c": "89.208.228.0/22", "n": 12, "p": 6, "e": 6, "i": 12}, {"c": "109.120.180.0/22", "n": 91, "p": 5, "e": 6, "i": 80}, {"c": "90.156.150.0/23", "n": 10, "p": 4, "e": 4, "i": 10}, {"c": "95.163.180.0/23", "n": 36, "p": 3, "e": 5, "i": 24}, {"c": "146.185.208.0/22", "n": 8, "p": 3, "e": 3, "i": 8}, {"c": "95.163.248.0/22", "n": 1, "p": 1, "e": 1, "i": 1}, {"c": "161.104.108.0/23", "n": 45, "p": 0, "e": 0, "i": 45}], "matrix": [{"c": "83.166.248.0/21", "partial": 588, "v": [81, 57, 51, 86, 46]}, {"c": "212.233.72.0/21", "partial": 366, "v": [82, 65, 57, 0, 57]}, {"c": "161.104.104.0/22", "partial": 328, "v": [88, 53, 48, 0, 40]}, {"c": "87.239.104.0/21", "partial": 254, "v": [91, 37, 34, 56, 30]}, {"c": "83.166.232.0/21", "partial": 234, "v": [78, 58, 46, 89, 44]}, {"c": "90.156.212.0/22", "partial": 204, "v": [91, 48, 50, 69, 42]}, {"c": "212.233.88.0/21", "partial": 195, "v": [81, 70, 56, 0, 67]}, {"c": "185.130.112.0/22", "partial": 191, "v": [97, 19, 20, 0, 15]}, {"c": "95.163.208.0/22", "partial": 169, "v": [85, 51, 43, 42, 38]}, {"c": "89.208.220.0/22", "partial": 134, "v": [87, 54, 50, 78, 38]}, {"c": "95.163.182.0/23", "partial": 122, "v": [74, 69, 48, 73, 45]}, {"c": "84.23.52.0/22", "partial": 122, "v": [88, 63, 48, 80, 41]}, {"c": "212.111.84.0/22", "partial": 116, "v": [95, 23, 15, 0, 16]}, {"c": "146.185.240.0/22", "partial": 116, "v": [87, 38, 30, 7, 24]}, {"c": "89.208.208.0/22", "partial": 107, "v": [88, 43, 33, 57, 28]}, {"c": "89.208.196.0/22", "partial": 105, "v": [92, 36, 31, 52, 29]}, {"c": "212.233.120.0/22", "partial": 101, "v": [83, 62, 54, 0, 71]}, {"c": "89.208.84.0/22", "partial": 93, "v": [83, 33, 27, 47, 31]}, {"c": "37.139.32.0/22", "partial": 87, "v": [86, 33, 30, 57, 26]}, {"c": "109.120.180.0/22", "partial": 86, "v": [90, 67, 59, 28, 48]}, {"c": "95.163.212.0/22", "partial": 83, "v": [86, 39, 29, 14, 24]}, {"c": "79.137.174.0/23", "partial": 74, "v": [85, 41, 39, 59, 28]}, {"c": "185.241.192.0/22", "partial": 65, "v": [91, 48, 29, 0, 22]}, {"c": "90.156.216.0/22", "partial": 64, "v": [89, 38, 31, 50, 25]}, {"c": "185.86.144.0/22", "partial": 62, "v": [94, 37, 32, 0, 18]}, {"c": "37.139.40.0/22", "partial": 58, "v": [84, 29, 33, 52, 24]}, {"c": "91.219.226.0/23", "partial": 54, "v": [96, 33, 15, 35, 28]}, {"c": "161.104.108.0/23", "partial": 45, "v": [87, 82, 73, 0, 49]}, {"c": "94.139.244.0/22", "partial": 44, "v": [82, 27, 36, 41, 20]}, {"c": "85.192.32.0/22", "partial": 44, "v": [91, 27, 20, 36, 20]}, {"c": "217.16.24.0/22", "partial": 40, "v": [65, 2, 0, 0, 2]}, {"c": "95.163.180.0/23", "partial": 33, "v": [76, 61, 42, 82, 52]}, {"c": "213.219.212.0/22", "partial": 31, "v": [87, 61, 35, 0, 61]}, {"c": "Line truncated
|
||||||
|
const TARGETS = ['packages.ubuntu.com','dl-cdn.alpinelinux.org','repo.almalinux.org','hub.docker.com','github.com'];
|
||||||
|
const fmt = n => Math.round(n).toLocaleString('ru-RU');
|
||||||
|
const pct = (a, b) => b ? Math.round(a / b * 100) : 0;
|
||||||
|
const pct1 = (a, b) => b ? (a / b * 100).toLocaleString('ru-RU', {maximumFractionDigits: 1}) : '0';
|
||||||
|
|
||||||
|
/* Base run: real numbers. Demo runs: the same shape, scaled and shifted with a fixed pattern. */
|
||||||
|
function baseRun() {
|
||||||
|
const subs = REAL.subnets.map(s => ({c: s.c, n: s.n, pass: s.p, eg: s.e, ing: s.i}));
|
||||||
|
return {
|
||||||
|
id: 'r3', demo: false, label: '02.10 13:47 → 22:29 · ручной · 6 440 адр. · 30% pass', kind: 'ручной (скан Floating IP)',
|
||||||
|
start: '02.10.2026 13:47', end: '02.10.2026 22:29', dur: '8 ч 42 мин', rechecked: 9,
|
||||||
|
subs, matrix: REAL.matrix.map(m => ({c: m.c, partial: m.partial, v: m.v.slice()})),
|
||||||
|
reasons: [['Только egress', 4146], ['Ingress и egress', 157], ['Egress и неполный набор', 125], ['Ingress, egress и неполный набор', 9], ['Только неполный набор', 33], ['Только ingress', 8]],
|
||||||
|
late: 246, lateAddr: 50, incomplete: 167, mismatch: 50,
|
||||||
|
errLate: 844, egHttpsAny: 4409, egHttpsAll: 307, egHttpsAllFull: 290, ingSshAll: 7, ingSshAny: 222,
|
||||||
|
targets: {https: [3841, 2193, 1872, 1805, 1728], icmp: [79, 0, 0, 1, 0]},
|
||||||
|
sites: [['rxmsk', 6319, 6165, 6319, 6128, 6319, 6179], ['rxyc', 6439, 6435, 6439, 6429, 6439, 6434], ['misha-v', 6364, 6257, 6364, 6207, 6364, 6266], ['vk-kaz', 6426, 6400, 6426, 6392, 6426, 6402]],
|
||||||
|
errs: [['SSH: таймаут', 327], ['ICMP: нет ответа', 276], ['TCP-22: таймаут', 260], ['SSH: баннер «Not allowed»', 47], ['SSH: нет маршрута', 18], ['ICMP: time exceeded', 15], ['TCP-22: нет маршрута', 7]],
|
||||||
|
vals: [[1595,999],[1630,1071],[1618,1046],[1613,1042],[1597,998],[1622,1093],[1615,1045],[1599,1012],[1594,991],[1602,1049],[1610,1043],[1595,1014],[1630,1069],[1576,974],[1634,1073],[1589,1006],[1620,1062],[1613,1021],[1610,1047],[1614,1082]]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
function variant(b, id, label, kind, start, end, dur, scale, phase, shift) {
|
||||||
|
const r = JSON.parse(JSON.stringify(b));
|
||||||
|
Object.assign(r, {id, demo: true, label, kind, start, end, dur, rechecked: 0});
|
||||||
|
r.subs = b.subs.map((s, i) => {
|
||||||
|
const k = 1 + 0.22 * Math.sin(i * 1.7 + phase);
|
||||||
|
const n = Math.max(1, Math.round(s.n * scale * (1 + 0.1 * Math.cos(i + phase))));
|
||||||
|
const pass = Math.min(n, Math.max(0, Math.round(n * (s.pass / s.n) * k + n * shift)));
|
||||||
|
return {c: s.c, n, pass, eg: Math.min(n, Math.round(n * (s.eg / s.n) * k + n * shift)), ing: Math.min(n, Math.round(n * (s.ing / s.n)))};
|
||||||
|
});
|
||||||
|
const total = r.subs.reduce((a, s) => a + s.n, 0);
|
||||||
|
const f = total / 6440;
|
||||||
|
r.matrix = b.matrix.map((m, i) => ({c: m.c, partial: Math.max(1, Math.round(m.partial * scale)), v: m.v.map((x, j) => Math.max(0, Math.min(100, Math.round(x * (1 + 0.2 * Math.sin(i + j + phase)) + shift * 100))))}));
|
||||||
|
r.reasons = b.reasons.map(([k, v]) => [k, Math.round(v * f)]);
|
||||||
|
r.late = Math.round(b.late * f); r.lateAddr = Math.round(b.lateAddr * f); r.incomplete = Math.round(b.incomplete * f); r.mismatch = Math.round(b.mismatch * f);
|
||||||
|
r.errLate = Math.round(b.errLate * f); r.egHttpsAny = Math.round(b.egHttpsAny * f); r.egHttpsAll = Math.round(b.egHttpsAll * f); r.egHttpsAllFull = Math.round(b.egHttpsAllFull * f); r.ingSshAll = Math.round(b.ingSshAll * f); r.ingSshAny = Math.round(b.ingSshAny * f);
|
||||||
|
r.targets = {https: b.targets.https.map(x => Math.round(x * f * (1 - shift * 2))), icmp: b.targets.icmp.map(x => Math.round(x * f))};
|
||||||
|
r.sites = b.sites.map(s => s.map((x, j) => j === 0 ? x : Math.round(x * f)));
|
||||||
|
r.errs = b.errs.map(([k, v]) => [k, Math.round(v * f)]);
|
||||||
|
r.vals = b.vals.map(([t, o]) => [Math.round(t * f), Math.round(o * f * (1 + shift * 0.5))]);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
const BASE = baseRun();
|
||||||
|
const RUNS = [
|
||||||
|
variant(BASE, 'r1', '01.10 07:59 → 08:41 · авто · демо', 'автоцикл (демо)', '01.10.2026 07:59', '01.10.2026 08:41', '42 мин', 0.04, 0.6, 0.12),
|
||||||
|
variant(BASE, 'r2', '03.10 10:05 → 12:20 · ручной · демо', 'перепроверка (демо)', '03.10.2026 10:05', '03.10.2026 12:20', '2 ч 15 мин', 0.16, 2.1, 0.06),
|
||||||
|
BASE
|
||||||
|
];
|
||||||
|
const OPEN = {label: '03.10 15:30 → идёт · ручной · 120 из 800 · недоступен', disabled: true};
|
||||||
|
|
||||||
|
const $ = id => document.getElementById(id);
|
||||||
|
const state = {run: RUNS[RUNS.length - 1], sort: 'worst', all: false, type: 'https'};
|
||||||
|
|
||||||
|
function sum(run) {
|
||||||
|
const n = run.subs.reduce((a, s) => a + s.n, 0), pass = run.subs.reduce((a, s) => a + s.pass, 0);
|
||||||
|
const eg = run.subs.reduce((a, s) => a + s.eg, 0), ing = run.subs.reduce((a, s) => a + s.ing, 0);
|
||||||
|
return {n, pass, partial: n - pass, eg, ing};
|
||||||
|
}
|
||||||
|
function heatClass(v) { return 'h' + (v >= 90 ? 7 : v >= 75 ? 6 : v >= 60 ? 5 : v >= 45 ? 4 : v >= 30 ? 3 : v >= 15 ? 2 : 1); }
|
||||||
|
function bar(v, max) { return `<div class="track"><div class="fill" style="width:${max ? Math.max(1, v / max * 100) : 0}%"></div></div>`; }
|
||||||
|
function tipAttr(t) { return `data-tip="${t.replace(/"/g, '"')}"`; }
|
||||||
|
|
||||||
|
function render() {
|
||||||
|
const r = state.run, s = sum(r);
|
||||||
|
$('run').value = r.id;
|
||||||
|
$('prev').disabled = RUNS.indexOf(r) === 0; $('next').disabled = RUNS.indexOf(r) === RUNS.length - 1;
|
||||||
|
$('runnote').innerHTML = `Тип: ${r.kind}. Начало ${r.start}, завершён ${r.end}, длительность ${r.dur}.` + (r.rechecked ? ` Перепроверено внутри запуска: ${r.rechecked} адр. (берётся последний цикл).` : '') + (r.demo ? ' <b>Демонстрационные данные.</b>' : '');
|
||||||
|
$('kpis').innerHTML = [
|
||||||
|
['Адресов', fmt(s.n), 'последний цикл каждого адреса', ''],
|
||||||
|
['pass', fmt(s.pass), `${pct(s.pass, s.n)}% адресов`, '<span class="tag t-ok">успех</span>'],
|
||||||
|
['partial', fmt(s.partial), `${pct(s.partial, s.n)}% адресов`, '<span class="tag t-warn">частично</span>'],
|
||||||
|
['fail', '0', 'ни одной полностью проваленной', '<span class="tag t-n">нет</span>'],
|
||||||
|
['Egress OK', pct1(s.eg, s.n) + '%', 'все egress-проверки адреса успешны', ''],
|
||||||
|
['Ingress OK', pct1(s.ing, s.n) + '%', 'все ingress-проверки адреса успешны', ''],
|
||||||
|
['Egress https: есть провалы', fmt(r.egHttpsAny), `${pct1(r.egHttpsAny, s.n)}% адресов, хотя бы одна цель недоступна`, '<span class="tag t-warn">прикладной</span> <span class="go">список →</span>', 'egany'],
|
||||||
|
['Ingress ssh: есть провалы', fmt(r.ingSshAny), `${pct1(r.ingSshAny, s.n)}% адресов, хотя бы с одной площадки`, '<span class="tag t-warn">прикладной</span> <span class="go">список →</span>', 'sshany'],
|
||||||
|
['Egress https: все провалены', fmt(r.egHttpsAll), `${pct1(r.egHttpsAll, s.n)}% адресов, по всем 5 целям: ${fmt(r.egHttpsAllFull)}`, '<span class="tag t-bad">прикладной</span> <span class="go">список →</span>', 'eg'],
|
||||||
|
['Ingress ssh: все провалены', fmt(r.ingSshAll), `${pct1(r.ingSshAll, s.n)}% адресов, ssh провален со всех площадок`, '<span class="tag t-bad">прикладной</span> <span class="go">список →</span>', 'ssh'],
|
||||||
|
['Длительность', r.dur, `${fmt(s.n / Math.max(1, parseDur(r.dur)))} адр./мин`, ''],
|
||||||
|
['Поздние результаты', fmt(r.late), `у ${fmt(r.lateAddr)} адресов, после вердикта`, '<span class="tag t-warn">внимание</span>']
|
||||||
|
].map(([k, v, d, t, key]) => { const inner = `<div class="k">${k}</div><div class="v">${v}</div><div class="d">${d} ${t}</div>`; return key ? `<button type="button" class="kpi" data-list="${key}" aria-haspopup="dialog">${inner}</button>` : `<div class="kpi">${inner}</div>`; }).join('');
|
||||||
|
|
||||||
|
const rmax = Math.max(...r.reasons.map(x => x[1]));
|
||||||
|
$('reasons').innerHTML = r.reasons.map(([k, v]) => `<div class="bar-row" ${tipAttr(k + ': ' + fmt(v) + ' адр. (' + pct(v, s.partial) + '% от partial)')}><span class="n">${k}</span>${bar(v, rmax)}<span class="num">${fmt(v)}</span></div>`).join('');
|
||||||
|
$('dq').innerHTML = [
|
||||||
|
['Поздние провалы у адресов с вердиктом pass', `${fmt(r.late)} / ${fmt(r.lateAddr)} адр.`],
|
||||||
|
['Провалы ingress, пришедшие после вердикта', `${fmt(r.errLate)} из ${fmt(r.errs.reduce((a, e) => a + e[1], 0))}`],
|
||||||
|
['Неполный набор проверок', `${fmt(r.incomplete)} адр.`],
|
||||||
|
['Вердикт pass, но есть проваленные проверки', `${fmt(r.mismatch)} адр.`],
|
||||||
|
['pass по вердикту → по фактическим проверкам', `${fmt(s.pass)} → ${fmt(s.pass - r.mismatch)}`]
|
||||||
|
].map(([k, v]) => `<div class="row"><span>${k}</span><span>${v}</span></div>`).join('');
|
||||||
|
|
||||||
|
renderSubnets(r); renderTargets(r); renderSites(r); renderErrs(r); renderVals(r);
|
||||||
|
}
|
||||||
|
function parseDur(d) { const h = /(\d+) ч/.exec(d), m = /(\d+) мин/.exec(d); return (h ? +h[1] * 60 : 0) + (m ? +m[1] : 0) || 1; }
|
||||||
|
|
||||||
|
function pbar(a, n) { const p = pct(a, n); return `<div class="pb"><div class="track">${'<div class="fill" style="width:' + p + '%"></div>'}</div><span class="num">${p}%</span></div>`; }
|
||||||
|
function renderSubnets(r) {
|
||||||
|
let list = r.subs.slice();
|
||||||
|
list.sort(state.sort === 'worst' ? (a, b) => a.pass / a.n - b.pass / b.n || b.n - a.n : (a, b) => b.n - a.n);
|
||||||
|
const shown = state.all ? list : list.slice(0, 10);
|
||||||
|
$('allsub').textContent = state.all ? 'свернуть до 10' : `показать все ${list.length}`;
|
||||||
|
$('subtbl').innerHTML = `<thead><tr><th>Подсеть</th><th class="r">Адресов</th><th class="r">pass</th><th class="r">Egress OK</th><th class="r">Ingress OK</th></tr></thead><tbody>` +
|
||||||
|
shown.map(s => `<tr><td class="a"><a href="#" onclick="return false" title="Открыть в реестре: запуск ${r.id}, подсеть ${s.c}">${s.c}</a></td><td class="num r">${fmt(s.n)}</td><td class="r" ${tipAttr(s.c + ': pass ' + fmt(s.pass) + ' из ' + fmt(s.n))}>${pbar(s.pass, s.n)}</td><td class="r" ${tipAttr(s.c + ': egress OK ' + fmt(s.eg) + ' из ' + fmt(s.n))}>${pbar(s.eg, s.n)}</td><td class="r" ${tipAttr(s.c + ': ingress OK ' + fmt(s.ing) + ' из ' + fmt(s.n))}>${pbar(s.ing, s.n)}</td></tr>`).join('') + '</tbody>';
|
||||||
|
}
|
||||||
|
function renderTargets(r) {
|
||||||
|
const t = state.type, vals = r.targets[t], s = sum(r), max = Math.max(...vals, 1);
|
||||||
|
$('targets').innerHTML = TARGETS.map((n, i) => `<div class="bar-row" ${tipAttr(n + ' · ' + t + ': провал у ' + fmt(vals[i]) + ' адр. (' + pct(vals[i], s.n) + '% всех)')}><span class="n">${n}</span>${bar(vals[i], max)}<span class="num">${fmt(vals[i])} · ${pct(vals[i], s.n)}%</span></div>`).join('');
|
||||||
|
if (t === 'https') {
|
||||||
|
$('matrixwrap').hidden = false;
|
||||||
|
$('hlegend').innerHTML = ['0–14', '15–29', '30–44', '45–59', '60–74', '75–89', '90–100'].map((l, i) => `<span><i style="background:var(--h${i + 1})"></i> ${l}%</span>`).join('');
|
||||||
|
const list = r.matrix.slice().sort((a, b) => b.partial - a.partial).slice(0, state.all ? 99 : 10);
|
||||||
|
$('matrix').innerHTML = `<thead><tr><th>Подсеть</th><th class="r">partial</th>${TARGETS.map(x => `<th class="r">${x.replace('.com', '').replace('.org', '')}</th>`).join('')}</tr></thead><tbody>` +
|
||||||
|
list.map(m => `<tr><td class="a"><a href="#" onclick="return false" title="Открыть адреса в реестре">${m.c}</a></td><td class="num r">${fmt(m.partial)}</td>${m.v.map((v, j) => `<td class="c"><span class="cell ${heatClass(v)}" ${tipAttr(m.c + ' → ' + TARGETS[j] + ': ' + v + '% адресов partial провалили https')}>${v}%</span></td>`).join('')}</tr>`).join('') + '</tbody>';
|
||||||
|
$('matrixnote').textContent = 'Доля адресов partial подсети, проваливших https к цели. Строки — подсети с наибольшим числом partial; полный список включается кнопкой «показать все» выше.';
|
||||||
|
} else {
|
||||||
|
$('matrixwrap').hidden = true;
|
||||||
|
$('matrixnote').textContent = 'Тип icmp: провалов почти нет, почти все относятся к packages.ubuntu.com. Матрица по подсетям для icmp в макете не показана, в рабочей странице она строится для любого типа.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function renderSites(r) {
|
||||||
|
$('sites').innerHTML = `<thead><tr><th>Площадка</th><th class="r">icmp</th><th class="r">ssh</th><th class="r">tcp</th></tr></thead><tbody>` +
|
||||||
|
r.sites.map(s => `<tr><td class="a">${s[0]}</td>${[1, 3, 5].map(i => `<td class="r"><span class="cell h${heatClass(100 - pct(s[i + 1], s[i]) * 8 > 100 ? 100 : Math.min(100, (100 - pct(s[i + 1], s[i])) * 8)).slice(1)}" ${tipAttr(s[0] + ' · ' + ['icmp', 'ssh', 'tcp'][(i - 1) / 2] + ': ' + fmt(s[i + 1]) + ' из ' + fmt(s[i]) + ' успешно')}>${fmt(s[i + 1])} / ${fmt(s[i])}</span></td>`).join('')}</tr>`).join('') + '</tbody>';
|
||||||
|
}
|
||||||
|
function renderErrs(r) {
|
||||||
|
const max = Math.max(...r.errs.map(e => e[1]), 1);
|
||||||
|
$('errs').innerHTML = r.errs.map(([k, v]) => `<button type="button" class="bar-row" data-cls="${k}" aria-haspopup="dialog" ${tipAttr(k + ': ' + fmt(v) + ' проверок. Нажмите, чтобы открыть список')}><span class="n">${k}</span>${bar(v, max)}<span class="num">${fmt(v)}</span></button>`).join('');
|
||||||
|
}
|
||||||
|
function renderVals(r) {
|
||||||
|
const f = r.vals.map(([t, o]) => t ? (1 - o / t) : 0), avg = f.reduce((a, b) => a + b, 0) / f.length;
|
||||||
|
$('vals').innerHTML = f.map((x, i) => `<div class="col" style="height:${x * 100}%" ${tipAttr('validator ' + (i + 1) + ': провал ' + Math.round(x * 100) + '% из ' + fmt(r.vals[i][0]) + ' https-проверок')}></div>`).join('') + `<div class="avg" style="bottom:${avg * 100}%"></div>`;
|
||||||
|
$('vavg').textContent = `среднее ${Math.round(avg * 100)}% (шкала 0–100%)`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* controls */
|
||||||
|
const sel = $('run');
|
||||||
|
sel.innerHTML = RUNS.slice().reverse().map(r => `<option value="${r.id}">${r.label}</option>`).join('') + `<option disabled>${OPEN.label}</option>`;
|
||||||
|
sel.addEventListener('change', () => { state.run = RUNS.find(r => r.id === sel.value); render(); });
|
||||||
|
$('prev').addEventListener('click', () => { const i = RUNS.indexOf(state.run); if (i > 0) { state.run = RUNS[i - 1]; render(); } });
|
||||||
|
$('next').addEventListener('click', () => { const i = RUNS.indexOf(state.run); if (i < RUNS.length - 1) { state.run = RUNS[i + 1]; render(); } });
|
||||||
|
document.querySelectorAll('[data-sort]').forEach(b => b.addEventListener('click', () => { state.sort = b.dataset.sort; document.querySelectorAll('[data-sort]').forEach(x => x.setAttribute('aria-pressed', x === b)); render(); }));
|
||||||
|
document.querySelectorAll('[data-type]').forEach(b => b.addEventListener('click', () => { state.type = b.dataset.type; document.querySelectorAll('[data-type]').forEach(x => x.setAttribute('aria-pressed', x === b)); render(); }));
|
||||||
|
$('allsub').addEventListener('click', () => { state.all = !state.all; render(); });
|
||||||
|
|
||||||
|
|
||||||
|
/* modal: address lists (two indicators) and failed checks of one ingress error class */
|
||||||
|
const LISTS = {
|
||||||
|
egany: {title: 'Egress https: адреса с проваленными проверками', file: 'egress-https-any-failed', cols: ['Адрес', 'Подсеть', 'Валидатор', 'Провалено https', 'Проваленные цели'], hints: {2: 'Валидатор, с которого шли egress-проверки адреса.', 3: 'Сколько https-проверок адреса провалено из всех записанных в цикле.'}, rows: () => REAL.egAnyList, n: r => r.egHttpsAny,
|
||||||
|
note: 'Хотя бы одна egress-проверка https адреса провалена в последнем цикле запуска.'},
|
||||||
|
sshany: {title: 'Ingress ssh: адреса с проваленными проверками', file: 'ingress-ssh-any-failed', cols: ['Адрес', 'Подсеть', 'Провалено ssh', 'Площадки с провалом', 'Ошибка'], hints: {2: 'Сколько площадок не смогли выполнить ssh-проверку адреса из всех, где она выполнялась.', 3: 'Площадки пробера, с которых ssh-проверка адреса провалена.', 4: 'Класс ошибки: таймаут, баннер «Not allowed», нет маршрута.'}, rows: () => REAL.sshAnyList, n: r => r.ingSshAny,
|
||||||
|
note: 'ssh провален хотя бы с одной площадки в последнем цикле запуска.'},
|
||||||
|
eg: {title: 'Egress https: адреса, провалившие все проверки', file: 'egress-https-all-failed', cols: ['Адрес', 'Подсеть', 'Валидатор', 'https-проверок', 'Проваленные цели'], hints: {2: 'Валидатор, с которого шли egress-проверки адреса.', 3: 'Сколько https-проверок записано у адреса в цикле. Все они провалены. Меньше 5 значит, что часть результатов не пришла.'}, rows: () => REAL.egList, n: r => r.egHttpsAll,
|
||||||
|
note: 'Все записанные egress-проверки https адреса провалены в последнем цикле запуска.'},
|
||||||
|
ssh: {title: 'Ingress ssh: адреса, провалившие все проверки', file: 'ingress-ssh-all-failed', cols: ['Адрес', 'Подсеть', 'Площадки с провалом ssh', 'Ошибка'], hints: {2: 'Площадки пробера, с которых ssh-проверка адреса провалена.', 3: 'Класс ошибки ssh-проверки: таймаут, баннер «Not allowed», нет маршрута.'}, rows: () => REAL.sshList, n: r => r.ingSshAll,
|
||||||
|
note: 'ssh провален со всех площадок, на которых он проверялся, в последнем цикле запуска.'}
|
||||||
|
};
|
||||||
|
const VERDICT_HINT = 'Итог всего адреса за цикл, который система выставила при агрегации. pass: все проверки (egress и ingress), полученные к этому моменту, успешны. partial: часть проверок провалена или результатов не хватает. fail: все проверки провалены. Это оценка адреса, а не этой проверки.';
|
||||||
|
const STATUS_HINT = 'Состояние именно этой проверки (она всегда проваленная). «в вердикте»: результат пришёл до того, как система выставила вердикт адресу, и повлиял на него. «после вердикта»: результат пришёл позже, вердикт уже был выставлен и не пересчитывался. Поэтому у адреса с вердиктом pass может быть проваленная проверка.';
|
||||||
|
const VERDICT_VAL = {pass: 'pass: к моменту вердикта все полученные проверки адреса были успешны. Эта проверка провалилась позже и в вердикт не вошла.', partial: 'partial: часть проверок адреса провалена или результатов не хватило, вердикт не pass.', fail: 'fail: все проверки адреса провалены.'};
|
||||||
|
const STATUS_VAL = v => String(v).includes('после') ? 'Результат пришёл после вердикта адреса и в него не вошёл.' : 'Результат пришёл до вердикта и учтён в нём.';
|
||||||
|
const ERRCOLS = ['Адрес', 'Подсеть', 'Площадка', 'Валидатор', 'Вердикт адреса', 'Статус проверки'];
|
||||||
|
let cur = null;
|
||||||
|
function showModal(m) {
|
||||||
|
cur = m;
|
||||||
|
$('dlg-title').textContent = `${m.title} · ${fmt(m.rows.length)}`;
|
||||||
|
$('dlg-note').textContent = `Запуск: ${m.r.label}. ${m.note}` + (m.r.demo ? ' Демонстрационный запуск: список — первые строки реального запуска от 02.10.' : '');
|
||||||
|
$('dlg-dist').hidden = !m.dist; $('dlg-dist').innerHTML = m.dist || '';
|
||||||
|
const hint = (m.hints || {});
|
||||||
|
$('dlg-tbl').innerHTML = `<thead><tr>${m.cols.map((c, i) => hint[i] ? `<th ${tipAttr(hint[i])} tabindex="0">${c}<span class="hint" aria-hidden="true">ⓘ</span></th>` : `<th>${c}</th>`).join('')}</tr></thead><tbody>` + m.rows.map(x => `<tr>${x.map((v, i) => { const h = m.cellHints && m.cellHints[i] ? m.cellHints[i](v) : ''; return `<td class="${i < 2 ? 'a' : ''}"${h ? ' ' + tipAttr(h) : ''}>${v}</td>`; }).join('')}</tr>`).join('') + '</tbody>';
|
||||||
|
$('dlg-msg').textContent = '';
|
||||||
|
const d = $('dlg'); if (d.showModal) d.showModal(); else d.setAttribute('open', '');
|
||||||
|
}
|
||||||
|
function openList(key) {
|
||||||
|
const L = LISTS[key], r = state.run, all = L.rows(), n = Math.min(all.length, L.n(r));
|
||||||
|
showModal({title: L.title, note: L.note, file: L.file, cols: L.cols, hints: L.hints, rows: r.demo ? all.slice(0, n) : all, r});
|
||||||
|
}
|
||||||
|
function openErr(cls) {
|
||||||
|
const r = state.run, n = (r.errs.find(e => e[0] === cls) || [0, 0])[1];
|
||||||
|
const all = REAL.errRows.filter(x => x[0] === cls), rows = (r.demo ? all.slice(0, n) : all).map(x => x.slice(1));
|
||||||
|
const byVal = new Array(20).fill(0); rows.forEach(x => { byVal[+x[3].slice(1) - 1]++; });
|
||||||
|
const max = Math.max(...byVal, 1), late = rows.filter(x => x[5] === 1).length, pass = rows.filter(x => x[4] === 'pass').length;
|
||||||
|
const dist = `<h2>Распределение по валидаторам</h2>
|
||||||
|
<div class="cols20" role="img" aria-label="Число проваленных проверок по валидаторам">${byVal.map((v, i) => `<div style="height:${Math.max(1, v / max * 100)}%" ${tipAttr('валидатор ' + (i + 1) + ': ' + v + ' проверок')}></div>`).join('')}</div>
|
||||||
|
<div class="lab20">${byVal.map((v, i) => `<span>${i + 1}</span>`).join('')}</div>
|
||||||
|
<div class="chips"><span class="tag t-n">всего ${fmt(rows.length)}</span><span class="tag t-ok">вердикт pass: ${fmt(pass)}</span><span class="tag t-warn">вердикт partial: ${fmt(rows.length - pass)}</span><span class="tag t-bad">после вердикта: ${fmt(late)}</span><span class="tag t-n">в вердикте: ${fmt(rows.length - late)}</span></div>`;
|
||||||
|
const view = rows.map(x => [x[0], x[1], x[2], x[3], x[4], x[5] ? 'провал, после вердикта' : 'провал, в вердикте']);
|
||||||
|
showModal({title: 'Ingress: ' + cls, note: 'Проваленные проверки этого класса в последнем цикле каждого адреса. Валидатор — тот, к которому был привязан адрес в этом цикле. «После вердикта» — результат пришёл позже агрегации и в вердикт адреса не вошёл.',
|
||||||
|
file: 'ingress-errors-' + cls.toLowerCase().replace(/[^a-z0-9а-я]+/g, '-').replace(/^-|-$/g, ''), cols: ERRCOLS, rows: view, r, dist,
|
||||||
|
hints: {3: 'Валидатор, к которому был привязан адрес в этом цикле (берётся из события привязки Floating IP).', 4: VERDICT_HINT, 5: STATUS_HINT},
|
||||||
|
cellHints: {4: v => VERDICT_VAL[v] || '', 5: STATUS_VAL}});
|
||||||
|
}
|
||||||
|
function csvText(cols, rows) {
|
||||||
|
const q = v => '"' + String(v).replace(/"/g, '""') + '"';
|
||||||
|
return '\ufeff' + [cols, ...rows].map(row => row.map(q).join(',')).join('\r\n') + '\r\n';
|
||||||
|
}
|
||||||
|
async function saveCsv() {
|
||||||
|
const name = `${cur.file}_${cur.r.id}.csv`, text = csvText(cur.cols, cur.rows), msg = $('dlg-msg');
|
||||||
|
let dl = null;
|
||||||
|
try { dl = window.claude && window.claude.use ? await window.claude.use('downloads') : null; } catch (e) { dl = null; }
|
||||||
|
if (dl) {
|
||||||
|
try { await dl.save({filename: name, data: text}); msg.textContent = 'Файл ' + name + ' сохранён.'; }
|
||||||
|
catch (e) { msg.textContent = e && e.code === 'declined' ? 'Сохранение отменено.' : 'Сохранить не удалось. Используйте «Копировать».'; }
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([text], {type: 'text/csv;charset=utf-8'})); a.download = name;
|
||||||
|
document.body.appendChild(a); a.click(); a.remove(); msg.textContent = 'Файл ' + name + ' отправлен на скачивание.';
|
||||||
|
} catch (e) { msg.textContent = 'Сохранить не удалось. Используйте «Копировать».'; }
|
||||||
|
}
|
||||||
|
async function copyCsv() {
|
||||||
|
const msg = $('dlg-msg');
|
||||||
|
try { await navigator.clipboard.writeText(csvText(cur.cols, cur.rows).replace('\ufeff', '')); msg.textContent = 'CSV скопирован в буфер обмена.'; }
|
||||||
|
catch (e) { msg.textContent = 'Буфер обмена недоступен в этом окне.'; }
|
||||||
|
}
|
||||||
|
$('kpis').addEventListener('click', e => { const b = e.target.closest('[data-list]'); if (b) openList(b.dataset.list); });
|
||||||
|
$('errs').addEventListener('click', e => { const b = e.target.closest('[data-cls]'); if (b) openErr(b.dataset.cls); });
|
||||||
|
$('dlg-csv').addEventListener('click', saveCsv);
|
||||||
|
$('dlg-copy').addEventListener('click', copyCsv);
|
||||||
|
$('dlg-close').addEventListener('click', () => $('dlg').close());
|
||||||
|
$('dlg').addEventListener('click', e => { if (e.target === $('dlg')) $('dlg').close(); });
|
||||||
|
|
||||||
|
/* tooltip (moved into the open dialog, otherwise the modal's top layer would cover it) */
|
||||||
|
const tip = $('tip');
|
||||||
|
function tipHost() { const d = $('dlg'); return d && d.open ? d : document.body; }
|
||||||
|
document.addEventListener('mouseover', e => { const t = e.target.closest('[data-tip]'); if (t) { const h = tipHost(); if (tip.parentNode !== h) h.appendChild(tip); tip.textContent = t.dataset.tip; tip.style.opacity = 1; } });
|
||||||
|
document.addEventListener('mousemove', e => { tip.style.left = Math.max(8, Math.min(e.clientX + 14, innerWidth - 376)) + 'px'; tip.style.top = (e.clientY + 16) + 'px'; });
|
||||||
|
document.addEventListener('mouseout', e => { if (e.target.closest('[data-tip]')) tip.style.opacity = 0; });
|
||||||
|
render();
|
||||||
|
</script>
|
||||||
|
</body></html>
|
||||||
@@ -0,0 +1,668 @@
|
|||||||
|
// Package analytics turns the stored checks of one finished run into the
|
||||||
|
// numbers behind the dashboard's analytics page. It works on facts: every
|
||||||
|
// check stored for the latest cycle of each address in the run, whenever it
|
||||||
|
// arrived. The verdict is shown next to those facts, never mixed into them.
|
||||||
|
package analytics
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/netip"
|
||||||
|
"net/url"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"cloudipvalidator/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Input is everything Compute needs, already read from the database.
|
||||||
|
type Input struct {
|
||||||
|
Run db.CheckRun
|
||||||
|
Results []db.RunResult
|
||||||
|
Subnets []db.Subnet
|
||||||
|
SiteNames map[int]string // site index -> site id
|
||||||
|
Rechecked int // addresses with more than one cycle in the run
|
||||||
|
// Each feeds every check of the run's result cycles to fn.
|
||||||
|
Each func(fn func(db.RunCheck)) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Report is the data of the analytics page for one run.
|
||||||
|
type Report struct {
|
||||||
|
Run RunInfo `json:"run"`
|
||||||
|
Summary Summary `json:"summary"`
|
||||||
|
Reasons []Reason `json:"reasons"`
|
||||||
|
Quality Quality `json:"quality"`
|
||||||
|
Subnets []SubnetRow `json:"subnets"`
|
||||||
|
Targets TargetsBlock `json:"targets"`
|
||||||
|
Matrix map[string][]MatrixRow `json:"matrix"`
|
||||||
|
Sites SitesBlock `json:"sites"`
|
||||||
|
Errors []ErrorClass `json:"errors"`
|
||||||
|
Validators []ValidatorRow `json:"validators"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type RunInfo struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
State string `json:"state"`
|
||||||
|
StartedAt time.Time `json:"started_at"`
|
||||||
|
FinalizedAt *time.Time `json:"finalized_at"`
|
||||||
|
DurationSec int `json:"duration_seconds"`
|
||||||
|
Rechecked int `json:"rechecked"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Summary struct {
|
||||||
|
Addresses int `json:"addresses"`
|
||||||
|
Pass int `json:"pass"`
|
||||||
|
Partial int `json:"partial"`
|
||||||
|
Fail int `json:"fail"`
|
||||||
|
Cancelled int `json:"cancelled"`
|
||||||
|
EgressOK int `json:"egress_ok"`
|
||||||
|
IngressOK int `json:"ingress_ok"`
|
||||||
|
EgressHTTPSAny int `json:"egress_https_any_failed"`
|
||||||
|
EgressHTTPSAll int `json:"egress_https_all_failed"`
|
||||||
|
// EgressHTTPSAllTargets counts the addresses that failed https to every
|
||||||
|
// target of the full set (as many checks as the best-covered address).
|
||||||
|
EgressHTTPSAllTargets int `json:"egress_https_all_targets_failed"`
|
||||||
|
IngressSSHAny int `json:"ingress_ssh_any_failed"`
|
||||||
|
IngressSSHAll int `json:"ingress_ssh_all_failed"`
|
||||||
|
PerMinute float64 `json:"addresses_per_minute"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Reason struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Count int `json:"count"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Quality is the data-quality block: how the verdict relates to the checks.
|
||||||
|
type Quality struct {
|
||||||
|
LateFailedAtPass int `json:"late_failed_checks_at_pass"`
|
||||||
|
LateFailedAtPassAddresses int `json:"late_failed_addresses_at_pass"`
|
||||||
|
IngressFailed int `json:"ingress_failed_checks"`
|
||||||
|
IngressFailedLate int `json:"ingress_failed_late"`
|
||||||
|
Incomplete int `json:"incomplete_addresses"`
|
||||||
|
PassWithFailed int `json:"pass_with_failed_addresses"`
|
||||||
|
PassByFacts int `json:"pass_by_facts"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SubnetRow struct {
|
||||||
|
CIDR string `json:"cidr"`
|
||||||
|
Label string `json:"label,omitempty"`
|
||||||
|
Addresses int `json:"addresses"`
|
||||||
|
Pass int `json:"pass"`
|
||||||
|
EgressOK int `json:"egress_ok"`
|
||||||
|
IngressOK int `json:"ingress_ok"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type TargetsBlock struct {
|
||||||
|
Types []string `json:"types"`
|
||||||
|
Targets []string `json:"targets"`
|
||||||
|
Failed map[string][]int `json:"failed"` // type -> failed addresses per target, in Targets order
|
||||||
|
}
|
||||||
|
|
||||||
|
type MatrixRow struct {
|
||||||
|
CIDR string `json:"cidr"`
|
||||||
|
Partial int `json:"partial"`
|
||||||
|
Percent []int `json:"percent"` // per target, in Targets order
|
||||||
|
}
|
||||||
|
|
||||||
|
type SitesBlock struct {
|
||||||
|
Types []string `json:"types"`
|
||||||
|
Rows []SiteRow `json:"rows"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SiteRow struct {
|
||||||
|
Site string `json:"site"`
|
||||||
|
Stats []SiteStat `json:"stats"` // per type, in Types order
|
||||||
|
}
|
||||||
|
|
||||||
|
type SiteStat struct {
|
||||||
|
Total int `json:"total"`
|
||||||
|
OK int `json:"ok"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ErrorClass struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Count int `json:"count"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ValidatorRow struct {
|
||||||
|
Validator string `json:"validator"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
OK int `json:"ok"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type typeStat struct{ n, ok int }
|
||||||
|
|
||||||
|
type failedIngress struct {
|
||||||
|
class, site, validator string
|
||||||
|
late bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// addr is everything known about one address of the run.
|
||||||
|
type addr struct {
|
||||||
|
res db.RunResult
|
||||||
|
subnet string
|
||||||
|
egress typeStat
|
||||||
|
ingress typeStat
|
||||||
|
stored int
|
||||||
|
https struct {
|
||||||
|
typeStat
|
||||||
|
validator string
|
||||||
|
failedTargets []string
|
||||||
|
}
|
||||||
|
ssh struct {
|
||||||
|
typeStat
|
||||||
|
sites []string
|
||||||
|
errs map[string]bool
|
||||||
|
}
|
||||||
|
failedTargets map[string]bool // family\x00target -> failed
|
||||||
|
failedIngress []failedIngress
|
||||||
|
lateFailed int
|
||||||
|
}
|
||||||
|
|
||||||
|
// incomplete is true when fewer checks are stored than the cycle expected; an
|
||||||
|
// unknown expectation (-1) is never incomplete.
|
||||||
|
func (a *addr) incomplete() bool { return a.res.ExpectedChecks >= 0 && a.stored < a.res.ExpectedChecks }
|
||||||
|
|
||||||
|
// Analysis is a computed report plus the per-address data the lists are cut from.
|
||||||
|
type Analysis struct {
|
||||||
|
Report Report
|
||||||
|
addrs []*addr
|
||||||
|
siteNames map[int]string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compute reads the checks of the run once and builds the report.
|
||||||
|
func Compute(in Input) (*Analysis, error) {
|
||||||
|
byReg := make(map[int64]*addr, len(in.Results))
|
||||||
|
var addrs []*addr
|
||||||
|
subnetOf := newSubnetMatcher(in.Subnets)
|
||||||
|
for _, r := range in.Results {
|
||||||
|
a := &addr{res: r, subnet: subnetOf(r.IPAddress), failedTargets: map[string]bool{}}
|
||||||
|
a.ssh.errs = map[string]bool{}
|
||||||
|
byReg[r.RegistryID] = a
|
||||||
|
addrs = append(addrs, a)
|
||||||
|
}
|
||||||
|
siteName := func(source string) string {
|
||||||
|
idx, _ := strconv.Atoi(strings.TrimPrefix(source, "inbound-site-"))
|
||||||
|
if n := in.SiteNames[idx]; n != "" {
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
return "site-" + strconv.Itoa(idx)
|
||||||
|
}
|
||||||
|
|
||||||
|
type key struct{ site, typ string }
|
||||||
|
siteStats := map[key]*typeStat{}
|
||||||
|
siteTypes := map[string]bool{}
|
||||||
|
egressTypes := map[string]bool{}
|
||||||
|
valHTTPS := map[string]*typeStat{}
|
||||||
|
targetSet := map[string]bool{}
|
||||||
|
errCount := map[string]int{}
|
||||||
|
|
||||||
|
err := in.Each(func(c db.RunCheck) {
|
||||||
|
a := byReg[c.RegistryID]
|
||||||
|
if a == nil || a.res.Verdict == db.ResultCancelled {
|
||||||
|
return // a cancelled address was stopped, its checks say nothing
|
||||||
|
}
|
||||||
|
a.stored++
|
||||||
|
late := c.AfterVerdict || c.RecordedAt.After(a.res.AggregatedAt)
|
||||||
|
family := db.CheckFamily(c.CheckType)
|
||||||
|
switch db.CheckLevel(c.Source) {
|
||||||
|
case db.LevelEgress:
|
||||||
|
a.egress.n++
|
||||||
|
if c.Success {
|
||||||
|
a.egress.ok++
|
||||||
|
}
|
||||||
|
egressTypes[family] = true
|
||||||
|
target := normalizeTarget(c.Target)
|
||||||
|
targetSet[target] = true
|
||||||
|
if !c.Success {
|
||||||
|
a.failedTargets[family+"\x00"+target] = true
|
||||||
|
}
|
||||||
|
if family == "https" {
|
||||||
|
a.https.n++
|
||||||
|
a.https.validator = c.ValidatorID
|
||||||
|
if c.Success {
|
||||||
|
a.https.ok++
|
||||||
|
} else {
|
||||||
|
a.https.failedTargets = append(a.https.failedTargets, target)
|
||||||
|
}
|
||||||
|
v := valHTTPS[c.ValidatorID]
|
||||||
|
if v == nil {
|
||||||
|
v = &typeStat{}
|
||||||
|
valHTTPS[c.ValidatorID] = v
|
||||||
|
}
|
||||||
|
v.n++
|
||||||
|
if c.Success {
|
||||||
|
v.ok++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case db.LevelIngress:
|
||||||
|
a.ingress.n++
|
||||||
|
if c.Success {
|
||||||
|
a.ingress.ok++
|
||||||
|
}
|
||||||
|
site := siteName(c.Source)
|
||||||
|
siteTypes[family] = true
|
||||||
|
ss := siteStats[key{site, family}]
|
||||||
|
if ss == nil {
|
||||||
|
ss = &typeStat{}
|
||||||
|
siteStats[key{site, family}] = ss
|
||||||
|
}
|
||||||
|
ss.n++
|
||||||
|
if c.Success {
|
||||||
|
ss.ok++
|
||||||
|
}
|
||||||
|
if family == "ssh" {
|
||||||
|
a.ssh.n++
|
||||||
|
if c.Success {
|
||||||
|
a.ssh.ok++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !c.Success {
|
||||||
|
class := ErrorClassOf(c.CheckType, c.Detail)
|
||||||
|
errCount[class]++
|
||||||
|
a.failedIngress = append(a.failedIngress, failedIngress{class: class, site: site, validator: c.ValidatorID, late: late})
|
||||||
|
if family == "ssh" {
|
||||||
|
a.ssh.sites = append(a.ssh.sites, site)
|
||||||
|
a.ssh.errs[errorReason(c.CheckType, c.Detail)] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if late && !c.Success {
|
||||||
|
a.lateFailed++
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
rep := Report{Matrix: map[string][]MatrixRow{}}
|
||||||
|
rep.Run = RunInfo{ID: in.Run.ID, Kind: in.Run.Kind, State: in.Run.State, StartedAt: in.Run.StartedAt,
|
||||||
|
FinalizedAt: in.Run.FinalizedAt, Rechecked: in.Rechecked}
|
||||||
|
if in.Run.FinalizedAt != nil {
|
||||||
|
rep.Run.DurationSec = int(in.Run.FinalizedAt.Sub(in.Run.StartedAt).Seconds())
|
||||||
|
}
|
||||||
|
|
||||||
|
maxHTTPS := 0
|
||||||
|
for _, a := range addrs {
|
||||||
|
if a.https.n > maxHTTPS {
|
||||||
|
maxHTTPS = a.https.n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
reasonCount := map[string]int{}
|
||||||
|
type subAgg struct {
|
||||||
|
n, pass, eg, ing, partial int
|
||||||
|
failed map[string]int
|
||||||
|
}
|
||||||
|
subs := map[string]*subAgg{}
|
||||||
|
sum := &rep.Summary
|
||||||
|
for _, a := range addrs {
|
||||||
|
v := a.res.Verdict
|
||||||
|
if v == db.ResultCancelled {
|
||||||
|
sum.Cancelled++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
sum.Addresses++
|
||||||
|
switch v {
|
||||||
|
case db.ResultPass:
|
||||||
|
sum.Pass++
|
||||||
|
case db.ResultPartial:
|
||||||
|
sum.Partial++
|
||||||
|
case db.ResultFail:
|
||||||
|
sum.Fail++
|
||||||
|
}
|
||||||
|
egOK := a.egress.n > 0 && a.egress.ok == a.egress.n
|
||||||
|
inOK := a.ingress.n > 0 && a.ingress.ok == a.ingress.n
|
||||||
|
if egOK {
|
||||||
|
sum.EgressOK++
|
||||||
|
}
|
||||||
|
if inOK {
|
||||||
|
sum.IngressOK++
|
||||||
|
}
|
||||||
|
if a.https.n > 0 && a.https.ok < a.https.n {
|
||||||
|
sum.EgressHTTPSAny++
|
||||||
|
if a.https.ok == 0 {
|
||||||
|
sum.EgressHTTPSAll++
|
||||||
|
if a.https.n == maxHTTPS {
|
||||||
|
sum.EgressHTTPSAllTargets++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if a.ssh.n > 0 && a.ssh.ok < a.ssh.n {
|
||||||
|
sum.IngressSSHAny++
|
||||||
|
if a.ssh.ok == 0 {
|
||||||
|
sum.IngressSSHAll++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
egFail := a.egress.ok < a.egress.n
|
||||||
|
inFail := a.ingress.ok < a.ingress.n
|
||||||
|
incomplete := a.incomplete()
|
||||||
|
if incomplete {
|
||||||
|
rep.Quality.Incomplete++
|
||||||
|
}
|
||||||
|
if v == db.ResultPartial {
|
||||||
|
reasonCount[reasonName(egFail, inFail, incomplete)]++
|
||||||
|
}
|
||||||
|
if v == db.ResultPass {
|
||||||
|
if a.egress.ok < a.egress.n || a.ingress.ok < a.ingress.n {
|
||||||
|
rep.Quality.PassWithFailed++
|
||||||
|
rep.Quality.LateFailedAtPass += a.lateFailed
|
||||||
|
rep.Quality.LateFailedAtPassAddresses++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sa := subs[a.subnet]
|
||||||
|
if sa == nil {
|
||||||
|
sa = &subAgg{failed: map[string]int{}}
|
||||||
|
subs[a.subnet] = sa
|
||||||
|
}
|
||||||
|
sa.n++
|
||||||
|
if v == db.ResultPass {
|
||||||
|
sa.pass++
|
||||||
|
}
|
||||||
|
if egOK {
|
||||||
|
sa.eg++
|
||||||
|
}
|
||||||
|
if inOK {
|
||||||
|
sa.ing++
|
||||||
|
}
|
||||||
|
if v == db.ResultPartial {
|
||||||
|
sa.partial++
|
||||||
|
for k := range a.failedTargets {
|
||||||
|
sa.failed[k]++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rep.Quality.PassByFacts = sum.Pass - rep.Quality.PassWithFailed
|
||||||
|
if sum.Addresses > 0 && rep.Run.DurationSec > 0 {
|
||||||
|
sum.PerMinute = float64(sum.Addresses) / (float64(rep.Run.DurationSec) / 60)
|
||||||
|
}
|
||||||
|
for _, a := range addrs {
|
||||||
|
for _, f := range a.failedIngress {
|
||||||
|
rep.Quality.IngressFailed++
|
||||||
|
if f.late {
|
||||||
|
rep.Quality.IngressFailedLate++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, name := range reasonOrder {
|
||||||
|
if n := reasonCount[name]; n > 0 {
|
||||||
|
rep.Reasons = append(rep.Reasons, Reason{Name: name, Count: n})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Subnets: worst first is the page's job; the report lists them by size.
|
||||||
|
labels := map[string]string{}
|
||||||
|
for _, s := range in.Subnets {
|
||||||
|
labels[s.CIDR] = s.Label
|
||||||
|
}
|
||||||
|
for cidr, sa := range subs {
|
||||||
|
rep.Subnets = append(rep.Subnets, SubnetRow{CIDR: cidr, Label: labels[cidr], Addresses: sa.n, Pass: sa.pass, EgressOK: sa.eg, IngressOK: sa.ing})
|
||||||
|
}
|
||||||
|
sort.Slice(rep.Subnets, func(i, j int) bool {
|
||||||
|
if rep.Subnets[i].Addresses != rep.Subnets[j].Addresses {
|
||||||
|
return rep.Subnets[i].Addresses > rep.Subnets[j].Addresses
|
||||||
|
}
|
||||||
|
return rep.Subnets[i].CIDR < rep.Subnets[j].CIDR
|
||||||
|
})
|
||||||
|
|
||||||
|
// Targets and the subnet x target matrix, per egress check family.
|
||||||
|
types := sortedKeys(egressTypes)
|
||||||
|
rep.Targets.Types = types
|
||||||
|
failedAddrs := map[string]int{} // family\x00target -> addresses
|
||||||
|
for _, a := range addrs {
|
||||||
|
if a.res.Verdict == db.ResultCancelled {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for k := range a.failedTargets {
|
||||||
|
failedAddrs[k]++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
targets := sortedKeys(targetSet)
|
||||||
|
lead := ""
|
||||||
|
if len(types) > 0 {
|
||||||
|
lead = types[0]
|
||||||
|
for _, t := range types {
|
||||||
|
if t == "https" {
|
||||||
|
lead = t
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.SliceStable(targets, func(i, j int) bool {
|
||||||
|
fi, fj := failedAddrs[lead+"\x00"+targets[i]], failedAddrs[lead+"\x00"+targets[j]]
|
||||||
|
if fi != fj {
|
||||||
|
return fi > fj
|
||||||
|
}
|
||||||
|
return targets[i] < targets[j]
|
||||||
|
})
|
||||||
|
rep.Targets.Targets = targets
|
||||||
|
rep.Targets.Failed = map[string][]int{}
|
||||||
|
for _, t := range types {
|
||||||
|
row := make([]int, len(targets))
|
||||||
|
for i, tg := range targets {
|
||||||
|
row[i] = failedAddrs[t+"\x00"+tg]
|
||||||
|
}
|
||||||
|
rep.Targets.Failed[t] = row
|
||||||
|
}
|
||||||
|
for _, t := range types {
|
||||||
|
var rows []MatrixRow
|
||||||
|
for cidr, sa := range subs {
|
||||||
|
if sa.partial == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
pc := make([]int, len(targets))
|
||||||
|
for i, tg := range targets {
|
||||||
|
pc[i] = int(float64(sa.failed[t+"\x00"+tg])/float64(sa.partial)*100 + 0.5)
|
||||||
|
}
|
||||||
|
rows = append(rows, MatrixRow{CIDR: cidr, Partial: sa.partial, Percent: pc})
|
||||||
|
}
|
||||||
|
sort.Slice(rows, func(i, j int) bool {
|
||||||
|
if rows[i].Partial != rows[j].Partial {
|
||||||
|
return rows[i].Partial > rows[j].Partial
|
||||||
|
}
|
||||||
|
return rows[i].CIDR < rows[j].CIDR
|
||||||
|
})
|
||||||
|
rep.Matrix[t] = rows
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sites.
|
||||||
|
rep.Sites.Types = sortedKeys(siteTypes)
|
||||||
|
names := map[string]bool{}
|
||||||
|
for k := range siteStats {
|
||||||
|
names[k.site] = true
|
||||||
|
}
|
||||||
|
siteList := sortedKeys(names)
|
||||||
|
sort.Slice(siteList, func(i, j int) bool {
|
||||||
|
return siteIndexOf(in.SiteNames, siteList[i]) < siteIndexOf(in.SiteNames, siteList[j])
|
||||||
|
})
|
||||||
|
for _, s := range siteList {
|
||||||
|
row := SiteRow{Site: s}
|
||||||
|
for _, t := range rep.Sites.Types {
|
||||||
|
st := siteStats[key{s, t}]
|
||||||
|
if st == nil {
|
||||||
|
st = &typeStat{}
|
||||||
|
}
|
||||||
|
row.Stats = append(row.Stats, SiteStat{Total: st.n, OK: st.ok})
|
||||||
|
}
|
||||||
|
rep.Sites.Rows = append(rep.Sites.Rows, row)
|
||||||
|
}
|
||||||
|
|
||||||
|
for name, n := range errCount {
|
||||||
|
rep.Errors = append(rep.Errors, ErrorClass{Name: name, Count: n})
|
||||||
|
}
|
||||||
|
sort.Slice(rep.Errors, func(i, j int) bool {
|
||||||
|
if rep.Errors[i].Count != rep.Errors[j].Count {
|
||||||
|
return rep.Errors[i].Count > rep.Errors[j].Count
|
||||||
|
}
|
||||||
|
return rep.Errors[i].Name < rep.Errors[j].Name
|
||||||
|
})
|
||||||
|
|
||||||
|
for id, st := range valHTTPS {
|
||||||
|
rep.Validators = append(rep.Validators, ValidatorRow{Validator: id, Total: st.n, OK: st.ok})
|
||||||
|
}
|
||||||
|
sort.Slice(rep.Validators, func(i, j int) bool {
|
||||||
|
a, b := validatorNumber(rep.Validators[i].Validator), validatorNumber(rep.Validators[j].Validator)
|
||||||
|
if a != b {
|
||||||
|
return a < b
|
||||||
|
}
|
||||||
|
return rep.Validators[i].Validator < rep.Validators[j].Validator
|
||||||
|
})
|
||||||
|
|
||||||
|
return &Analysis{Report: rep, addrs: addrs, siteNames: in.SiteNames}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var reasonOrder = []string{
|
||||||
|
"Только egress",
|
||||||
|
"Ingress и egress",
|
||||||
|
"Egress и неполный набор",
|
||||||
|
"Ingress, egress и неполный набор",
|
||||||
|
"Только неполный набор",
|
||||||
|
"Только ingress",
|
||||||
|
"Ingress и неполный набор",
|
||||||
|
"Прочее",
|
||||||
|
}
|
||||||
|
|
||||||
|
func reasonName(egress, ingress, incomplete bool) string {
|
||||||
|
switch {
|
||||||
|
case egress && ingress && incomplete:
|
||||||
|
return "Ingress, egress и неполный набор"
|
||||||
|
case egress && ingress:
|
||||||
|
return "Ingress и egress"
|
||||||
|
case egress && incomplete:
|
||||||
|
return "Egress и неполный набор"
|
||||||
|
case egress:
|
||||||
|
return "Только egress"
|
||||||
|
case ingress && incomplete:
|
||||||
|
return "Ingress и неполный набор"
|
||||||
|
case ingress:
|
||||||
|
return "Только ingress"
|
||||||
|
case incomplete:
|
||||||
|
return "Только неполный набор"
|
||||||
|
}
|
||||||
|
return "Прочее"
|
||||||
|
}
|
||||||
|
|
||||||
|
func sortedKeys(m map[string]bool) []string {
|
||||||
|
out := make([]string, 0, len(m))
|
||||||
|
for k := range m {
|
||||||
|
out = append(out, k)
|
||||||
|
}
|
||||||
|
sort.Strings(out)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func siteIndexOf(names map[int]string, site string) int {
|
||||||
|
for i, n := range names {
|
||||||
|
if n == site {
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if n, err := strconv.Atoi(strings.TrimPrefix(site, "site-")); err == nil {
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
return 1 << 20
|
||||||
|
}
|
||||||
|
|
||||||
|
// validatorNumber is the trailing number of a validator id ("vkiplab-v12" ->
|
||||||
|
// 12), or 1<<20 when there is none, so numbered validators sort naturally.
|
||||||
|
func validatorNumber(id string) int {
|
||||||
|
i := len(id)
|
||||||
|
for i > 0 && id[i-1] >= '0' && id[i-1] <= '9' {
|
||||||
|
i--
|
||||||
|
}
|
||||||
|
if i == len(id) {
|
||||||
|
return 1 << 20
|
||||||
|
}
|
||||||
|
n, _ := strconv.Atoi(id[i:])
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShortValidator is the validator id as the page shows it: "vkiplab-v12" ->
|
||||||
|
// "v12"; ids without a number stay whole.
|
||||||
|
func ShortValidator(id string) string {
|
||||||
|
n := validatorNumber(id)
|
||||||
|
if n == 1<<20 {
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
return "v" + strconv.Itoa(n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// normalizeTarget is the host of an egress target: https://host/path -> host.
|
||||||
|
func normalizeTarget(t string) string {
|
||||||
|
if u, err := url.Parse(t); err == nil && u.Host != "" {
|
||||||
|
return u.Hostname()
|
||||||
|
}
|
||||||
|
return strings.TrimSuffix(t, "/")
|
||||||
|
}
|
||||||
|
|
||||||
|
// newSubnetMatcher returns a function that maps an address to the most
|
||||||
|
// specific configured subnet. With no subnets configured addresses group by
|
||||||
|
// /24 (/64 for IPv6). An address outside the list goes to "прочие".
|
||||||
|
func newSubnetMatcher(subnets []db.Subnet) func(string) string {
|
||||||
|
type entry struct {
|
||||||
|
p netip.Prefix
|
||||||
|
name string
|
||||||
|
}
|
||||||
|
var list []entry
|
||||||
|
for _, s := range subnets {
|
||||||
|
if p, err := netip.ParsePrefix(s.CIDR); err == nil {
|
||||||
|
list = append(list, entry{p.Masked(), p.Masked().String()})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Slice(list, func(i, j int) bool { return list[i].p.Bits() > list[j].p.Bits() })
|
||||||
|
return func(ip string) string {
|
||||||
|
a, err := netip.ParseAddr(ip)
|
||||||
|
if err != nil {
|
||||||
|
return "прочие"
|
||||||
|
}
|
||||||
|
if len(list) == 0 {
|
||||||
|
bits := 24
|
||||||
|
if a.Is6() {
|
||||||
|
bits = 64
|
||||||
|
}
|
||||||
|
p, _ := a.Prefix(bits)
|
||||||
|
return p.String()
|
||||||
|
}
|
||||||
|
for _, e := range list {
|
||||||
|
if e.p.Contains(a) {
|
||||||
|
return e.name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "прочие"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrorClassOf names the class of a failed ingress check: the check type and
|
||||||
|
// the reason, e.g. "SSH: таймаут", "ICMP: нет ответа".
|
||||||
|
func ErrorClassOf(checkType, detail string) string {
|
||||||
|
return strings.ToUpper(checkType) + ": " + errorReason(checkType, detail)
|
||||||
|
}
|
||||||
|
|
||||||
|
func errorReason(checkType, detail string) string {
|
||||||
|
d := strings.ToLower(detail)
|
||||||
|
switch {
|
||||||
|
case strings.Contains(d, "unexpected banner prefix"):
|
||||||
|
if strings.Contains(d, "not allo") {
|
||||||
|
return "баннер «Not allowed»"
|
||||||
|
}
|
||||||
|
return "неожиданный баннер"
|
||||||
|
case strings.Contains(d, "no route to host"):
|
||||||
|
return "нет маршрута"
|
||||||
|
case strings.Contains(d, "time exceeded"):
|
||||||
|
return "time exceeded"
|
||||||
|
case strings.Contains(d, "connection refused"):
|
||||||
|
return "отказ в соединении"
|
||||||
|
case strings.Contains(d, "timeout") || strings.Contains(d, "deadline exceeded"):
|
||||||
|
if strings.EqualFold(checkType, "icmp") {
|
||||||
|
return "нет ответа"
|
||||||
|
}
|
||||||
|
return "таймаут"
|
||||||
|
}
|
||||||
|
if strings.EqualFold(checkType, "icmp") {
|
||||||
|
return "нет ответа"
|
||||||
|
}
|
||||||
|
return "прочее"
|
||||||
|
}
|
||||||
@@ -0,0 +1,326 @@
|
|||||||
|
package analytics
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"cloudipvalidator/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
var t0 = time.Date(2026, 10, 2, 13, 0, 0, 0, time.UTC)
|
||||||
|
|
||||||
|
type fixture struct {
|
||||||
|
results []db.RunResult
|
||||||
|
checks []db.RunCheck
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fixture) addr(reg int64, ip, verdict string, expected int) {
|
||||||
|
f.results = append(f.results, db.RunResult{RegistryID: reg, IPAddress: ip, CycleID: 1, Verdict: verdict,
|
||||||
|
AggregatedAt: t0.Add(time.Minute), ExpectedChecks: expected})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fixture) check(reg int64, source, typ, target string, ok bool, validator, detail string, late bool) {
|
||||||
|
rec := t0
|
||||||
|
if late {
|
||||||
|
rec = t0.Add(time.Hour)
|
||||||
|
}
|
||||||
|
f.checks = append(f.checks, db.RunCheck{RegistryID: reg, Source: source, CheckType: typ, Target: target, Success: ok,
|
||||||
|
ValidatorID: validator, Detail: detail, RecordedAt: rec})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fixture) compute(t *testing.T, subnets []db.Subnet) *Analysis {
|
||||||
|
t.Helper()
|
||||||
|
end := t0.Add(10 * time.Minute)
|
||||||
|
an, err := Compute(Input{
|
||||||
|
Run: db.CheckRun{ID: 7, Kind: db.RunManual, State: db.RunFinalized, StartedAt: t0, FinalizedAt: &end},
|
||||||
|
Results: f.results,
|
||||||
|
Subnets: subnets,
|
||||||
|
SiteNames: map[int]string{1: "rxmsk", 2: "rxyc"},
|
||||||
|
Each: func(fn func(db.RunCheck)) error {
|
||||||
|
for _, c := range f.checks {
|
||||||
|
fn(c)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return an
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
eg = db.SourceEgress
|
||||||
|
s1 = "inbound-site-1"
|
||||||
|
s2 = "inbound-site-2"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestComputeCountsFactsPerAddress(t *testing.T) {
|
||||||
|
f := &fixture{}
|
||||||
|
// 1: all fine
|
||||||
|
f.addr(1, "10.0.0.1", db.ResultPass, 6)
|
||||||
|
// 2: egress https fails on both targets, rest fine
|
||||||
|
f.addr(2, "10.0.0.2", db.ResultPartial, 6)
|
||||||
|
// 3: ingress ssh fails on one site, set incomplete (5 of 6 stored)
|
||||||
|
f.addr(3, "10.0.1.1", db.ResultPartial, 6)
|
||||||
|
// 4: pass at the verdict, but a failed ingress check arrived afterwards
|
||||||
|
f.addr(4, "10.0.1.2", db.ResultPass, 6)
|
||||||
|
// 5: cancelled, not counted
|
||||||
|
f.addr(5, "10.0.1.3", db.ResultCancelled, 6)
|
||||||
|
|
||||||
|
good := func(reg int64) {
|
||||||
|
f.check(reg, eg, "https", "https://a.test/x", true, "vkiplab-v1", "", false)
|
||||||
|
f.check(reg, eg, "https", "https://b.test", true, "vkiplab-v1", "", false)
|
||||||
|
f.check(reg, s1, "icmp", "ip", true, "vkiplab-v1", "", false)
|
||||||
|
f.check(reg, s1, "ssh", "ip", true, "vkiplab-v1", "", false)
|
||||||
|
f.check(reg, s2, "icmp", "ip", true, "vkiplab-v1", "", false)
|
||||||
|
f.check(reg, s2, "ssh", "ip", true, "vkiplab-v1", "", false)
|
||||||
|
}
|
||||||
|
good(1)
|
||||||
|
f.check(2, eg, "https", "https://a.test/x", false, "vkiplab-v2", `Get "https://a.test/x": context deadline exceeded`, false)
|
||||||
|
f.check(2, eg, "https", "https://b.test", false, "vkiplab-v2", "", false)
|
||||||
|
for _, s := range []string{s1, s2} {
|
||||||
|
f.check(2, s, "icmp", "ip", true, "vkiplab-v2", "", false)
|
||||||
|
f.check(2, s, "ssh", "ip", true, "vkiplab-v2", "", false)
|
||||||
|
}
|
||||||
|
f.check(3, eg, "https", "https://a.test/x", true, "vkiplab-v3", "", false)
|
||||||
|
f.check(3, eg, "https", "https://b.test", true, "vkiplab-v3", "", false)
|
||||||
|
f.check(3, s1, "icmp", "ip", true, "vkiplab-v3", "", false)
|
||||||
|
f.check(3, s1, "ssh", "ip", false, "vkiplab-v3", "dial tcp 1.2.3.4:22: i/o timeout", false)
|
||||||
|
f.check(3, s2, "icmp", "ip", true, "vkiplab-v3", "", false) // the 6th check is missing
|
||||||
|
// 4: the failed ssh arrived after the verdict
|
||||||
|
f.check(4, eg, "https", "https://a.test/x", true, "vkiplab-v4", "", false)
|
||||||
|
f.check(4, eg, "https", "https://b.test", true, "vkiplab-v4", "", false)
|
||||||
|
f.check(4, s1, "icmp", "ip", true, "vkiplab-v4", "", false)
|
||||||
|
f.check(4, s1, "ssh", "ip", false, "vkiplab-v4", `unexpected banner prefix "Not allo"`, true)
|
||||||
|
f.check(4, s2, "icmp", "ip", true, "vkiplab-v4", "", false)
|
||||||
|
f.check(4, s2, "ssh", "ip", true, "vkiplab-v4", "", false)
|
||||||
|
good(5)
|
||||||
|
|
||||||
|
an := f.compute(t, []db.Subnet{{CIDR: "10.0.0.0/24"}, {CIDR: "10.0.1.0/24"}})
|
||||||
|
r := an.Report
|
||||||
|
|
||||||
|
want := Summary{Addresses: 4, Pass: 2, Partial: 2, Cancelled: 1, EgressOK: 3, IngressOK: 2,
|
||||||
|
EgressHTTPSAny: 1, EgressHTTPSAll: 1, EgressHTTPSAllTargets: 1, IngressSSHAny: 2, IngressSSHAll: 1}
|
||||||
|
got := r.Summary
|
||||||
|
got.PerMinute = 0
|
||||||
|
if got != want {
|
||||||
|
t.Errorf("summary = %+v\nwant %+v", got, want)
|
||||||
|
}
|
||||||
|
if r.Run.DurationSec != 600 || r.Run.ID != 7 {
|
||||||
|
t.Errorf("run info: %+v", r.Run)
|
||||||
|
}
|
||||||
|
|
||||||
|
if wantReasons := []Reason{{"Только egress", 1}, {"Ingress и неполный набор", 1}}; !reflect.DeepEqual(r.Reasons, wantReasons) {
|
||||||
|
t.Errorf("reasons = %+v, want %+v", r.Reasons, wantReasons)
|
||||||
|
}
|
||||||
|
|
||||||
|
q := r.Quality
|
||||||
|
if q.Incomplete != 1 || q.PassWithFailed != 1 || q.PassByFacts != 1 || q.LateFailedAtPass != 1 || q.LateFailedAtPassAddresses != 1 ||
|
||||||
|
q.IngressFailed != 2 || q.IngressFailedLate != 1 {
|
||||||
|
t.Errorf("quality = %+v", q)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Errors are classed by check type and reason.
|
||||||
|
wantErrs := []ErrorClass{{"SSH: баннер «Not allowed»", 1}, {"SSH: таймаут", 1}}
|
||||||
|
if !reflect.DeepEqual(r.Errors, wantErrs) {
|
||||||
|
t.Errorf("errors = %+v", r.Errors)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Targets: hosts, https is the lead type; address 2 failed both.
|
||||||
|
if !reflect.DeepEqual(r.Targets.Targets, []string{"a.test", "b.test"}) || !reflect.DeepEqual(r.Targets.Failed["https"], []int{1, 1}) {
|
||||||
|
t.Errorf("targets = %+v", r.Targets)
|
||||||
|
}
|
||||||
|
if len(r.Subnets) != 2 || r.Subnets[0].Addresses != 2 {
|
||||||
|
t.Errorf("subnets = %+v", r.Subnets)
|
||||||
|
}
|
||||||
|
if rows := r.Matrix["https"]; len(rows) != 2 || rows[0].CIDR != "10.0.0.0/24" && rows[0].CIDR != "10.0.1.0/24" {
|
||||||
|
t.Errorf("matrix = %+v", r.Matrix)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sites in index order, types sorted.
|
||||||
|
if !reflect.DeepEqual(r.Sites.Types, []string{"icmp", "ssh"}) || len(r.Sites.Rows) != 2 || r.Sites.Rows[0].Site != "rxmsk" {
|
||||||
|
t.Errorf("sites = %+v", r.Sites)
|
||||||
|
}
|
||||||
|
// ssh at rxmsk: addresses 1, 2, 3, 4 (the cancelled one is not counted) -> 4 checks, 2 failed.
|
||||||
|
if st := r.Sites.Rows[0].Stats[1]; st.Total != 4 || st.OK != 2 {
|
||||||
|
t.Errorf("rxmsk ssh = %+v", st)
|
||||||
|
}
|
||||||
|
// Validators by number.
|
||||||
|
if len(r.Validators) != 4 || r.Validators[0].Validator != "vkiplab-v1" || r.Validators[0].Total != 2 {
|
||||||
|
t.Errorf("validators = %+v", r.Validators)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSubnetMatching(t *testing.T) {
|
||||||
|
in := []db.Subnet{{CIDR: "10.0.0.0/8"}, {CIDR: "10.1.0.0/16"}}
|
||||||
|
m := newSubnetMatcher(in)
|
||||||
|
for ip, want := range map[string]string{"10.1.2.3": "10.1.0.0/16", "10.2.0.1": "10.0.0.0/8", "192.0.2.1": "прочие", "garbage": "прочие"} {
|
||||||
|
if got := m(ip); got != want {
|
||||||
|
t.Errorf("%s -> %s, want %s", ip, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
auto := newSubnetMatcher(nil)
|
||||||
|
if got := auto("203.0.113.77"); got != "203.0.113.0/24" {
|
||||||
|
t.Errorf("without a list addresses group by /24, got %s", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestErrorClassOf(t *testing.T) {
|
||||||
|
for _, c := range []struct{ typ, detail, want string }{
|
||||||
|
{"ssh", `read banner: read tcp 1.2.3.4:5->6.7.8.9:22: i/o timeout`, "SSH: таймаут"},
|
||||||
|
{"ssh", `unexpected banner prefix "Not allo"`, "SSH: баннер «Not allowed»"},
|
||||||
|
{"ssh", `dial tcp 1.2.3.4:22: connect: no route to host`, "SSH: нет маршрута"},
|
||||||
|
{"tcp-22", `dial tcp 1.2.3.4:22: i/o timeout`, "TCP-22: таймаут"},
|
||||||
|
{"tcp-22", `connect: connection refused`, "TCP-22: отказ в соединении"},
|
||||||
|
{"icmp", `read echo reply: read ip4 0.0.0.0: i/o timeout`, "ICMP: нет ответа"},
|
||||||
|
{"icmp", `unexpected icmp type time exceeded`, "ICMP: time exceeded"},
|
||||||
|
{"ssh", `something new`, "SSH: прочее"},
|
||||||
|
} {
|
||||||
|
if got := ErrorClassOf(c.typ, c.detail); got != c.want {
|
||||||
|
t.Errorf("%s %q = %q, want %q", c.typ, c.detail, got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListsAndShortValidator(t *testing.T) {
|
||||||
|
f := &fixture{}
|
||||||
|
f.addr(1, "10.0.0.9", db.ResultPartial, 4)
|
||||||
|
f.addr(2, "10.0.0.10", db.ResultPass, 4)
|
||||||
|
f.check(1, eg, "https", "https://a.test", false, "vkiplab-v12", "", false)
|
||||||
|
f.check(1, eg, "https", "https://b.test", false, "vkiplab-v12", "", false)
|
||||||
|
f.check(1, s2, "ssh", "ip", false, "vkiplab-v12", "dial tcp: i/o timeout", false)
|
||||||
|
f.check(1, s1, "ssh", "ip", false, "vkiplab-v12", "dial tcp: i/o timeout", true)
|
||||||
|
f.check(2, eg, "https", "https://a.test", true, "vkiplab-v3", "", false)
|
||||||
|
f.check(2, eg, "https", "https://b.test", false, "vkiplab-v3", "", false)
|
||||||
|
an := f.compute(t, nil)
|
||||||
|
|
||||||
|
l, err := an.List(ListEgressHTTPSAny, "")
|
||||||
|
if err != nil || len(l.Rows) != 2 || l.Rows[0][0] != "10.0.0.9" || l.Rows[1][0] != "10.0.0.10" { // numeric order
|
||||||
|
t.Fatalf("any: %+v %v", l, err)
|
||||||
|
}
|
||||||
|
if l.Rows[0][2] != "v12" || l.Rows[0][3] != "2 из 2" || l.Rows[1][3] != "1 из 2" || l.Rows[1][4] != "b.test" {
|
||||||
|
t.Errorf("any rows: %+v", l.Rows)
|
||||||
|
}
|
||||||
|
l, _ = an.List(ListEgressHTTPSAll, "")
|
||||||
|
if len(l.Rows) != 1 || l.Rows[0][3] != "2" || l.Rows[0][4] != "a.test, b.test" {
|
||||||
|
t.Errorf("all: %+v", l.Rows)
|
||||||
|
}
|
||||||
|
l, _ = an.List(ListIngressSSHAll, "")
|
||||||
|
if len(l.Rows) != 1 || l.Rows[0][2] != "rxmsk, rxyc" || l.Rows[0][3] != "таймаут" { // sites in index order
|
||||||
|
t.Errorf("ssh all: %+v", l.Rows)
|
||||||
|
}
|
||||||
|
l, _ = an.List(ListError, "SSH: таймаут")
|
||||||
|
if len(l.Rows) != 2 || l.Rows[0][2] != "rxmsk" || l.Rows[0][5] != "провал, после вердикта" || l.Rows[1][5] != "провал, в вердикте" {
|
||||||
|
t.Errorf("error list: %+v", l.Rows)
|
||||||
|
}
|
||||||
|
if _, err := an.List(ListError, ""); err == nil {
|
||||||
|
t.Error("an error list needs a class")
|
||||||
|
}
|
||||||
|
if _, err := an.List("nonsense", ""); err == nil {
|
||||||
|
t.Error("unknown list must fail")
|
||||||
|
}
|
||||||
|
for in, want := range map[string]string{"vkiplab-v12": "v12", "validator": "validator", "": ""} {
|
||||||
|
if got := ShortValidator(in); got != want {
|
||||||
|
t.Errorf("ShortValidator(%q) = %q", in, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestVerdictLists(t *testing.T) {
|
||||||
|
f := &fixture{}
|
||||||
|
f.addr(1, "10.0.0.10", db.ResultPass, 4) // late failed ssh: pass by verdict, failed by facts
|
||||||
|
f.addr(2, "10.0.0.2", db.ResultPass, 4)
|
||||||
|
f.addr(3, "10.0.0.9", db.ResultPartial, 4) // egress failed, one check missing
|
||||||
|
f.addr(4, "10.0.0.3", db.ResultPartial, -1) // expected number unknown
|
||||||
|
f.addr(5, "10.0.0.5", db.ResultFail, 1) // no egress checks at all
|
||||||
|
f.addr(6, "10.0.0.4", db.ResultFail, 2)
|
||||||
|
f.addr(7, "10.0.0.1", db.ResultCancelled, 4)
|
||||||
|
for _, reg := range []int64{1, 2} {
|
||||||
|
f.check(reg, eg, "https", "https://a.test", true, "vkiplab-v1", "", false)
|
||||||
|
f.check(reg, eg, "https", "https://b.test", true, "vkiplab-v1", "", false)
|
||||||
|
f.check(reg, s1, "icmp", "ip", true, "vkiplab-v1", "", false)
|
||||||
|
}
|
||||||
|
f.check(1, s1, "ssh", "ip", false, "vkiplab-v1", "dial tcp: i/o timeout", true)
|
||||||
|
f.check(2, s1, "ssh", "ip", true, "vkiplab-v1", "", false)
|
||||||
|
f.check(3, eg, "https", "https://a.test", false, "vkiplab-v12", "", false)
|
||||||
|
f.check(3, eg, "https", "https://b.test", false, "vkiplab-v12", "", false)
|
||||||
|
f.check(3, s1, "icmp", "ip", true, "vkiplab-v12", "", false)
|
||||||
|
f.check(4, eg, "https", "https://a.test", true, "vkiplab-v3", "", false)
|
||||||
|
f.check(4, s1, "ssh", "ip", false, "vkiplab-v3", "dial tcp: i/o timeout", false)
|
||||||
|
f.check(5, s1, "icmp", "ip", false, "vkiplab-v5", "", false)
|
||||||
|
f.check(6, eg, "https", "https://a.test", false, "vkiplab-v5", "", false)
|
||||||
|
f.check(6, s1, "icmp", "ip", false, "vkiplab-v5", "", false)
|
||||||
|
f.check(7, eg, "https", "https://a.test", true, "vkiplab-v1", "", false)
|
||||||
|
an := f.compute(t, nil)
|
||||||
|
|
||||||
|
// Every list has as many rows as its number on the card; the cancelled address is in none.
|
||||||
|
s := an.Report.Summary
|
||||||
|
rows := map[string][][]string{}
|
||||||
|
for kind, want := range map[string]int{ListVerdictPass: s.Pass, ListVerdictPartial: s.Partial, ListVerdictFail: s.Fail} {
|
||||||
|
l, err := an.List(kind, "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if l.Kind != kind || len(l.Rows) != want || want != 2 {
|
||||||
|
t.Fatalf("%s: %d rows, summary %d", kind, len(l.Rows), want)
|
||||||
|
}
|
||||||
|
for _, r := range l.Rows {
|
||||||
|
if r[0] == "10.0.0.1" || len(r) != len(l.Columns) {
|
||||||
|
t.Errorf("%s: bad row %v for columns %v", kind, r, l.Columns)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows[kind] = l.Rows
|
||||||
|
}
|
||||||
|
|
||||||
|
// Numeric address order, not text order.
|
||||||
|
if p := rows[ListVerdictPass]; p[0][0] != "10.0.0.2" || p[1][0] != "10.0.0.10" {
|
||||||
|
t.Errorf("pass order: %v", p)
|
||||||
|
}
|
||||||
|
l, _ := an.List(ListVerdictPass, "")
|
||||||
|
if want := []string{"Адрес", "Подсеть", "Валидатор", "Egress", "Ingress", "Проверок в цикле"}; !reflect.DeepEqual(l.Columns, want) {
|
||||||
|
t.Errorf("pass columns: %v", l.Columns)
|
||||||
|
}
|
||||||
|
// Levels count successful of all; the failed late ssh shows in ingress.
|
||||||
|
if want := []string{"10.0.0.2", "10.0.0.0/24", "v1", "2 из 2", "2 из 2", "4 из 4"}; !reflect.DeepEqual(rows[ListVerdictPass][0], want) {
|
||||||
|
t.Errorf("pass row: %v", rows[ListVerdictPass][0])
|
||||||
|
}
|
||||||
|
if r := rows[ListVerdictPass][1]; r[3] != "2 из 2" || r[4] != "1 из 2" || r[5] != "4 из 4" {
|
||||||
|
t.Errorf("pass with a late failure: %v", r)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Partial has the reason of the "why partial" block; a short set shows stored of expected,
|
||||||
|
// an unknown expectation only the stored number.
|
||||||
|
l, _ = an.List(ListVerdictPartial, "")
|
||||||
|
if len(l.Columns) != 7 || l.Columns[6] != "Причина" {
|
||||||
|
t.Errorf("partial columns: %v", l.Columns)
|
||||||
|
}
|
||||||
|
if want := []string{"10.0.0.3", "10.0.0.0/24", "v3", "1 из 1", "0 из 1", "2", "Только ingress"}; !reflect.DeepEqual(l.Rows[0], want) {
|
||||||
|
t.Errorf("partial unknown expected: %v", l.Rows[0])
|
||||||
|
}
|
||||||
|
if want := []string{"10.0.0.9", "10.0.0.0/24", "v12", "0 из 2", "1 из 1", "3 из 4", "Egress и неполный набор"}; !reflect.DeepEqual(l.Rows[1], want) {
|
||||||
|
t.Errorf("partial incomplete: %v", l.Rows[1])
|
||||||
|
}
|
||||||
|
byReason := map[string]int{}
|
||||||
|
for _, r := range l.Rows {
|
||||||
|
byReason[r[6]]++
|
||||||
|
}
|
||||||
|
for _, x := range an.Report.Reasons {
|
||||||
|
if byReason[x.Name] != x.Count {
|
||||||
|
t.Errorf("reason %q: %d rows, %d in the report", x.Name, byReason[x.Name], x.Count)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A level without checks shows a dash, so does a missing validator.
|
||||||
|
l, _ = an.List(ListVerdictFail, "")
|
||||||
|
if len(l.Columns) != 6 {
|
||||||
|
t.Errorf("fail columns: %v", l.Columns)
|
||||||
|
}
|
||||||
|
if want := []string{"10.0.0.4", "10.0.0.0/24", "v5", "0 из 1", "0 из 1", "2 из 2"}; !reflect.DeepEqual(l.Rows[0], want) {
|
||||||
|
t.Errorf("fail row: %v", l.Rows[0])
|
||||||
|
}
|
||||||
|
if want := []string{"10.0.0.5", "10.0.0.0/24", "—", "—", "0 из 1", "1 из 1"}; !reflect.DeepEqual(l.Rows[1], want) {
|
||||||
|
t.Errorf("fail row without egress: %v", l.Rows[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,432 @@
|
|||||||
|
package analytics
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"cloudipvalidator/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// indicator is one of the seven counters of the analytics page. Its key is the
|
||||||
|
// name of the list behind the counter; has repeats the condition Compute counts
|
||||||
|
// it by (an address with a cancelled result is never asked).
|
||||||
|
type indicator struct {
|
||||||
|
key, name string
|
||||||
|
has func(a *addr) bool
|
||||||
|
}
|
||||||
|
|
||||||
|
var indicators = []indicator{
|
||||||
|
{ListVerdictPass, "pass", func(a *addr) bool { return a.res.Verdict == db.ResultPass }},
|
||||||
|
{ListVerdictPartial, "partial", func(a *addr) bool { return a.res.Verdict == db.ResultPartial }},
|
||||||
|
{ListVerdictFail, "fail", func(a *addr) bool { return a.res.Verdict == db.ResultFail }},
|
||||||
|
{ListEgressHTTPSAny, "Egress https: есть провалы", func(a *addr) bool { return a.https.n > 0 && a.https.ok < a.https.n }},
|
||||||
|
{ListEgressHTTPSAll, "Egress https: все провалены", func(a *addr) bool { return a.https.n > 0 && a.https.ok == 0 }},
|
||||||
|
{ListIngressSSHAny, "Ingress ssh: есть провалы", func(a *addr) bool { return a.ssh.n > 0 && a.ssh.ok < a.ssh.n }},
|
||||||
|
{ListIngressSSHAll, "Ingress ssh: все провалены", func(a *addr) bool { return a.ssh.n > 0 && a.ssh.ok == 0 }},
|
||||||
|
}
|
||||||
|
|
||||||
|
// indicatorIndex is the position of an indicator key in the table, -1 if unknown.
|
||||||
|
func indicatorIndex(key string) int {
|
||||||
|
for i, ind := range indicators {
|
||||||
|
if ind.key == key {
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
// verdicts are the rows and columns of the transition matrix.
|
||||||
|
var verdicts = []string{db.ResultPass, db.ResultPartial, db.ResultFail}
|
||||||
|
|
||||||
|
func verdictIndex(v string) int {
|
||||||
|
for i, x := range verdicts {
|
||||||
|
if x == v {
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
// membership is the set of indicators an address belongs to, one bit per
|
||||||
|
// entry of the indicators table.
|
||||||
|
func membership(a *addr) uint8 {
|
||||||
|
var m uint8
|
||||||
|
for i, ind := range indicators {
|
||||||
|
if ind.has(a) {
|
||||||
|
m |= 1 << i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
// Comparison is the difference between two finished runs: the base (older) and
|
||||||
|
// the target (newer) one. An address is its IP; one with a cancelled result is
|
||||||
|
// not in its run.
|
||||||
|
type Comparison struct {
|
||||||
|
Runs CompareRuns `json:"runs"`
|
||||||
|
Groups CompareGroups `json:"groups"`
|
||||||
|
Indicators []IndicatorDiff `json:"indicators"`
|
||||||
|
Transitions Transitions `json:"transitions"`
|
||||||
|
Cancelled CompareCancel `json:"cancelled"`
|
||||||
|
|
||||||
|
rows []*cmpRow // numeric address order
|
||||||
|
target *Analysis
|
||||||
|
}
|
||||||
|
|
||||||
|
type CompareRuns struct {
|
||||||
|
Base CompareRun `json:"base"`
|
||||||
|
Target CompareRun `json:"target"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CompareRun struct {
|
||||||
|
RunInfo
|
||||||
|
Addresses int `json:"addresses"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CompareGroups counts the addresses by how they relate to the two runs:
|
||||||
|
// New are only in the target, Left only in the base, Common in both, and
|
||||||
|
// Common = Changed + Same.
|
||||||
|
type CompareGroups struct {
|
||||||
|
New int `json:"new"`
|
||||||
|
Left int `json:"left"`
|
||||||
|
Common int `json:"common"`
|
||||||
|
Changed int `json:"changed"`
|
||||||
|
Same int `json:"same"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// IndicatorDiff is one indicator in both runs. Delta = Target - Base =
|
||||||
|
// New - Left + Entered - Exited.
|
||||||
|
type IndicatorDiff struct {
|
||||||
|
Key string `json:"key"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Base int `json:"base"`
|
||||||
|
Target int `json:"target"`
|
||||||
|
Delta int `json:"delta"`
|
||||||
|
New int `json:"new"` // new addresses that are in the indicator
|
||||||
|
Left int `json:"left"` // left addresses that were in it
|
||||||
|
Entered int `json:"entered"` // common addresses that entered it
|
||||||
|
Exited int `json:"exited"` // common addresses that left it
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transitions is the verdict of the common addresses: Matrix[from][to] with
|
||||||
|
// the verdicts of the base on the rows and of the target on the columns. New
|
||||||
|
// holds the new addresses by their verdict in the target, Left the addresses
|
||||||
|
// that left by their verdict in the base.
|
||||||
|
type Transitions struct {
|
||||||
|
Verdicts []string `json:"verdicts"`
|
||||||
|
Matrix [][]int `json:"matrix"`
|
||||||
|
New []int `json:"new"`
|
||||||
|
Left []int `json:"left"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CompareCancel struct {
|
||||||
|
Base int `json:"base"`
|
||||||
|
Target int `json:"target"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// cmpRow is one address with its state in each run (nil when absent) and the
|
||||||
|
// indicators it belongs to there.
|
||||||
|
type cmpRow struct {
|
||||||
|
ip string
|
||||||
|
a, b *addr
|
||||||
|
ma, mb uint8
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *cmpRow) common() bool { return r.a != nil && r.b != nil }
|
||||||
|
func (r *cmpRow) changed() bool { return r.common() && r.ma != r.mb }
|
||||||
|
|
||||||
|
// Compare puts two analyses side by side; base is the older run, target the newer.
|
||||||
|
func Compare(base, target *Analysis) *Comparison {
|
||||||
|
byIP := map[string]*cmpRow{}
|
||||||
|
var rows []*cmpRow
|
||||||
|
add := func(list []*addr, isBase bool) {
|
||||||
|
for _, x := range list {
|
||||||
|
r := byIP[x.res.IPAddress]
|
||||||
|
if r == nil {
|
||||||
|
r = &cmpRow{ip: x.res.IPAddress}
|
||||||
|
byIP[r.ip] = r
|
||||||
|
rows = append(rows, r)
|
||||||
|
}
|
||||||
|
if isBase {
|
||||||
|
r.a, r.ma = x, membership(x)
|
||||||
|
} else {
|
||||||
|
r.b, r.mb = x, membership(x)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
add(base.sorted(), true)
|
||||||
|
add(target.sorted(), false)
|
||||||
|
sort.Slice(rows, func(i, j int) bool { return lessIP(rows[i].ip, rows[j].ip) })
|
||||||
|
|
||||||
|
c := &Comparison{rows: rows, target: target}
|
||||||
|
c.Runs = CompareRuns{
|
||||||
|
Base: CompareRun{RunInfo: base.Report.Run, Addresses: base.Report.Summary.Addresses},
|
||||||
|
Target: CompareRun{RunInfo: target.Report.Run, Addresses: target.Report.Summary.Addresses},
|
||||||
|
}
|
||||||
|
c.Cancelled = CompareCancel{Base: base.Report.Summary.Cancelled, Target: target.Report.Summary.Cancelled}
|
||||||
|
c.Indicators = make([]IndicatorDiff, len(indicators))
|
||||||
|
for i, ind := range indicators {
|
||||||
|
c.Indicators[i] = IndicatorDiff{Key: ind.key, Name: ind.name}
|
||||||
|
}
|
||||||
|
tr := &c.Transitions
|
||||||
|
tr.Verdicts = verdicts
|
||||||
|
tr.New, tr.Left = make([]int, len(verdicts)), make([]int, len(verdicts))
|
||||||
|
tr.Matrix = make([][]int, len(verdicts))
|
||||||
|
for i := range tr.Matrix {
|
||||||
|
tr.Matrix[i] = make([]int, len(verdicts))
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, r := range rows {
|
||||||
|
switch {
|
||||||
|
case r.a == nil:
|
||||||
|
c.Groups.New++
|
||||||
|
if v := verdictIndex(r.b.res.Verdict); v >= 0 {
|
||||||
|
tr.New[v]++
|
||||||
|
}
|
||||||
|
case r.b == nil:
|
||||||
|
c.Groups.Left++
|
||||||
|
if v := verdictIndex(r.a.res.Verdict); v >= 0 {
|
||||||
|
tr.Left[v]++
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
c.Groups.Common++
|
||||||
|
if r.changed() {
|
||||||
|
c.Groups.Changed++
|
||||||
|
} else {
|
||||||
|
c.Groups.Same++
|
||||||
|
}
|
||||||
|
if from, to := verdictIndex(r.a.res.Verdict), verdictIndex(r.b.res.Verdict); from >= 0 && to >= 0 {
|
||||||
|
tr.Matrix[from][to]++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i := range indicators {
|
||||||
|
bit := uint8(1) << i
|
||||||
|
inA, inB := r.ma&bit != 0, r.mb&bit != 0
|
||||||
|
d := &c.Indicators[i]
|
||||||
|
if inA {
|
||||||
|
d.Base++
|
||||||
|
}
|
||||||
|
if inB {
|
||||||
|
d.Target++
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case r.a == nil && inB:
|
||||||
|
d.New++
|
||||||
|
case r.b == nil && inA:
|
||||||
|
d.Left++
|
||||||
|
case r.common() && !inA && inB:
|
||||||
|
d.Entered++
|
||||||
|
case r.common() && inA && !inB:
|
||||||
|
d.Exited++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i := range c.Indicators {
|
||||||
|
c.Indicators[i].Delta = c.Indicators[i].Target - c.Indicators[i].Base
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
// Groups served by Comparison.List.
|
||||||
|
const (
|
||||||
|
GroupNew = "new"
|
||||||
|
GroupLeft = "left"
|
||||||
|
GroupCommon = "common"
|
||||||
|
GroupChanged = "changed"
|
||||||
|
GroupSame = "same"
|
||||||
|
GroupEntered = "entered"
|
||||||
|
GroupExited = "exited"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CompareFilter narrows a group. Indicator is a list key of the indicator
|
||||||
|
// table: for new and left the address is in it in its own run, for common,
|
||||||
|
// changed and same in either run, for entered and exited it is required.
|
||||||
|
// From and To, only together, keep the common addresses whose verdict was From
|
||||||
|
// in the base and is To in the target.
|
||||||
|
type CompareFilter struct {
|
||||||
|
Indicator string
|
||||||
|
From, To string
|
||||||
|
}
|
||||||
|
|
||||||
|
// CompareList is a table of addresses of one group.
|
||||||
|
type CompareList struct {
|
||||||
|
Group string `json:"group"`
|
||||||
|
Indicator string `json:"indicator,omitempty"`
|
||||||
|
Columns []string `json:"columns"`
|
||||||
|
Rows [][]string `json:"rows"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// List builds the table of a group; an unknown group, indicator or verdict, or
|
||||||
|
// a filter that does not fit the group, is an ErrUnknownList.
|
||||||
|
func (c *Comparison) List(group string, f CompareFilter) (*CompareList, error) {
|
||||||
|
switch group {
|
||||||
|
case GroupNew, GroupLeft, GroupCommon, GroupChanged, GroupSame, GroupEntered, GroupExited:
|
||||||
|
default:
|
||||||
|
return nil, ErrUnknownList(group)
|
||||||
|
}
|
||||||
|
var bit uint8
|
||||||
|
if f.Indicator != "" {
|
||||||
|
i := indicatorIndex(f.Indicator)
|
||||||
|
if i < 0 {
|
||||||
|
return nil, ErrUnknownList("indicator " + f.Indicator)
|
||||||
|
}
|
||||||
|
bit = 1 << i
|
||||||
|
}
|
||||||
|
if bit == 0 && (group == GroupEntered || group == GroupExited) {
|
||||||
|
return nil, ErrUnknownList(group + " without indicator")
|
||||||
|
}
|
||||||
|
if (f.From != "") != (f.To != "") {
|
||||||
|
return nil, ErrUnknownList("from without to")
|
||||||
|
}
|
||||||
|
if f.From != "" {
|
||||||
|
if verdictIndex(f.From) < 0 || verdictIndex(f.To) < 0 {
|
||||||
|
return nil, ErrUnknownList("verdict " + f.From + " → " + f.To)
|
||||||
|
}
|
||||||
|
if group == GroupNew || group == GroupLeft {
|
||||||
|
return nil, ErrUnknownList("from and to for " + group)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
l := &CompareList{Group: group, Indicator: f.Indicator, Rows: [][]string{}}
|
||||||
|
if group == GroupNew || group == GroupLeft {
|
||||||
|
l.Columns = []string{"Адрес", "Подсеть", "Вердикт", "Egress", "Ingress", "Индикаторы"}
|
||||||
|
} else {
|
||||||
|
l.Columns = []string{"Адрес", "Подсеть", "Вердикт (A → B)", "Egress (A → B)", "Ingress (A → B)", "Что изменилось"}
|
||||||
|
}
|
||||||
|
for _, r := range c.rows {
|
||||||
|
var ok bool
|
||||||
|
switch group {
|
||||||
|
case GroupNew:
|
||||||
|
ok = r.a == nil && (bit == 0 || r.mb&bit != 0)
|
||||||
|
case GroupLeft:
|
||||||
|
ok = r.b == nil && (bit == 0 || r.ma&bit != 0)
|
||||||
|
case GroupCommon:
|
||||||
|
ok = r.common()
|
||||||
|
case GroupChanged:
|
||||||
|
ok = r.changed()
|
||||||
|
case GroupSame:
|
||||||
|
ok = r.common() && !r.changed()
|
||||||
|
case GroupEntered:
|
||||||
|
ok = r.common() && r.ma&bit == 0 && r.mb&bit != 0
|
||||||
|
case GroupExited:
|
||||||
|
ok = r.common() && r.ma&bit != 0 && r.mb&bit == 0
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if r.common() && bit != 0 && group != GroupEntered && group != GroupExited && (r.ma|r.mb)&bit == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if f.From != "" && (r.a.res.Verdict != f.From || r.b.res.Verdict != f.To) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case r.a == nil:
|
||||||
|
l.Rows = append(l.Rows, []string{r.ip, r.b.subnet, r.b.res.Verdict, okOf(r.b.egress), okOf(r.b.ingress), indicatorsCell(r.mb)})
|
||||||
|
case r.b == nil:
|
||||||
|
l.Rows = append(l.Rows, []string{r.ip, r.a.subnet, r.a.res.Verdict, okOf(r.a.egress), okOf(r.a.ingress), indicatorsCell(r.ma)})
|
||||||
|
default:
|
||||||
|
l.Rows = append(l.Rows, []string{r.ip, r.b.subnet, arrow(r.a.res.Verdict, r.b.res.Verdict),
|
||||||
|
arrow(okOf(r.a.egress), okOf(r.b.egress)), arrow(okOf(r.a.ingress), okOf(r.b.ingress)), c.changeText(r)})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return l, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func arrow(from, to string) string { return from + " → " + to }
|
||||||
|
|
||||||
|
// indicatorsCell names the indicators of a membership set, "—" for none.
|
||||||
|
func indicatorsCell(m uint8) string {
|
||||||
|
var names []string
|
||||||
|
for i, ind := range indicators {
|
||||||
|
if m&(1<<i) != 0 {
|
||||||
|
names = append(names, ind.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(names) == 0 {
|
||||||
|
return "—"
|
||||||
|
}
|
||||||
|
return strings.Join(names, ", ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// changeText says step by step what differs between the two runs for a common
|
||||||
|
// address. An address with the same indicators is "без изменений" even if its
|
||||||
|
// failed targets or sites differ.
|
||||||
|
func (c *Comparison) changeText(r *cmpRow) string {
|
||||||
|
if r.ma == r.mb {
|
||||||
|
return "без изменений"
|
||||||
|
}
|
||||||
|
var steps []string
|
||||||
|
if r.a.res.Verdict != r.b.res.Verdict {
|
||||||
|
steps = append(steps, "вердикт "+arrow(r.a.res.Verdict, r.b.res.Verdict))
|
||||||
|
}
|
||||||
|
var in, out []string
|
||||||
|
for i, ind := range indicators {
|
||||||
|
if strings.HasPrefix(ind.key, "verdict_") {
|
||||||
|
continue // the verdict step says it
|
||||||
|
}
|
||||||
|
bit := uint8(1) << i
|
||||||
|
switch {
|
||||||
|
case r.ma&bit == 0 && r.mb&bit != 0:
|
||||||
|
in = append(in, ind.name)
|
||||||
|
case r.ma&bit != 0 && r.mb&bit == 0:
|
||||||
|
out = append(out, ind.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(in) > 0 {
|
||||||
|
steps = append(steps, "вошёл в: "+strings.Join(in, ", "))
|
||||||
|
}
|
||||||
|
if len(out) > 0 {
|
||||||
|
steps = append(steps, "вышел из: "+strings.Join(out, ", "))
|
||||||
|
}
|
||||||
|
if added, removed := setDiff(r.a.https.failedTargets, r.b.https.failedTargets, sortedStrings); len(added)+len(removed) > 0 {
|
||||||
|
steps = append(steps, "https: провалены цели "+signed(added, removed))
|
||||||
|
}
|
||||||
|
if added, removed := setDiff(r.a.ssh.sites, r.b.ssh.sites, c.target.sortSites); len(added)+len(removed) > 0 {
|
||||||
|
steps = append(steps, "ssh: площадки "+signed(added, removed))
|
||||||
|
}
|
||||||
|
if was, now := r.a.https.validator, r.b.https.validator; was != "" && now != "" && was != now {
|
||||||
|
steps = append(steps, "валидатор "+arrow(ShortValidator(was), ShortValidator(now)))
|
||||||
|
}
|
||||||
|
return strings.Join(steps, "; ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// setDiff is what is in now and not in was, and the reverse, each ordered by order.
|
||||||
|
func setDiff(was, now []string, order func([]string) []string) (added, removed []string) {
|
||||||
|
in := func(list []string) map[string]bool {
|
||||||
|
m := make(map[string]bool, len(list))
|
||||||
|
for _, s := range list {
|
||||||
|
m[s] = true
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
w, n := in(was), in(now)
|
||||||
|
for s := range n {
|
||||||
|
if !w[s] {
|
||||||
|
added = append(added, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for s := range w {
|
||||||
|
if !n[s] {
|
||||||
|
removed = append(removed, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return order(added), order(removed)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sortedStrings(s []string) []string {
|
||||||
|
sort.Strings(s)
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// signed writes a set difference as "+new1 +new2 −gone1".
|
||||||
|
func signed(added, removed []string) string {
|
||||||
|
parts := make([]string, 0, len(added)+len(removed))
|
||||||
|
for _, s := range added {
|
||||||
|
parts = append(parts, "+"+s)
|
||||||
|
}
|
||||||
|
for _, s := range removed {
|
||||||
|
parts = append(parts, "−"+s)
|
||||||
|
}
|
||||||
|
return strings.Join(parts, " ")
|
||||||
|
}
|
||||||
@@ -0,0 +1,335 @@
|
|||||||
|
package analytics
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"cloudipvalidator/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// set stores the four checks of an address: https to a.test and b.test, ssh
|
||||||
|
// from the two sites.
|
||||||
|
func (f *fixture) set(reg int64, validator string, a, b, ssh1, ssh2 bool) {
|
||||||
|
f.check(reg, eg, "https", "https://a.test", a, validator, "", false)
|
||||||
|
f.check(reg, eg, "https", "https://b.test", b, validator, "", false)
|
||||||
|
f.check(reg, s1, "ssh", "ip", ssh1, validator, "dial tcp: i/o timeout", false)
|
||||||
|
f.check(reg, s2, "ssh", "ip", ssh2, validator, "dial tcp: i/o timeout", false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// comparedRuns builds the older and the newer run:
|
||||||
|
//
|
||||||
|
// 10.0.0.1 pass -> pass, nothing changed
|
||||||
|
// 10.0.0.2 partial -> pass: https recovered on both targets, another validator
|
||||||
|
// 10.0.0.3 pass -> partial: ssh fails from rxmsk
|
||||||
|
// 10.0.0.20 partial -> partial: another https target fails, same indicators
|
||||||
|
// 10.0.0.10 only in the old run (fail)
|
||||||
|
// 10.0.0.14 only in the old run (pass), cancelled in the new one
|
||||||
|
// 10.0.0.11 only in the new run (partial, https fails everywhere)
|
||||||
|
// 10.0.0.12 only in the new run (pass)
|
||||||
|
// 10.0.0.13 only in the new run (pass), cancelled in the old one
|
||||||
|
func comparedRuns(t *testing.T) (base, target *Analysis) {
|
||||||
|
t.Helper()
|
||||||
|
fa, fb := &fixture{}, &fixture{}
|
||||||
|
fa.addr(1, "10.0.0.1", db.ResultPass, 4)
|
||||||
|
fa.set(1, "vkiplab-v1", true, true, true, true)
|
||||||
|
fa.addr(2, "10.0.0.2", db.ResultPartial, 4)
|
||||||
|
fa.set(2, "vkiplab-v2", false, false, true, true)
|
||||||
|
fa.addr(3, "10.0.0.3", db.ResultPass, 4)
|
||||||
|
fa.set(3, "vkiplab-v3", true, true, true, true)
|
||||||
|
fa.addr(4, "10.0.0.20", db.ResultPartial, 4)
|
||||||
|
fa.set(4, "vkiplab-v4", false, true, true, true)
|
||||||
|
fa.addr(5, "10.0.0.10", db.ResultFail, 4)
|
||||||
|
fa.set(5, "vkiplab-v5", false, false, false, false)
|
||||||
|
fa.addr(6, "10.0.0.13", db.ResultCancelled, 4)
|
||||||
|
fa.set(6, "vkiplab-v6", true, true, true, true)
|
||||||
|
fa.addr(7, "10.0.0.14", db.ResultPass, 4)
|
||||||
|
fa.set(7, "vkiplab-v7", true, true, true, true)
|
||||||
|
|
||||||
|
fb.addr(1, "10.0.0.1", db.ResultPass, 4)
|
||||||
|
fb.set(1, "vkiplab-v1", true, true, true, true)
|
||||||
|
fb.addr(2, "10.0.0.2", db.ResultPass, 4)
|
||||||
|
fb.set(2, "vkiplab-v5", true, true, true, true)
|
||||||
|
fb.addr(3, "10.0.0.3", db.ResultPartial, 4)
|
||||||
|
fb.set(3, "vkiplab-v3", true, true, false, true)
|
||||||
|
fb.addr(4, "10.0.0.20", db.ResultPartial, 4)
|
||||||
|
fb.set(4, "vkiplab-v4", true, false, true, true)
|
||||||
|
fb.addr(8, "10.0.0.11", db.ResultPartial, 4)
|
||||||
|
fb.set(8, "vkiplab-v6", false, false, true, true)
|
||||||
|
fb.addr(9, "10.0.0.12", db.ResultPass, 4)
|
||||||
|
fb.set(9, "vkiplab-v6", true, true, true, true)
|
||||||
|
fb.addr(10, "10.0.0.13", db.ResultPass, 4)
|
||||||
|
fb.set(10, "vkiplab-v6", true, true, true, true)
|
||||||
|
fb.addr(11, "10.0.0.14", db.ResultCancelled, 4)
|
||||||
|
fb.set(11, "vkiplab-v7", true, true, true, true)
|
||||||
|
return fa.compute(t, nil), fb.compute(t, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ips(l *CompareList) []string {
|
||||||
|
out := []string{}
|
||||||
|
for _, r := range l.Rows {
|
||||||
|
out = append(out, r[0])
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustList(t *testing.T, c *Comparison, group string, f CompareFilter) *CompareList {
|
||||||
|
t.Helper()
|
||||||
|
l, err := c.List(group, f)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s %+v: %v", group, f, err)
|
||||||
|
}
|
||||||
|
for _, r := range l.Rows {
|
||||||
|
if len(r) != len(l.Columns) {
|
||||||
|
t.Errorf("%s: row %v for columns %v", group, r, l.Columns)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompareGroupsAndIndicators(t *testing.T) {
|
||||||
|
base, target := comparedRuns(t)
|
||||||
|
c := Compare(base, target)
|
||||||
|
|
||||||
|
if want := (CompareGroups{New: 3, Left: 2, Common: 4, Changed: 2, Same: 2}); c.Groups != want {
|
||||||
|
t.Errorf("groups = %+v, want %+v", c.Groups, want)
|
||||||
|
}
|
||||||
|
// Every address is in exactly one of new, left, common; common = changed + same.
|
||||||
|
if c.Groups.New+c.Groups.Common != target.Report.Summary.Addresses || c.Groups.Left+c.Groups.Common != base.Report.Summary.Addresses ||
|
||||||
|
c.Groups.Changed+c.Groups.Same != c.Groups.Common {
|
||||||
|
t.Errorf("groups do not add up: %+v, runs %d and %d addresses", c.Groups, base.Report.Summary.Addresses, target.Report.Summary.Addresses)
|
||||||
|
}
|
||||||
|
if c.Cancelled != (CompareCancel{Base: 1, Target: 1}) {
|
||||||
|
t.Errorf("cancelled = %+v", c.Cancelled)
|
||||||
|
}
|
||||||
|
if c.Runs.Base.Addresses != 6 || c.Runs.Target.Addresses != 7 || c.Runs.Base.ID != 7 {
|
||||||
|
t.Errorf("runs = %+v", c.Runs)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The count of each indicator in each run is the number of its card.
|
||||||
|
sa, sb := base.Report.Summary, target.Report.Summary
|
||||||
|
cards := map[string][2]int{
|
||||||
|
ListVerdictPass: {sa.Pass, sb.Pass}, ListVerdictPartial: {sa.Partial, sb.Partial}, ListVerdictFail: {sa.Fail, sb.Fail},
|
||||||
|
ListEgressHTTPSAny: {sa.EgressHTTPSAny, sb.EgressHTTPSAny}, ListEgressHTTPSAll: {sa.EgressHTTPSAll, sb.EgressHTTPSAll},
|
||||||
|
ListIngressSSHAny: {sa.IngressSSHAny, sb.IngressSSHAny}, ListIngressSSHAll: {sa.IngressSSHAll, sb.IngressSSHAll},
|
||||||
|
}
|
||||||
|
if len(c.Indicators) != len(cards) {
|
||||||
|
t.Fatalf("%d indicators", len(c.Indicators))
|
||||||
|
}
|
||||||
|
for _, d := range c.Indicators {
|
||||||
|
if want := cards[d.Key]; d.Base != want[0] || d.Target != want[1] {
|
||||||
|
t.Errorf("%s: %d -> %d, summaries say %v", d.Key, d.Base, d.Target, want)
|
||||||
|
}
|
||||||
|
if d.Delta != d.Target-d.Base || d.Delta != d.New-d.Left+d.Entered-d.Exited {
|
||||||
|
t.Errorf("%s: delta %d, new %d left %d entered %d exited %d", d.Key, d.Delta, d.New, d.Left, d.Entered, d.Exited)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
want := map[string]IndicatorDiff{
|
||||||
|
ListVerdictPass: {Base: 3, Target: 4, Delta: 1, New: 2, Left: 1, Entered: 1, Exited: 1},
|
||||||
|
ListVerdictPartial: {Base: 2, Target: 3, Delta: 1, New: 1, Entered: 1, Exited: 1},
|
||||||
|
ListVerdictFail: {Base: 1, Target: 0, Delta: -1, Left: 1},
|
||||||
|
ListEgressHTTPSAny: {Base: 3, Target: 2, Delta: -1, New: 1, Left: 1, Exited: 1},
|
||||||
|
ListEgressHTTPSAll: {Base: 2, Target: 1, Delta: -1, New: 1, Left: 1, Exited: 1},
|
||||||
|
ListIngressSSHAny: {Base: 1, Target: 1, Left: 1, Entered: 1},
|
||||||
|
ListIngressSSHAll: {Base: 1, Target: 0, Delta: -1, Left: 1},
|
||||||
|
}
|
||||||
|
for _, d := range c.Indicators {
|
||||||
|
w := want[d.Key]
|
||||||
|
w.Key, w.Name = d.Key, d.Name
|
||||||
|
if d != w || d.Name == "" {
|
||||||
|
t.Errorf("%s = %+v, want %+v", d.Key, d, w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verdicts of the common addresses, and of the new and of the left ones.
|
||||||
|
tr := c.Transitions
|
||||||
|
if !reflect.DeepEqual(tr.Verdicts, []string{"pass", "partial", "fail"}) ||
|
||||||
|
!reflect.DeepEqual(tr.Matrix, [][]int{{1, 1, 0}, {1, 1, 0}, {0, 0, 0}}) ||
|
||||||
|
!reflect.DeepEqual(tr.New, []int{2, 1, 0}) || !reflect.DeepEqual(tr.Left, []int{1, 0, 1}) {
|
||||||
|
t.Errorf("transitions = %+v", tr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompareLists(t *testing.T) {
|
||||||
|
base, target := comparedRuns(t)
|
||||||
|
c := Compare(base, target)
|
||||||
|
|
||||||
|
// New and left: the state in the run the address is in; numeric order.
|
||||||
|
l := mustList(t, c, GroupNew, CompareFilter{})
|
||||||
|
if want := []string{"Адрес", "Подсеть", "Вердикт", "Egress", "Ingress", "Индикаторы"}; !reflect.DeepEqual(l.Columns, want) {
|
||||||
|
t.Errorf("new columns: %v", l.Columns)
|
||||||
|
}
|
||||||
|
if got := ips(l); !reflect.DeepEqual(got, []string{"10.0.0.11", "10.0.0.12", "10.0.0.13"}) {
|
||||||
|
t.Errorf("new: %v", got)
|
||||||
|
}
|
||||||
|
if want := []string{"10.0.0.11", "10.0.0.0/24", "partial", "0 из 2", "2 из 2", "partial, Egress https: есть провалы, Egress https: все провалены"}; !reflect.DeepEqual(l.Rows[0], want) {
|
||||||
|
t.Errorf("new row: %v", l.Rows[0])
|
||||||
|
}
|
||||||
|
if got := ips(mustList(t, c, GroupNew, CompareFilter{Indicator: ListVerdictPass})); !reflect.DeepEqual(got, []string{"10.0.0.12", "10.0.0.13"}) {
|
||||||
|
t.Errorf("new, pass: %v", got)
|
||||||
|
}
|
||||||
|
if got := ips(mustList(t, c, GroupNew, CompareFilter{Indicator: ListEgressHTTPSAll})); !reflect.DeepEqual(got, []string{"10.0.0.11"}) {
|
||||||
|
t.Errorf("new, https all: %v", got)
|
||||||
|
}
|
||||||
|
l = mustList(t, c, GroupLeft, CompareFilter{})
|
||||||
|
if got := ips(l); !reflect.DeepEqual(got, []string{"10.0.0.10", "10.0.0.14"}) {
|
||||||
|
t.Errorf("left: %v", got)
|
||||||
|
}
|
||||||
|
if want := "fail"; l.Rows[0][2] != want || l.Rows[0][5] != "fail, Egress https: есть провалы, Egress https: все провалены, Ingress ssh: есть провалы, Ingress ssh: все провалены" {
|
||||||
|
t.Errorf("left row: %v", l.Rows[0])
|
||||||
|
}
|
||||||
|
if got := ips(mustList(t, c, GroupLeft, CompareFilter{Indicator: ListVerdictPass})); !reflect.DeepEqual(got, []string{"10.0.0.14"}) {
|
||||||
|
t.Errorf("left, pass: %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Changed: what changed, step by step.
|
||||||
|
l = mustList(t, c, GroupChanged, CompareFilter{})
|
||||||
|
if got := ips(l); !reflect.DeepEqual(got, []string{"10.0.0.2", "10.0.0.3"}) {
|
||||||
|
t.Fatalf("changed: %v", got)
|
||||||
|
}
|
||||||
|
if l.Columns[2] != "Вердикт (A → B)" || l.Columns[5] != "Что изменилось" {
|
||||||
|
t.Errorf("changed columns: %v", l.Columns)
|
||||||
|
}
|
||||||
|
if want := []string{"10.0.0.2", "10.0.0.0/24", "partial → pass", "0 из 2 → 2 из 2", "2 из 2 → 2 из 2",
|
||||||
|
"вердикт partial → pass; вышел из: Egress https: есть провалы, Egress https: все провалены; https: провалены цели −a.test −b.test; валидатор v2 → v5"}; !reflect.DeepEqual(l.Rows[0], want) {
|
||||||
|
t.Errorf("changed row 1: %v", l.Rows[0])
|
||||||
|
}
|
||||||
|
if want := []string{"10.0.0.3", "10.0.0.0/24", "pass → partial", "2 из 2 → 2 из 2", "2 из 2 → 1 из 2",
|
||||||
|
"вердикт pass → partial; вошёл в: Ingress ssh: есть провалы; ssh: площадки +rxmsk"}; !reflect.DeepEqual(l.Rows[1], want) {
|
||||||
|
t.Errorf("changed row 2: %v", l.Rows[1])
|
||||||
|
}
|
||||||
|
// A filter by indicator keeps the addresses that are in it in either run.
|
||||||
|
if got := ips(mustList(t, c, GroupChanged, CompareFilter{Indicator: ListIngressSSHAny})); !reflect.DeepEqual(got, []string{"10.0.0.3"}) {
|
||||||
|
t.Errorf("changed, ssh any: %v", got)
|
||||||
|
}
|
||||||
|
if got := ips(mustList(t, c, GroupChanged, CompareFilter{Indicator: ListEgressHTTPSAll})); !reflect.DeepEqual(got, []string{"10.0.0.2"}) {
|
||||||
|
t.Errorf("changed, https all: %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Same: another failed target does not change the indicators; numeric order (20 after 1).
|
||||||
|
l = mustList(t, c, GroupSame, CompareFilter{})
|
||||||
|
if got := ips(l); !reflect.DeepEqual(got, []string{"10.0.0.1", "10.0.0.20"}) {
|
||||||
|
t.Fatalf("same: %v", got)
|
||||||
|
}
|
||||||
|
if want := []string{"10.0.0.20", "10.0.0.0/24", "partial → partial", "1 из 2 → 1 из 2", "2 из 2 → 2 из 2", "без изменений"}; !reflect.DeepEqual(l.Rows[1], want) {
|
||||||
|
t.Errorf("same row: %v", l.Rows[1])
|
||||||
|
}
|
||||||
|
if got := ips(mustList(t, c, GroupSame, CompareFilter{Indicator: ListEgressHTTPSAny})); !reflect.DeepEqual(got, []string{"10.0.0.20"}) {
|
||||||
|
t.Errorf("same, https any: %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Common is changed + same, in address order.
|
||||||
|
l = mustList(t, c, GroupCommon, CompareFilter{})
|
||||||
|
if got := ips(l); !reflect.DeepEqual(got, []string{"10.0.0.1", "10.0.0.2", "10.0.0.3", "10.0.0.20"}) || l.Rows[3][5] != "без изменений" {
|
||||||
|
t.Errorf("common: %v", l.Rows)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entered and exited need an indicator.
|
||||||
|
for _, x := range []struct {
|
||||||
|
group, ind string
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{GroupEntered, ListVerdictPass, []string{"10.0.0.2"}},
|
||||||
|
{GroupExited, ListVerdictPass, []string{"10.0.0.3"}},
|
||||||
|
{GroupEntered, ListVerdictPartial, []string{"10.0.0.3"}},
|
||||||
|
{GroupEntered, ListIngressSSHAny, []string{"10.0.0.3"}},
|
||||||
|
{GroupExited, ListEgressHTTPSAll, []string{"10.0.0.2"}},
|
||||||
|
{GroupExited, ListEgressHTTPSAny, []string{"10.0.0.2"}},
|
||||||
|
{GroupEntered, ListEgressHTTPSAny, []string{}},
|
||||||
|
{GroupEntered, ListVerdictFail, []string{}},
|
||||||
|
} {
|
||||||
|
got := ips(mustList(t, c, x.group, CompareFilter{Indicator: x.ind}))
|
||||||
|
if !reflect.DeepEqual(got, x.want) {
|
||||||
|
t.Errorf("%s %s: %v, want %v", x.group, x.ind, got, x.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A cell of the transition matrix: the verdict in the old and in the new run.
|
||||||
|
for _, x := range []struct {
|
||||||
|
group, from, to string
|
||||||
|
want []string
|
||||||
|
}{
|
||||||
|
{GroupCommon, "partial", "pass", []string{"10.0.0.2"}},
|
||||||
|
{GroupCommon, "pass", "partial", []string{"10.0.0.3"}},
|
||||||
|
{GroupCommon, "pass", "pass", []string{"10.0.0.1"}},
|
||||||
|
{GroupCommon, "partial", "partial", []string{"10.0.0.20"}},
|
||||||
|
{GroupSame, "partial", "partial", []string{"10.0.0.20"}},
|
||||||
|
{GroupChanged, "pass", "pass", []string{}},
|
||||||
|
{GroupCommon, "fail", "pass", []string{}},
|
||||||
|
} {
|
||||||
|
got := ips(mustList(t, c, x.group, CompareFilter{From: x.from, To: x.to}))
|
||||||
|
if !reflect.DeepEqual(got, x.want) {
|
||||||
|
t.Errorf("%s %s -> %s: %v, want %v", x.group, x.from, x.to, got, x.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The cells of the matrix and the lists add up.
|
||||||
|
n := 0
|
||||||
|
for _, from := range verdicts {
|
||||||
|
for _, to := range verdicts {
|
||||||
|
n += len(mustList(t, c, GroupCommon, CompareFilter{From: from, To: to}).Rows)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if n != c.Groups.Common {
|
||||||
|
t.Errorf("matrix cells hold %d addresses, %d are common", n, c.Groups.Common)
|
||||||
|
}
|
||||||
|
// The size of every list equals its number in the report.
|
||||||
|
for _, d := range c.Indicators {
|
||||||
|
for group, want := range map[string]int{GroupNew: d.New, GroupLeft: d.Left, GroupEntered: d.Entered, GroupExited: d.Exited} {
|
||||||
|
if got := len(mustList(t, c, group, CompareFilter{Indicator: d.Key}).Rows); got != want {
|
||||||
|
t.Errorf("%s %s: %d rows, report says %d", group, d.Key, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for group, want := range map[string]int{GroupNew: c.Groups.New, GroupLeft: c.Groups.Left, GroupCommon: c.Groups.Common, GroupChanged: c.Groups.Changed, GroupSame: c.Groups.Same} {
|
||||||
|
if got := len(mustList(t, c, group, CompareFilter{}).Rows); got != want {
|
||||||
|
t.Errorf("%s: %d rows, report says %d", group, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompareListErrors(t *testing.T) {
|
||||||
|
base, target := comparedRuns(t)
|
||||||
|
c := Compare(base, target)
|
||||||
|
for name, x := range map[string]struct {
|
||||||
|
group string
|
||||||
|
f CompareFilter
|
||||||
|
}{
|
||||||
|
"unknown group": {"nonsense", CompareFilter{}},
|
||||||
|
"unknown indicator": {GroupNew, CompareFilter{Indicator: "nonsense"}},
|
||||||
|
"entered needs one": {GroupEntered, CompareFilter{}},
|
||||||
|
"exited needs one": {GroupExited, CompareFilter{}},
|
||||||
|
"from without to": {GroupCommon, CompareFilter{From: "pass"}},
|
||||||
|
"to without from": {GroupCommon, CompareFilter{To: "pass"}},
|
||||||
|
"unknown verdict": {GroupCommon, CompareFilter{From: "pass", To: "cancelled"}},
|
||||||
|
"verdicts of new addrs": {GroupNew, CompareFilter{From: "pass", To: "pass"}},
|
||||||
|
"verdicts of left addrs": {GroupLeft, CompareFilter{From: "pass", To: "pass"}},
|
||||||
|
} {
|
||||||
|
l, err := c.List(x.group, x.f)
|
||||||
|
if _, ok := err.(ErrUnknownList); !ok || l != nil {
|
||||||
|
t.Errorf("%s: %v %v", name, l, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A run compared with itself: nothing new, nothing left, nothing changed, and
|
||||||
|
// the empty lists are empty tables, not nil.
|
||||||
|
func TestCompareWithItself(t *testing.T) {
|
||||||
|
base, _ := comparedRuns(t)
|
||||||
|
c := Compare(base, base)
|
||||||
|
if want := (CompareGroups{Common: 6, Same: 6}); c.Groups != want {
|
||||||
|
t.Errorf("groups = %+v", c.Groups)
|
||||||
|
}
|
||||||
|
for _, d := range c.Indicators {
|
||||||
|
if d.Delta != 0 || d.New != 0 || d.Left != 0 || d.Entered != 0 || d.Exited != 0 || d.Base != d.Target {
|
||||||
|
t.Errorf("%+v", d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, group := range []string{GroupNew, GroupLeft, GroupChanged} {
|
||||||
|
if l := mustList(t, c, group, CompareFilter{}); l.Rows == nil || len(l.Rows) != 0 {
|
||||||
|
t.Errorf("%s: %#v", group, l.Rows)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(c.Transitions.Matrix, [][]int{{3, 0, 0}, {0, 2, 0}, {0, 0, 1}}) {
|
||||||
|
t.Errorf("matrix = %v", c.Transitions.Matrix)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
package analytics
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/netip"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"cloudipvalidator/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// List kinds served by Analysis.List.
|
||||||
|
const (
|
||||||
|
ListEgressHTTPSAny = "egress_https_any"
|
||||||
|
ListEgressHTTPSAll = "egress_https_all"
|
||||||
|
ListIngressSSHAny = "ingress_ssh_any"
|
||||||
|
ListIngressSSHAll = "ingress_ssh_all"
|
||||||
|
ListError = "error"
|
||||||
|
// Addresses by the verdict the system gave them at aggregation.
|
||||||
|
ListVerdictPass = "verdict_" + db.ResultPass
|
||||||
|
ListVerdictPartial = "verdict_" + db.ResultPartial
|
||||||
|
ListVerdictFail = "verdict_" + db.ResultFail
|
||||||
|
)
|
||||||
|
|
||||||
|
// List is a table of addresses behind one indicator or one error class.
|
||||||
|
type List struct {
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Class string `json:"class,omitempty"`
|
||||||
|
Columns []string `json:"columns"`
|
||||||
|
Rows [][]string `json:"rows"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrUnknownList is returned for a list kind that does not exist.
|
||||||
|
type ErrUnknownList string
|
||||||
|
|
||||||
|
func (e ErrUnknownList) Error() string { return fmt.Sprintf("unknown list %q", string(e)) }
|
||||||
|
|
||||||
|
// List builds the table for a kind; class is only used with ListError.
|
||||||
|
func (an *Analysis) List(kind, class string) (*List, error) {
|
||||||
|
l := &List{Kind: kind, Class: class, Rows: [][]string{}}
|
||||||
|
switch kind {
|
||||||
|
case ListEgressHTTPSAny, ListEgressHTTPSAll:
|
||||||
|
l.Columns = []string{"Адрес", "Подсеть", "Валидатор", "https-проверок", "Проваленные цели"}
|
||||||
|
if kind == ListEgressHTTPSAny {
|
||||||
|
l.Columns[3] = "Провалено https"
|
||||||
|
}
|
||||||
|
for _, a := range an.sorted() {
|
||||||
|
if a.https.n == 0 || a.https.ok == a.https.n || (kind == ListEgressHTTPSAll && a.https.ok != 0) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
targets := append([]string(nil), a.https.failedTargets...)
|
||||||
|
sort.Strings(targets)
|
||||||
|
count := fmt.Sprint(a.https.n)
|
||||||
|
if kind == ListEgressHTTPSAny {
|
||||||
|
count = fmt.Sprintf("%d из %d", a.https.n-a.https.ok, a.https.n)
|
||||||
|
}
|
||||||
|
l.Rows = append(l.Rows, []string{a.res.IPAddress, a.subnet, ShortValidator(a.https.validator), count, strings.Join(targets, ", ")})
|
||||||
|
}
|
||||||
|
case ListIngressSSHAny, ListIngressSSHAll:
|
||||||
|
l.Columns = []string{"Адрес", "Подсеть", "Провалено ssh", "Площадки с провалом", "Ошибка"}
|
||||||
|
if kind == ListIngressSSHAll {
|
||||||
|
l.Columns = []string{"Адрес", "Подсеть", "Площадки с провалом ssh", "Ошибка"}
|
||||||
|
}
|
||||||
|
for _, a := range an.sorted() {
|
||||||
|
if a.ssh.n == 0 || a.ssh.ok == a.ssh.n || (kind == ListIngressSSHAll && a.ssh.ok != 0) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
sites := an.sortSites(a.ssh.sites)
|
||||||
|
errs := make([]string, 0, len(a.ssh.errs))
|
||||||
|
for e := range a.ssh.errs {
|
||||||
|
errs = append(errs, e)
|
||||||
|
}
|
||||||
|
sort.Strings(errs)
|
||||||
|
if kind == ListIngressSSHAny {
|
||||||
|
l.Rows = append(l.Rows, []string{a.res.IPAddress, a.subnet, fmt.Sprintf("%d из %d", len(a.ssh.sites), a.ssh.n), strings.Join(sites, ", "), strings.Join(errs, ", ")})
|
||||||
|
} else {
|
||||||
|
l.Rows = append(l.Rows, []string{a.res.IPAddress, a.subnet, strings.Join(sites, ", "), strings.Join(errs, ", ")})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case ListVerdictPass, ListVerdictPartial, ListVerdictFail:
|
||||||
|
verdict := strings.TrimPrefix(kind, "verdict_")
|
||||||
|
l.Columns = []string{"Адрес", "Подсеть", "Валидатор", "Egress", "Ingress", "Проверок в цикле"}
|
||||||
|
if kind == ListVerdictPartial {
|
||||||
|
l.Columns = append(l.Columns, "Причина")
|
||||||
|
}
|
||||||
|
for _, a := range an.sorted() {
|
||||||
|
if a.res.Verdict != verdict {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
row := []string{a.res.IPAddress, a.subnet, orDash(ShortValidator(a.https.validator)), okOf(a.egress), okOf(a.ingress), a.checksCell()}
|
||||||
|
if kind == ListVerdictPartial {
|
||||||
|
row = append(row, reasonName(a.egress.ok < a.egress.n, a.ingress.ok < a.ingress.n, a.incomplete()))
|
||||||
|
}
|
||||||
|
l.Rows = append(l.Rows, row)
|
||||||
|
}
|
||||||
|
case ListError:
|
||||||
|
if class == "" {
|
||||||
|
return nil, ErrUnknownList("error without class")
|
||||||
|
}
|
||||||
|
l.Columns = []string{"Адрес", "Подсеть", "Площадка", "Валидатор", "Вердикт адреса", "Статус проверки"}
|
||||||
|
for _, a := range an.sorted() {
|
||||||
|
fs := append([]failedIngress(nil), a.failedIngress...)
|
||||||
|
sort.SliceStable(fs, func(i, j int) bool { return an.siteIndex(fs[i].site) < an.siteIndex(fs[j].site) })
|
||||||
|
for _, f := range fs {
|
||||||
|
if f.class != class {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
status := "провал, в вердикте"
|
||||||
|
if f.late {
|
||||||
|
status = "провал, после вердикта"
|
||||||
|
}
|
||||||
|
l.Rows = append(l.Rows, []string{a.res.IPAddress, a.subnet, f.site, ShortValidator(f.validator), a.res.Verdict, status})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return nil, ErrUnknownList(kind)
|
||||||
|
}
|
||||||
|
return l, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// checksCell is "stored из expected", or just stored when expected is unknown.
|
||||||
|
func (a *addr) checksCell() string {
|
||||||
|
if a.res.ExpectedChecks < 0 {
|
||||||
|
return fmt.Sprint(a.stored)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%d из %d", a.stored, a.res.ExpectedChecks)
|
||||||
|
}
|
||||||
|
|
||||||
|
// okOf is "successful из all" of one level, "—" when it has no checks.
|
||||||
|
func okOf(t typeStat) string {
|
||||||
|
if t.n == 0 {
|
||||||
|
return "—"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%d из %d", t.ok, t.n)
|
||||||
|
}
|
||||||
|
|
||||||
|
func orDash(s string) string {
|
||||||
|
if s == "" {
|
||||||
|
return "—"
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// sorted returns the non-cancelled addresses in numeric address order.
|
||||||
|
func (an *Analysis) sorted() []*addr {
|
||||||
|
out := make([]*addr, 0, len(an.addrs))
|
||||||
|
for _, a := range an.addrs {
|
||||||
|
if a.res.Verdict != db.ResultCancelled {
|
||||||
|
out = append(out, a)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Slice(out, func(i, j int) bool { return lessIP(out[i].res.IPAddress, out[j].res.IPAddress) })
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// lessIP orders addresses numerically; text that is not an address by its text.
|
||||||
|
func lessIP(a, b string) bool {
|
||||||
|
x, errX := netip.ParseAddr(a)
|
||||||
|
y, errY := netip.ParseAddr(b)
|
||||||
|
if errX != nil || errY != nil {
|
||||||
|
return a < b
|
||||||
|
}
|
||||||
|
return x.Less(y)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (an *Analysis) siteIndex(site string) int { return siteIndexOf(an.siteNames, site) }
|
||||||
|
|
||||||
|
func (an *Analysis) sortSites(sites []string) []string {
|
||||||
|
out := append([]string(nil), sites...)
|
||||||
|
sort.SliceStable(out, func(i, j int) bool { return an.siteIndex(out[i]) < an.siteIndex(out[j]) })
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package analytics
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"cloudipvalidator/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Load reads a finished run from the database and computes its analysis.
|
||||||
|
func Load(ctx context.Context, d *db.DB, runID int64) (*Analysis, error) {
|
||||||
|
run, err := d.GetRun(ctx, runID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
results, err := d.ListRunResults(ctx, runID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
subnets, err := d.ListSubnets(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
sites, err := d.ListSites(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
names := map[int]string{}
|
||||||
|
for _, s := range sites {
|
||||||
|
names[s.Index] = s.SiteID
|
||||||
|
}
|
||||||
|
rechecked, err := d.CountRecheckedInRun(ctx, runID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return Compute(Input{
|
||||||
|
Run: *run, Results: results, Subnets: subnets, SiteNames: names, Rechecked: rechecked,
|
||||||
|
Each: func(fn func(db.RunCheck)) error { return d.EachRunCheck(ctx, runID, fn) },
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -244,6 +244,8 @@ func (c *client) ScanStatus(ctx context.Context) (scanStatusDTO, error) {
|
|||||||
type registryQuery struct {
|
type registryQuery struct {
|
||||||
Q string
|
Q string
|
||||||
LastResult string
|
LastResult string
|
||||||
|
Run int64 // only addresses with a result in this run
|
||||||
|
Subnet string // only addresses inside this CIDR
|
||||||
Limit int
|
Limit int
|
||||||
Offset int
|
Offset int
|
||||||
}
|
}
|
||||||
@@ -264,6 +266,12 @@ func (c *client) ListRegistryPage(ctx context.Context, q registryQuery) (registr
|
|||||||
if q.LastResult != "" {
|
if q.LastResult != "" {
|
||||||
v.Set("last_result", q.LastResult)
|
v.Set("last_result", q.LastResult)
|
||||||
}
|
}
|
||||||
|
if q.Run > 0 {
|
||||||
|
v.Set("run", strconv.FormatInt(q.Run, 10))
|
||||||
|
}
|
||||||
|
if q.Subnet != "" {
|
||||||
|
v.Set("subnet", q.Subnet)
|
||||||
|
}
|
||||||
var out registryPage
|
var out registryPage
|
||||||
err := c.do(ctx, http.MethodGet, "/api/v1/admin/registry?"+v.Encode(), nil, &out)
|
err := c.do(ctx, http.MethodGet, "/api/v1/admin/registry?"+v.Encode(), nil, &out)
|
||||||
return out, err
|
return out, err
|
||||||
@@ -348,10 +356,10 @@ func (c *client) GetOrchestratorSettings(ctx context.Context) (orchestratorSetti
|
|||||||
return out, err
|
return out, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *client) PutOrchestratorSettings(ctx context.Context, fipSettleSeconds, historyRetentionCycles int) (orchestratorSettingsDTO, error) {
|
func (c *client) PutOrchestratorSettings(ctx context.Context, fipSettleSeconds, historyRetentionCycles, selfCheckMaxAttempts int) (orchestratorSettingsDTO, error) {
|
||||||
var out orchestratorSettingsDTO
|
var out orchestratorSettingsDTO
|
||||||
err := c.do(ctx, http.MethodPut, "/api/v1/admin/config/orchestrator",
|
err := c.do(ctx, http.MethodPut, "/api/v1/admin/config/orchestrator",
|
||||||
orchestratorSettingsDTO{FIPSettleSeconds: fipSettleSeconds, HistoryRetentionCycles: historyRetentionCycles}, &out)
|
orchestratorSettingsDTO{FIPSettleSeconds: fipSettleSeconds, HistoryRetentionCycles: historyRetentionCycles, SelfCheckMaxAttempts: selfCheckMaxAttempts}, &out)
|
||||||
return out, err
|
return out, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -392,3 +400,151 @@ func (c *client) StopAutoCycle(ctx context.Context) (autoCycleDTO, error) {
|
|||||||
err := c.do(ctx, http.MethodPost, "/api/v1/admin/auto-cycle/stop", nil, &out)
|
err := c.do(ctx, http.MethodPost, "/api/v1/admin/auto-cycle/stop", nil, &out)
|
||||||
return out, err
|
return out, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// analyticsRun is one entry of GET /admin/analytics/runs (the run selector).
|
||||||
|
type analyticsRun struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
State string `json:"state"`
|
||||||
|
StartedAt time.Time `json:"started_at"`
|
||||||
|
FinalizedAt *time.Time `json:"finalized_at"`
|
||||||
|
Addresses int `json:"addresses"`
|
||||||
|
Pass int `json:"pass"`
|
||||||
|
Partial int `json:"partial"`
|
||||||
|
Fail int `json:"fail"`
|
||||||
|
Cancelled int `json:"cancelled"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
Pending int `json:"pending"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *client) ListAnalyticsRuns(ctx context.Context) ([]analyticsRun, error) {
|
||||||
|
var out []analyticsRun
|
||||||
|
err := c.do(ctx, http.MethodGet, "/api/v1/admin/analytics/runs", nil, &out)
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAnalyticsReport returns the analytics of one finished run as the raw
|
||||||
|
// JSON control-api computed; the page's script reads it as it is.
|
||||||
|
func (c *client) GetAnalyticsReport(ctx context.Context, runID int64) (json.RawMessage, error) {
|
||||||
|
var out json.RawMessage
|
||||||
|
err := c.do(ctx, http.MethodGet, "/api/v1/admin/analytics/runs/"+strconv.FormatInt(runID, 10), nil, &out)
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func analyticsListPath(runID int64, kind, class string, csv bool) string {
|
||||||
|
v := url.Values{}
|
||||||
|
if class != "" {
|
||||||
|
v.Set("class", class)
|
||||||
|
}
|
||||||
|
if csv {
|
||||||
|
v.Set("format", "csv")
|
||||||
|
}
|
||||||
|
p := "/api/v1/admin/analytics/runs/" + strconv.FormatInt(runID, 10) + "/lists/" + url.PathEscape(kind)
|
||||||
|
if len(v) > 0 {
|
||||||
|
p += "?" + v.Encode()
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAnalyticsList returns one address table (JSON) of a run.
|
||||||
|
func (c *client) GetAnalyticsList(ctx context.Context, runID int64, kind, class string) (json.RawMessage, error) {
|
||||||
|
var out json.RawMessage
|
||||||
|
err := c.do(ctx, http.MethodGet, analyticsListPath(runID, kind, class, false), nil, &out)
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAnalyticsListCSV returns the CSV file of one address table, with the
|
||||||
|
// file name control-api proposed.
|
||||||
|
func (c *client) GetAnalyticsListCSV(ctx context.Context, runID int64, kind, class string) ([]byte, string, error) {
|
||||||
|
return c.getCSV(ctx, analyticsListPath(runID, kind, class, true))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *client) getCSV(ctx context.Context, path string) ([]byte, string, error) {
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+path, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", fmt.Errorf("build request: %w", err)
|
||||||
|
}
|
||||||
|
if c.token != "" {
|
||||||
|
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||||
|
}
|
||||||
|
resp, err := c.http.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", &apiErr{Status: 0, Message: err.Error()}
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
if resp.StatusCode >= 300 {
|
||||||
|
msg := string(body)
|
||||||
|
var er errorResponse
|
||||||
|
if json.Unmarshal(body, &er) == nil && er.Error != "" {
|
||||||
|
msg = er.Error
|
||||||
|
}
|
||||||
|
return nil, "", &apiErr{Status: resp.StatusCode, Message: msg}
|
||||||
|
}
|
||||||
|
return body, resp.Header.Get("Content-Disposition"), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// compareFilter narrows one list of the comparison of two runs.
|
||||||
|
type compareFilter struct{ Indicator, From, To string }
|
||||||
|
|
||||||
|
func analyticsCompareQuery(base, target int64) url.Values {
|
||||||
|
return url.Values{"base": {strconv.FormatInt(base, 10)}, "target": {strconv.FormatInt(target, 10)}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func analyticsCompareListPath(base, target int64, group string, f compareFilter, csv bool) string {
|
||||||
|
v := analyticsCompareQuery(base, target)
|
||||||
|
if f.Indicator != "" {
|
||||||
|
v.Set("indicator", f.Indicator)
|
||||||
|
}
|
||||||
|
if f.From != "" || f.To != "" {
|
||||||
|
v.Set("from", f.From)
|
||||||
|
v.Set("to", f.To)
|
||||||
|
}
|
||||||
|
if csv {
|
||||||
|
v.Set("format", "csv")
|
||||||
|
}
|
||||||
|
return "/api/v1/admin/analytics/compare/lists/" + url.PathEscape(group) + "?" + v.Encode()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAnalyticsCompare returns the comparison of two finished runs (base is the
|
||||||
|
// older one) as the raw JSON control-api computed.
|
||||||
|
func (c *client) GetAnalyticsCompare(ctx context.Context, base, target int64) (json.RawMessage, error) {
|
||||||
|
var out json.RawMessage
|
||||||
|
err := c.do(ctx, http.MethodGet, "/api/v1/admin/analytics/compare?"+analyticsCompareQuery(base, target).Encode(), nil, &out)
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAnalyticsCompareList returns one address table (JSON) of the comparison.
|
||||||
|
func (c *client) GetAnalyticsCompareList(ctx context.Context, base, target int64, group string, f compareFilter) (json.RawMessage, error) {
|
||||||
|
var out json.RawMessage
|
||||||
|
err := c.do(ctx, http.MethodGet, analyticsCompareListPath(base, target, group, f, false), nil, &out)
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetAnalyticsCompareListCSV returns the CSV file of one comparison table,
|
||||||
|
// with the file name control-api proposed.
|
||||||
|
func (c *client) GetAnalyticsCompareListCSV(ctx context.Context, base, target int64, group string, f compareFilter) ([]byte, string, error) {
|
||||||
|
return c.getCSV(ctx, analyticsCompareListPath(base, target, group, f, true))
|
||||||
|
}
|
||||||
|
|
||||||
|
// subnetEntry is one line of the subnet list (GET/PUT /admin/config/subnets).
|
||||||
|
type subnetEntry struct {
|
||||||
|
CIDR string `json:"cidr"`
|
||||||
|
Label string `json:"label,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type subnetList struct {
|
||||||
|
Subnets []subnetEntry `json:"subnets"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *client) GetSubnets(ctx context.Context) (subnetList, error) {
|
||||||
|
var out subnetList
|
||||||
|
err := c.do(ctx, http.MethodGet, "/api/v1/admin/config/subnets", nil, &out)
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *client) PutSubnets(ctx context.Context, in subnetList) (subnetList, error) {
|
||||||
|
var out subnetList
|
||||||
|
err := c.do(ctx, http.MethodPut, "/api/v1/admin/config/subnets", in, &out)
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
@@ -37,6 +37,23 @@ type fakeControlAPI struct {
|
|||||||
inboundICMP bool
|
inboundICMP bool
|
||||||
|
|
||||||
historyRetentionCycles int
|
historyRetentionCycles int
|
||||||
|
selfCheckMaxAttempts int
|
||||||
|
// selfCheckFailedOn is served as self_check_failed_on of the address
|
||||||
|
// detail and registry history endpoints.
|
||||||
|
selfCheckFailedOn []string
|
||||||
|
|
||||||
|
// Analytics: the run selector, the report JSON per run, the lists per
|
||||||
|
// "run/kind[/class]" and the subnet list of /settings.
|
||||||
|
runs []analyticsRun
|
||||||
|
reports map[int64]string
|
||||||
|
lists map[string]string
|
||||||
|
// compares is the comparison JSON per "base-target", compareLists the lists
|
||||||
|
// per "base-target/group[/indicator]".
|
||||||
|
compares map[string]string
|
||||||
|
compareLists map[string]string
|
||||||
|
|
||||||
|
subnets subnetList
|
||||||
|
analyticsReqs []string
|
||||||
// scanFreeAddresses is what POST /ips/scan "discovers" — tests set it
|
// scanFreeAddresses is what POST /ips/scan "discovers" — tests set it
|
||||||
// directly rather than this fake reimplementing OpenStack floating-IP
|
// directly rather than this fake reimplementing OpenStack floating-IP
|
||||||
// filtering (already covered by internal/orchestrator's own tests).
|
// filtering (already covered by internal/orchestrator's own tests).
|
||||||
@@ -86,6 +103,8 @@ func newFakeControlAPI(t *testing.T) (*fakeControlAPI, string) {
|
|||||||
registry: map[string]registryItem{},
|
registry: map[string]registryItem{},
|
||||||
registryChecks: map[string][]check{},
|
registryChecks: map[string][]check{},
|
||||||
autoCycle: autoCycleDTO{IntervalSeconds: 3600, Phase: "idle"},
|
autoCycle: autoCycleDTO{IntervalSeconds: 3600, Phase: "idle"},
|
||||||
|
|
||||||
|
selfCheckMaxAttempts: 5,
|
||||||
}
|
}
|
||||||
ts := httptest.NewServer(f.handler())
|
ts := httptest.NewServer(f.handler())
|
||||||
t.Cleanup(ts.Close)
|
t.Cleanup(ts.Close)
|
||||||
@@ -183,7 +202,7 @@ func (f *fakeControlAPI) handler() http.Handler {
|
|||||||
addr := r.PathValue("ip")
|
addr := r.PathValue("ip")
|
||||||
for _, ip := range f.ips {
|
for _, ip := range f.ips {
|
||||||
if ip.IPAddress == addr {
|
if ip.IPAddress == addr {
|
||||||
writeJSON(w, http.StatusOK, ipDetailResponse{IP: ip, Checks: []check{}, Events: []event{}})
|
writeJSON(w, http.StatusOK, ipDetailResponse{IP: ip, Checks: []check{}, Events: []event{}, SelfCheckFailedOn: f.selfCheckFailedOn})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -302,6 +321,7 @@ func (f *fakeControlAPI) handler() http.Handler {
|
|||||||
writeJSON(w, http.StatusOK, orchestratorSettingsDTO{
|
writeJSON(w, http.StatusOK, orchestratorSettingsDTO{
|
||||||
FIPSettleSeconds: f.fipSettleSeconds,
|
FIPSettleSeconds: f.fipSettleSeconds,
|
||||||
HistoryRetentionCycles: f.historyRetentionCycles,
|
HistoryRetentionCycles: f.historyRetentionCycles,
|
||||||
|
SelfCheckMaxAttempts: f.selfCheckMaxAttempts,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
mux.HandleFunc("PUT /api/v1/admin/config/orchestrator", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("PUT /api/v1/admin/config/orchestrator", func(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -317,11 +337,17 @@ func (f *fakeControlAPI) handler() http.Handler {
|
|||||||
writeAPIErr(w, http.StatusBadRequest, "history_retention_cycles must be >= 0")
|
writeAPIErr(w, http.StatusBadRequest, "history_retention_cycles must be >= 0")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if req.SelfCheckMaxAttempts < 1 || req.SelfCheckMaxAttempts > 50 {
|
||||||
|
writeAPIErr(w, http.StatusBadRequest, "self_check_max_attempts must be in 1..50")
|
||||||
|
return
|
||||||
|
}
|
||||||
f.fipSettleSeconds = req.FIPSettleSeconds
|
f.fipSettleSeconds = req.FIPSettleSeconds
|
||||||
f.historyRetentionCycles = req.HistoryRetentionCycles
|
f.historyRetentionCycles = req.HistoryRetentionCycles
|
||||||
|
f.selfCheckMaxAttempts = req.SelfCheckMaxAttempts
|
||||||
writeJSON(w, http.StatusOK, orchestratorSettingsDTO{
|
writeJSON(w, http.StatusOK, orchestratorSettingsDTO{
|
||||||
FIPSettleSeconds: f.fipSettleSeconds,
|
FIPSettleSeconds: f.fipSettleSeconds,
|
||||||
HistoryRetentionCycles: f.historyRetentionCycles,
|
HistoryRetentionCycles: f.historyRetentionCycles,
|
||||||
|
SelfCheckMaxAttempts: f.selfCheckMaxAttempts,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -466,9 +492,114 @@ func (f *fakeControlAPI) handler() http.Handler {
|
|||||||
writeAPIErr(w, http.StatusNotFound, "unknown ip: "+addr)
|
writeAPIErr(w, http.StatusNotFound, "unknown ip: "+addr)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, registryHistoryResponse{Registry: item, Checks: f.registryChecks[addr]})
|
writeJSON(w, http.StatusOK, registryHistoryResponse{Registry: item, Checks: f.registryChecks[addr], SelfCheckFailedOn: f.selfCheckFailedOn})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
mux.HandleFunc("GET /api/v1/admin/config/subnets", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
out := f.subnets
|
||||||
|
if out.Subnets == nil {
|
||||||
|
out.Subnets = []subnetEntry{}
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, out)
|
||||||
|
})
|
||||||
|
mux.HandleFunc("PUT /api/v1/admin/config/subnets", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var in subnetList
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||||
|
writeAPIErr(w, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, s := range in.Subnets {
|
||||||
|
if !strings.Contains(s.CIDR, "/") {
|
||||||
|
writeAPIErr(w, http.StatusBadRequest, "subnet "+s.CIDR+": not a CIDR")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
f.subnets = in
|
||||||
|
writeJSON(w, http.StatusOK, in)
|
||||||
|
})
|
||||||
|
mux.HandleFunc("GET /api/v1/admin/analytics/runs", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
out := f.runs
|
||||||
|
if out == nil {
|
||||||
|
out = []analyticsRun{}
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, out)
|
||||||
|
})
|
||||||
|
mux.HandleFunc("GET /api/v1/admin/analytics/runs/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
id, _ := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||||
|
f.analyticsReqs = append(f.analyticsReqs, r.URL.RequestURI())
|
||||||
|
rep, ok := f.reports[id]
|
||||||
|
if !ok {
|
||||||
|
writeAPIErr(w, http.StatusNotFound, "run not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _ = w.Write([]byte(rep))
|
||||||
|
})
|
||||||
|
mux.HandleFunc("GET /api/v1/admin/analytics/runs/{id}/lists/{kind}", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
f.analyticsReqs = append(f.analyticsReqs, r.URL.RequestURI())
|
||||||
|
key := r.PathValue("id") + "/" + r.PathValue("kind")
|
||||||
|
if c := r.URL.Query().Get("class"); c != "" {
|
||||||
|
key += "/" + c
|
||||||
|
}
|
||||||
|
l, ok := f.lists[key]
|
||||||
|
if !ok {
|
||||||
|
writeAPIErr(w, http.StatusNotFound, "unknown list")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.URL.Query().Get("format") == "csv" {
|
||||||
|
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||||
|
w.Header().Set("Content-Disposition", `attachment; filename="`+r.PathValue("kind")+`_run`+r.PathValue("id")+`.csv"`)
|
||||||
|
_, _ = w.Write([]byte("Адрес\r\n1.2.3.4\r\n"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _ = w.Write([]byte(l))
|
||||||
|
})
|
||||||
|
mux.HandleFunc("GET /api/v1/admin/analytics/compare", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
f.analyticsReqs = append(f.analyticsReqs, r.URL.RequestURI())
|
||||||
|
rep, ok := f.compares[r.URL.Query().Get("base")+"-"+r.URL.Query().Get("target")]
|
||||||
|
if !ok {
|
||||||
|
writeAPIErr(w, http.StatusNotFound, "run not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _ = w.Write([]byte(rep))
|
||||||
|
})
|
||||||
|
mux.HandleFunc("GET /api/v1/admin/analytics/compare/lists/{group}", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
f.analyticsReqs = append(f.analyticsReqs, r.URL.RequestURI())
|
||||||
|
q := r.URL.Query()
|
||||||
|
key := q.Get("base") + "-" + q.Get("target") + "/" + r.PathValue("group")
|
||||||
|
if ind := q.Get("indicator"); ind != "" {
|
||||||
|
key += "/" + ind
|
||||||
|
}
|
||||||
|
l, ok := f.compareLists[key]
|
||||||
|
if !ok {
|
||||||
|
writeAPIErr(w, http.StatusNotFound, "unknown list")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if q.Get("format") == "csv" {
|
||||||
|
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||||
|
w.Header().Set("Content-Disposition", `attachment; filename="compare_`+r.PathValue("group")+`_run`+q.Get("base")+"-"+q.Get("target")+`.csv"`)
|
||||||
|
_, _ = w.Write([]byte("Адрес\r\n1.2.3.4\r\n"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _ = w.Write([]byte(l))
|
||||||
|
})
|
||||||
mux.HandleFunc("GET /api/v1/admin/config/inbound-checks", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("GET /api/v1/admin/config/inbound-checks", func(w http.ResponseWriter, r *http.Request) {
|
||||||
f.mu.Lock()
|
f.mu.Lock()
|
||||||
defer f.mu.Unlock()
|
defer f.mu.Unlock()
|
||||||
|
|||||||
@@ -95,6 +95,9 @@ type ipDetailResponse struct {
|
|||||||
IP ipQueueItem `json:"ip"`
|
IP ipQueueItem `json:"ip"`
|
||||||
Checks []check `json:"checks"`
|
Checks []check `json:"checks"`
|
||||||
Events []event `json:"events"`
|
Events []event `json:"events"`
|
||||||
|
// SelfCheckFailedOn lists the validators whose self-check of this address
|
||||||
|
// failed (in its current run).
|
||||||
|
SelfCheckFailedOn []string `json:"self_check_failed_on"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type validator struct {
|
type validator struct {
|
||||||
@@ -264,11 +267,53 @@ type registryItem struct {
|
|||||||
LastCheckedAt *time.Time `json:"last_checked_at"`
|
LastCheckedAt *time.Time `json:"last_checked_at"`
|
||||||
InQueue bool `json:"in_queue"`
|
InQueue bool `json:"in_queue"`
|
||||||
CurrentState string `json:"current_state"`
|
CurrentState string `json:"current_state"`
|
||||||
|
// LastCycleID is the cycle counted by Egress and Ingress (0 = no checks).
|
||||||
|
LastCycleID int `json:"last_cycle_id"`
|
||||||
|
Egress levelResult `json:"egress"`
|
||||||
|
Ingress levelResult `json:"ingress"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// levelResult is "ok of total" recorded checks of one level (egress or
|
||||||
|
// ingress) in the last cycle, split by check family — see httpapi's
|
||||||
|
// levelResultDTO.
|
||||||
|
type levelResult struct {
|
||||||
|
Total int `json:"total"`
|
||||||
|
OK int `json:"ok"`
|
||||||
|
ByType []typeStat `json:"by_type"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type typeStat struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
OK int `json:"ok"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// statClass picks the colour of an "ok of total" figure: all checks passed,
|
||||||
|
// none passed, some passed, or nothing recorded.
|
||||||
|
func statClass(ok, total int) string {
|
||||||
|
switch {
|
||||||
|
case total == 0:
|
||||||
|
return "none"
|
||||||
|
case ok == total:
|
||||||
|
return "ok"
|
||||||
|
case ok == 0:
|
||||||
|
return "fail"
|
||||||
|
}
|
||||||
|
return "part"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Class is the CSS modifier for the level's total.
|
||||||
|
func (l levelResult) Class() string { return statClass(l.OK, l.Total) }
|
||||||
|
|
||||||
|
// Class is the CSS modifier for one check family.
|
||||||
|
func (t typeStat) Class() string { return statClass(t.OK, t.Total) }
|
||||||
|
|
||||||
type registryHistoryResponse struct {
|
type registryHistoryResponse struct {
|
||||||
Registry registryItem `json:"registry"`
|
Registry registryItem `json:"registry"`
|
||||||
Checks []check `json:"checks"`
|
Checks []check `json:"checks"`
|
||||||
|
// SelfCheckFailedOn lists the validators whose self-check of this address
|
||||||
|
// failed, over every run.
|
||||||
|
SelfCheckFailedOn []string `json:"self_check_failed_on"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type validatorDTO struct {
|
type validatorDTO struct {
|
||||||
@@ -305,6 +350,7 @@ type errorResponse struct {
|
|||||||
type orchestratorSettingsDTO struct {
|
type orchestratorSettingsDTO struct {
|
||||||
FIPSettleSeconds int `json:"fip_settle_seconds"`
|
FIPSettleSeconds int `json:"fip_settle_seconds"`
|
||||||
HistoryRetentionCycles int `json:"history_retention_cycles"`
|
HistoryRetentionCycles int `json:"history_retention_cycles"`
|
||||||
|
SelfCheckMaxAttempts int `json:"self_check_max_attempts"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type inboundChecksDTO struct {
|
type inboundChecksDTO struct {
|
||||||
|
|||||||
@@ -0,0 +1,459 @@
|
|||||||
|
package dashboard
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"html/template"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// runOption is one entry of the run selector.
|
||||||
|
type runOption struct {
|
||||||
|
ID int64
|
||||||
|
Label string
|
||||||
|
Disabled bool
|
||||||
|
Selected bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type analyticsPageData struct {
|
||||||
|
PageData
|
||||||
|
Runs []runOption
|
||||||
|
RunID int64
|
||||||
|
PrevURL string // older run, "" when there is none
|
||||||
|
NextURL string // newer run
|
||||||
|
// DataJSON is the page's data for analytics.js (run meta, labels, report),
|
||||||
|
// HTML-safe JSON.
|
||||||
|
DataJSON template.JS
|
||||||
|
HasRun bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// analyticsMeta is what analytics.js needs besides the report.
|
||||||
|
type analyticsMeta struct {
|
||||||
|
RunID int64 `json:"run_id"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Start string `json:"start"`
|
||||||
|
End string `json:"end"`
|
||||||
|
Duration string `json:"duration"`
|
||||||
|
Rechecked int `json:"rechecked"`
|
||||||
|
ListURL string `json:"list_url"`
|
||||||
|
CSVURL string `json:"csv_url"`
|
||||||
|
Registry string `json:"registry_url"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleAnalyticsPage renders the analytics of one finished run: ?run=ID, by
|
||||||
|
// default the newest finished run. The run selector lists every run, the open
|
||||||
|
// one disabled; nothing of any other run is on the page.
|
||||||
|
func (s *Server) handleAnalyticsPage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
data := analyticsPageData{}
|
||||||
|
data.ActiveNav = "analytics"
|
||||||
|
|
||||||
|
runs, err := s.CA.ListAnalyticsRuns(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
data.Banner = bannerFor(err)
|
||||||
|
s.renderPage(w, r, "analytics_page", data)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
want, _ := strconv.ParseInt(r.URL.Query().Get("run"), 10, 64)
|
||||||
|
var chosen *analyticsRun
|
||||||
|
for i := range runs { // newest first
|
||||||
|
if runs[i].State != "finalized" || runs[i].Addresses == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if want == 0 || runs[i].ID == want {
|
||||||
|
chosen = &runs[i]
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var finished []analyticsRun // newest first
|
||||||
|
for _, x := range runs {
|
||||||
|
if x.State == "finalized" && x.Addresses > 0 {
|
||||||
|
finished = append(finished, x)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, x := range runs {
|
||||||
|
if x.State == "finalized" && x.Addresses == 0 {
|
||||||
|
continue // nothing to show for it, hide
|
||||||
|
}
|
||||||
|
opt := runOption{ID: x.ID, Label: runLabel(x), Disabled: x.State != "finalized"}
|
||||||
|
if chosen != nil && x.ID == chosen.ID {
|
||||||
|
opt.Selected = true
|
||||||
|
}
|
||||||
|
data.Runs = append(data.Runs, opt)
|
||||||
|
}
|
||||||
|
if chosen == nil {
|
||||||
|
if want != 0 {
|
||||||
|
data.Banner = bannerData{Message: fmt.Sprintf("Запуск %d не найден или ещё не завершён.", want), Client: true}
|
||||||
|
}
|
||||||
|
s.renderPage(w, r, "analytics_page", data)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data.RunID = chosen.ID
|
||||||
|
for i, x := range finished {
|
||||||
|
if x.ID == chosen.ID {
|
||||||
|
if i+1 < len(finished) {
|
||||||
|
data.PrevURL = "/analytics?run=" + strconv.FormatInt(finished[i+1].ID, 10)
|
||||||
|
}
|
||||||
|
if i > 0 {
|
||||||
|
data.NextURL = "/analytics?run=" + strconv.FormatInt(finished[i-1].ID, 10)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
report, err := s.CA.GetAnalyticsReport(r.Context(), chosen.ID)
|
||||||
|
if err != nil {
|
||||||
|
data.Banner = bannerFor(err)
|
||||||
|
s.renderPage(w, r, "analytics_page", data)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var info struct {
|
||||||
|
Run struct {
|
||||||
|
Rechecked int `json:"rechecked"`
|
||||||
|
} `json:"run"`
|
||||||
|
}
|
||||||
|
_ = json.Unmarshal(report, &info)
|
||||||
|
id := strconv.FormatInt(chosen.ID, 10)
|
||||||
|
meta := analyticsMeta{
|
||||||
|
RunID: chosen.ID, Kind: kindLabel(chosen.Kind),
|
||||||
|
Start: fmtShort(chosen.StartedAt), Duration: "—", Rechecked: info.Run.Rechecked,
|
||||||
|
ListURL: "/analytics/lists/",
|
||||||
|
CSVURL: "/analytics/csv/",
|
||||||
|
Registry: "/registry?run=" + id,
|
||||||
|
}
|
||||||
|
if chosen.FinalizedAt != nil {
|
||||||
|
meta.End = fmtShort(*chosen.FinalizedAt)
|
||||||
|
meta.Duration = fmtRunDuration(chosen.FinalizedAt.Sub(chosen.StartedAt))
|
||||||
|
}
|
||||||
|
payload, err := json.Marshal(struct {
|
||||||
|
Meta analyticsMeta `json:"meta"`
|
||||||
|
Report json.RawMessage `json:"report"`
|
||||||
|
}{meta, report})
|
||||||
|
if err != nil {
|
||||||
|
data.Banner = bannerFor(err)
|
||||||
|
s.renderPage(w, r, "analytics_page", data)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data.HasRun = true
|
||||||
|
data.DataJSON = template.JS(payload)
|
||||||
|
s.renderPage(w, r, "analytics_page", data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseRunParam(r *http.Request) (int64, bool) {
|
||||||
|
id, err := strconv.ParseInt(r.URL.Query().Get("run"), 10, 64)
|
||||||
|
return id, err == nil && id > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleAnalyticsList proxies one address table of a run as JSON.
|
||||||
|
func (s *Server) handleAnalyticsList(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, ok := parseRunParam(r)
|
||||||
|
if !ok {
|
||||||
|
http.Error(w, "run is required", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out, err := s.CA.GetAnalyticsList(r.Context(), id, r.PathValue("kind"), r.URL.Query().Get("class"))
|
||||||
|
if err != nil {
|
||||||
|
writeProxyError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
_, _ = w.Write(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleAnalyticsCSV proxies the CSV file of one address table as a download.
|
||||||
|
func (s *Server) handleAnalyticsCSV(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, ok := parseRunParam(r)
|
||||||
|
if !ok {
|
||||||
|
http.Error(w, "run is required", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
body, disposition, err := s.CA.GetAnalyticsListCSV(r.Context(), id, r.PathValue("kind"), r.URL.Query().Get("class"))
|
||||||
|
if err != nil {
|
||||||
|
writeProxyError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||||
|
if disposition != "" {
|
||||||
|
w.Header().Set("Content-Disposition", disposition)
|
||||||
|
}
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
_, _ = w.Write(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
// analyticsComparePageData is the page that compares two finished runs.
|
||||||
|
type analyticsComparePageData struct {
|
||||||
|
PageData
|
||||||
|
RunsA, RunsB []runOption // finished runs; the chosen one of each is selected
|
||||||
|
HasReport bool
|
||||||
|
// DataJSON is the page's data for analytics-compare.js (run meta, the
|
||||||
|
// comparison), HTML-safe JSON.
|
||||||
|
DataJSON template.JS
|
||||||
|
}
|
||||||
|
|
||||||
|
// compareRunMeta is how analytics-compare.js names one of the two runs.
|
||||||
|
type compareRunMeta struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Start string `json:"start"`
|
||||||
|
End string `json:"end"`
|
||||||
|
Duration string `json:"duration"`
|
||||||
|
Label string `json:"label"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type compareMeta struct {
|
||||||
|
Base compareRunMeta `json:"base"`
|
||||||
|
Target compareRunMeta `json:"target"`
|
||||||
|
ListURL string `json:"list_url"`
|
||||||
|
CSVURL string `json:"csv_url"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func newCompareRunMeta(x analyticsRun) compareRunMeta {
|
||||||
|
m := compareRunMeta{ID: x.ID, Kind: kindLabel(x.Kind), Start: fmtShort(x.StartedAt), End: "—", Duration: "—", Label: runLabel(x)}
|
||||||
|
if x.FinalizedAt != nil {
|
||||||
|
m.End = fmtShort(*x.FinalizedAt)
|
||||||
|
m.Duration = fmtRunDuration(x.FinalizedAt.Sub(x.StartedAt))
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
// runIDParam reads a run id from a query value: set is false for an empty
|
||||||
|
// value, ok for a positive number.
|
||||||
|
func runIDParam(v string) (id int64, set, ok bool) {
|
||||||
|
if v == "" {
|
||||||
|
return 0, false, true
|
||||||
|
}
|
||||||
|
id, err := strconv.ParseInt(v, 10, 64)
|
||||||
|
return id, true, err == nil && id > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleAnalyticsComparePage compares two finished runs: ?base=A (older) and
|
||||||
|
// ?target=B (newer). By default B is the newest finished run and A the one
|
||||||
|
// before it; with only target the run before it is the base, with only base
|
||||||
|
// the newest other run is the target. The state of the page is its address.
|
||||||
|
func (s *Server) handleAnalyticsComparePage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
data := analyticsComparePageData{}
|
||||||
|
data.ActiveNav = "analytics"
|
||||||
|
|
||||||
|
runs, err := s.CA.ListAnalyticsRuns(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
data.Banner = bannerFor(err)
|
||||||
|
s.renderPage(w, r, "analytics_compare_page", data)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var finished []analyticsRun // newest first
|
||||||
|
for _, x := range runs {
|
||||||
|
if x.State == "finalized" && x.Addresses > 0 {
|
||||||
|
finished = append(finished, x)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(finished) < 2 {
|
||||||
|
data.Banner = bannerData{Message: "Для сравнения нужно минимум два завершённых запуска с адресами.", Client: true}
|
||||||
|
s.renderPage(w, r, "analytics_compare_page", data)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
find := func(id int64) *analyticsRun {
|
||||||
|
for i := range finished {
|
||||||
|
if finished[i].ID == id {
|
||||||
|
return &finished[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
bid, bset, bok := runIDParam(r.URL.Query().Get("base"))
|
||||||
|
tid, tset, tok := runIDParam(r.URL.Query().Get("target"))
|
||||||
|
// The default pair is the newest run as B and the one before it as A.
|
||||||
|
a, b := &finished[1], &finished[0]
|
||||||
|
warn := ""
|
||||||
|
switch {
|
||||||
|
case !bok || !tok:
|
||||||
|
warn = "Неверный номер запуска."
|
||||||
|
case bset && tset && bid == tid:
|
||||||
|
warn = "Выберите два разных запуска."
|
||||||
|
case bset || tset:
|
||||||
|
a, b = nil, nil
|
||||||
|
if bset {
|
||||||
|
if a = find(bid); a == nil {
|
||||||
|
warn = fmt.Sprintf("Запуск %d не найден или ещё не завершён.", bid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if tset {
|
||||||
|
if b = find(tid); b == nil {
|
||||||
|
warn = fmt.Sprintf("Запуск %d не найден или ещё не завершён.", tid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if warn == "" {
|
||||||
|
for i := range finished { // only one end is given: the other is next to it
|
||||||
|
switch {
|
||||||
|
case a == nil && i > 0 && finished[i-1].ID == b.ID:
|
||||||
|
a = &finished[i]
|
||||||
|
case b == nil && finished[i].ID != a.ID:
|
||||||
|
b = &finished[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if a == nil || b == nil {
|
||||||
|
warn = "Для этого запуска нет второго запуска для сравнения."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
selA, selB := finished[1].ID, finished[0].ID
|
||||||
|
if a != nil {
|
||||||
|
selA = a.ID
|
||||||
|
}
|
||||||
|
if b != nil {
|
||||||
|
selB = b.ID
|
||||||
|
}
|
||||||
|
for _, x := range finished {
|
||||||
|
opt := runOption{ID: x.ID, Label: runLabel(x)}
|
||||||
|
optA, optB := opt, opt
|
||||||
|
optA.Selected, optB.Selected = x.ID == selA, x.ID == selB
|
||||||
|
data.RunsA = append(data.RunsA, optA)
|
||||||
|
data.RunsB = append(data.RunsB, optB)
|
||||||
|
}
|
||||||
|
if warn != "" {
|
||||||
|
data.Banner = bannerData{Message: warn, Client: true}
|
||||||
|
s.renderPage(w, r, "analytics_compare_page", data)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
report, err := s.CA.GetAnalyticsCompare(r.Context(), a.ID, b.ID)
|
||||||
|
if err != nil {
|
||||||
|
data.Banner = bannerFor(err)
|
||||||
|
s.renderPage(w, r, "analytics_compare_page", data)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
payload, err := json.Marshal(struct {
|
||||||
|
Meta compareMeta `json:"meta"`
|
||||||
|
Report json.RawMessage `json:"report"`
|
||||||
|
}{compareMeta{Base: newCompareRunMeta(*a), Target: newCompareRunMeta(*b),
|
||||||
|
ListURL: "/analytics/compare/lists/", CSVURL: "/analytics/compare/csv/"}, report})
|
||||||
|
if err != nil {
|
||||||
|
data.Banner = bannerFor(err)
|
||||||
|
s.renderPage(w, r, "analytics_compare_page", data)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data.HasReport = true
|
||||||
|
data.DataJSON = template.JS(payload)
|
||||||
|
s.renderPage(w, r, "analytics_compare_page", data)
|
||||||
|
}
|
||||||
|
|
||||||
|
// compareParams reads the two run ids and the list filter of a proxied
|
||||||
|
// comparison list; it writes the 400 itself when an id is missing.
|
||||||
|
func compareParams(w http.ResponseWriter, r *http.Request) (base, target int64, f compareFilter, ok bool) {
|
||||||
|
q := r.URL.Query()
|
||||||
|
base, _ = strconv.ParseInt(q.Get("base"), 10, 64)
|
||||||
|
target, _ = strconv.ParseInt(q.Get("target"), 10, 64)
|
||||||
|
if base <= 0 || target <= 0 {
|
||||||
|
http.Error(w, "base and target are required", http.StatusBadRequest)
|
||||||
|
return 0, 0, f, false
|
||||||
|
}
|
||||||
|
return base, target, compareFilter{Indicator: q.Get("indicator"), From: q.Get("from"), To: q.Get("to")}, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleAnalyticsCompareList proxies one address table of the comparison as JSON.
|
||||||
|
func (s *Server) handleAnalyticsCompareList(w http.ResponseWriter, r *http.Request) {
|
||||||
|
base, target, f, ok := compareParams(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out, err := s.CA.GetAnalyticsCompareList(r.Context(), base, target, r.PathValue("group"), f)
|
||||||
|
if err != nil {
|
||||||
|
writeProxyError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
_, _ = w.Write(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleAnalyticsCompareCSV proxies the CSV file of one comparison table as a download.
|
||||||
|
func (s *Server) handleAnalyticsCompareCSV(w http.ResponseWriter, r *http.Request) {
|
||||||
|
base, target, f, ok := compareParams(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
body, disposition, err := s.CA.GetAnalyticsCompareListCSV(r.Context(), base, target, r.PathValue("group"), f)
|
||||||
|
if err != nil {
|
||||||
|
writeProxyError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||||
|
if disposition != "" {
|
||||||
|
w.Header().Set("Content-Disposition", disposition)
|
||||||
|
}
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
_, _ = w.Write(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeProxyError(w http.ResponseWriter, err error) {
|
||||||
|
status := http.StatusBadGateway
|
||||||
|
if ae, ok := err.(*apiErr); ok && ae.Status >= 400 && ae.Status < 500 {
|
||||||
|
status = ae.Status
|
||||||
|
}
|
||||||
|
http.Error(w, err.Error(), status)
|
||||||
|
}
|
||||||
|
|
||||||
|
func kindLabel(kind string) string {
|
||||||
|
if kind == "auto" {
|
||||||
|
return "авто"
|
||||||
|
}
|
||||||
|
return "ручной"
|
||||||
|
}
|
||||||
|
|
||||||
|
// groupThousands writes n with a space between thousands: 6440 -> "6 440".
|
||||||
|
func groupThousands(n int) string {
|
||||||
|
s := strconv.Itoa(n)
|
||||||
|
if len(s) <= 3 {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
for i, c := range s {
|
||||||
|
if i > 0 && (len(s)-i)%3 == 0 {
|
||||||
|
b.WriteString(" ")
|
||||||
|
}
|
||||||
|
b.WriteRune(c)
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// fmtShort is a run timestamp as the page shows it: 02.10.2026 13:47.
|
||||||
|
func fmtShort(t time.Time) string { return t.Local().Format("02.01.2006 15:04") }
|
||||||
|
|
||||||
|
// fmtDuration is "8 ч 42 мин", "42 мин", "под минуту".
|
||||||
|
func fmtRunDuration(d time.Duration) string {
|
||||||
|
m := int(d.Round(time.Minute) / time.Minute)
|
||||||
|
switch {
|
||||||
|
case m <= 0:
|
||||||
|
return "меньше минуты"
|
||||||
|
case m < 60:
|
||||||
|
return fmt.Sprintf("%d мин", m)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%d ч %d мин", m/60, m%60)
|
||||||
|
}
|
||||||
|
|
||||||
|
// runLabel is the text of a run in the selector, e.g.
|
||||||
|
// "02.10 13:47 → 22:29 · ручной · 6 440 адр. · 30% pass"; an open run reads
|
||||||
|
// "03.10 15:30 → идёт · ручной · 120 из 800 · недоступен".
|
||||||
|
func runLabel(x analyticsRun) string {
|
||||||
|
start := x.StartedAt.Local().Format("02.01 15:04")
|
||||||
|
if x.State != "finalized" {
|
||||||
|
return fmt.Sprintf("%s → идёт · %s · %s из %s · недоступен", start, kindLabel(x.Kind),
|
||||||
|
groupThousands(x.Total-x.Pending), groupThousands(x.Total))
|
||||||
|
}
|
||||||
|
end := "—"
|
||||||
|
if x.FinalizedAt != nil {
|
||||||
|
e := x.FinalizedAt.Local()
|
||||||
|
if e.Format("02.01") == x.StartedAt.Local().Format("02.01") {
|
||||||
|
end = e.Format("15:04")
|
||||||
|
} else {
|
||||||
|
end = e.Format("02.01 15:04")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pass := 0
|
||||||
|
if x.Addresses > 0 {
|
||||||
|
pass = int(float64(x.Pass)/float64(x.Addresses)*100 + 0.5)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%s → %s · %s · %s адр. · %d%% pass", start, end, kindLabel(x.Kind), groupThousands(x.Addresses), pass)
|
||||||
|
}
|
||||||
@@ -0,0 +1,428 @@
|
|||||||
|
package dashboard
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func fakeRun(id int64, state string, addresses, pass int) analyticsRun {
|
||||||
|
start := time.Date(2026, 10, 2, 13, 47, 0, 0, time.UTC)
|
||||||
|
end := start.Add(8*time.Hour + 42*time.Minute)
|
||||||
|
r := analyticsRun{ID: id, Kind: "manual", State: state, StartedAt: start, Addresses: addresses, Pass: pass,
|
||||||
|
Partial: addresses - pass, Total: addresses}
|
||||||
|
if state == "finalized" {
|
||||||
|
r.FinalizedAt = &end
|
||||||
|
} else {
|
||||||
|
r.Pending = 80
|
||||||
|
r.Total = addresses + r.Pending
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
// reportWith is the minimal report JSON the page needs; addresses is a marker
|
||||||
|
// that tells the runs apart in the page source.
|
||||||
|
func reportWith(addresses string) string {
|
||||||
|
return `{"run":{"rechecked":0},"summary":{"addresses":` + addresses + `,"pass":1,"partial":0,"fail":0,"cancelled":0,` +
|
||||||
|
`"egress_ok":1,"ingress_ok":1,"egress_https_any_failed":0,"egress_https_all_failed":0,"egress_https_all_targets_failed":0,` +
|
||||||
|
`"ingress_ssh_any_failed":0,"ingress_ssh_all_failed":0,"addresses_per_minute":1},"reasons":[],"quality":{},"subnets":[],` +
|
||||||
|
`"targets":{"types":[],"targets":[],"failed":{}},"matrix":{},"sites":{"types":[],"rows":[]},"errors":[],"validators":[]}`
|
||||||
|
}
|
||||||
|
|
||||||
|
func analyticsFake(t *testing.T) (*fakeControlAPI, *httptest.Server) {
|
||||||
|
t.Helper()
|
||||||
|
fake, caURL := newFakeControlAPI(t)
|
||||||
|
fake.runs = []analyticsRun{fakeRun(3, "open", 120, 40), fakeRun(2, "finalized", 900, 300), fakeRun(1, "finalized", 6440, 1962)}
|
||||||
|
fake.reports = map[int64]string{1: reportWith("6440"), 2: reportWith("900")}
|
||||||
|
fake.lists = map[string]string{
|
||||||
|
"1/egress_https_any": `{"kind":"egress_https_any","columns":["Адрес","Подсеть"],"rows":[["1.2.3.4","1.2.3.0/24"]]}`,
|
||||||
|
"1/error/SSH: таймаут": `{"kind":"error","class":"SSH: таймаут","columns":["Адрес"],"rows":[["1.2.3.4"]]}`,
|
||||||
|
}
|
||||||
|
return fake, newTestServer(t, caURL)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The page shows one run, by default the newest finished one, and asks
|
||||||
|
// control-api for that run only; the selector lists every run, the open one
|
||||||
|
// disabled.
|
||||||
|
func TestAnalyticsPageShowsOneRun(t *testing.T) {
|
||||||
|
fake, ts := analyticsFake(t)
|
||||||
|
|
||||||
|
page := get(t, ts, "/analytics")
|
||||||
|
for _, want := range []string{
|
||||||
|
`id="an-run"`, `id="analytics-data"`, `"addresses":900`, // newest finished run (2)
|
||||||
|
"идёт · ручной · 120 из 200 · недоступен",
|
||||||
|
"6 440 адр. · 30% pass", // run 1's option, from the run list
|
||||||
|
`/analytics?run=1`, // the older run is one step back
|
||||||
|
} {
|
||||||
|
if !strings.Contains(page, want) {
|
||||||
|
t.Fatalf("expected %q in the page, got:\n%s", want, page)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(page, `"addresses":6440`) {
|
||||||
|
t.Fatalf("the data of run 1 is on the page of run 2")
|
||||||
|
}
|
||||||
|
if !strings.Contains(page, `value="3" disabled`) {
|
||||||
|
t.Fatalf("the open run must be listed but disabled:\n%s", page)
|
||||||
|
}
|
||||||
|
for _, r := range fake.analyticsReqs {
|
||||||
|
if strings.Contains(r, "/runs/1") || strings.Contains(r, "/runs/3") {
|
||||||
|
t.Fatalf("the page must request only the chosen run, got %v", fake.analyticsReqs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
other := get(t, ts, "/analytics?run=1")
|
||||||
|
if !strings.Contains(other, `"addresses":6440`) || strings.Contains(other, `"addresses":900`) {
|
||||||
|
t.Fatalf("run 1 page must carry only run 1's data:\n%s", other)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAnalyticsPageWithoutRunsAndWithUnknownRun(t *testing.T) {
|
||||||
|
_, caURL := newFakeControlAPI(t)
|
||||||
|
ts := newTestServer(t, caURL)
|
||||||
|
page := get(t, ts, "/analytics")
|
||||||
|
if !strings.Contains(page, "Запусков проверки пока нет") || strings.Contains(page, `id="analytics-data"`) {
|
||||||
|
t.Fatalf("expected the empty state, got:\n%s", page)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, ts = analyticsFake(t)
|
||||||
|
for _, run := range []string{"99", "3"} { // unknown, and the open one
|
||||||
|
page = get(t, ts, "/analytics?run="+run)
|
||||||
|
if !strings.Contains(page, "не найден или ещё не завершён") {
|
||||||
|
t.Fatalf("run %s: expected a warning, got:\n%s", run, page)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAnalyticsListProxyAndCSV(t *testing.T) {
|
||||||
|
_, ts := analyticsFake(t)
|
||||||
|
|
||||||
|
resp, err := http.Get(ts.URL + "/analytics/lists/egress_https_any?run=1")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusOK || !strings.Contains(string(body), `"1.2.3.4"`) {
|
||||||
|
t.Fatalf("list: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
q := url.Values{"run": {"1"}, "class": {"SSH: таймаут"}}
|
||||||
|
resp, err = http.Get(ts.URL + "/analytics/lists/error?" + q.Encode())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body, _ = io.ReadAll(resp.Body)
|
||||||
|
resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusOK || !strings.Contains(string(body), `"class":"SSH: таймаут"`) {
|
||||||
|
t.Fatalf("error list: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err = http.Get(ts.URL + "/analytics/csv/egress_https_any?run=1")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body, _ = io.ReadAll(resp.Body)
|
||||||
|
resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusOK || !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/csv") ||
|
||||||
|
!strings.Contains(resp.Header.Get("Content-Disposition"), `attachment; filename="egress_https_any_run1.csv"`) {
|
||||||
|
t.Fatalf("csv: %d %v %s", resp.StatusCode, resp.Header, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
for path, want := range map[string]int{
|
||||||
|
"/analytics/lists/egress_https_any": http.StatusBadRequest, // no run
|
||||||
|
"/analytics/csv/egress_https_any?run=abc": http.StatusBadRequest,
|
||||||
|
"/analytics/lists/nonsense?run=1": http.StatusNotFound, // control-api says unknown list
|
||||||
|
} {
|
||||||
|
resp, err := http.Get(ts.URL + path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
resp.Body.Close()
|
||||||
|
if resp.StatusCode != want {
|
||||||
|
t.Fatalf("%s: %d, want %d", path, resp.StatusCode, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// compareWith is the minimal comparison JSON the page needs; new is a marker
|
||||||
|
// that tells the pairs of runs apart in the page source.
|
||||||
|
func compareWith(newAddrs string) string {
|
||||||
|
return `{"runs":{"base":{"id":1,"rechecked":0,"addresses":6440},"target":{"id":2,"rechecked":0,"addresses":900}},` +
|
||||||
|
`"groups":{"new":` + newAddrs + `,"left":2,"common":3,"changed":1,"same":2},"indicators":[],` +
|
||||||
|
`"transitions":{"verdicts":["pass","partial","fail"],"matrix":[[0,0,0],[0,0,0],[0,0,0]],"new":[0,0,0],"left":[0,0,0]},"cancelled":{"base":0,"target":0}}`
|
||||||
|
}
|
||||||
|
|
||||||
|
// compareFake is analyticsFake with the comparisons of runs 1 and 2 (run 3 is open).
|
||||||
|
func compareFake(t *testing.T) (*fakeControlAPI, *httptest.Server) {
|
||||||
|
t.Helper()
|
||||||
|
fake, ts := analyticsFake(t)
|
||||||
|
fake.compares = map[string]string{"1-2": compareWith("111"), "2-1": compareWith("222")}
|
||||||
|
fake.compareLists = map[string]string{
|
||||||
|
"1-2/changed": `{"group":"changed","columns":["Адрес","Подсеть"],"rows":[["1.2.3.4","1.2.3.0/24"]]}`,
|
||||||
|
"1-2/new/verdict_pass": `{"group":"new","indicator":"verdict_pass","columns":["Адрес"],"rows":[["5.6.7.8"]]}`,
|
||||||
|
}
|
||||||
|
return fake, ts
|
||||||
|
}
|
||||||
|
|
||||||
|
func compareRequests(fake *fakeControlAPI) []string {
|
||||||
|
var out []string
|
||||||
|
for _, r := range fake.analyticsReqs {
|
||||||
|
if strings.Contains(r, "/compare") {
|
||||||
|
out = append(out, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// By default B is the newest finished run and A the one before it; the open
|
||||||
|
// run is not offered; the page asks control-api for that pair only.
|
||||||
|
func TestAnalyticsComparePageDefaultPair(t *testing.T) {
|
||||||
|
fake, ts := compareFake(t)
|
||||||
|
|
||||||
|
page := get(t, ts, "/analytics/compare")
|
||||||
|
for _, want := range []string{
|
||||||
|
`id="an-base"`, `id="an-target"`, `id="an-swap"`, `id="analytics-data"`, `"new":111`,
|
||||||
|
`<option value="1" selected>`, `<option value="2" selected>`, // A is run 1, B is run 2
|
||||||
|
`id="an-dlg"`, `/static/analytics-dialog.js`, `/static/analytics-compare.js`,
|
||||||
|
"6\u00a0440 адр. · 30% pass",
|
||||||
|
} {
|
||||||
|
if !strings.Contains(page, want) {
|
||||||
|
t.Fatalf("expected %q in the page, got:\n%s", want, page)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Count(page, `<option value="1" selected>`) != 1 || strings.Count(page, `<option value="2" selected>`) != 1 {
|
||||||
|
t.Fatalf("one run is chosen in each list:\n%s", page)
|
||||||
|
}
|
||||||
|
if strings.Contains(page, `value="3"`) {
|
||||||
|
t.Fatalf("an open run must not be offered:\n%s", page)
|
||||||
|
}
|
||||||
|
if got := compareRequests(fake); len(got) != 1 || !strings.Contains(got[0], "base=1") || !strings.Contains(got[0], "target=2") {
|
||||||
|
t.Fatalf("expected one request for base=1&target=2, got %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The pair in the address: both ends, only the new one (the base is the run
|
||||||
|
// before it), only the old one (the target is the newest other run).
|
||||||
|
func TestAnalyticsComparePageExplicitPair(t *testing.T) {
|
||||||
|
fake, ts := compareFake(t)
|
||||||
|
|
||||||
|
page := get(t, ts, "/analytics/compare?base=2&target=1")
|
||||||
|
if !strings.Contains(page, `"new":222`) || !strings.Contains(page, `<option value="2" selected>`) {
|
||||||
|
t.Fatalf("swapped pair:\n%s", page)
|
||||||
|
}
|
||||||
|
if page = get(t, ts, "/analytics/compare?target=2"); !strings.Contains(page, `"new":111`) {
|
||||||
|
t.Fatalf("only target=2 must compare with run 1:\n%s", page)
|
||||||
|
}
|
||||||
|
if page = get(t, ts, "/analytics/compare?base=2"); !strings.Contains(page, `"new":222`) {
|
||||||
|
t.Fatalf("only base=2 must compare with the newest other run, 1:\n%s", page)
|
||||||
|
}
|
||||||
|
if page = get(t, ts, "/analytics/compare?target=1"); strings.Contains(page, `id="analytics-data"`) ||
|
||||||
|
!strings.Contains(page, "нет второго запуска") {
|
||||||
|
t.Fatalf("run 1 is the oldest, nothing to compare it with:\n%s", page)
|
||||||
|
}
|
||||||
|
if got := compareRequests(fake); len(got) != 3 {
|
||||||
|
t.Fatalf("the refused pair must not reach control-api, got %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAnalyticsComparePageWarnings(t *testing.T) {
|
||||||
|
fake, ts := compareFake(t)
|
||||||
|
for _, c := range []struct{ query, want string }{
|
||||||
|
{"base=1&target=1", "Выберите два разных запуска"},
|
||||||
|
{"base=99&target=1", "Запуск 99 не найден или ещё не завершён"},
|
||||||
|
// the open run
|
||||||
|
{"base=1&target=3", "Запуск 3 не найден или ещё не завершён"},
|
||||||
|
{"base=abc&target=1", "Неверный номер запуска"},
|
||||||
|
{"base=0&target=1", "Неверный номер запуска"},
|
||||||
|
} {
|
||||||
|
page := get(t, ts, "/analytics/compare?"+c.query)
|
||||||
|
if !strings.Contains(page, c.want) || strings.Contains(page, `id="analytics-data"`) || !strings.Contains(page, `id="an-base"`) {
|
||||||
|
t.Fatalf("%s: expected the warning %q and the run lists without data, got:\n%s", c.query, c.want, page)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := compareRequests(fake); len(got) != 0 {
|
||||||
|
t.Fatalf("a bad pair must not reach control-api, got %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fewer than two finished runs: nothing to compare.
|
||||||
|
fake, caURL := newFakeControlAPI(t)
|
||||||
|
fake.runs = []analyticsRun{fakeRun(3, "open", 120, 40), fakeRun(1, "finalized", 6440, 1962)}
|
||||||
|
page := get(t, newTestServer(t, caURL), "/analytics/compare")
|
||||||
|
if !strings.Contains(page, "минимум два завершённых запуска") || strings.Contains(page, `id="an-base"`) {
|
||||||
|
t.Fatalf("expected the empty state, got:\n%s", page)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAnalyticsCompareListProxyAndCSV(t *testing.T) {
|
||||||
|
_, ts := compareFake(t)
|
||||||
|
fetch := func(path string) (int, http.Header, string) {
|
||||||
|
t.Helper()
|
||||||
|
resp, err := http.Get(ts.URL + path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
resp.Body.Close()
|
||||||
|
return resp.StatusCode, resp.Header, string(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
code, _, body := fetch("/analytics/compare/lists/changed?base=1&target=2")
|
||||||
|
if code != http.StatusOK || !strings.Contains(body, `"1.2.3.4"`) {
|
||||||
|
t.Fatalf("list: %d %s", code, body)
|
||||||
|
}
|
||||||
|
// The indicator and the verdicts travel to control-api.
|
||||||
|
code, _, body = fetch("/analytics/compare/lists/new?base=1&target=2&indicator=verdict_pass")
|
||||||
|
if code != http.StatusOK || !strings.Contains(body, `"5.6.7.8"`) {
|
||||||
|
t.Fatalf("list with an indicator: %d %s", code, body)
|
||||||
|
}
|
||||||
|
code, header, body := fetch("/analytics/compare/csv/changed?base=1&target=2")
|
||||||
|
if code != http.StatusOK || !strings.HasPrefix(header.Get("Content-Type"), "text/csv") ||
|
||||||
|
!strings.Contains(header.Get("Content-Disposition"), `attachment; filename="compare_changed_run1-2.csv"`) {
|
||||||
|
t.Fatalf("csv: %d %v %s", code, header, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, c := range []struct {
|
||||||
|
path string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
// no runs
|
||||||
|
{"/analytics/compare/lists/changed", http.StatusBadRequest},
|
||||||
|
{"/analytics/compare/lists/changed?base=1", http.StatusBadRequest},
|
||||||
|
{"/analytics/compare/csv/changed?base=abc&target=2", http.StatusBadRequest},
|
||||||
|
// control-api says unknown list
|
||||||
|
{"/analytics/compare/lists/nonsense?base=1&target=2", http.StatusNotFound},
|
||||||
|
{"/analytics/compare/csv/nonsense?base=1&target=2", http.StatusNotFound},
|
||||||
|
} {
|
||||||
|
if code, _, _ := fetch(c.path); code != c.want {
|
||||||
|
t.Errorf("%s: %d, want %d", c.path, code, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The single-run page after the dialog moved to analytics-dialog.js: it still
|
||||||
|
// carries the dialog, loads the shared script before its own, offers the
|
||||||
|
// comparison, and both scripts are served.
|
||||||
|
func TestAnalyticsPageUsesSharedDialog(t *testing.T) {
|
||||||
|
_, ts := analyticsFake(t)
|
||||||
|
|
||||||
|
page := get(t, ts, "/analytics")
|
||||||
|
iDialog, iPage := strings.Index(page, "/static/analytics-dialog.js"), strings.Index(page, "/static/analytics.js")
|
||||||
|
if iDialog < 0 || iPage < 0 || iDialog > iPage {
|
||||||
|
t.Fatalf("analytics-dialog.js must come before analytics.js (%d, %d):\n%s", iDialog, iPage, page)
|
||||||
|
}
|
||||||
|
for _, want := range []string{`id="an-dlg"`, `id="an-dlg-tbl"`, `id="an-dlg-csv"`, `id="an-tip"`, `href="/analytics/compare?target=2"`} {
|
||||||
|
if !strings.Contains(page, want) {
|
||||||
|
t.Fatalf("expected %q in the page, got:\n%s", want, page)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for path, want := range map[string]string{
|
||||||
|
"/static/analytics-dialog.js": "window.AnalyticsDialog =",
|
||||||
|
"/static/analytics.js": "window.AnalyticsDialog",
|
||||||
|
"/static/analytics-compare.js": "window.AnalyticsDialog",
|
||||||
|
} {
|
||||||
|
if body := get(t, ts, path); !strings.Contains(body, want) {
|
||||||
|
t.Errorf("%s does not contain %q", path, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The sidebar: no window-chrome dots next to the logo, the Analytics entry,
|
||||||
|
// and the link state, theme toggle and logout above the navigation.
|
||||||
|
func TestSidebarSessionBlockOnTop(t *testing.T) {
|
||||||
|
_, caURL := newFakeControlAPI(t)
|
||||||
|
_, ts := newAuthTestServer(t, caURL, nil)
|
||||||
|
cookie := login(t, ts)
|
||||||
|
_, page := doReq(t, ts, reqOpts{path: "/overview", cookie: cookie})
|
||||||
|
|
||||||
|
if strings.Contains(page, "brand-chrome") {
|
||||||
|
t.Fatalf("the three dots next to the logo are back")
|
||||||
|
}
|
||||||
|
iBrand := strings.Index(page, `class="brand"`)
|
||||||
|
iAPI := strings.Index(page, `class="session-api"`)
|
||||||
|
iLogout := strings.Index(page, `action="/logout"`)
|
||||||
|
iNav := strings.Index(page, `class="nav-groups"`)
|
||||||
|
iFoot := strings.Index(page, "sidebar-foot")
|
||||||
|
if !(iBrand >= 0 && iBrand < iAPI && iAPI < iLogout && iLogout < iNav) || iFoot >= 0 {
|
||||||
|
t.Fatalf("expected brand < control-api state < logout < navigation (and no old footer): %d %d %d %d foot=%d", iBrand, iAPI, iLogout, iNav, iFoot)
|
||||||
|
}
|
||||||
|
for _, link := range []string{`href="/analytics"`, `href="/registry"`, `href="/settings"`} {
|
||||||
|
if !strings.Contains(page, link) {
|
||||||
|
t.Fatalf("missing nav link %s", link)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(page, "pulse-dot down") {
|
||||||
|
t.Fatalf("the link state must be fine while control-api answers")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The link indicator turns red when control-api cannot be reached.
|
||||||
|
func TestSidebarShowsLostControlAPI(t *testing.T) {
|
||||||
|
ts := newTestServer(t, "http://127.0.0.1:1") // nothing listens there
|
||||||
|
page := get(t, ts, "/overview")
|
||||||
|
if !strings.Contains(page, "pulse-dot down") || !strings.Contains(page, "нет связи") {
|
||||||
|
t.Fatalf("expected the lost-link indicator, got:\n%s", page)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSettingsSubnetsForm(t *testing.T) {
|
||||||
|
fake, caURL := newFakeControlAPI(t)
|
||||||
|
ts := newTestServer(t, caURL)
|
||||||
|
|
||||||
|
body := postForm(t, ts, "PUT", "/settings/subnets", url.Values{"subnets": {"83.166.248.0/21 москва\n\n 10.0.0.0/8\n"}})
|
||||||
|
if len(fake.subnets.Subnets) != 2 ||
|
||||||
|
fake.subnets.Subnets[0] != (subnetEntry{CIDR: "83.166.248.0/21", Label: "москва"}) ||
|
||||||
|
fake.subnets.Subnets[1] != (subnetEntry{CIDR: "10.0.0.0/8"}) {
|
||||||
|
t.Fatalf("subnets saved: %+v", fake.subnets)
|
||||||
|
}
|
||||||
|
if !strings.Contains(body, "83.166.248.0/21 москва") || !strings.Contains(body, "10.0.0.0/8") {
|
||||||
|
t.Fatalf("the saved list must come back in the form:\n%s", body)
|
||||||
|
}
|
||||||
|
|
||||||
|
body = postForm(t, ts, "PUT", "/settings/subnets", url.Values{"subnets": {"not-a-cidr"}})
|
||||||
|
if !strings.Contains(body, "alert-warning") || !strings.Contains(body, "not a CIDR") {
|
||||||
|
t.Fatalf("expected the validation error in the banner:\n%s", body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The drill-down from the analytics page: run and subnet go to control-api,
|
||||||
|
// come back as hidden fields and a visible chip; a malformed subnet is dropped.
|
||||||
|
func TestRegistryDrillDownFromAnalytics(t *testing.T) {
|
||||||
|
fake, caURL := newFakeControlAPI(t)
|
||||||
|
ts := newTestServer(t, caURL)
|
||||||
|
|
||||||
|
page := get(t, ts, "/registry?run=2&subnet="+url.QueryEscape("10.0.0.0/24"))
|
||||||
|
if len(fake.registryQueries) == 0 {
|
||||||
|
t.Fatal("no registry request")
|
||||||
|
}
|
||||||
|
last := fake.registryQueries[len(fake.registryQueries)-1]
|
||||||
|
if !strings.Contains(last, "run=2") || !strings.Contains(last, "subnet=10.0.0.0%2F24") {
|
||||||
|
t.Fatalf("control-api request %q lacks the run or subnet", last)
|
||||||
|
}
|
||||||
|
for _, want := range []string{`name="run" value="2"`, `name="subnet" value="10.0.0.0/24"`, "запуск 2", "подсеть 10.0.0.0/24", "сбросить фильтр"} {
|
||||||
|
if !strings.Contains(page, want) {
|
||||||
|
t.Fatalf("expected %q in:\n%s", want, page)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
page = get(t, ts, "/registry?subnet=garbage")
|
||||||
|
last = fake.registryQueries[len(fake.registryQueries)-1]
|
||||||
|
if strings.Contains(last, "subnet=") || strings.Contains(page, "сбросить фильтр") {
|
||||||
|
t.Fatalf("a malformed subnet must be ignored: %q", last)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The filter of a comparison list goes to control-api as it is.
|
||||||
|
func TestAnalyticsCompareListPath(t *testing.T) {
|
||||||
|
got := analyticsCompareListPath(1, 2, "common", compareFilter{Indicator: "verdict_pass", From: "partial", To: "pass"}, true)
|
||||||
|
want := "/api/v1/admin/analytics/compare/lists/common?base=1&format=csv&from=partial&indicator=verdict_pass&target=2&to=pass"
|
||||||
|
if got != want {
|
||||||
|
t.Errorf("path = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
if got := analyticsCompareListPath(3, 4, "new", compareFilter{}, false); got != "/api/v1/admin/analytics/compare/lists/new?base=3&target=4" {
|
||||||
|
t.Errorf("path = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,9 @@ package dashboard
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/netip"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -11,6 +13,8 @@ type registryPageData struct {
|
|||||||
Items []registryItem
|
Items []registryItem
|
||||||
Query string
|
Query string
|
||||||
StatusFilter string
|
StatusFilter string
|
||||||
|
Run int64 // drill-down from the analytics page
|
||||||
|
Subnet string
|
||||||
Page, PerPage int
|
Page, PerPage int
|
||||||
Total int
|
Total int
|
||||||
Pager pagerData
|
Pager pagerData
|
||||||
@@ -37,7 +41,15 @@ func (s *Server) handleRegistryPage(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
perPage := parsePerPage(r.URL.Query().Get("per_page"))
|
perPage := parsePerPage(r.URL.Query().Get("per_page"))
|
||||||
page := parsePage(r.URL.Query().Get("page"))
|
page := parsePage(r.URL.Query().Get("page"))
|
||||||
query := registryQuery{Q: q, LastResult: status, Limit: perPage, Offset: (page - 1) * perPage}
|
run, _ := strconv.ParseInt(r.URL.Query().Get("run"), 10, 64)
|
||||||
|
if run < 0 {
|
||||||
|
run = 0
|
||||||
|
}
|
||||||
|
subnet := strings.TrimSpace(r.URL.Query().Get("subnet"))
|
||||||
|
if _, err := netip.ParsePrefix(subnet); err != nil {
|
||||||
|
subnet = ""
|
||||||
|
}
|
||||||
|
query := registryQuery{Q: q, LastResult: status, Run: run, Subnet: subnet, Limit: perPage, Offset: (page - 1) * perPage}
|
||||||
|
|
||||||
res, err := s.CA.ListRegistryPage(r.Context(), query)
|
res, err := s.CA.ListRegistryPage(r.Context(), query)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -54,7 +66,15 @@ func (s *Server) handleRegistryPage(w http.ResponseWriter, r *http.Request) {
|
|||||||
if status != "" {
|
if status != "" {
|
||||||
params.Set("status", status)
|
params.Set("status", status)
|
||||||
}
|
}
|
||||||
|
if run > 0 {
|
||||||
|
params.Set("run", strconv.FormatInt(run, 10))
|
||||||
|
}
|
||||||
|
if subnet != "" {
|
||||||
|
params.Set("subnet", subnet)
|
||||||
|
}
|
||||||
data := registryPageData{
|
data := registryPageData{
|
||||||
|
Run: run,
|
||||||
|
Subnet: subnet,
|
||||||
Items: res.Items,
|
Items: res.Items,
|
||||||
Query: q,
|
Query: q,
|
||||||
StatusFilter: status,
|
StatusFilter: status,
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ type settingsPageData struct {
|
|||||||
Inbound inboundChecksDTO
|
Inbound inboundChecksDTO
|
||||||
// AutoCycle is the automatic-check-cycle panel's status/parameters.
|
// AutoCycle is the automatic-check-cycle panel's status/parameters.
|
||||||
AutoCycle autoCycleDTO
|
AutoCycle autoCycleDTO
|
||||||
|
// Subnets is the list the analytics page groups addresses by.
|
||||||
|
Subnets subnetList
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleSettingsPage(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleSettingsPage(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -26,7 +28,11 @@ func (s *Server) handleSettingsPage(w http.ResponseWriter, r *http.Request) {
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
err = autoCycleErr
|
err = autoCycleErr
|
||||||
}
|
}
|
||||||
data := settingsPageData{Settings: settings, Inbound: inbound, AutoCycle: autoCycle}
|
subnets, subnetsErr := s.CA.GetSubnets(r.Context())
|
||||||
|
if err == nil {
|
||||||
|
err = subnetsErr
|
||||||
|
}
|
||||||
|
data := settingsPageData{Settings: settings, Inbound: inbound, AutoCycle: autoCycle, Subnets: subnets}
|
||||||
data.ActiveNav = "settings"
|
data.ActiveNav = "settings"
|
||||||
data.Banner = bannerFor(err)
|
data.Banner = bannerFor(err)
|
||||||
s.renderPage(w, r, "settings_page", data)
|
s.renderPage(w, r, "settings_page", data)
|
||||||
@@ -49,7 +55,11 @@ func (s *Server) renderSettingsForm(w http.ResponseWriter, r *http.Request, acti
|
|||||||
if actionErr == nil {
|
if actionErr == nil {
|
||||||
actionErr = autoCycleErr
|
actionErr = autoCycleErr
|
||||||
}
|
}
|
||||||
s.renderFragment(w, "settings_form", settingsPageData{Settings: settings, Inbound: inbound, AutoCycle: autoCycle}, actionErr)
|
subnets, subnetsErr := s.CA.GetSubnets(r.Context())
|
||||||
|
if actionErr == nil {
|
||||||
|
actionErr = subnetsErr
|
||||||
|
}
|
||||||
|
s.renderFragment(w, "settings_form", settingsPageData{Settings: settings, Inbound: inbound, AutoCycle: autoCycle, Subnets: subnets}, actionErr)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleSettingsPut(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleSettingsPut(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -67,7 +77,12 @@ func (s *Server) handleSettingsPut(w http.ResponseWriter, r *http.Request) {
|
|||||||
s.renderSettingsForm(w, r, &apiErr{Status: http.StatusBadRequest, Message: "глубина истории должна быть целым числом циклов"})
|
s.renderSettingsForm(w, r, &apiErr{Status: http.StatusBadRequest, Message: "глубина истории должна быть целым числом циклов"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_, err = s.CA.PutOrchestratorSettings(r.Context(), seconds, retentionCycles)
|
selfCheckMax, err := strconv.Atoi(r.PostFormValue("self_check_max_attempts"))
|
||||||
|
if err != nil {
|
||||||
|
s.renderSettingsForm(w, r, &apiErr{Status: http.StatusBadRequest, Message: "потолок провалов self-check должен быть целым числом"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, err = s.CA.PutOrchestratorSettings(r.Context(), seconds, retentionCycles, selfCheckMax)
|
||||||
s.renderSettingsForm(w, r, err)
|
s.renderSettingsForm(w, r, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,6 +117,26 @@ func (s *Server) handleInboundChecksPut(w http.ResponseWriter, r *http.Request)
|
|||||||
s.renderSettingsForm(w, r, err)
|
s.renderSettingsForm(w, r, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// handleSubnetsPut saves the subnet list from the textarea of /settings: one
|
||||||
|
// subnet per line, CIDR first and an optional label after a space.
|
||||||
|
func (s *Server) handleSubnetsPut(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if err := r.ParseForm(); err != nil {
|
||||||
|
s.renderSettingsForm(w, r, fmt.Errorf("invalid form: %w", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
list := subnetList{Subnets: []subnetEntry{}}
|
||||||
|
for _, line := range strings.Split(r.PostFormValue("subnets"), "\n") {
|
||||||
|
line = strings.TrimSpace(line)
|
||||||
|
if line == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
cidr, label, _ := strings.Cut(line, " ")
|
||||||
|
list.Subnets = append(list.Subnets, subnetEntry{CIDR: strings.TrimSpace(cidr), Label: strings.TrimSpace(label)})
|
||||||
|
}
|
||||||
|
_, err := s.CA.PutSubnets(r.Context(), list)
|
||||||
|
s.renderSettingsForm(w, r, err)
|
||||||
|
}
|
||||||
|
|
||||||
// parseMinutes converts a form field holding a (possibly fractional) number
|
// parseMinutes converts a form field holding a (possibly fractional) number
|
||||||
// of minutes into whole seconds.
|
// of minutes into whole seconds.
|
||||||
func parseMinutes(raw string) (int, error) {
|
func parseMinutes(raw string) (int, error) {
|
||||||
|
|||||||
@@ -307,9 +307,12 @@ func TestSettingsGetAndPut(t *testing.T) {
|
|||||||
if !strings.Contains(page, `value="0"`) {
|
if !strings.Contains(page, `value="0"`) {
|
||||||
t.Fatalf("expected default 0 in the form, got:\n%s", page)
|
t.Fatalf("expected default 0 in the form, got:\n%s", page)
|
||||||
}
|
}
|
||||||
|
if !strings.Contains(page, "Потолок провалов self-check на адрес") || !strings.Contains(page, `id="self_check_max_attempts" name="self_check_max_attempts" min="1" max="50" step="1" value="5"`) {
|
||||||
|
t.Fatalf("expected the self-check ceiling field with the default 5, got:\n%s", page)
|
||||||
|
}
|
||||||
|
|
||||||
body := postForm(t, ts, "PUT", "/settings", map[string][]string{
|
body := postForm(t, ts, "PUT", "/settings", map[string][]string{
|
||||||
"fip_settle_seconds": {"15"}, "history_retention_cycles": {"10"},
|
"fip_settle_seconds": {"15"}, "history_retention_cycles": {"10"}, "self_check_max_attempts": {"8"},
|
||||||
})
|
})
|
||||||
if !strings.Contains(body, `value="15"`) || !strings.Contains(body, `value="10"`) {
|
if !strings.Contains(body, `value="15"`) || !strings.Contains(body, `value="10"`) {
|
||||||
t.Fatalf("expected updated values 15/10 in re-rendered form, got:\n%s", body)
|
t.Fatalf("expected updated values 15/10 in re-rendered form, got:\n%s", body)
|
||||||
@@ -320,11 +323,14 @@ func TestSettingsGetAndPut(t *testing.T) {
|
|||||||
if fake.historyRetentionCycles != 10 {
|
if fake.historyRetentionCycles != 10 {
|
||||||
t.Fatalf("expected fake control-api history_retention_cycles updated, got %d", fake.historyRetentionCycles)
|
t.Fatalf("expected fake control-api history_retention_cycles updated, got %d", fake.historyRetentionCycles)
|
||||||
}
|
}
|
||||||
|
if fake.selfCheckMaxAttempts != 8 || !strings.Contains(body, `name="self_check_max_attempts" min="1" max="50" step="1" value="8"`) {
|
||||||
|
t.Fatalf("expected the self-check ceiling 8 saved and shown, got %d:\n%s", fake.selfCheckMaxAttempts, body)
|
||||||
|
}
|
||||||
|
|
||||||
// A control-api validation error (negative value here) surfaces via
|
// A control-api validation error (negative value here) surfaces via
|
||||||
// the banner, not a crash.
|
// the banner, not a crash.
|
||||||
body = postForm(t, ts, "PUT", "/settings", map[string][]string{
|
body = postForm(t, ts, "PUT", "/settings", map[string][]string{
|
||||||
"fip_settle_seconds": {"-1"}, "history_retention_cycles": {"10"},
|
"fip_settle_seconds": {"-1"}, "history_retention_cycles": {"10"}, "self_check_max_attempts": {"8"},
|
||||||
})
|
})
|
||||||
if !strings.Contains(body, "alert-warning") {
|
if !strings.Contains(body, "alert-warning") {
|
||||||
t.Fatalf("expected client error banner for invalid value, got:\n%s", body)
|
t.Fatalf("expected client error banner for invalid value, got:\n%s", body)
|
||||||
@@ -333,7 +339,7 @@ func TestSettingsGetAndPut(t *testing.T) {
|
|||||||
// A non-numeric value is caught by the dashboard itself before it ever
|
// A non-numeric value is caught by the dashboard itself before it ever
|
||||||
// reaches control-api.
|
// reaches control-api.
|
||||||
body = postForm(t, ts, "PUT", "/settings", map[string][]string{
|
body = postForm(t, ts, "PUT", "/settings", map[string][]string{
|
||||||
"fip_settle_seconds": {"not-a-number"}, "history_retention_cycles": {"10"},
|
"fip_settle_seconds": {"not-a-number"}, "history_retention_cycles": {"10"}, "self_check_max_attempts": {"8"},
|
||||||
})
|
})
|
||||||
if !strings.Contains(body, "alert-warning") {
|
if !strings.Contains(body, "alert-warning") {
|
||||||
t.Fatalf("expected client error banner for non-numeric value, got:\n%s", body)
|
t.Fatalf("expected client error banner for non-numeric value, got:\n%s", body)
|
||||||
@@ -341,11 +347,49 @@ func TestSettingsGetAndPut(t *testing.T) {
|
|||||||
|
|
||||||
// Same for a non-numeric retention value.
|
// Same for a non-numeric retention value.
|
||||||
body = postForm(t, ts, "PUT", "/settings", map[string][]string{
|
body = postForm(t, ts, "PUT", "/settings", map[string][]string{
|
||||||
"fip_settle_seconds": {"15"}, "history_retention_cycles": {"not-a-number"},
|
"fip_settle_seconds": {"15"}, "history_retention_cycles": {"not-a-number"}, "self_check_max_attempts": {"8"},
|
||||||
})
|
})
|
||||||
if !strings.Contains(body, "alert-warning") {
|
if !strings.Contains(body, "alert-warning") {
|
||||||
t.Fatalf("expected client error banner for non-numeric retention value, got:\n%s", body)
|
t.Fatalf("expected client error banner for non-numeric retention value, got:\n%s", body)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A ceiling outside 1..50 is refused by control-api and shown as a
|
||||||
|
// warning; the form keeps the stored value.
|
||||||
|
body = postForm(t, ts, "PUT", "/settings", map[string][]string{
|
||||||
|
"fip_settle_seconds": {"15"}, "history_retention_cycles": {"10"}, "self_check_max_attempts": {"51"},
|
||||||
|
})
|
||||||
|
if !strings.Contains(body, "alert-warning") || fake.selfCheckMaxAttempts != 8 {
|
||||||
|
t.Fatalf("expected a warning and the stored ceiling 8 kept, got %d:\n%s", fake.selfCheckMaxAttempts, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A non-numeric ceiling is caught by the dashboard itself.
|
||||||
|
body = postForm(t, ts, "PUT", "/settings", map[string][]string{
|
||||||
|
"fip_settle_seconds": {"15"}, "history_retention_cycles": {"10"}, "self_check_max_attempts": {"many"},
|
||||||
|
})
|
||||||
|
if !strings.Contains(body, "alert-warning") {
|
||||||
|
t.Fatalf("expected client error banner for non-numeric ceiling, got:\n%s", body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The address pages say on which validators the self-check failed.
|
||||||
|
func TestAddressPagesShowSelfCheckFailedOn(t *testing.T) {
|
||||||
|
fake, caURL := newFakeControlAPI(t)
|
||||||
|
now := time.Now()
|
||||||
|
fake.ips = []ipQueueItem{{IPAddress: "5.5.5.5", State: "checking", UpdatedAt: now, CreatedAt: now}}
|
||||||
|
fake.registry["5.5.5.5"] = registryItem{IPAddress: "5.5.5.5", FirstSeenAt: now, LastSeenAt: now}
|
||||||
|
ts := newTestServer(t, caURL)
|
||||||
|
|
||||||
|
for _, path := range []string{"/ips/5.5.5.5", "/registry/5.5.5.5"} {
|
||||||
|
if page := get(t, ts, path); strings.Contains(page, "Self-check не прошёл на") {
|
||||||
|
t.Fatalf("%s: no failures, but the line is shown:\n%s", path, page)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fake.selfCheckFailedOn = []string{"vkiplab-v17", "vkiplab-v13"}
|
||||||
|
for _, path := range []string{"/ips/5.5.5.5", "/registry/5.5.5.5"} {
|
||||||
|
if page := get(t, ts, path); !strings.Contains(page, "Self-check не прошёл на: vkiplab-v17, vkiplab-v13") {
|
||||||
|
t.Fatalf("%s: expected the failed validators line, got:\n%s", path, page)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSettingsPageShowsInboundChecks(t *testing.T) {
|
func TestSettingsPageShowsInboundChecks(t *testing.T) {
|
||||||
@@ -590,6 +634,38 @@ func TestRegistryPageAndDetail(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestRegistryPageShowsEgressIngressLevels proves the list shows, under the
|
||||||
|
// verdict, "ok из total" per level and per check family, coloured by outcome,
|
||||||
|
// and omits the block for an address with no recorded cycle.
|
||||||
|
func TestRegistryPageShowsEgressIngressLevels(t *testing.T) {
|
||||||
|
fake, caURL := newFakeControlAPI(t)
|
||||||
|
now := time.Now()
|
||||||
|
fake.registry["9.9.9.9"] = registryItem{
|
||||||
|
IPAddress: "9.9.9.9", FirstSeenAt: now, LastSeenAt: now, TotalCycles: 1, LastResult: "partial",
|
||||||
|
LastCycleID: 1,
|
||||||
|
Egress: levelResult{Total: 5, OK: 5, ByType: []typeStat{{"https", 3, 3}, {"icmp", 2, 2}}},
|
||||||
|
Ingress: levelResult{Total: 4, OK: 3, ByType: []typeStat{{"icmp", 1, 1}, {"tcp", 3, 2}}},
|
||||||
|
}
|
||||||
|
fake.registry["8.8.8.8"] = registryItem{IPAddress: "8.8.8.8", FirstSeenAt: now, LastSeenAt: now}
|
||||||
|
ts := newTestServer(t, caURL)
|
||||||
|
|
||||||
|
body := get(t, ts, "/registry")
|
||||||
|
for _, want := range []string{
|
||||||
|
"Egress", "Ingress",
|
||||||
|
`stat stat-ok">5 из 5<`, `stat stat-part">3 из 4<`,
|
||||||
|
`chip chip-ok">https 3 из 3<`, `chip chip-ok">icmp 2 из 2<`,
|
||||||
|
`chip chip-part">tcp 2 из 3<`,
|
||||||
|
"цикла 1",
|
||||||
|
} {
|
||||||
|
if !strings.Contains(body, want) {
|
||||||
|
t.Fatalf("expected %q in registry page, got:\n%s", want, body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Count(body, `class="levels"`) != 1 {
|
||||||
|
t.Fatalf("expected the levels block only for the address with checks, got:\n%s", body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestRegistryFilterByQueryAndStatus proves the ?q=&status= params on
|
// TestRegistryFilterByQueryAndStatus proves the ?q=&status= params on
|
||||||
// /registry narrow the list by address substring and by LastResult, and
|
// /registry narrow the list by address substring and by LastResult, and
|
||||||
// that the filter form echoes the applied values back into its inputs.
|
// that the filter form echoes the applied values back into its inputs.
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package dashboard
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"html/template"
|
"html/template"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -115,6 +116,24 @@ var funcMap = template.FuncMap{
|
|||||||
"join": strings.Join,
|
"join": strings.Join,
|
||||||
"joinInts": joinInts,
|
"joinInts": joinInts,
|
||||||
"pluralAddr": pluralAddr,
|
"pluralAddr": pluralAddr,
|
||||||
|
"dict": dict,
|
||||||
|
}
|
||||||
|
|
||||||
|
// dict builds a map from alternating key/value arguments, so a sub-template
|
||||||
|
// can be given several values: {{template "x" dict "Name" .A "L" .B}}.
|
||||||
|
func dict(kv ...any) (map[string]any, error) {
|
||||||
|
if len(kv)%2 != 0 {
|
||||||
|
return nil, fmt.Errorf("dict: odd number of arguments")
|
||||||
|
}
|
||||||
|
m := make(map[string]any, len(kv)/2)
|
||||||
|
for i := 0; i < len(kv); i += 2 {
|
||||||
|
k, ok := kv[i].(string)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("dict: key %v is not a string", kv[i])
|
||||||
|
}
|
||||||
|
m[k] = kv[i+1]
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// pluralAddr returns the correctly declined Russian word for "address"
|
// pluralAddr returns the correctly declined Russian word for "address"
|
||||||
|
|||||||
@@ -29,6 +29,13 @@ func (s *Server) routes(mux *http.ServeMux) {
|
|||||||
mux.HandleFunc("GET /registry", s.handleRegistryPage)
|
mux.HandleFunc("GET /registry", s.handleRegistryPage)
|
||||||
mux.HandleFunc("GET /registry/{ip}", s.handleRegistryDetail)
|
mux.HandleFunc("GET /registry/{ip}", s.handleRegistryDetail)
|
||||||
|
|
||||||
|
mux.HandleFunc("GET /analytics", s.handleAnalyticsPage)
|
||||||
|
mux.HandleFunc("GET /analytics/lists/{kind}", s.handleAnalyticsList)
|
||||||
|
mux.HandleFunc("GET /analytics/csv/{kind}", s.handleAnalyticsCSV)
|
||||||
|
mux.HandleFunc("GET /analytics/compare", s.handleAnalyticsComparePage)
|
||||||
|
mux.HandleFunc("GET /analytics/compare/lists/{group}", s.handleAnalyticsCompareList)
|
||||||
|
mux.HandleFunc("GET /analytics/compare/csv/{group}", s.handleAnalyticsCompareCSV)
|
||||||
|
|
||||||
mux.HandleFunc("GET /validators", s.handleValidatorsPage)
|
mux.HandleFunc("GET /validators", s.handleValidatorsPage)
|
||||||
mux.HandleFunc("POST /validators", s.handleValidatorCreate)
|
mux.HandleFunc("POST /validators", s.handleValidatorCreate)
|
||||||
mux.HandleFunc("PUT /validators/{id}", s.handleValidatorUpdate)
|
mux.HandleFunc("PUT /validators/{id}", s.handleValidatorUpdate)
|
||||||
@@ -52,6 +59,7 @@ func (s *Server) routes(mux *http.ServeMux) {
|
|||||||
mux.HandleFunc("GET /settings", s.handleSettingsPage)
|
mux.HandleFunc("GET /settings", s.handleSettingsPage)
|
||||||
mux.HandleFunc("PUT /settings", s.handleSettingsPut)
|
mux.HandleFunc("PUT /settings", s.handleSettingsPut)
|
||||||
mux.HandleFunc("PUT /settings/inbound-checks", s.handleInboundChecksPut)
|
mux.HandleFunc("PUT /settings/inbound-checks", s.handleInboundChecksPut)
|
||||||
|
mux.HandleFunc("PUT /settings/subnets", s.handleSubnetsPut)
|
||||||
mux.HandleFunc("PUT /settings/auto-cycle", s.handleAutoCyclePut)
|
mux.HandleFunc("PUT /settings/auto-cycle", s.handleAutoCyclePut)
|
||||||
mux.HandleFunc("POST /settings/auto-cycle/start", s.handleAutoCycleStart)
|
mux.HandleFunc("POST /settings/auto-cycle/start", s.handleAutoCycleStart)
|
||||||
mux.HandleFunc("POST /settings/auto-cycle/stop", s.handleAutoCycleStop)
|
mux.HandleFunc("POST /settings/auto-cycle/stop", s.handleAutoCycleStop)
|
||||||
|
|||||||
@@ -0,0 +1,136 @@
|
|||||||
|
/* Comparison of two finished runs: renders the comparison embedded as JSON in
|
||||||
|
#analytics-data (the groups of addresses, the dynamics of the seven
|
||||||
|
indicators, the verdict transitions) and opens the address list behind each
|
||||||
|
number in the shared dialog (analytics-dialog.js). The state of the page is
|
||||||
|
its address: ?base=A&target=B. */
|
||||||
|
(function () {
|
||||||
|
'use strict';
|
||||||
|
var D = JSON.parse(document.getElementById('analytics-data').textContent);
|
||||||
|
var R = D.report, M = D.meta, G = R.groups, T = R.transitions;
|
||||||
|
var A = window.AnalyticsDialog, $ = A.$, fmt = A.fmt, esc = A.esc, tipAttr = A.tipAttr;
|
||||||
|
|
||||||
|
function pct(a, b) { return b ? Math.round(a / b * 100) : 0; }
|
||||||
|
var NAME = {};
|
||||||
|
R.indicators.forEach(function (d) { NAME[d.key] = d.name; });
|
||||||
|
|
||||||
|
/* ---- what each list says about itself ---- */
|
||||||
|
var GROUP = {
|
||||||
|
new: ['Новые адреса', 'Есть в запуске B, в A их не было: прибыли в проект и подключились к анализу. Столбцы показывают состояние в B.'],
|
||||||
|
left: ['Выбывшие адреса', 'Были в запуске A, в B их нет: вышли из состава проекта. Столбцы показывают состояние в A.'],
|
||||||
|
common: ['Общие адреса', 'Есть в обоих запусках. Столбцы показывают состояние в A → B.'],
|
||||||
|
changed: ['Изменившиеся адреса', 'Есть в обоих запусках, принадлежность хотя бы к одному из семи индикаторов в A и в B разная.'],
|
||||||
|
same: ['Адреса без изменений', 'Есть в обоих запусках, принадлежность ко всем индикаторам та же. Другой набор проваленных целей или площадок изменением не считается.'],
|
||||||
|
entered: ['Вошли в индикатор', 'Общие адреса, которые в A не входили в этот индикатор, а в B входят.'],
|
||||||
|
exited: ['Вышли из индикатора', 'Общие адреса, которые в A входили в этот индикатор, а в B не входят.']
|
||||||
|
};
|
||||||
|
var HINT_ONE = {
|
||||||
|
2: 'Вердикт адреса, который система выставила при агрегации, а не итог всех проверок.',
|
||||||
|
3: 'Сколько egress-проверок адреса успешно из всех записанных в последнем цикле запуска. «—» — egress-проверок нет.',
|
||||||
|
4: 'Сколько ingress-проверок адреса успешно из всех записанных в последнем цикле запуска. «—» — ingress-проверок нет.',
|
||||||
|
5: 'Индикаторы страницы «Аналитика», в которые входит адрес. Один адрес может входить в несколько; вердикт — ровно в один из трёх.'
|
||||||
|
};
|
||||||
|
var HINT_PAIR = {
|
||||||
|
2: 'Вердикт адреса в запуске A и в запуске B.',
|
||||||
|
3: 'Сколько egress-проверок адреса успешно из всех записанных в последнем цикле: в A → в B.',
|
||||||
|
4: 'Сколько ingress-проверок адреса успешно из всех записанных в последнем цикле: в A → в B.',
|
||||||
|
5: 'Что изменилось между запусками, по шагам: вердикт, вход в индикатор и выход из него, проваленные цели https и площадки ssh, валидатор. У адреса без изменений в индикаторах — «без изменений», даже если набор проваленных целей другой.'
|
||||||
|
};
|
||||||
|
|
||||||
|
function describe(f) {
|
||||||
|
var g = GROUP[f.group], ind = f.ind ? '«' + (NAME[f.ind] || f.ind) + '»' : '';
|
||||||
|
var title = g[0] + (f.ind ? ': ' + (NAME[f.ind] || f.ind) : '') + (f.from ? ' · вердикт ' + f.from + ' → ' + f.to : '');
|
||||||
|
var note = g[1];
|
||||||
|
if (f.ind && f.group === 'new') note += ' Только входящие в индикатор ' + ind + ' в запуске B.';
|
||||||
|
if (f.ind && f.group === 'left') note += ' Только входившие в индикатор ' + ind + ' в запуске A.';
|
||||||
|
if (f.ind && (f.group === 'common' || f.group === 'changed' || f.group === 'same')) note += ' Только входящие в индикатор ' + ind + ' хотя бы в одном из запусков.';
|
||||||
|
if (f.from) note += ' Только адреса с вердиктом ' + f.from + ' в A и ' + f.to + ' в B.';
|
||||||
|
return { title: title, note: note, hints: f.group === 'new' || f.group === 'left' ? HINT_ONE : HINT_PAIR };
|
||||||
|
}
|
||||||
|
|
||||||
|
function listURL(root, f) {
|
||||||
|
return root + encodeURIComponent(f.group) + '?base=' + M.base.id + '&target=' + M.target.id +
|
||||||
|
(f.ind ? '&indicator=' + encodeURIComponent(f.ind) : '') +
|
||||||
|
(f.from ? '&from=' + encodeURIComponent(f.from) + '&to=' + encodeURIComponent(f.to) : '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function openList(f) {
|
||||||
|
var t = describe(f);
|
||||||
|
A.load(listURL(M.list_url, f), t.title).then(function (l) {
|
||||||
|
if (!l) return;
|
||||||
|
A.fill({
|
||||||
|
title: t.title, note: t.note, hints: t.hints, scope: 'Запуски', runLabel: 'A — ' + M.base.label + '; B — ' + M.target.label,
|
||||||
|
cols: l.columns, rows: l.rows, csvURL: listURL(M.csv_url, f)
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- the page ---- */
|
||||||
|
function renderNote() {
|
||||||
|
function line(name, m, r, cancelled) {
|
||||||
|
return '<div>' + esc(name + ': запуск ' + m.id + ', ' + m.kind + ', начало ' + m.start + ', завершён ' + m.end + ', длительность ' + m.duration +
|
||||||
|
', ' + fmt(r.addresses) + ' адр.' + (r.rechecked ? ', перепроверено внутри запуска: ' + fmt(r.rechecked) : '') +
|
||||||
|
(cancelled ? ', отменено (не участвуют в сравнении): ' + fmt(cancelled) : '') + '.') + '</div>';
|
||||||
|
}
|
||||||
|
$('an-cmp-note').innerHTML = line('A', M.base, R.runs.base, R.cancelled.base) + line('B', M.target, R.runs.target, R.cancelled.target);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderKpis() {
|
||||||
|
var GO = ' <span class="an-go">список →</span>';
|
||||||
|
var tiles = [
|
||||||
|
['Новые', G.new, 'есть в B, не было в A', 'new'],
|
||||||
|
['Выбывшие', G.left, 'были в A, нет в B', 'left'],
|
||||||
|
['Общие', G.common, 'есть в обоих запусках', 'common'],
|
||||||
|
['Изменились', G.changed, pct(G.changed, G.common) + '% общих адресов', 'changed'],
|
||||||
|
['Без изменений', G.same, pct(G.same, G.common) + '% общих адресов', 'same']
|
||||||
|
];
|
||||||
|
$('an-cmp-kpis').innerHTML = tiles.map(function (t) {
|
||||||
|
var inner = '<div class="an-k">' + t[0] + '</div><div class="an-v">' + fmt(t[1]) + '</div><div class="an-d">' + t[2] + (t[1] ? GO : '') + '</div>';
|
||||||
|
return t[1]
|
||||||
|
? '<button type="button" class="an-kpi" data-group="' + t[3] + '" aria-haspopup="dialog">' + inner + '</button>'
|
||||||
|
: '<div class="an-kpi">' + inner + '</div>';
|
||||||
|
}).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
/* a number that opens a list; zero is plain text */
|
||||||
|
function link(n, attrs, tip) {
|
||||||
|
return n ? '<button type="button" class="an-lnk" ' + attrs + ' ' + tipAttr(tip) + '>' + fmt(n) + '</button>' : '<span class="an-zero">0</span>';
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderIndicators() {
|
||||||
|
var COLS = [['new', 'Новые', 'новые адреса, входящие в индикатор'], ['left', 'Выбывшие', 'выбывшие адреса, входившие в индикатор'],
|
||||||
|
['entered', 'Вошли', 'общие адреса, вошедшие в индикатор'], ['exited', 'Вышли', 'общие адреса, вышедшие из индикатора']];
|
||||||
|
$('an-cmp-ind').innerHTML = '<thead><tr><th>Индикатор</th><th class="an-r">A</th><th class="an-r">B</th><th class="an-r">Δ</th>' +
|
||||||
|
COLS.map(function (c) { return '<th class="an-r">' + c[1] + '</th>'; }).join('') + '</tr></thead><tbody>' +
|
||||||
|
R.indicators.map(function (d) {
|
||||||
|
var good = d.key === 'verdict_pass' ? d.delta > 0 : d.delta < 0;
|
||||||
|
var delta = d.delta > 0 ? '+' + fmt(d.delta) : d.delta < 0 ? '−' + fmt(-d.delta) : '0';
|
||||||
|
return '<tr><td>' + esc(d.name) + '</td><td class="an-num an-r">' + fmt(d.base) + '</td><td class="an-num an-r">' + fmt(d.target) + '</td>' +
|
||||||
|
'<td class="an-num an-r' + (d.delta ? (good ? ' an-good' : ' an-bad') : '') + '">' + delta + '</td>' +
|
||||||
|
COLS.map(function (c) {
|
||||||
|
return '<td class="an-num an-r">' + link(d[c[0]], 'data-group="' + c[0] + '" data-ind="' + d.key + '"', d.name + ': ' + c[2]) + '</td>';
|
||||||
|
}).join('') + '</tr>';
|
||||||
|
}).join('') + '</tbody>';
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderTransitions() {
|
||||||
|
var V = T.verdicts;
|
||||||
|
$('an-cmp-tr').innerHTML = '<thead><tr><th></th>' + V.map(function (v) { return '<th class="an-r">B: ' + esc(v) + '</th>'; }).join('') + '<th class="an-r">нет в B</th></tr></thead><tbody>' +
|
||||||
|
V.map(function (from, i) {
|
||||||
|
return '<tr><td>A: ' + esc(from) + '</td>' + V.map(function (to, j) {
|
||||||
|
return '<td class="an-num an-r">' + link(T.matrix[i][j], 'data-group="common" data-from="' + from + '" data-to="' + to + '"', 'вердикт ' + from + ' в A → ' + to + ' в B') + '</td>';
|
||||||
|
}).join('') + '<td class="an-num an-r">' + link(T.left[i], 'data-group="left" data-ind="verdict_' + from + '"', 'выбыли, вердикт в A: ' + from) + '</td></tr>';
|
||||||
|
}).join('') +
|
||||||
|
'<tr><td>нет в A</td>' + V.map(function (to, j) {
|
||||||
|
return '<td class="an-num an-r">' + link(T.new[j], 'data-group="new" data-ind="verdict_' + to + '"', 'новые, вердикт в B: ' + to) + '</td>';
|
||||||
|
}).join('') + '<td class="an-num an-r">—</td></tr></tbody>';
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- wiring ---- */
|
||||||
|
function onOpen(e) {
|
||||||
|
var b = e.target.closest('[data-group]');
|
||||||
|
if (b) openList({ group: b.dataset.group, ind: b.dataset.ind || '', from: b.dataset.from || '', to: b.dataset.to || '' });
|
||||||
|
}
|
||||||
|
|
||||||
|
renderNote(); renderKpis(); renderIndicators(); renderTransitions();
|
||||||
|
['an-cmp-kpis', 'an-cmp-ind', 'an-cmp-tr'].forEach(function (id) { $(id).addEventListener('click', onOpen); });
|
||||||
|
})();
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
/* The address-list dialog of the analytics pages (markup: the "analytics_dialog"
|
||||||
|
template) and the tooltip that goes with it. A page loads a list with
|
||||||
|
AnalyticsDialog.load(url, title), then shows it with AnalyticsDialog.fill(m);
|
||||||
|
copying and the CSV download work on the list shown last. */
|
||||||
|
(function () {
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
function $(id) { return document.getElementById(id); }
|
||||||
|
function fmt(n) { return Math.round(n).toLocaleString('ru-RU'); }
|
||||||
|
function esc(s) {
|
||||||
|
return String(s).replace(/[&<>"']/g, function (c) {
|
||||||
|
return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function tipAttr(t) { return 'data-tip="' + esc(t) + '"'; }
|
||||||
|
|
||||||
|
var cur = null; // the list shown in the dialog
|
||||||
|
|
||||||
|
function csvText(cols, rows) {
|
||||||
|
function q(v) { return '"' + String(v).replace(/"/g, '""') + '"'; }
|
||||||
|
return [cols].concat(rows).map(function (r) { return r.map(q).join(','); }).join('\r\n') + '\r\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
function open() {
|
||||||
|
var d = $('an-dlg');
|
||||||
|
if (d.open) return;
|
||||||
|
if (d.showModal) d.showModal(); else d.setAttribute('open', '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/* m: title, note, scope ("Запуск" by default), runLabel, cols, rows, hints
|
||||||
|
(column index -> text), cellHints (column index -> function of the value),
|
||||||
|
dist (HTML above the table), csvURL (the file behind "Скачать CSV"). */
|
||||||
|
function fill(m) {
|
||||||
|
cur = m;
|
||||||
|
$('an-dlg-title').textContent = m.title + ' · ' + fmt(m.rows.length);
|
||||||
|
$('an-dlg-note').textContent = (m.scope || 'Запуск') + ': ' + m.runLabel + '. ' + m.note;
|
||||||
|
$('an-dlg-dist').hidden = !m.dist;
|
||||||
|
$('an-dlg-dist').innerHTML = m.dist || '';
|
||||||
|
var hint = m.hints || {};
|
||||||
|
$('an-dlg-tbl').innerHTML = '<thead><tr>' + m.cols.map(function (c, i) {
|
||||||
|
return hint[i] ? '<th ' + tipAttr(hint[i]) + ' tabindex="0">' + esc(c) + '<span class="an-hint" aria-hidden="true">ⓘ</span></th>' : '<th>' + esc(c) + '</th>';
|
||||||
|
}).join('') + '</tr></thead><tbody>' + m.rows.map(function (x) {
|
||||||
|
return '<tr>' + x.map(function (v, i) {
|
||||||
|
var h = m.cellHints && m.cellHints[i] ? m.cellHints[i](v) : '';
|
||||||
|
return '<td class="' + (i < 2 ? 'an-a' : '') + '"' + (h ? ' ' + tipAttr(h) : '') + '>' + esc(v) + '</td>';
|
||||||
|
}).join('') + '</tr>';
|
||||||
|
}).join('') + '</tbody>';
|
||||||
|
$('an-dlg-msg').textContent = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Opens the dialog with the title and "Загрузка…", fetches the list as JSON;
|
||||||
|
resolves with it, or with null (and a message in the dialog) on a failure. */
|
||||||
|
function load(url, title) {
|
||||||
|
$('an-dlg-title').textContent = title;
|
||||||
|
$('an-dlg-note').textContent = 'Загрузка…';
|
||||||
|
$('an-dlg-dist').hidden = true;
|
||||||
|
$('an-dlg-tbl').innerHTML = '';
|
||||||
|
$('an-dlg-msg').textContent = '';
|
||||||
|
cur = null;
|
||||||
|
open();
|
||||||
|
return fetch(url, { headers: { Accept: 'application/json' }, credentials: 'same-origin' })
|
||||||
|
.then(function (r) { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); })
|
||||||
|
.then(function (l) { return l; })
|
||||||
|
.catch(function (e) {
|
||||||
|
$('an-dlg-note').textContent = 'Не удалось загрузить список: ' + e.message;
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function copyCsv() {
|
||||||
|
var msg = $('an-dlg-msg');
|
||||||
|
if (!cur) return;
|
||||||
|
var text = csvText(cur.cols, cur.rows);
|
||||||
|
var done = function () { msg.textContent = 'CSV скопирован в буфер обмена.'; };
|
||||||
|
var fail = function () { msg.textContent = 'Буфер обмена недоступен в этом окне.'; };
|
||||||
|
if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(text).then(done, fail); else fail();
|
||||||
|
}
|
||||||
|
|
||||||
|
function downloadCsv() {
|
||||||
|
if (!cur) return;
|
||||||
|
window.location.href = cur.csvURL;
|
||||||
|
}
|
||||||
|
|
||||||
|
$('an-dlg-csv').addEventListener('click', downloadCsv);
|
||||||
|
$('an-dlg-copy').addEventListener('click', copyCsv);
|
||||||
|
$('an-dlg-close').addEventListener('click', function () { $('an-dlg').close(); });
|
||||||
|
$('an-dlg').addEventListener('click', function (e) { if (e.target === $('an-dlg')) $('an-dlg').close(); });
|
||||||
|
|
||||||
|
/* tooltip: moved into the open dialog, otherwise the modal's top layer covers it */
|
||||||
|
var tip = $('an-tip');
|
||||||
|
function tipHost() { var d = $('an-dlg'); return d && d.open ? d : document.body; }
|
||||||
|
document.addEventListener('mouseover', function (e) {
|
||||||
|
var t = e.target.closest('[data-tip]');
|
||||||
|
if (!t) return;
|
||||||
|
var h = tipHost();
|
||||||
|
if (tip.parentNode !== h) h.appendChild(tip);
|
||||||
|
tip.textContent = t.dataset.tip;
|
||||||
|
tip.style.opacity = 1;
|
||||||
|
});
|
||||||
|
document.addEventListener('mousemove', function (e) {
|
||||||
|
tip.style.left = Math.max(8, Math.min(e.clientX + 14, window.innerWidth - 376)) + 'px';
|
||||||
|
tip.style.top = (e.clientY + 16) + 'px';
|
||||||
|
});
|
||||||
|
document.addEventListener('mouseout', function (e) { if (e.target.closest('[data-tip]')) tip.style.opacity = 0; });
|
||||||
|
|
||||||
|
window.AnalyticsDialog = { $: $, fmt: fmt, esc: esc, tipAttr: tipAttr, load: load, fill: fill };
|
||||||
|
})();
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
/* Analytics page. Everything is prefixed an-; the dashboard's own tokens
|
||||||
|
(--surface, --border, --accent, ...) are used as they are. */
|
||||||
|
:root {
|
||||||
|
--an-radius: 4px;
|
||||||
|
--an-shadow: 0 1px 2px rgba(12,18,30,.06), 0 1px 1px rgba(12,18,30,.05);
|
||||||
|
--an-bar: #3987e5; --an-bar-track: #E4E9F0;
|
||||||
|
/* heat ramp: one blue hue, validated sequential steps (light = low) */
|
||||||
|
--an-h1:#cde2fb; --an-h2:#9ec5f4; --an-h3:#6da7ec; --an-h4:#3987e5; --an-h5:#256abf; --an-h6:#184f95; --an-h7:#0d366b;
|
||||||
|
--an-hi1:#12161F; --an-hi2:#12161F; --an-hi3:#12161F; --an-hi4:#FFFFFF; --an-hi5:#FFFFFF; --an-hi6:#FFFFFF; --an-hi7:#FFFFFF;
|
||||||
|
}
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root:not([data-theme="light"]) {
|
||||||
|
--an-shadow: 0 1px 2px rgba(0,0,0,.4);
|
||||||
|
--an-bar: #5C8CFF; --an-bar-track: #1D2430;
|
||||||
|
--an-h1:#0d366b; --an-h2:#104281; --an-h3:#184f95; --an-h4:#256abf; --an-h5:#3987e5; --an-h6:#6da7ec; --an-h7:#9ec5f4;
|
||||||
|
--an-hi1:#B8C9E8; --an-hi2:#C3D6F5; --an-hi3:#E7ECF5; --an-hi4:#FFFFFF; --an-hi5:#0A0D13; --an-hi6:#0A0D13; --an-hi7:#0A0D13;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
:root[data-theme="dark"] {
|
||||||
|
--an-shadow: 0 1px 2px rgba(0,0,0,.4);
|
||||||
|
--an-bar: #5C8CFF; --an-bar-track: #1D2430;
|
||||||
|
--an-h1:#0d366b; --an-h2:#104281; --an-h3:#184f95; --an-h4:#256abf; --an-h5:#3987e5; --an-h6:#6da7ec; --an-h7:#9ec5f4;
|
||||||
|
--an-hi1:#B8C9E8; --an-hi2:#C3D6F5; --an-hi3:#E7ECF5; --an-hi4:#FFFFFF; --an-hi5:#0A0D13; --an-hi6:#0A0D13; --an-hi7:#0A0D13;
|
||||||
|
}
|
||||||
|
|
||||||
|
.an { display: grid; gap: 16px; align-content: start; min-width: 0; font-family: var(--font-ui); font-size: 14px; line-height: 1.5; }
|
||||||
|
.an * { box-sizing: border-box; }
|
||||||
|
.an-title { font: 700 18px var(--font-mono); margin: 0; }
|
||||||
|
.an h2 { font: 700 12px var(--font-mono); text-transform: uppercase; letter-spacing: .06em; color: var(--text-muted); margin: 0; }
|
||||||
|
.an-sub { color: var(--text-muted); font-size: 12.5px; margin: 0; }
|
||||||
|
.an-panel { background: var(--surface); border: 1px solid var(--border); border-radius: var(--an-radius); box-shadow: var(--an-shadow); padding: 14px 16px; display: grid; gap: 12px; min-width: 0; align-content: start; }
|
||||||
|
.an-panel > * { min-width: 0; }
|
||||||
|
.an-head { display: flex; flex-wrap: wrap; gap: 6px 12px; align-items: baseline; justify-content: space-between; }
|
||||||
|
.an-runbar { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }
|
||||||
|
.an-runbar label { font: 700 12px var(--font-mono); color: var(--text-muted); text-transform: uppercase; letter-spacing: .06em; }
|
||||||
|
.an select, .an .an-btn { font: 500 13px var(--font-mono); background: var(--surface); color: var(--text); border: 1px solid var(--border); border-radius: var(--an-radius); padding: 7px 10px; }
|
||||||
|
.an select { min-width: 0; max-width: 100%; flex: 1 1 160px; }
|
||||||
|
.an-btn { cursor: pointer; } .an-btn:hover { background: var(--surface-alt); }
|
||||||
|
.an-tabs { display: inline-flex; gap: 0; }
|
||||||
|
.an-tabs button { font: 500 12px var(--font-mono); background: var(--surface); color: var(--text-muted); border: 1px solid var(--border); padding: 5px 12px; cursor: pointer; }
|
||||||
|
.an-tabs button + button { border-left: 0; }
|
||||||
|
.an-tabs button:first-child { border-radius: var(--an-radius) 0 0 var(--an-radius); } .an-tabs button:last-child { border-radius: 0 var(--an-radius) var(--an-radius) 0; }
|
||||||
|
.an-tabs button[aria-pressed="true"] { background: var(--accent-soft); color: var(--accent-strong); border-color: var(--accent); }
|
||||||
|
.an-kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(168px, 1fr)); gap: 12px; }
|
||||||
|
.an-kpi { background: var(--surface); border: 1px solid var(--border); border-radius: var(--an-radius); padding: 12px 14px; display: grid; gap: 2px; box-shadow: var(--an-shadow); }
|
||||||
|
.an-kpi .an-k { font: 700 11px var(--font-mono); text-transform: uppercase; letter-spacing: .06em; color: var(--text-muted); }
|
||||||
|
.an-kpi .an-v { font: 700 26px var(--font-mono); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||||
|
.an-kpi .an-d { font-size: 12px; color: var(--text-muted); }
|
||||||
|
.an-tag { display: inline-flex; align-items: center; gap: 5px; font: 700 10.5px var(--font-mono); text-transform: uppercase; letter-spacing: .03em; padding: 2px 7px; border-radius: 2px; }
|
||||||
|
.an-tag::before { content: ""; width: 5px; height: 5px; background: currentColor; border-radius: 1px; }
|
||||||
|
.an-t-ok { background: var(--success-soft); color: var(--success); } .an-t-warn { background: var(--warning-soft); color: var(--warning); } .an-t-bad { background: var(--danger-soft); color: var(--danger); } .an-t-n { background: var(--neutral-soft); color: var(--neutral); }
|
||||||
|
.an-cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 420px), 1fr)); gap: 16px; }
|
||||||
|
.an-rows { display: grid; gap: 7px; }
|
||||||
|
.an-bar-row { display: grid; grid-template-columns: minmax(110px, 38%) minmax(0,1fr) auto; gap: 10px; align-items: center; font-size: 13px; }
|
||||||
|
.an-bar-row .an-n { overflow-wrap: anywhere; }
|
||||||
|
.an-track { height: 12px; background: var(--an-bar-track); border-radius: 2px; position: relative; }
|
||||||
|
.an-fill { height: 100%; background: var(--an-bar); border-radius: 0 4px 4px 0; }
|
||||||
|
.an-num { font: 500 12.5px var(--font-mono); font-variant-numeric: tabular-nums; text-align: right; white-space: nowrap; }
|
||||||
|
.an-scroll { overflow-x: auto; }
|
||||||
|
.an table { border-collapse: collapse; width: 100%; font-size: 13px; }
|
||||||
|
.an th .an-hint { cursor: help; color: var(--accent-strong); margin-left: 3px; }
|
||||||
|
.an th { font: 700 11px var(--font-mono); text-transform: uppercase; letter-spacing: .05em; color: var(--text-muted); text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--border); white-space: nowrap; }
|
||||||
|
.an th.an-r, .an td.an-r { text-align: right; }
|
||||||
|
.an td { padding: 6px 8px; border-bottom: 1px solid var(--border-soft); vertical-align: middle; }
|
||||||
|
.an td.an-a { font-family: var(--font-mono); font-size: 12.5px; white-space: nowrap; }
|
||||||
|
.an td.an-a a { color: var(--accent-strong); text-decoration: none; } td.an-a a:hover { text-decoration: underline; }
|
||||||
|
.an-pb { display: grid; grid-template-columns: 70px 40px; gap: 6px; align-items: center; justify-content: end; }
|
||||||
|
.an-pb .an-track { height: 8px; }
|
||||||
|
.an-heat td.an-c { padding: 2px; }
|
||||||
|
.an-cell { display: block; min-width: 76px; text-align: center; font: 500 12px var(--font-mono); font-variant-numeric: tabular-nums; padding: 7px 4px; border-radius: 2px; cursor: default; }
|
||||||
|
.an-h1{background:var(--an-h1);color:var(--an-hi1)} .an-h2{background:var(--an-h2);color:var(--an-hi2)} .an-h3{background:var(--an-h3);color:var(--an-hi3)} .an-h4{background:var(--an-h4);color:var(--an-hi4)} .an-h5{background:var(--an-h5);color:var(--an-hi5)} .an-h6{background:var(--an-h6);color:var(--an-hi6)} .an-h7{background:var(--an-h7);color:var(--an-hi7)}
|
||||||
|
.an-legend { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; font-size: 12px; color: var(--text-muted); }
|
||||||
|
.an-legend i { display: inline-block; width: 28px; height: 10px; border-radius: 2px; }
|
||||||
|
.an-vals { display: flex; align-items: flex-end; gap: 4px; height: 120px; border-bottom: 1px solid var(--border); position: relative; }
|
||||||
|
.an-vals .an-col { flex: 1 1 0; min-width: 0; background: var(--an-bar); border-radius: 3px 3px 0 0; }
|
||||||
|
.an-vals .an-avg { position: absolute; left: 0; right: 0; border-top: 1px dashed var(--text-muted); }
|
||||||
|
.an-vlab { display: flex; justify-content: space-between; font: 500 11px var(--font-mono); color: var(--text-faint); }
|
||||||
|
.an-dq { display: grid; gap: 8px; }
|
||||||
|
.an-dq .an-row { display: flex; gap: 10px; justify-content: space-between; align-items: baseline; border-bottom: 1px solid var(--border-soft); padding-bottom: 6px; font-size: 13px; }
|
||||||
|
.an-dq .an-row span:last-child { font: 700 13px var(--font-mono); white-space: nowrap; }
|
||||||
|
.an-note { font-size: 12px; color: var(--text-muted); }
|
||||||
|
button.an-kpi { font: inherit; color: inherit; text-align: left; cursor: pointer; width: 100%; }
|
||||||
|
button.an-kpi:hover { border-color: var(--accent); }
|
||||||
|
button.an-kpi:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||||
|
.an-kpi .an-go { font: 700 11px var(--font-mono); color: var(--accent-strong); }
|
||||||
|
.an dialog { width: min(760px, calc(100% - 32px)); max-height: calc(100vh - 32px); max-height: calc(100dvh - 32px); padding: 0; overflow: hidden; border: 1px solid var(--border); border-radius: 6px; background: var(--surface); color: var(--text); box-shadow: 0 16px 40px rgba(0,0,0,.35); }
|
||||||
|
.an dialog[open] { display: flex; flex-direction: column; }
|
||||||
|
.an dialog::backdrop { background: rgba(10,14,20,.5); }
|
||||||
|
.an-dlg { display: flex; flex-direction: column; gap: 12px; padding: 16px; min-height: 0; flex: 1 1 auto; max-height: calc(100vh - 34px); max-height: calc(100dvh - 34px); }
|
||||||
|
.an-dlg h3 { font: 700 15px var(--font-mono); margin: 0; overflow-wrap: anywhere; flex: 0 0 auto; }
|
||||||
|
.an-dlg .an-note { flex: 0 0 auto; max-height: 6.5em; overflow: auto; margin: 0; }
|
||||||
|
.an-dlg .an-dist { flex: 0 0 auto; }
|
||||||
|
.an-dlg .an-list { flex: 0 1 auto; min-height: 96px; overflow: auto; border: 1px solid var(--border-soft); border-radius: var(--an-radius); }
|
||||||
|
.an-dlg table { font-size: 12.5px; } .an-dlg th { position: sticky; top: 0; background: var(--surface); }
|
||||||
|
.an-dlg .an-foot { flex: 0 0 auto; display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; padding-top: 4px; border-top: 1px solid var(--border-soft); }
|
||||||
|
.an-dlg .an-foot .an-acts { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||||
|
@media (max-width: 520px) { .an-dlg { padding: 12px; gap: 10px; } .an-dlg .an-foot .an-acts { width: 100%; } .an-dlg .an-foot .an-acts .an-btn { flex: 1 1 auto; } }
|
||||||
|
@media (max-height: 540px) { .an-dlg .an-dist { display: none; } }
|
||||||
|
@media (max-height: 640px) { .an-dist .an-cols20 { height: 44px; } .an-dlg .an-note { max-height: 3em; } .an-dlg .an-dist .an-chips { display: none; } }
|
||||||
|
.an-btn.an-primary { background: var(--accent); color: #fff; border-color: var(--accent); }
|
||||||
|
.an-btn.an-primary:hover { background: var(--accent-strong); }
|
||||||
|
button.an-bar-row { font: inherit; color: inherit; text-align: left; width: 100%; background: none; border: 0; border-radius: var(--an-radius); padding: 3px 4px; margin: -3px -4px; cursor: pointer; }
|
||||||
|
button.an-bar-row:hover { background: var(--surface-alt); }
|
||||||
|
button.an-bar-row:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
|
||||||
|
.an-dist { display: grid; gap: 8px; }
|
||||||
|
.an-dist .an-chips { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||||
|
.an-dist .an-cols20 { display: grid; grid-template-columns: repeat(20, minmax(0, 1fr)); gap: 3px; align-items: end; height: 84px; border-bottom: 1px solid var(--border); }
|
||||||
|
.an-dist .an-cols20 div { background: var(--an-bar); border-radius: 2px 2px 0 0; min-height: 1px; }
|
||||||
|
.an-dist .an-lab20 { display: grid; grid-template-columns: repeat(20, minmax(0, 1fr)); gap: 3px; font: 500 9.5px var(--font-mono); color: var(--text-faint); text-align: center; }
|
||||||
|
/* comparison of two runs: a number that opens a list, and the delta colours */
|
||||||
|
.an button.an-lnk { font: 500 12.5px var(--font-mono); font-variant-numeric: tabular-nums; color: var(--accent-strong); background: none; border: 0; border-bottom: 1px dashed var(--accent); padding: 0 2px; cursor: pointer; }
|
||||||
|
.an button.an-lnk:hover { background: var(--surface-alt); }
|
||||||
|
.an button.an-lnk:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||||
|
.an-zero { color: var(--text-faint); font: 500 12.5px var(--font-mono); }
|
||||||
|
.an td.an-good { color: var(--success); font-weight: 700; } .an td.an-bad { color: var(--danger); font-weight: 700; }
|
||||||
|
#an-tip { position: fixed; z-index: 10; pointer-events: none; background: var(--text); color: var(--bg); font: 500 12px/1.4 var(--font-mono); padding: 6px 9px; border-radius: 4px; max-width: min(360px, calc(100vw - 24px)); white-space: normal; opacity: 0; transition: opacity .08s; }
|
||||||
|
@media (prefers-reduced-motion: reduce) { #an-tip { transition: none; } }
|
||||||
|
|
||||||
|
/* dashboard.css turns every table into stacked cards on a phone; the tables on
|
||||||
|
this page are data tables and scroll sideways instead. */
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.an-kpi .an-v { font-size: 22px; }
|
||||||
|
.an thead { display: table-header-group; }
|
||||||
|
.an table { display: table; width: 100%; }
|
||||||
|
.an tbody { display: table-row-group; width: auto; }
|
||||||
|
.an tr, .an tbody tr { display: table-row; width: auto; padding: 0; border-bottom: 0; }
|
||||||
|
.an td { display: table-cell; width: auto; padding: 6px 8px; border-bottom: 1px solid var(--border-soft); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
/* Analytics page: renders the report of one finished run (embedded as JSON in
|
||||||
|
#analytics-data) and opens the address lists behind the indicators and the
|
||||||
|
error classes in the shared dialog (analytics-dialog.js). No other run's data
|
||||||
|
is on the page. */
|
||||||
|
(function () {
|
||||||
|
'use strict';
|
||||||
|
var D = JSON.parse(document.getElementById('analytics-data').textContent);
|
||||||
|
var R = D.report, M = D.meta, S = R.summary, Q = R.quality;
|
||||||
|
|
||||||
|
var A = window.AnalyticsDialog, $ = A.$, fmt = A.fmt, esc = A.esc, tipAttr = A.tipAttr;
|
||||||
|
function pct(a, b) { return b ? Math.round(a / b * 100) : 0; }
|
||||||
|
function pct1(a, b) { return b ? (a / b * 100).toLocaleString('ru-RU', { maximumFractionDigits: 1 }) : '0'; }
|
||||||
|
function vnum(id) { var m = /(\d+)$/.exec(id); return m ? +m[1] : null; }
|
||||||
|
function vshort(id) { var n = vnum(id); return n === null ? id : 'v' + n; }
|
||||||
|
|
||||||
|
var state = { sort: 'worst', all: false, type: R.targets.types.indexOf('https') >= 0 ? 'https' : (R.targets.types[0] || '') };
|
||||||
|
|
||||||
|
/* ---- indicators ---- */
|
||||||
|
function renderKpis() {
|
||||||
|
var late = Q.late_failed_checks_at_pass, GO = ' <span class="an-go">список →</span>';
|
||||||
|
var tiles = [
|
||||||
|
['Адресов', fmt(S.addresses), 'последний цикл каждого адреса', '', ''],
|
||||||
|
['pass', fmt(S.pass), pct(S.pass, S.addresses) + '% адресов', '<span class="an-tag an-t-ok">успех</span>' + GO, 'verdict_pass'],
|
||||||
|
['partial', fmt(S.partial), pct(S.partial, S.addresses) + '% адресов', '<span class="an-tag an-t-warn">частично</span>' + GO, 'verdict_partial'],
|
||||||
|
['fail', fmt(S.fail), S.fail ? pct(S.fail, S.addresses) + '% адресов' : 'ни одной полностью проваленной',
|
||||||
|
S.fail ? '<span class="an-tag an-t-bad">провал</span>' + GO : '<span class="an-tag an-t-n">нет</span>', S.fail ? 'verdict_fail' : ''],
|
||||||
|
['Egress OK', pct1(S.egress_ok, S.addresses) + '%', 'все egress-проверки адреса успешны', '', ''],
|
||||||
|
['Ingress OK', pct1(S.ingress_ok, S.addresses) + '%', 'все ingress-проверки адреса успешны', '', ''],
|
||||||
|
['Egress https: есть провалы', fmt(S.egress_https_any_failed), pct1(S.egress_https_any_failed, S.addresses) + '% адресов, хотя бы одна цель недоступна',
|
||||||
|
'<span class="an-tag an-t-warn">прикладной</span> <span class="an-go">список →</span>', 'egress_https_any'],
|
||||||
|
['Ingress ssh: есть провалы', fmt(S.ingress_ssh_any_failed), pct1(S.ingress_ssh_any_failed, S.addresses) + '% адресов, хотя бы с одной площадки',
|
||||||
|
'<span class="an-tag an-t-warn">прикладной</span> <span class="an-go">список →</span>', 'ingress_ssh_any'],
|
||||||
|
['Egress https: все провалены', fmt(S.egress_https_all_failed), pct1(S.egress_https_all_failed, S.addresses) + '% адресов, по всем целям: ' + fmt(S.egress_https_all_targets_failed),
|
||||||
|
'<span class="an-tag an-t-bad">прикладной</span> <span class="an-go">список →</span>', 'egress_https_all'],
|
||||||
|
['Ingress ssh: все провалены', fmt(S.ingress_ssh_all_failed), pct1(S.ingress_ssh_all_failed, S.addresses) + '% адресов, ssh провален со всех площадок',
|
||||||
|
'<span class="an-tag an-t-bad">прикладной</span> <span class="an-go">список →</span>', 'ingress_ssh_all'],
|
||||||
|
['Длительность', esc(M.duration), fmt(S.addresses_per_minute) + ' адр./мин', '', ''],
|
||||||
|
['Поздние результаты', fmt(late), 'у ' + fmt(Q.late_failed_addresses_at_pass) + ' адресов, после вердикта',
|
||||||
|
late ? '<span class="an-tag an-t-warn">внимание</span>' : '<span class="an-tag an-t-ok">в норме</span>', '']
|
||||||
|
];
|
||||||
|
$('an-kpis').innerHTML = tiles.map(function (t) {
|
||||||
|
var inner = '<div class="an-k">' + t[0] + '</div><div class="an-v">' + t[1] + '</div><div class="an-d">' + t[2] + ' ' + t[3] + '</div>';
|
||||||
|
return t[4]
|
||||||
|
? '<button type="button" class="an-kpi" data-list="' + t[4] + '" aria-haspopup="dialog">' + inner + '</button>'
|
||||||
|
: '<div class="an-kpi">' + inner + '</div>';
|
||||||
|
}).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
function bar(v, max) {
|
||||||
|
return '<div class="an-track"><div class="an-fill" style="width:' + (max ? Math.max(1, v / max * 100) : 0) + '%"></div></div>';
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderReasons() {
|
||||||
|
var max = Math.max.apply(null, R.reasons.map(function (x) { return x.count; }).concat([1]));
|
||||||
|
$('an-reasons').innerHTML = R.reasons.map(function (x) {
|
||||||
|
return '<div class="an-bar-row" ' + tipAttr(x.name + ': ' + fmt(x.count) + ' адр. (' + pct(x.count, S.partial) + '% от partial)') + '><span class="an-n">' + esc(x.name) + '</span>' + bar(x.count, max) + '<span class="an-num">' + fmt(x.count) + '</span></div>';
|
||||||
|
}).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderQuality() {
|
||||||
|
var errTotal = Q.ingress_failed_checks;
|
||||||
|
var rows = [
|
||||||
|
['Поздние провалы у адресов с вердиктом pass', fmt(Q.late_failed_checks_at_pass) + ' / ' + fmt(Q.late_failed_addresses_at_pass) + ' адр.'],
|
||||||
|
['Провалы ingress, пришедшие после вердикта', fmt(Q.ingress_failed_late) + ' из ' + fmt(errTotal)],
|
||||||
|
['Неполный набор проверок', fmt(Q.incomplete_addresses) + ' адр.'],
|
||||||
|
['Вердикт pass, но есть проваленные проверки', fmt(Q.pass_with_failed_addresses) + ' адр.'],
|
||||||
|
['pass по вердикту → по фактическим проверкам', fmt(S.pass) + ' → ' + fmt(Q.pass_by_facts)]
|
||||||
|
];
|
||||||
|
$('an-dq').innerHTML = rows.map(function (r) { return '<div class="an-row"><span>' + r[0] + '</span><span>' + r[1] + '</span></div>'; }).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
function pbar(a, n) {
|
||||||
|
var p = pct(a, n);
|
||||||
|
return '<div class="an-pb"><div class="an-track"><div class="an-fill" style="width:' + p + '%"></div></div><span class="an-num">' + p + '%</span></div>';
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderSubnets() {
|
||||||
|
var list = R.subnets.slice();
|
||||||
|
list.sort(state.sort === 'worst'
|
||||||
|
? function (a, b) { return a.pass / a.addresses - b.pass / b.addresses || b.addresses - a.addresses; }
|
||||||
|
: function (a, b) { return b.addresses - a.addresses; });
|
||||||
|
var shown = state.all ? list : list.slice(0, 10);
|
||||||
|
$('an-allsub').textContent = state.all ? 'свернуть до 10' : 'показать все ' + list.length;
|
||||||
|
$('an-allsub').hidden = list.length <= 10;
|
||||||
|
$('an-subtbl').innerHTML = '<thead><tr><th>Подсеть</th><th class="an-r">Адресов</th><th class="an-r">pass</th><th class="an-r">Egress OK</th><th class="an-r">Ingress OK</th></tr></thead><tbody>' +
|
||||||
|
shown.map(function (s) {
|
||||||
|
var name = s.label ? s.cidr + ' · ' + s.label : s.cidr;
|
||||||
|
var link = s.cidr === 'прочие' ? esc(name) : '<a href="' + M.registry_url + '&subnet=' + encodeURIComponent(s.cidr) + '" title="Открыть в реестре: запуск ' + M.run_id + ', подсеть ' + esc(s.cidr) + '">' + esc(name) + '</a>';
|
||||||
|
return '<tr><td class="an-a">' + link + '</td><td class="an-num an-r">' + fmt(s.addresses) + '</td>' +
|
||||||
|
'<td class="an-r" ' + tipAttr(s.cidr + ': pass ' + fmt(s.pass) + ' из ' + fmt(s.addresses)) + '>' + pbar(s.pass, s.addresses) + '</td>' +
|
||||||
|
'<td class="an-r" ' + tipAttr(s.cidr + ': egress OK ' + fmt(s.egress_ok) + ' из ' + fmt(s.addresses)) + '>' + pbar(s.egress_ok, s.addresses) + '</td>' +
|
||||||
|
'<td class="an-r" ' + tipAttr(s.cidr + ': ingress OK ' + fmt(s.ingress_ok) + ' из ' + fmt(s.addresses)) + '>' + pbar(s.ingress_ok, s.addresses) + '</td></tr>';
|
||||||
|
}).join('') + '</tbody>';
|
||||||
|
}
|
||||||
|
|
||||||
|
function heatClass(v) { return 'an-h' + (v >= 90 ? 7 : v >= 75 ? 6 : v >= 60 ? 5 : v >= 45 ? 4 : v >= 30 ? 3 : v >= 15 ? 2 : 1); }
|
||||||
|
|
||||||
|
function renderTypes() {
|
||||||
|
$('an-types').innerHTML = R.targets.types.map(function (t) {
|
||||||
|
return '<button type="button" data-type="' + esc(t) + '" aria-pressed="' + (t === state.type) + '">' + esc(t) + '</button>';
|
||||||
|
}).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderTargets() {
|
||||||
|
var t = state.type, T = R.targets, vals = T.failed[t] || [];
|
||||||
|
var max = Math.max.apply(null, vals.concat([1]));
|
||||||
|
$('an-targets').innerHTML = T.targets.map(function (n, i) {
|
||||||
|
return '<div class="an-bar-row" ' + tipAttr(n + ' · ' + t + ': провал у ' + fmt(vals[i]) + ' адр. (' + pct(vals[i], S.addresses) + '% всех)') + '><span class="an-n">' + esc(n) + '</span>' + bar(vals[i], max) + '<span class="an-num">' + fmt(vals[i]) + ' · ' + pct(vals[i], S.addresses) + '%</span></div>';
|
||||||
|
}).join('');
|
||||||
|
var rows = (R.matrix[t] || []).slice(0, state.all ? 100000 : 10);
|
||||||
|
$('an-matrixwrap').hidden = !rows.length;
|
||||||
|
$('an-hlegend').innerHTML = ['0–14', '15–29', '30–44', '45–59', '60–74', '75–89', '90–100'].map(function (l, i) {
|
||||||
|
return '<span><i style="background:var(--an-h' + (i + 1) + ')"></i> ' + l + '%</span>';
|
||||||
|
}).join('');
|
||||||
|
$('an-matrix').innerHTML = '<thead><tr><th>Подсеть</th><th class="an-r">partial</th>' + T.targets.map(function (x) {
|
||||||
|
return '<th class="an-r">' + esc(x.replace('.com', '').replace('.org', '')) + '</th>';
|
||||||
|
}).join('') + '</tr></thead><tbody>' + rows.map(function (m) {
|
||||||
|
var link = m.cidr === 'прочие' ? esc(m.cidr) : '<a href="' + M.registry_url + '&subnet=' + encodeURIComponent(m.cidr) + '" title="Открыть адреса в реестре">' + esc(m.cidr) + '</a>';
|
||||||
|
return '<tr><td class="an-a">' + link + '</td><td class="an-num an-r">' + fmt(m.partial) + '</td>' + m.percent.map(function (v, j) {
|
||||||
|
return '<td class="an-c"><span class="an-cell ' + heatClass(v) + '" ' + tipAttr(m.cidr + ' → ' + T.targets[j] + ': ' + v + '% адресов partial провалили ' + t) + '>' + v + '%</span></td>';
|
||||||
|
}).join('') + '</tr>';
|
||||||
|
}).join('') + '</tbody>';
|
||||||
|
$('an-matrixnote').textContent = 'Доля адресов partial подсети, провалившие ' + t + ' к цели. Строки — подсети с наибольшим числом partial; полный список включается кнопкой «показать все» выше.';
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderSites() {
|
||||||
|
var T = R.sites;
|
||||||
|
$('an-sites').innerHTML = '<thead><tr><th>Площадка</th>' + T.types.map(function (t) { return '<th class="an-r">' + esc(t) + '</th>'; }).join('') + '</tr></thead><tbody>' +
|
||||||
|
T.rows.map(function (row) {
|
||||||
|
return '<tr><td class="an-a">' + esc(row.site) + '</td>' + row.stats.map(function (st, i) {
|
||||||
|
return '<td class="an-r" ' + tipAttr(row.site + ' · ' + T.types[i] + ': успешно ' + fmt(st.ok) + ' из ' + fmt(st.total)) + '><span class="an-num">' + pct1(st.total - st.ok, st.total) + '%</span> <span class="an-note">провал</span></td>';
|
||||||
|
}).join('') + '</tr>';
|
||||||
|
}).join('') + '</tbody>';
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderErrors() {
|
||||||
|
var max = Math.max.apply(null, R.errors.map(function (e) { return e.count; }).concat([1]));
|
||||||
|
$('an-errs').innerHTML = R.errors.length ? R.errors.map(function (e) {
|
||||||
|
return '<button type="button" class="an-bar-row" data-cls="' + esc(e.name) + '" aria-haspopup="dialog" ' + tipAttr(e.name + ': ' + fmt(e.count) + ' проверок. Нажмите, чтобы открыть список') + '><span class="an-n">' + esc(e.name) + '</span>' + bar(e.count, max) + '<span class="an-num">' + fmt(e.count) + '</span></button>';
|
||||||
|
}).join('') : '<p class="an-note">Проваленных ingress-проверок нет.</p>';
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderValidators() {
|
||||||
|
var V = R.validators;
|
||||||
|
var f = V.map(function (v) { return v.total ? 1 - v.ok / v.total : 0; });
|
||||||
|
var avg = f.length ? f.reduce(function (a, b) { return a + b; }, 0) / f.length : 0;
|
||||||
|
$('an-vals').innerHTML = f.map(function (x, i) {
|
||||||
|
return '<div class="an-col" style="height:' + (x * 100) + '%" ' + tipAttr(vshort(V[i].validator) + ': провал ' + Math.round(x * 100) + '% из ' + fmt(V[i].total) + ' https-проверок') + '></div>';
|
||||||
|
}).join('') + '<div class="an-avg" style="bottom:' + (avg * 100) + '%"></div>';
|
||||||
|
$('an-vfirst').textContent = V.length ? 'валидатор ' + vshort(V[0].validator) : '';
|
||||||
|
$('an-vlast').textContent = V.length > 1 ? 'валидатор ' + vshort(V[V.length - 1].validator) : '';
|
||||||
|
$('an-vavg').textContent = V.length ? 'среднее ' + Math.round(avg * 100) + '% (шкала 0–100%)' : 'нет данных';
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- address lists in the dialog ---- */
|
||||||
|
var VERDICT_HINT = 'Итог всего адреса за цикл, который система выставила при агрегации. pass: все проверки (egress и ingress), полученные к этому моменту, успешны. partial: часть проверок провалена или результатов не хватает. fail: все проверки провалены. Это оценка адреса, а не этой проверки.';
|
||||||
|
var STATUS_HINT = 'Состояние именно этой проверки (она всегда проваленная). «в вердикте»: результат пришёл до того, как система выставила вердикт адресу, и повлиял на него. «после вердикта»: результат пришёл позже, вердикт уже был выставлен и не пересчитывался. Поэтому у адреса с вердиктом pass может быть проваленная проверка.';
|
||||||
|
var VERDICT_VAL = {
|
||||||
|
pass: 'pass: к моменту вердикта все полученные проверки адреса были успешны. Эта проверка провалилась позже и в вердикт не вошла.',
|
||||||
|
partial: 'partial: часть проверок адреса провалена или результатов не хватило, вердикт не pass.',
|
||||||
|
fail: 'fail: все проверки адреса провалены.'
|
||||||
|
};
|
||||||
|
function statusVal(v) { return String(v).indexOf('после') >= 0 ? 'Результат пришёл после вердикта адреса и в него не вошёл.' : 'Результат пришёл до вердикта и учтён в нём.'; }
|
||||||
|
|
||||||
|
var VERDICT_NOTE = ' Это вердикт адреса, который система выставила при агрегации, а не итог всех проверок: после него могли прийти ещё результаты, поэтому у адреса pass бывают проваленные проверки. Столбцы Egress и Ingress показывают фактические проверки адреса.';
|
||||||
|
var VERDICT_HINTS = {
|
||||||
|
2: 'Валидатор, с которого шли egress-проверки адреса. «—» — у адреса нет https-проверок.',
|
||||||
|
3: 'Сколько egress-проверок адреса успешно из всех записанных в цикле. «—» — egress-проверок нет.',
|
||||||
|
4: 'Сколько ingress-проверок адреса успешно из всех записанных в цикле (со всех площадок и всех типов). «—» — ingress-проверок нет.',
|
||||||
|
5: 'Сколько проверок записано в цикле из ожидаемых. Меньше ожидаемого значит, что часть результатов не пришла (неполный набор). Если ожидаемое число неизвестно, показано только записанное.'
|
||||||
|
};
|
||||||
|
function verdictList(title, note, reason) {
|
||||||
|
var hints = {};
|
||||||
|
Object.keys(VERDICT_HINTS).forEach(function (k) { hints[k] = VERDICT_HINTS[k]; });
|
||||||
|
if (reason) hints[6] = 'Что не так у адреса: провалены egress-проверки, ingress-проверки или не хватает результатов (неполный набор). Те же названия, что в блоке «Почему partial».';
|
||||||
|
return { title: title, note: note + VERDICT_NOTE, hints: hints };
|
||||||
|
}
|
||||||
|
|
||||||
|
var LISTS = {
|
||||||
|
verdict_pass: verdictList('Адреса с вердиктом pass',
|
||||||
|
'Вердикт pass: адрес за последний цикл запуска получил успех по всем проверкам, полученным к моменту агрегации.'),
|
||||||
|
verdict_partial: verdictList('Адреса с вердиктом partial',
|
||||||
|
'Вердикт partial: часть проверок адреса провалена или результатов не хватило.', true),
|
||||||
|
verdict_fail: verdictList('Адреса с вердиктом fail',
|
||||||
|
'Вердикт fail: все проверки адреса провалены.'),
|
||||||
|
egress_https_any: {
|
||||||
|
title: 'Egress https: адреса с проваленными проверками',
|
||||||
|
note: 'Хотя бы одна egress-проверка https адреса провалена в последнем цикле запуска.',
|
||||||
|
hints: { 2: 'Валидатор, с которого шли egress-проверки адреса.', 3: 'Сколько https-проверок адреса провалено из всех записанных в цикле.' }
|
||||||
|
},
|
||||||
|
ingress_ssh_any: {
|
||||||
|
title: 'Ingress ssh: адреса с проваленными проверками',
|
||||||
|
note: 'ssh провален хотя бы с одной площадки в последнем цикле запуска.',
|
||||||
|
hints: { 2: 'Сколько площадок не смогли выполнить ssh-проверку адреса из всех, где она выполнялась.', 3: 'Площадки пробера, с которых ssh-проверка адреса провалена.', 4: 'Класс ошибки: таймаут, баннер «Not allowed», нет маршрута.' }
|
||||||
|
},
|
||||||
|
egress_https_all: {
|
||||||
|
title: 'Egress https: адреса, провалившие все проверки',
|
||||||
|
note: 'Все записанные egress-проверки https адреса провалены в последнем цикле запуска.',
|
||||||
|
hints: { 2: 'Валидатор, с которого шли egress-проверки адреса.', 3: 'Сколько https-проверок записано у адреса в цикле. Все они провалены. Меньше полного набора значит, что часть результатов не пришла.' }
|
||||||
|
},
|
||||||
|
ingress_ssh_all: {
|
||||||
|
title: 'Ingress ssh: адреса, провалившие все проверки',
|
||||||
|
note: 'ssh провален со всех площадок, на которых он проверялся, в последнем цикле запуска.',
|
||||||
|
hints: { 2: 'Площадки пробера, с которых ssh-проверка адреса провалена.', 3: 'Класс ошибки ssh-проверки: таймаут, баннер «Not allowed», нет маршрута.' }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
function listURL(base, kind, cls) {
|
||||||
|
return base + encodeURIComponent(kind) + '?run=' + M.run_id + (cls ? '&class=' + encodeURIComponent(cls) : '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadList(kind, cls, meta) { return A.load(listURL(M.list_url, kind, cls), meta.title); }
|
||||||
|
|
||||||
|
function runLabel() {
|
||||||
|
var o = document.getElementById('an-run');
|
||||||
|
return o && o.selectedOptions[0] ? o.selectedOptions[0].textContent : 'запуск ' + M.run_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
function openIndicator(kind) {
|
||||||
|
var meta = LISTS[kind];
|
||||||
|
loadList(kind, '', meta).then(function (l) {
|
||||||
|
if (!l) return;
|
||||||
|
A.fill({ title: meta.title, note: meta.note, hints: meta.hints, cols: l.columns, rows: l.rows, runLabel: runLabel(), csvURL: listURL(M.csv_url, kind, '') });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function openError(cls) {
|
||||||
|
loadList('error', cls, { title: 'Ingress: ' + cls }).then(function (l) {
|
||||||
|
if (!l) return;
|
||||||
|
var rows = l.rows, labels = R.validators.map(function (v) { return vshort(v.validator); });
|
||||||
|
rows.forEach(function (x) { if (labels.indexOf(x[3]) < 0) labels.push(x[3]); });
|
||||||
|
var byVal = labels.map(function (lab) { return rows.filter(function (x) { return x[3] === lab; }).length; });
|
||||||
|
var max = Math.max.apply(null, byVal.concat([1]));
|
||||||
|
var late = rows.filter(function (x) { return x[5].indexOf('после') >= 0; }).length;
|
||||||
|
var pass = rows.filter(function (x) { return x[4] === 'pass'; }).length;
|
||||||
|
var grid = 'grid-template-columns:repeat(' + labels.length + ',minmax(0,1fr))';
|
||||||
|
var dist = '<h2>Распределение по валидаторам</h2>' +
|
||||||
|
'<div class="an-cols20" style="' + grid + '" role="img" aria-label="Число проваленных проверок по валидаторам">' + byVal.map(function (v, i) {
|
||||||
|
return '<div style="height:' + Math.max(1, v / max * 100) + '%" ' + tipAttr('валидатор ' + labels[i] + ': ' + v + ' проверок') + '></div>';
|
||||||
|
}).join('') + '</div>' +
|
||||||
|
'<div class="an-lab20" style="' + grid + '">' + labels.map(function (lab) { return '<span>' + esc(lab.replace(/^v/, '')) + '</span>'; }).join('') + '</div>' +
|
||||||
|
'<div class="an-chips"><span class="an-tag an-t-n">всего ' + fmt(rows.length) + '</span><span class="an-tag an-t-ok">вердикт pass: ' + fmt(pass) + '</span><span class="an-tag an-t-warn">вердикт partial: ' + fmt(rows.length - pass) + '</span><span class="an-tag an-t-bad">после вердикта: ' + fmt(late) + '</span><span class="an-tag an-t-n">в вердикте: ' + fmt(rows.length - late) + '</span></div>';
|
||||||
|
A.fill({
|
||||||
|
title: 'Ingress: ' + cls,
|
||||||
|
note: 'Проваленные проверки этого класса в последнем цикле каждого адреса. Валидатор — тот, к которому был привязан адрес в этом цикле. «После вердикта» — результат пришёл позже агрегации и в вердикт адреса не вошёл.',
|
||||||
|
cols: l.columns, rows: rows, runLabel: runLabel(), dist: dist, csvURL: listURL(M.csv_url, 'error', cls),
|
||||||
|
hints: { 3: 'Валидатор, к которому был привязан адрес в этом цикле (берётся из события привязки Floating IP).', 4: VERDICT_HINT, 5: STATUS_HINT },
|
||||||
|
cellHints: { 4: function (v) { return VERDICT_VAL[v] || ''; }, 5: statusVal }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- wiring ---- */
|
||||||
|
function renderAll() {
|
||||||
|
renderSubnets();
|
||||||
|
renderTypes();
|
||||||
|
renderTargets();
|
||||||
|
}
|
||||||
|
|
||||||
|
$('an-runnote').textContent = 'Тип: ' + M.kind + '. Начало ' + M.start + ', завершён ' + M.end + ', длительность ' + M.duration + '.' +
|
||||||
|
(M.rechecked ? ' Перепроверено внутри запуска: ' + M.rechecked + ' адр. (берётся последний цикл).' : '');
|
||||||
|
renderKpis(); renderReasons(); renderQuality(); renderErrors(); renderSites(); renderValidators(); renderAll();
|
||||||
|
|
||||||
|
$('an-kpis').addEventListener('click', function (e) { var b = e.target.closest('[data-list]'); if (b) openIndicator(b.dataset.list); });
|
||||||
|
$('an-errs').addEventListener('click', function (e) { var b = e.target.closest('[data-cls]'); if (b) openError(b.dataset.cls); });
|
||||||
|
document.querySelectorAll('[data-sort]').forEach(function (b) {
|
||||||
|
b.addEventListener('click', function () {
|
||||||
|
state.sort = b.dataset.sort;
|
||||||
|
document.querySelectorAll('[data-sort]').forEach(function (x) { x.setAttribute('aria-pressed', x === b); });
|
||||||
|
renderSubnets();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
$('an-types').addEventListener('click', function (e) {
|
||||||
|
var b = e.target.closest('[data-type]');
|
||||||
|
if (!b) return;
|
||||||
|
state.type = b.dataset.type;
|
||||||
|
renderTypes(); renderTargets();
|
||||||
|
});
|
||||||
|
$('an-allsub').addEventListener('click', function () { state.all = !state.all; renderSubnets(); renderTargets(); });
|
||||||
|
})();
|
||||||
@@ -180,11 +180,9 @@ main > h2.section-title:first-child { margin-top: 0; }
|
|||||||
padding: 18px 12px;
|
padding: 18px 12px;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 20px;
|
gap: 14px;
|
||||||
}
|
}
|
||||||
.brand { display: flex; align-items: center; gap: 9px; padding: 0 6px 12px; border-bottom: 1px solid var(--border-soft); }
|
.brand { display: flex; align-items: center; gap: 9px; padding: 0 6px 12px; border-bottom: 1px solid var(--border-soft); }
|
||||||
.brand-chrome { display: flex; gap: 4px; }
|
|
||||||
.brand-chrome i { width: 6px; height: 6px; border-radius: 50%; background: var(--border); }
|
|
||||||
.brand-mark {
|
.brand-mark {
|
||||||
width: 26px; height: 26px;
|
width: 26px; height: 26px;
|
||||||
border-radius: var(--radius-xs);
|
border-radius: var(--radius-xs);
|
||||||
@@ -218,8 +216,10 @@ nav.nav-groups { display: flex; flex-direction: column; gap: 1px; }
|
|||||||
.nav-link.active svg { opacity: 1; }
|
.nav-link.active svg { opacity: 1; }
|
||||||
.nav-link:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
|
.nav-link:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
|
||||||
|
|
||||||
.sidebar-foot {
|
/* Session block at the top of the sidebar: link state to control-api, theme
|
||||||
margin-top: auto;
|
toggle and, with login enabled, who is signed in and the logout button. */
|
||||||
|
.sidebar-session {
|
||||||
|
display: grid; gap: 8px;
|
||||||
padding: 9px 10px;
|
padding: 9px 10px;
|
||||||
border-radius: var(--radius-sm);
|
border-radius: var(--radius-sm);
|
||||||
background: var(--surface-alt);
|
background: var(--surface-alt);
|
||||||
@@ -227,9 +227,16 @@ nav.nav-groups { display: flex; flex-direction: column; gap: 1px; }
|
|||||||
font-family: var(--font-display);
|
font-family: var(--font-display);
|
||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
display: flex; align-items: center; justify-content: space-between; gap: 7px;
|
|
||||||
}
|
}
|
||||||
.sidebar-foot-status { display: flex; align-items: center; gap: 7px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
.session-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-width: 0; margin: 0; }
|
||||||
|
.session-api { display: flex; align-items: center; gap: 7px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.session-user { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.nav-group-title {
|
||||||
|
font-family: var(--font-display); font-weight: 700; font-size: 10px;
|
||||||
|
letter-spacing: .08em; text-transform: uppercase; color: var(--text-faint);
|
||||||
|
padding: 12px 9px 4px;
|
||||||
|
}
|
||||||
|
nav.nav-groups > .nav-group-title:first-child { padding-top: 0; }
|
||||||
.pulse-dot {
|
.pulse-dot {
|
||||||
width: 6px; height: 6px; border-radius: 1px;
|
width: 6px; height: 6px; border-radius: 1px;
|
||||||
background: var(--success);
|
background: var(--success);
|
||||||
@@ -238,6 +245,7 @@ nav.nav-groups { display: flex; flex-direction: column; gap: 1px; }
|
|||||||
animation: pulse 2.2s ease-in-out infinite;
|
animation: pulse 2.2s ease-in-out infinite;
|
||||||
}
|
}
|
||||||
@media (prefers-reduced-motion: reduce) { .pulse-dot { animation: none; } }
|
@media (prefers-reduced-motion: reduce) { .pulse-dot { animation: none; } }
|
||||||
|
.pulse-dot.down { background: var(--danger); box-shadow: 0 0 0 3px var(--danger-soft); animation: none; }
|
||||||
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: .35; } }
|
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: .35; } }
|
||||||
|
|
||||||
.theme-toggle {
|
.theme-toggle {
|
||||||
@@ -422,6 +430,22 @@ td.num { font-family: var(--font-mono); font-variant-numeric: tabular-nums; colo
|
|||||||
.pill-cancel { background: var(--cancel-soft); color: var(--cancel); }
|
.pill-cancel { background: var(--cancel-soft); color: var(--cancel); }
|
||||||
.pill-occupied { background: var(--occupied-soft); color: var(--occupied); }
|
.pill-occupied { background: var(--occupied-soft); color: var(--occupied); }
|
||||||
|
|
||||||
|
/* ---------- registry: egress / ingress levels ---------- */
|
||||||
|
.levels { margin-top: 6px; display: grid; gap: 4px; }
|
||||||
|
.level { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 8px; font-size: 12px; }
|
||||||
|
.level-name { min-width: 52px; color: var(--neutral); font-weight: 600; }
|
||||||
|
.level-types { display: inline-flex; flex-wrap: wrap; gap: 4px; }
|
||||||
|
.stat { font-weight: 700; white-space: nowrap; }
|
||||||
|
.stat-ok { color: var(--success); }
|
||||||
|
.stat-part { color: var(--warning); }
|
||||||
|
.stat-fail { color: var(--danger); }
|
||||||
|
.stat-none { color: var(--neutral); }
|
||||||
|
.chip { padding: 1px 6px; border-radius: var(--radius-xs); font-size: 11px; white-space: nowrap; }
|
||||||
|
.chip-ok { background: var(--success-soft); color: var(--success); }
|
||||||
|
.chip-part { background: var(--warning-soft); color: var(--warning); }
|
||||||
|
.chip-fail { background: var(--danger-soft); color: var(--danger); }
|
||||||
|
.chip-none { background: var(--neutral-soft); color: var(--neutral); }
|
||||||
|
|
||||||
/* ---------- alerts ---------- */
|
/* ---------- alerts ---------- */
|
||||||
.alert {
|
.alert {
|
||||||
display: flex; gap: 10px; align-items: flex-start;
|
display: flex; gap: 10px; align-items: flex-start;
|
||||||
@@ -552,13 +576,6 @@ textarea.autosize { overflow-y: hidden; resize: none; }
|
|||||||
.login-card .panel-body { display: flex; flex-direction: column; gap: 14px; }
|
.login-card .panel-body { display: flex; flex-direction: column; gap: 14px; }
|
||||||
/* .field is flex: 1 1 220px (for rows); in this column the basis would become a 220px height. */
|
/* .field is flex: 1 1 220px (for rows); in this column the basis would become a 220px height. */
|
||||||
.login-card .field { flex: 0 0 auto; }
|
.login-card .field { flex: 0 0 auto; }
|
||||||
.sidebar-user {
|
|
||||||
margin-top: auto; margin-bottom: 8px;
|
|
||||||
display: flex; align-items: center; justify-content: space-between; gap: 8px;
|
|
||||||
font-family: var(--font-display); font-size: 11px; color: var(--text-muted);
|
|
||||||
}
|
|
||||||
.sidebar-user-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
||||||
.sidebar-user + .sidebar-foot { margin-top: 0; }
|
|
||||||
|
|
||||||
/* ---------- scan progress, progress bars, pager, bulk selection ---------- */
|
/* ---------- scan progress, progress bars, pager, bulk selection ---------- */
|
||||||
progress {
|
progress {
|
||||||
|
|||||||
@@ -0,0 +1,122 @@
|
|||||||
|
{{define "analytics_page"}}
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>{{template "html_head" .}}
|
||||||
|
<link rel="stylesheet" href="/static/analytics.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="bg-grid"></div>
|
||||||
|
<input type="checkbox" id="nav-toggle" class="nav-toggle">
|
||||||
|
<div class="shell">
|
||||||
|
{{template "sidebar_nav" .}}
|
||||||
|
<div>
|
||||||
|
{{template "topbar_mobile" .}}
|
||||||
|
<main class="main">
|
||||||
|
<div id="error-banner">{{template "banner_inner" .Banner}}</div>
|
||||||
|
{{template "analytics_content" .}}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{{if .HasRun}}
|
||||||
|
<script type="application/json" id="analytics-data">{{.DataJSON}}</script>
|
||||||
|
<script src="/static/analytics-dialog.js"></script>
|
||||||
|
<script src="/static/analytics.js"></script>
|
||||||
|
{{end}}
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
{{end}}
|
||||||
|
|
||||||
|
{{define "analytics_content"}}
|
||||||
|
<div class="an">
|
||||||
|
<div class="an-head">
|
||||||
|
<h1 class="an-title">Аналитика</h1>
|
||||||
|
<p class="an-sub">Один выбранный запуск. Данные других запусков на странице не участвуют.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{{if not .Runs}}
|
||||||
|
<section class="an-panel">
|
||||||
|
<p class="an-note">Запусков проверки пока нет. Они появляются, когда адреса ставятся в очередь на странице <a href="/ips">«Очередь IP»</a> или запускается автоматический цикл.</p>
|
||||||
|
</section>
|
||||||
|
{{else}}
|
||||||
|
<section class="an-panel" aria-label="Выбор запуска">
|
||||||
|
<div class="an-runbar">
|
||||||
|
<label for="an-run">Запуск</label>
|
||||||
|
{{if .PrevURL}}<a class="an-btn" href="{{.PrevURL}}" aria-label="Предыдущий запуск">◀</a>{{else}}<span class="an-btn" aria-disabled="true" style="opacity:.4">◀</span>{{end}}
|
||||||
|
<select id="an-run" onchange="if (this.value) location.href = '/analytics?run=' + encodeURIComponent(this.value)">
|
||||||
|
{{range .Runs}}<option value="{{.ID}}"{{if .Selected}} selected{{end}}{{if .Disabled}} disabled{{end}}>{{.Label}}</option>
|
||||||
|
{{end}}
|
||||||
|
</select>
|
||||||
|
{{if .NextURL}}<a class="an-btn" href="{{.NextURL}}" aria-label="Следующий запуск">▶</a>{{else}}<span class="an-btn" aria-disabled="true" style="opacity:.4">▶</span>{{end}}
|
||||||
|
{{if .HasRun}}<a class="an-btn" href="/analytics/compare?target={{.RunID}}">Сравнить с другим запуском</a>{{end}}
|
||||||
|
</div>
|
||||||
|
{{if .HasRun}}<p class="an-note" id="an-runnote"></p>{{else}}<p class="an-note">Завершённых запусков пока нет: данные появятся, когда все адреса запуска получат итог.</p>{{end}}
|
||||||
|
</section>
|
||||||
|
{{end}}
|
||||||
|
|
||||||
|
{{if .HasRun}}
|
||||||
|
<div class="an-kpis" id="an-kpis"></div>
|
||||||
|
|
||||||
|
<div class="an-cols">
|
||||||
|
<section class="an-panel" aria-labelledby="an-h-reasons">
|
||||||
|
<h2 id="an-h-reasons">Почему partial</h2>
|
||||||
|
<div class="an-rows" id="an-reasons"></div>
|
||||||
|
<p class="an-note">Адрес считается один раз, по главной причине. Всё, где есть egress, учитывается как egress.</p>
|
||||||
|
</section>
|
||||||
|
<section class="an-panel" aria-labelledby="an-h-dq">
|
||||||
|
<h2 id="an-h-dq">Качество данных</h2>
|
||||||
|
<div class="an-dq" id="an-dq"></div>
|
||||||
|
<p class="an-note">Вердикт ставится при агрегации. Результаты, пришедшие позже, остаются в этом же запуске, но в вердикт не входят.</p>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="an-panel" aria-labelledby="an-h-sub">
|
||||||
|
<div class="an-head">
|
||||||
|
<h2 id="an-h-sub">Подсети</h2>
|
||||||
|
<div class="an-runbar">
|
||||||
|
<div class="an-tabs" role="group" aria-label="Сортировка подсетей">
|
||||||
|
<button type="button" data-sort="worst" aria-pressed="true">хуже всего</button>
|
||||||
|
<button type="button" data-sort="size" aria-pressed="false">больше адресов</button>
|
||||||
|
</div>
|
||||||
|
<button class="an-btn" id="an-allsub" type="button"></button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="an-scroll"><table id="an-subtbl"></table></div>
|
||||||
|
<p class="an-note">Строка ведёт в «Реестр» с фильтром по запуску и подсети.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="an-panel" aria-labelledby="an-h-eg">
|
||||||
|
<div class="an-head">
|
||||||
|
<h2 id="an-h-eg">Egress по целям</h2>
|
||||||
|
<div class="an-tabs" role="group" aria-label="Тип проверки" id="an-types"></div>
|
||||||
|
</div>
|
||||||
|
<div class="an-rows" id="an-targets"></div>
|
||||||
|
<div id="an-matrixwrap">
|
||||||
|
<div class="an-head"><h2 style="margin-top:6px">Подсеть × цель</h2>
|
||||||
|
<div class="an-legend" id="an-hlegend"></div></div>
|
||||||
|
<div class="an-scroll"><table class="an-heat" id="an-matrix"></table></div>
|
||||||
|
</div>
|
||||||
|
<p class="an-note" id="an-matrixnote"></p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="an-cols">
|
||||||
|
<section class="an-panel" aria-labelledby="an-h-in">
|
||||||
|
<h2 id="an-h-in">Ingress по площадкам</h2>
|
||||||
|
<div class="an-scroll"><table id="an-sites"></table></div>
|
||||||
|
</section>
|
||||||
|
<section class="an-panel" aria-labelledby="an-h-err">
|
||||||
|
<h2 id="an-h-err">Классы ошибок ingress</h2>
|
||||||
|
<div class="an-rows" id="an-errs"></div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="an-panel" aria-labelledby="an-h-val">
|
||||||
|
<h2 id="an-h-val">Валидаторы: доля провалов egress https</h2>
|
||||||
|
<div class="an-vals" id="an-vals" role="img" aria-label="Доля проваленных https-проверок по валидаторам"></div>
|
||||||
|
<div class="an-vlab"><span id="an-vfirst"></span><span id="an-vavg"></span><span id="an-vlast"></span></div>
|
||||||
|
<p class="an-note">Ровная полоса значит: проблема зависит от подсети адреса, а не от валидатора.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{{template "analytics_dialog"}}
|
||||||
|
{{end}}
|
||||||
|
</div>
|
||||||
|
{{end}}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
{{define "analytics_compare_page"}}
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>{{template "html_head" .}}
|
||||||
|
<link rel="stylesheet" href="/static/analytics.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="bg-grid"></div>
|
||||||
|
<input type="checkbox" id="nav-toggle" class="nav-toggle">
|
||||||
|
<div class="shell">
|
||||||
|
{{template "sidebar_nav" .}}
|
||||||
|
<div>
|
||||||
|
{{template "topbar_mobile" .}}
|
||||||
|
<main class="main">
|
||||||
|
<div id="error-banner">{{template "banner_inner" .Banner}}</div>
|
||||||
|
{{template "analytics_compare_content" .}}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{{if .HasReport}}
|
||||||
|
<script type="application/json" id="analytics-data">{{.DataJSON}}</script>
|
||||||
|
<script src="/static/analytics-dialog.js"></script>
|
||||||
|
<script src="/static/analytics-compare.js"></script>
|
||||||
|
{{end}}
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
{{end}}
|
||||||
|
|
||||||
|
{{define "analytics_compare_content"}}
|
||||||
|
<div class="an">
|
||||||
|
<div class="an-head">
|
||||||
|
<h1 class="an-title">Сравнение запусков</h1>
|
||||||
|
<p class="an-sub">Динамика между двумя завершёнными запусками. <a href="/analytics">К аналитике одного запуска</a>.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{{if .RunsA}}
|
||||||
|
<section class="an-panel" aria-label="Выбор запусков">
|
||||||
|
<form class="an-runbar" method="get" action="/analytics/compare">
|
||||||
|
<label for="an-base">Запуск A (старый)</label>
|
||||||
|
<select id="an-base" name="base">
|
||||||
|
{{range .RunsA}}<option value="{{.ID}}"{{if .Selected}} selected{{end}}>{{.Label}}</option>
|
||||||
|
{{end}}
|
||||||
|
</select>
|
||||||
|
<button class="an-btn" type="button" id="an-swap" onclick="var a = document.getElementById('an-base'), b = document.getElementById('an-target'), v = a.value; a.value = b.value; b.value = v; this.form.submit()">Поменять местами</button>
|
||||||
|
<label for="an-target">Запуск B (новый)</label>
|
||||||
|
<select id="an-target" name="target">
|
||||||
|
{{range .RunsB}}<option value="{{.ID}}"{{if .Selected}} selected{{end}}>{{.Label}}</option>
|
||||||
|
{{end}}
|
||||||
|
</select>
|
||||||
|
<button class="an-btn an-primary" type="submit">Сравнить</button>
|
||||||
|
</form>
|
||||||
|
{{if .HasReport}}<div class="an-note" id="an-cmp-note"></div>{{end}}
|
||||||
|
<p class="an-note">«Новые» — адреса, которые есть в B и которых не было в A; «выбывшие» — были в A, в B их нет. Адрес изменился, если его принадлежность к индикаторам в A и B разная. Если запуски разного состава (например, перепроверка части адресов), новых и выбывших будет много: это состав запусков, а не динамика.</p>
|
||||||
|
</section>
|
||||||
|
{{end}}
|
||||||
|
|
||||||
|
{{if .HasReport}}
|
||||||
|
<div class="an-kpis" id="an-cmp-kpis"></div>
|
||||||
|
|
||||||
|
<section class="an-panel" aria-labelledby="an-h-ind">
|
||||||
|
<h2 id="an-h-ind">Динамика по индикаторам</h2>
|
||||||
|
<div class="an-scroll"><table id="an-cmp-ind"></table></div>
|
||||||
|
<p class="an-note">Δ = B − A = новые − выбывшие + вошли − вышли. Зелёным выделен рост pass и падение остальных индикаторов, красным обратное. Числа в последних четырёх столбцах открывают список адресов.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="an-panel" aria-labelledby="an-h-tr">
|
||||||
|
<h2 id="an-h-tr">Переходы вердикта</h2>
|
||||||
|
<div class="an-scroll"><table id="an-cmp-tr"></table></div>
|
||||||
|
<p class="an-note">Вердикт адресов, которые есть в обоих запусках: по строкам вердикт в A, по столбцам в B. Строка «нет в A» — новые адреса по вердикту в B, столбец «нет в B» — выбывшие по вердикту в A.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{{template "analytics_dialog"}}
|
||||||
|
{{end}}
|
||||||
|
</div>
|
||||||
|
{{end}}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{{/* The address-list dialog and its tooltip, shared by the analytics pages;
|
||||||
|
analytics-dialog.js drives it. */}}
|
||||||
|
{{define "analytics_dialog"}}
|
||||||
|
<dialog id="an-dlg" aria-labelledby="an-dlg-title">
|
||||||
|
<div class="an-dlg">
|
||||||
|
<h3 id="an-dlg-title"></h3>
|
||||||
|
<p class="an-note" id="an-dlg-note"></p>
|
||||||
|
<div class="an-dist" id="an-dlg-dist" hidden></div>
|
||||||
|
<div class="an-list"><table id="an-dlg-tbl"></table></div>
|
||||||
|
<div class="an-foot">
|
||||||
|
<span class="an-note" id="an-dlg-msg" role="status"></span>
|
||||||
|
<div class="an-acts">
|
||||||
|
<button class="an-btn" type="button" id="an-dlg-copy">Копировать</button>
|
||||||
|
<button class="an-btn an-primary" type="button" id="an-dlg-csv">Скачать CSV</button>
|
||||||
|
<button class="an-btn" type="button" id="an-dlg-close" autofocus>Закрыть</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</dialog>
|
||||||
|
<div id="an-tip" role="tooltip"></div>
|
||||||
|
{{end}}
|
||||||
@@ -34,6 +34,7 @@
|
|||||||
создан: {{fmtTime .Detail.IP.CreatedAt}} · назначен: {{fmtTime .Detail.IP.AssignedAt}} ·
|
создан: {{fmtTime .Detail.IP.CreatedAt}} · назначен: {{fmtTime .Detail.IP.AssignedAt}} ·
|
||||||
агрегирован: {{fmtTime .Detail.IP.AggregatedAt}} · FIP освобождён: {{fmtTime .Detail.IP.FIPReleasedAt}}
|
агрегирован: {{fmtTime .Detail.IP.AggregatedAt}} · FIP освобождён: {{fmtTime .Detail.IP.FIPReleasedAt}}
|
||||||
</p>
|
</p>
|
||||||
|
{{if .Detail.SelfCheckFailedOn}}<p class="muted">Self-check не прошёл на: {{join .Detail.SelfCheckFailedOn ", "}}</p>{{end}}
|
||||||
|
|
||||||
<h2 class="section-title">Проверки (попытка {{.Detail.IP.AttemptNumber}})</h2>
|
<h2 class="section-title">Проверки (попытка {{.Detail.IP.AttemptNumber}})</h2>
|
||||||
{{if .Detail.Checks}}
|
{{if .Detail.Checks}}
|
||||||
|
|||||||
@@ -36,14 +36,29 @@
|
|||||||
{{define "sidebar_nav"}}
|
{{define "sidebar_nav"}}
|
||||||
<aside class="sidebar">
|
<aside class="sidebar">
|
||||||
<div class="brand">
|
<div class="brand">
|
||||||
<span class="brand-chrome"><i></i><i></i><i></i></span>
|
|
||||||
<span class="brand-mark">
|
<span class="brand-mark">
|
||||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2v6M12 16v6M2 12h6M16 12h6"/><circle cx="12" cy="12" r="3"/></svg>
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2v6M12 16v6M2 12h6M16 12h6"/><circle cx="12" cy="12" r="3"/></svg>
|
||||||
</span>
|
</span>
|
||||||
<span class="brand-name">Cloud IP Validator<small>admin</small></span>
|
<span class="brand-name">Cloud IP Validator<small>admin</small></span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<nav class="nav-groups">
|
<div class="sidebar-session">
|
||||||
|
{{$down := and .Banner.Message (not .Banner.Client)}}
|
||||||
|
<div class="session-row">
|
||||||
|
<span class="session-api" title="{{if $down}}Нет связи с control-api: {{.Banner.Message}}{{else}}Связь с control-api в порядке{{end}}"><span class="pulse-dot{{if $down}} down{{end}}"></span>control-api{{if $down}} · нет связи{{end}}</span>
|
||||||
|
<button type="button" class="theme-toggle" id="themeToggle" aria-label="Переключить тему" title="Переключить тему">
|
||||||
|
<svg class="icon-sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg>
|
||||||
|
<svg class="icon-moon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.8A9 9 0 1 1 11.2 3 7 7 0 0 0 21 12.8Z"/></svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{{if .AuthEnabled}}<form class="session-row" method="post" action="/logout">
|
||||||
|
<span class="session-user" title="{{.User}}">{{.User}}</span>
|
||||||
|
<button type="submit" class="btn btn-ghost btn-sm">Выйти</button>
|
||||||
|
</form>{{end}}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<nav class="nav-groups" aria-label="Разделы">
|
||||||
|
<div class="nav-group-title">Мониторинг</div>
|
||||||
<a class="nav-link{{if eq .ActiveNav "overview"}} active{{end}}" {{if eq .ActiveNav "overview"}}aria-current="page"{{end}} href="/overview">
|
<a class="nav-link{{if eq .ActiveNav "overview"}} active{{end}}" {{if eq .ActiveNav "overview"}}aria-current="page"{{end}} href="/overview">
|
||||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/></svg>
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/></svg>
|
||||||
Обзор
|
Обзор
|
||||||
@@ -56,6 +71,11 @@
|
|||||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2Z"/></svg>
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2Z"/></svg>
|
||||||
Реестр
|
Реестр
|
||||||
</a>
|
</a>
|
||||||
|
<a class="nav-link{{if eq .ActiveNav "analytics"}} active{{end}}" {{if eq .ActiveNav "analytics"}}aria-current="page"{{end}} href="/analytics">
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20V10M10 20V4M16 20v-7M22 20H2"/></svg>
|
||||||
|
Аналитика
|
||||||
|
</a>
|
||||||
|
<div class="nav-group-title">Настройка</div>
|
||||||
<a class="nav-link{{if eq .ActiveNav "validators"}} active{{end}}" {{if eq .ActiveNav "validators"}}aria-current="page"{{end}} href="/validators">
|
<a class="nav-link{{if eq .ActiveNav "validators"}} active{{end}}" {{if eq .ActiveNav "validators"}}aria-current="page"{{end}} href="/validators">
|
||||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="3" width="16" height="7" rx="1.5"/><rect x="4" y="14" width="16" height="7" rx="1.5"/><circle cx="8" cy="6.5" r="1"/><circle cx="8" cy="17.5" r="1"/></svg>
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="3" width="16" height="7" rx="1.5"/><rect x="4" y="14" width="16" height="7" rx="1.5"/><circle cx="8" cy="6.5" r="1"/><circle cx="8" cy="17.5" r="1"/></svg>
|
||||||
Валидаторы
|
Валидаторы
|
||||||
@@ -78,20 +98,6 @@
|
|||||||
</a>
|
</a>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
{{if .AuthEnabled}}
|
|
||||||
<form class="sidebar-user" method="post" action="/logout">
|
|
||||||
<span class="sidebar-user-name" title="{{.User}}">{{.User}}</span>
|
|
||||||
<button type="submit" class="btn btn-ghost btn-sm">Выйти</button>
|
|
||||||
</form>
|
|
||||||
{{end}}
|
|
||||||
|
|
||||||
<div class="sidebar-foot">
|
|
||||||
<span class="sidebar-foot-status"><span class="pulse-dot"></span>control-api</span>
|
|
||||||
<button type="button" class="theme-toggle" id="themeToggle" aria-label="Переключить тему" title="Переключить тему">
|
|
||||||
<svg class="icon-sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg>
|
|
||||||
<svg class="icon-moon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.8A9 9 0 1 1 11.2 3 7 7 0 0 0 21 12.8Z"/></svg>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</aside>
|
</aside>
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
|
|||||||
@@ -26,6 +26,13 @@
|
|||||||
Глубина хранимой истории на адрес настраивается на <a href="/settings">странице настроек</a>.</p>
|
Глубина хранимой истории на адрес настраивается на <a href="/settings">странице настроек</a>.</p>
|
||||||
|
|
||||||
<form id="registry-filter" class="panel" onsubmit="return false" style="margin-bottom:16px">
|
<form id="registry-filter" class="panel" onsubmit="return false" style="margin-bottom:16px">
|
||||||
|
{{if .Run}}<input type="hidden" name="run" value="{{.Run}}">{{end}}
|
||||||
|
{{if .Subnet}}<input type="hidden" name="subnet" value="{{.Subnet}}">{{end}}
|
||||||
|
{{if or .Run .Subnet}}<div class="panel-body" style="padding-bottom:0">
|
||||||
|
<span class="pill pill-info">Из аналитики:{{if .Run}} запуск {{.Run}}{{end}}{{if .Subnet}} · подсеть {{.Subnet}}{{end}}</span>
|
||||||
|
<a href="/registry" style="margin-left:10px">сбросить фильтр</a>
|
||||||
|
{{if .Run}}<a href="/analytics?run={{.Run}}" style="margin-left:10px">к аналитике</a>{{end}}
|
||||||
|
</div>{{end}}
|
||||||
<div class="panel-body field-row">
|
<div class="panel-body field-row">
|
||||||
<div class="field" style="flex:1 1 260px">
|
<div class="field" style="flex:1 1 260px">
|
||||||
<label for="registry-q">Поиск по IP</label>
|
<label for="registry-q">Поиск по IP</label>
|
||||||
@@ -66,6 +73,15 @@
|
|||||||
</div>
|
</div>
|
||||||
{{end}}
|
{{end}}
|
||||||
|
|
||||||
|
{{define "registry_level"}}
|
||||||
|
<div class="level">
|
||||||
|
<span class="level-name">{{.Name}}</span>
|
||||||
|
{{if .L.Total}}<span class="stat stat-{{.L.Class}}">{{.L.OK}} из {{.L.Total}}</span>
|
||||||
|
<span class="level-types">{{range .L.ByType}}<span class="chip chip-{{.Class}}">{{.Type}} {{.OK}} из {{.Total}}</span>{{end}}</span>
|
||||||
|
{{else}}<span class="stat stat-none">—</span>{{end}}
|
||||||
|
</div>
|
||||||
|
{{end}}
|
||||||
|
|
||||||
{{define "registry_table"}}
|
{{define "registry_table"}}
|
||||||
{{if .Items}}
|
{{if .Items}}
|
||||||
<div class="panel">
|
<div class="panel">
|
||||||
@@ -85,6 +101,10 @@
|
|||||||
{{else if eq .LastResult "fail"}}<span class="pill pill-danger">fail</span>
|
{{else if eq .LastResult "fail"}}<span class="pill pill-danger">fail</span>
|
||||||
{{else if eq .LastResult "cancelled"}}<span class="pill pill-cancel">cancelled</span>
|
{{else if eq .LastResult "cancelled"}}<span class="pill pill-cancel">cancelled</span>
|
||||||
{{else}}<span class="pill pill-neutral">—</span>{{end}}
|
{{else}}<span class="pill pill-neutral">—</span>{{end}}
|
||||||
|
{{if .LastCycleID}}<div class="levels" title="Считаются записанные проверки цикла {{.LastCycleID}}; вердикт учитывает ещё и недостающие результаты.">
|
||||||
|
{{template "registry_level" dict "Name" "Egress" "L" .Egress}}
|
||||||
|
{{template "registry_level" dict "Name" "Ingress" "L" .Ingress}}
|
||||||
|
</div>{{end}}
|
||||||
</td>
|
</td>
|
||||||
<td data-label="Сейчас в очереди">
|
<td data-label="Сейчас в очереди">
|
||||||
{{if .InQueue}}<span class="pill pill-info">{{.CurrentState}}</span>{{else}}<span class="pill pill-neutral">нет</span>{{end}}
|
{{if .InQueue}}<span class="pill pill-info">{{.CurrentState}}</span>{{else}}<span class="pill pill-neutral">нет</span>{{end}}
|
||||||
|
|||||||
@@ -34,6 +34,7 @@
|
|||||||
впервые замечен: {{fmtTime .History.Registry.FirstSeenAt}} · последний раз замечен: {{fmtTime .History.Registry.LastSeenAt}}
|
впервые замечен: {{fmtTime .History.Registry.FirstSeenAt}} · последний раз замечен: {{fmtTime .History.Registry.LastSeenAt}}
|
||||||
· всего циклов проверки: {{.History.Registry.TotalCycles}}
|
· всего циклов проверки: {{.History.Registry.TotalCycles}}
|
||||||
</p>
|
</p>
|
||||||
|
{{if .History.SelfCheckFailedOn}}<p class="muted">Self-check не прошёл на: {{join .History.SelfCheckFailedOn ", "}}</p>{{end}}
|
||||||
|
|
||||||
<h2 class="section-title">История проверок (все сохранённые циклы)</h2>
|
<h2 class="section-title">История проверок (все сохранённые циклы)</h2>
|
||||||
{{if .History.Checks}}
|
{{if .History.Checks}}
|
||||||
|
|||||||
@@ -80,6 +80,10 @@
|
|||||||
<a href="/registry">реестре</a> для каждого адреса. Адрес и его накопленная статистика остаются в реестре даже
|
<a href="/registry">реестре</a> для каждого адреса. Адрес и его накопленная статистика остаются в реестре даже
|
||||||
после удаления из очереди — эта настройка ограничивает только глубину истории конкретных проверок, не сам реестр.
|
после удаления из очереди — эта настройка ограничивает только глубину истории конкретных проверок, не сам реестр.
|
||||||
<code>0</code> — хранить без ограничения.</p>
|
<code>0</code> — хранить без ограничения.</p>
|
||||||
|
<p class="muted" style="margin-bottom:16px">Сколько раз self-check может не пройти у одного адреса, прежде чем адрес
|
||||||
|
получит итог <code>fail</code> (допустимо 1–50, по умолчанию 5). Повторы идут на других валидаторах: валидатор, на
|
||||||
|
котором адрес не прошёл self-check, этому адресу больше не выдаётся (на остальные адреса это не влияет).
|
||||||
|
Значение действует на следующих повторах, без перезапуска.</p>
|
||||||
<form hx-put="/settings" hx-target="#settings-form-wrap" hx-swap="innerHTML">
|
<form hx-put="/settings" hx-target="#settings-form-wrap" hx-swap="innerHTML">
|
||||||
<div class="field-row">
|
<div class="field-row">
|
||||||
<div class="field">
|
<div class="field">
|
||||||
@@ -90,6 +94,10 @@
|
|||||||
<label for="history_retention_cycles">Глубина истории проверок (циклов на адрес, 0 = не ограничено)</label>
|
<label for="history_retention_cycles">Глубина истории проверок (циклов на адрес, 0 = не ограничено)</label>
|
||||||
<input type="number" id="history_retention_cycles" name="history_retention_cycles" min="0" step="1" value="{{.Settings.HistoryRetentionCycles}}" required>
|
<input type="number" id="history_retention_cycles" name="history_retention_cycles" min="0" step="1" value="{{.Settings.HistoryRetentionCycles}}" required>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="self_check_max_attempts">Потолок провалов self-check на адрес</label>
|
||||||
|
<input type="number" id="self_check_max_attempts" name="self_check_max_attempts" min="1" max="50" step="1" value="{{.Settings.SelfCheckMaxAttempts}}" required>
|
||||||
|
</div>
|
||||||
<button type="submit" class="btn btn-primary">Сохранить</button>
|
<button type="submit" class="btn btn-primary">Сохранить</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
@@ -117,4 +125,23 @@ inbound-проверки к нулю, не трогая список площа
|
|||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panel-body">
|
||||||
|
<p class="muted" style="margin-bottom:16px">Подсети для страницы <a href="/analytics">«Аналитика»</a>: по ним
|
||||||
|
группируются адреса запуска. По одной в строке — <code>CIDR</code> и, через пробел, необязательная подпись
|
||||||
|
(<code>83.166.248.0/21 москва</code>). Адрес относится к самой узкой подходящей подсети, остальные идут в строку
|
||||||
|
«прочие». Пока список пуст, адреса группируются по /24.</p>
|
||||||
|
<form hx-put="/settings/subnets" hx-target="#settings-form-wrap" hx-swap="innerHTML">
|
||||||
|
<div class="field">
|
||||||
|
<label for="subnets_text">Подсети</label>
|
||||||
|
<textarea id="subnets_text" name="subnets" rows="8" spellcheck="false" placeholder="83.166.248.0/21 212.233.72.0/21 подпись">{{range .Subnets.Subnets}}{{.CIDR}}{{if .Label}} {{.Label}}{{end}}
|
||||||
|
{{end}}</textarea>
|
||||||
|
</div>
|
||||||
|
<div class="field-row">
|
||||||
|
<button type="submit" class="btn btn-primary">Сохранить</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
{{end}}
|
{{end}}
|
||||||
@@ -40,6 +40,15 @@ var autoCycleSchema string
|
|||||||
//go:embed migrations/0009_scale_indexes.sql
|
//go:embed migrations/0009_scale_indexes.sql
|
||||||
var scaleIndexesSchema string
|
var scaleIndexesSchema string
|
||||||
|
|
||||||
|
//go:embed migrations/0010_verdict_integrity.sql
|
||||||
|
var verdictIntegritySchema string
|
||||||
|
|
||||||
|
//go:embed migrations/0011_check_runs.sql
|
||||||
|
var checkRunsSchema string
|
||||||
|
|
||||||
|
//go:embed migrations/0012_self_check_failures.sql
|
||||||
|
var selfCheckFailuresSchema 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
|
||||||
@@ -57,6 +66,9 @@ var migrations = []struct {
|
|||||||
{7, ipRegistrySchema},
|
{7, ipRegistrySchema},
|
||||||
{8, autoCycleSchema},
|
{8, autoCycleSchema},
|
||||||
{9, scaleIndexesSchema},
|
{9, scaleIndexesSchema},
|
||||||
|
{10, verdictIntegritySchema},
|
||||||
|
{11, checkRunsSchema},
|
||||||
|
{12, selfCheckFailuresSchema},
|
||||||
}
|
}
|
||||||
|
|
||||||
type DB struct {
|
type DB struct {
|
||||||
@@ -92,6 +104,10 @@ func Open(ctx context.Context, path string) (*DB, error) {
|
|||||||
sqlDB.Close()
|
sqlDB.Close()
|
||||||
return nil, fmt.Errorf("migrate: %w", err)
|
return nil, fmt.Errorf("migrate: %w", err)
|
||||||
}
|
}
|
||||||
|
if err := d.adoptOrphanQueueRows(ctx); err != nil {
|
||||||
|
sqlDB.Close()
|
||||||
|
return nil, fmt.Errorf("adopt queue rows into a run: %w", err)
|
||||||
|
}
|
||||||
return d, nil
|
return d, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
-- Verdict integrity (see docs/changes/2026-10-03_17-21_verdict-no-late-results-plan.md).
|
||||||
|
--
|
||||||
|
-- ip_queue.checking_started_at: when the address entered the "checking" state.
|
||||||
|
-- The aggregation window (checking_window_seconds) is counted from here, not
|
||||||
|
-- from assigned_at, which also covers floating-IP association, the settle
|
||||||
|
-- pause and the self-check. NULL on rows that predate this migration; the
|
||||||
|
-- orchestrator falls back to assigned_at for them.
|
||||||
|
--
|
||||||
|
-- checks.recorded_at: when control-api last wrote the row, by its own clock.
|
||||||
|
-- checked_at comes from the probing machine's clock, so it cannot be compared
|
||||||
|
-- reliably with aggregated_at. Existing rows get created_at (their first
|
||||||
|
-- write); a later overwrite is not recoverable.
|
||||||
|
--
|
||||||
|
-- checks.after_verdict: 1 when the row was written after the address's
|
||||||
|
-- verdict (checked_at later than aggregated_at). Set here for existing data
|
||||||
|
-- only; new writes after the verdict are rejected, so it stays 0 afterwards.
|
||||||
|
|
||||||
|
ALTER TABLE ip_queue ADD COLUMN checking_started_at TIMESTAMP;
|
||||||
|
|
||||||
|
ALTER TABLE checks ADD COLUMN recorded_at TIMESTAMP;
|
||||||
|
UPDATE checks SET recorded_at = created_at;
|
||||||
|
|
||||||
|
ALTER TABLE checks ADD COLUMN after_verdict INTEGER NOT NULL DEFAULT 0;
|
||||||
|
UPDATE checks SET after_verdict = 1
|
||||||
|
WHERE EXISTS (
|
||||||
|
SELECT 1 FROM ip_queue q
|
||||||
|
WHERE q.registry_id = checks.registry_id
|
||||||
|
AND q.cycle_id = checks.cycle_id
|
||||||
|
AND q.aggregated_at IS NOT NULL
|
||||||
|
AND julianday(checks.checked_at) > julianday(q.aggregated_at)
|
||||||
|
);
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
-- Check runs (see docs/changes/2026-10-03_16-39_analytics-section-plan.md).
|
||||||
|
--
|
||||||
|
-- cycle_id counts per address, so it cannot tell one launch from another. A
|
||||||
|
-- run groups the cycles of one launch: it opens when an address enters an idle
|
||||||
|
-- queue, takes every address submitted or re-checked while it is open, and is
|
||||||
|
-- finalized when all its queue rows are terminal. checks.run_id and
|
||||||
|
-- ip_queue.run_id carry the membership; run_results keeps one row per address
|
||||||
|
-- and run (its latest cycle) with the verdict, which ip_queue overwrites on a
|
||||||
|
-- re-check.
|
||||||
|
--
|
||||||
|
-- No foreign keys on purpose: the manual cleanup in docs/ADMIN_CLEANUP.md
|
||||||
|
-- deletes from these tables freely.
|
||||||
|
|
||||||
|
CREATE TABLE check_runs (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
kind TEXT NOT NULL DEFAULT 'manual', -- manual | auto
|
||||||
|
state TEXT NOT NULL DEFAULT 'open', -- open | finalized
|
||||||
|
started_at TIMESTAMP NOT NULL,
|
||||||
|
finalized_at TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE run_results (
|
||||||
|
run_id INTEGER NOT NULL,
|
||||||
|
registry_id INTEGER NOT NULL,
|
||||||
|
ip_address TEXT NOT NULL,
|
||||||
|
cycle_id INTEGER NOT NULL,
|
||||||
|
verdict TEXT NOT NULL, -- pass | partial | fail | cancelled
|
||||||
|
verdict_derived INTEGER NOT NULL DEFAULT 0, -- 1: computed from checks, not stored by the orchestrator
|
||||||
|
aggregated_at TIMESTAMP NOT NULL,
|
||||||
|
expected_checks INTEGER, -- NULL when unknown
|
||||||
|
recorded_checks INTEGER NOT NULL DEFAULT 0, -- checks stored when the verdict was made
|
||||||
|
PRIMARY KEY (run_id, registry_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_run_results_registry ON run_results(registry_id);
|
||||||
|
|
||||||
|
CREATE TABLE subnets (
|
||||||
|
cidr TEXT PRIMARY KEY,
|
||||||
|
label TEXT NOT NULL DEFAULT ''
|
||||||
|
);
|
||||||
|
|
||||||
|
ALTER TABLE ip_queue ADD COLUMN run_id INTEGER;
|
||||||
|
ALTER TABLE checks ADD COLUMN run_id INTEGER;
|
||||||
|
CREATE INDEX idx_checks_run ON checks(run_id, registry_id, cycle_id);
|
||||||
|
|
||||||
|
-- ---- existing data -------------------------------------------------------
|
||||||
|
-- Ingress checks never stored the validator. The one holding the address in a
|
||||||
|
-- cycle is named by its fip_associated event.
|
||||||
|
UPDATE checks SET validator_id = COALESCE((
|
||||||
|
SELECT json_extract(e.payload, '$.validator_id') FROM events e
|
||||||
|
WHERE e.event_type = 'fip_associated' AND e.registry_id = checks.registry_id AND e.cycle_id = checks.cycle_id
|
||||||
|
ORDER BY e.id DESC LIMIT 1), '')
|
||||||
|
WHERE source LIKE 'inbound-site-%' AND validator_id = '';
|
||||||
|
|
||||||
|
-- Runs of existing data: cycles whose last checks end less than an hour apart
|
||||||
|
-- belong to one run.
|
||||||
|
CREATE TEMP TABLE _bf_cyc AS
|
||||||
|
WITH c AS (
|
||||||
|
SELECT registry_id, cycle_id, MAX(julianday(checked_at)) AS t, MIN(checked_at) AS first_at, MAX(checked_at) AS last_at
|
||||||
|
FROM checks GROUP BY registry_id, cycle_id
|
||||||
|
), o AS (
|
||||||
|
SELECT *, CASE WHEN t - LAG(t) OVER (ORDER BY t) > 60.0 / 1440.0 THEN 1 ELSE 0 END AS brk FROM c
|
||||||
|
)
|
||||||
|
SELECT *, 1 + SUM(brk) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS rid FROM o;
|
||||||
|
|
||||||
|
CREATE INDEX _bf_cyc_key ON _bf_cyc(registry_id, cycle_id);
|
||||||
|
|
||||||
|
INSERT INTO check_runs (id, kind, state, started_at, finalized_at)
|
||||||
|
SELECT rid, 'manual', 'finalized', MIN(first_at), MAX(last_at) FROM _bf_cyc GROUP BY rid;
|
||||||
|
|
||||||
|
UPDATE checks SET run_id = (
|
||||||
|
SELECT b.rid FROM _bf_cyc b WHERE b.registry_id = checks.registry_id AND b.cycle_id = checks.cycle_id);
|
||||||
|
|
||||||
|
UPDATE ip_queue SET run_id = (
|
||||||
|
SELECT b.rid FROM _bf_cyc b WHERE b.registry_id = ip_queue.registry_id AND b.cycle_id = ip_queue.cycle_id);
|
||||||
|
|
||||||
|
-- One result per address and run: the latest cycle of the address in the run.
|
||||||
|
-- The verdict is the orchestrator's when the queue row still holds that cycle,
|
||||||
|
-- otherwise it is derived from the stored checks.
|
||||||
|
INSERT INTO run_results (run_id, registry_id, ip_address, cycle_id, verdict, verdict_derived, aggregated_at, expected_checks, recorded_checks)
|
||||||
|
SELECT l.rid, l.registry_id, r.ip_address, l.cycle_id,
|
||||||
|
CASE WHEN q.id IS NOT NULL AND q.overall_result <> '' THEN q.overall_result
|
||||||
|
WHEN s.ok = 0 THEN 'fail' WHEN s.ok = s.n THEN 'pass' ELSE 'partial' END,
|
||||||
|
CASE WHEN q.id IS NOT NULL AND q.overall_result <> '' THEN 0 ELSE 1 END,
|
||||||
|
COALESCE(CASE WHEN q.overall_result <> '' THEN q.aggregated_at END, s.last_at),
|
||||||
|
(SELECT json_extract(e.payload, '$.checks') + json_extract(e.payload, '$.missing') FROM events e
|
||||||
|
WHERE e.event_type = 'aggregated' AND e.registry_id = l.registry_id AND e.cycle_id = l.cycle_id
|
||||||
|
ORDER BY e.id DESC LIMIT 1),
|
||||||
|
COALESCE((SELECT json_extract(e.payload, '$.checks') FROM events e
|
||||||
|
WHERE e.event_type = 'aggregated' AND e.registry_id = l.registry_id AND e.cycle_id = l.cycle_id
|
||||||
|
ORDER BY e.id DESC LIMIT 1), s.n_before)
|
||||||
|
FROM (SELECT rid, registry_id, MAX(cycle_id) AS cycle_id FROM _bf_cyc GROUP BY rid, registry_id) l
|
||||||
|
JOIN ip_registry r ON r.id = l.registry_id
|
||||||
|
JOIN (SELECT registry_id, cycle_id, COUNT(*) AS n, SUM(success) AS ok, MAX(checked_at) AS last_at,
|
||||||
|
SUM(CASE WHEN after_verdict = 0 THEN 1 ELSE 0 END) AS n_before
|
||||||
|
FROM checks GROUP BY registry_id, cycle_id) s ON s.registry_id = l.registry_id AND s.cycle_id = l.cycle_id
|
||||||
|
LEFT JOIN ip_queue q ON q.registry_id = l.registry_id AND q.cycle_id = l.cycle_id;
|
||||||
|
|
||||||
|
DROP TABLE _bf_cyc;
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
-- Self-check failures per address (see
|
||||||
|
-- docs/changes/2026-10-04_08-01_self-check-exclude-validator-plan.md).
|
||||||
|
--
|
||||||
|
-- A failed self-check no longer sends the address back to the validator that
|
||||||
|
-- failed it: ClaimNextQueued skips an address for every validator that failed
|
||||||
|
-- it in the current round. ip_self_check_failures is the permanent history of
|
||||||
|
-- those failures; it is keyed by registry_id (like checks and events), so it
|
||||||
|
-- outlives the ip_queue row and is not touched by re-checks. No foreign keys
|
||||||
|
-- on purpose: the manual cleanup in docs/ADMIN_CLEANUP.md deletes freely.
|
||||||
|
--
|
||||||
|
-- A round is the part of a series of failures in which validators that failed
|
||||||
|
-- stay excluded. ip_queue.sc_round_start_cycle is the first cycle_id of the
|
||||||
|
-- current round: a failure excludes its validator only if its cycle_id is not
|
||||||
|
-- below it. cycle_id (not attempt_number) is used because it never repeats for
|
||||||
|
-- an address, even when the ip_queue row is deleted and created again.
|
||||||
|
--
|
||||||
|
-- ip_queue.sc_failures counts self-check failures of the current series; a
|
||||||
|
-- manual re-check or re-submission starts a new series.
|
||||||
|
--
|
||||||
|
-- settings.self_check_max_attempts is the ceiling of self-check failures per
|
||||||
|
-- address, after which the address gets the verdict fail (1..50, default 5).
|
||||||
|
|
||||||
|
CREATE TABLE ip_self_check_failures (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
registry_id INTEGER NOT NULL,
|
||||||
|
run_id INTEGER,
|
||||||
|
cycle_id INTEGER NOT NULL,
|
||||||
|
attempt_number INTEGER NOT NULL,
|
||||||
|
validator_id TEXT NOT NULL,
|
||||||
|
failed_at TIMESTAMP NOT NULL,
|
||||||
|
detail TEXT NOT NULL DEFAULT ''
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_sc_failures_registry ON ip_self_check_failures(registry_id, validator_id);
|
||||||
|
|
||||||
|
ALTER TABLE ip_queue ADD COLUMN sc_failures INTEGER NOT NULL DEFAULT 0;
|
||||||
|
ALTER TABLE ip_queue ADD COLUMN sc_round_start_cycle INTEGER NOT NULL DEFAULT 0;
|
||||||
|
|
||||||
|
ALTER TABLE settings ADD COLUMN self_check_max_attempts INTEGER NOT NULL DEFAULT 5;
|
||||||
+48
-1
@@ -1,6 +1,9 @@
|
|||||||
package db
|
package db
|
||||||
|
|
||||||
import "time"
|
import (
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
// Validator and IP lifecycle states. Kept as typed string constants rather
|
// Validator and IP lifecycle states. Kept as typed string constants rather
|
||||||
// than a Go enum type so they round-trip through SQLite TEXT columns and
|
// than a Go enum type so they round-trip through SQLite TEXT columns and
|
||||||
@@ -71,6 +74,37 @@ func InboundSource(siteIndex int) string {
|
|||||||
return "inbound-site-" + itoa(siteIndex)
|
return "inbound-site-" + itoa(siteIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check levels: the two directions a check can run in, derived from
|
||||||
|
// checks.source (there is no separate direction column).
|
||||||
|
const (
|
||||||
|
LevelEgress = "egress"
|
||||||
|
LevelIngress = "ingress"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CheckLevel maps a checks.source value to its level: "egress" for the
|
||||||
|
// validator's own outbound checks, "ingress" for any prober site
|
||||||
|
// ("inbound-site-N"). Any other source yields "".
|
||||||
|
func CheckLevel(source string) string {
|
||||||
|
switch {
|
||||||
|
case source == SourceEgress:
|
||||||
|
return LevelEgress
|
||||||
|
case strings.HasPrefix(source, "inbound-site-"):
|
||||||
|
return LevelIngress
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckFamily maps a checks.check_type value to its family for grouping:
|
||||||
|
// the part before the first "-", so tcp-22 and tcp-443 are both "tcp" while
|
||||||
|
// https, icmp, ssh and tls-443 ("tls") stay distinct. A check type added in
|
||||||
|
// the future is grouped by its own name without code changes.
|
||||||
|
func CheckFamily(checkType string) string {
|
||||||
|
if i := strings.IndexByte(checkType, '-'); i > 0 {
|
||||||
|
return checkType[:i]
|
||||||
|
}
|
||||||
|
return checkType
|
||||||
|
}
|
||||||
|
|
||||||
func itoa(n int) string {
|
func itoa(n int) string {
|
||||||
if n == 0 {
|
if n == 0 {
|
||||||
return "0"
|
return "0"
|
||||||
@@ -118,6 +152,9 @@ type IPQueueItem struct {
|
|||||||
EgressComplete bool
|
EgressComplete bool
|
||||||
OverallResult string
|
OverallResult string
|
||||||
AssignedAt *time.Time
|
AssignedAt *time.Time
|
||||||
|
// CheckingStartedAt is when the address entered the checking state; the
|
||||||
|
// aggregation window counts from it. nil on rows that predate it.
|
||||||
|
CheckingStartedAt *time.Time
|
||||||
FIPAssociatedAt *time.Time
|
FIPAssociatedAt *time.Time
|
||||||
AggregatedAt *time.Time
|
AggregatedAt *time.Time
|
||||||
FIPReleasedAt *time.Time
|
FIPReleasedAt *time.Time
|
||||||
@@ -239,10 +276,20 @@ type Settings struct {
|
|||||||
// HistoryRetentionCycles caps how many recent check cycles are kept per
|
// HistoryRetentionCycles caps how many recent check cycles are kept per
|
||||||
// registry address (see PruneRegistryHistory); 0 means unlimited.
|
// registry address (see PruneRegistryHistory); 0 means unlimited.
|
||||||
HistoryRetentionCycles int
|
HistoryRetentionCycles int
|
||||||
|
// SelfCheckMaxAttempts is the ceiling of failed self-checks per address
|
||||||
|
// (1..MaxSelfCheckMaxAttempts); reaching it gives the address the verdict
|
||||||
|
// fail (see FailSelfCheck).
|
||||||
|
SelfCheckMaxAttempts int
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
UpdatedAt time.Time
|
UpdatedAt time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Bounds of Settings.SelfCheckMaxAttempts.
|
||||||
|
const (
|
||||||
|
MinSelfCheckMaxAttempts = 1
|
||||||
|
MaxSelfCheckMaxAttempts = 50
|
||||||
|
)
|
||||||
|
|
||||||
// InboundChecksSettings is the singleton row describing what the prober
|
// InboundChecksSettings is the singleton row describing what the prober
|
||||||
// checks on every site for every in-flight IP (TCP ports + optional ICMP).
|
// checks on every site for every in-flight IP (TCP ports + optional ICMP).
|
||||||
// Admin-configurable at runtime (see queries_inbound.go).
|
// Admin-configurable at runtime (see queries_inbound.go).
|
||||||
|
|||||||
@@ -15,20 +15,43 @@ import (
|
|||||||
// per-address cycle rather than the ip_queue row's attempt_number, so it
|
// per-address cycle rather than the ip_queue row's attempt_number, so it
|
||||||
// survives that row being deleted and the address later resubmitted.
|
// survives that row being deleted and the address later resubmitted.
|
||||||
func (d *DB) UpsertCheck(ctx context.Context, c Check) error {
|
func (d *DB) UpsertCheck(ctx context.Context, c Check) error {
|
||||||
_, err := d.ExecContext(ctx, `
|
_, err := d.UpsertCheckIfOpen(ctx, c)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpsertCheckIfOpen is UpsertCheck for the live write path. It stores the
|
||||||
|
// check only while the address can still take results: the queue row exists,
|
||||||
|
// c.AttemptNumber is its current attempt, and it has not reached the
|
||||||
|
// aggregating state or a terminal one. Once the verdict is being computed the
|
||||||
|
// checks are frozen, so the verdict always matches the stored rows and a late
|
||||||
|
// probe of an already released floating IP cannot change them. It returns
|
||||||
|
// false (and writes nothing) when the result was dropped. The state test and
|
||||||
|
// the write are one statement, so they cannot interleave with SetAggregating.
|
||||||
|
func (d *DB) UpsertCheckIfOpen(ctx context.Context, c Check) (bool, error) {
|
||||||
|
now := timeToDB(Now())
|
||||||
|
res, err := d.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)
|
source, check_type, target, success, latency_ms, detail, checked_at, created_at, recorded_at, run_id)
|
||||||
VALUES ((SELECT registry_id FROM ip_queue WHERE id=?), (SELECT cycle_id FROM ip_queue WHERE id=?),
|
SELECT q.registry_id, q.cycle_id, q.id, ?, q.attempt_number, COALESCE(NULLIF(?, ''), q.owner_validator_id, ''),
|
||||||
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
?, ?, ?, ?, ?, ?, ?, ?, ?, q.run_id
|
||||||
|
FROM ip_queue q
|
||||||
|
WHERE q.id=? AND q.attempt_number=? AND q.state NOT IN (?, ?, ?, ?)
|
||||||
ON CONFLICT(registry_id, cycle_id, source, check_type, target) DO UPDATE SET
|
ON CONFLICT(registry_id, cycle_id, source, check_type, target) DO UPDATE SET
|
||||||
validator_id=excluded.validator_id,
|
validator_id=excluded.validator_id,
|
||||||
success=excluded.success,
|
success=excluded.success,
|
||||||
latency_ms=excluded.latency_ms,
|
latency_ms=excluded.latency_ms,
|
||||||
detail=excluded.detail,
|
detail=excluded.detail,
|
||||||
checked_at=excluded.checked_at
|
checked_at=excluded.checked_at,
|
||||||
`, c.IPID, c.IPID, c.IPID, c.IPAddress, c.AttemptNumber, c.ValidatorID, c.Source, c.CheckType, c.Target,
|
recorded_at=excluded.recorded_at,
|
||||||
c.Success, c.LatencyMS, c.Detail, timeToDB(c.CheckedAt), timeToDB(Now()))
|
run_id=excluded.run_id
|
||||||
return err
|
`, c.IPAddress, c.ValidatorID, c.Source, c.CheckType, c.Target,
|
||||||
|
c.Success, c.LatencyMS, c.Detail, timeToDB(c.CheckedAt), now, now,
|
||||||
|
c.IPID, c.AttemptNumber, IPAggregating, IPDone, IPFailed, IPOccupied)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
n, err := res.RowsAffected()
|
||||||
|
return n > 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const checksSelect = `
|
const checksSelect = `
|
||||||
|
|||||||
+306
-25
@@ -21,6 +21,7 @@ func (d *DB) SeedQueue(ctx context.Context, addresses []string) error {
|
|||||||
defer tx.Rollback()
|
defer tx.Rollback()
|
||||||
|
|
||||||
now := timeToDB(Now())
|
now := timeToDB(Now())
|
||||||
|
runID := int64(0)
|
||||||
for i, addr := range addresses {
|
for i, addr := range addresses {
|
||||||
var exists bool
|
var exists bool
|
||||||
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM ip_queue WHERE ip_address=?)`, addr).Scan(&exists); err != nil {
|
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM ip_queue WHERE ip_address=?)`, addr).Scan(&exists); err != nil {
|
||||||
@@ -37,11 +38,16 @@ func (d *DB) SeedQueue(ctx context.Context, addresses []string) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if runID == 0 {
|
||||||
|
if runID, err = openRunTx(ctx, tx, RunManual, now); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
if _, err := tx.ExecContext(ctx, `
|
if _, err := tx.ExecContext(ctx, `
|
||||||
INSERT INTO ip_queue (ip_address, sequence, state, registry_id, cycle_id, created_at, updated_at)
|
INSERT INTO ip_queue (ip_address, sequence, state, registry_id, cycle_id, run_id, sc_round_start_cycle, created_at, updated_at)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
ON CONFLICT(ip_address) DO NOTHING
|
ON CONFLICT(ip_address) DO NOTHING
|
||||||
`, addr, i, IPQueued, registryID, cycle, now, now); err != nil {
|
`, addr, i, IPQueued, registryID, cycle, runID, cycle, now, now); err != nil {
|
||||||
return fmt.Errorf("seed %s: %w", addr, err)
|
return fmt.Errorf("seed %s: %w", addr, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -49,8 +55,11 @@ func (d *DB) SeedQueue(ctx context.Context, addresses []string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ClaimNextQueued atomically hands the next queued IP (lowest sequence) to
|
// ClaimNextQueued atomically hands the next queued IP (lowest sequence) to
|
||||||
// the given idle validator. It returns (nil, nil) if the validator isn't
|
// the given idle validator, skipping addresses this validator failed the
|
||||||
// idle or no IP is queued. The DB connection pool is capped at one physical
|
// self-check of in the current round (see FailSelfCheck): such an address
|
||||||
|
// stays queued for the other validators and does not block the ones behind
|
||||||
|
// it. It returns (nil, nil) if the validator isn't idle or no IP is
|
||||||
|
// claimable for it. The DB connection pool is capped at one physical
|
||||||
// connection (see Open), so this transaction already has exclusive access
|
// connection (see Open), so this transaction already has exclusive access
|
||||||
// to the database for its duration — no other claim, requeue, or update can
|
// to the database for its duration — no other claim, requeue, or update can
|
||||||
// interleave — which combined with the conditional UPDATEs (checked via
|
// interleave — which combined with the conditional UPDATEs (checked via
|
||||||
@@ -76,9 +85,12 @@ 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 id, ip_address, sequence, attempt_number, retry_count
|
SELECT q.id, q.ip_address, q.sequence, q.attempt_number, q.retry_count
|
||||||
FROM ip_queue WHERE state=? ORDER BY sequence LIMIT 1
|
FROM ip_queue q WHERE q.state=? AND NOT EXISTS (
|
||||||
`, IPQueued).Scan(&item.ID, &item.IPAddress, &item.Sequence, &item.AttemptNumber, &item.RetryCount)
|
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)
|
||||||
|
ORDER BY q.sequence LIMIT 1
|
||||||
|
`, IPQueued, validatorID).Scan(&item.ID, &item.IPAddress, &item.Sequence, &item.AttemptNumber, &item.RetryCount)
|
||||||
if err == sql.ErrNoRows {
|
if err == sql.ErrNoRows {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
@@ -180,9 +192,9 @@ func (d *DB) KnownAddresses(ctx context.Context, addresses []string) (map[string
|
|||||||
func (d *DB) SetChecking(ctx context.Context, ipID int64, leaseTTL time.Duration) error {
|
func (d *DB) SetChecking(ctx context.Context, ipID int64, leaseTTL time.Duration) error {
|
||||||
now := Now()
|
now := Now()
|
||||||
_, err := d.ExecContext(ctx, `
|
_, err := d.ExecContext(ctx, `
|
||||||
UPDATE ip_queue SET state=?, lease_expires_at=?, updated_at=?
|
UPDATE ip_queue SET state=?, lease_expires_at=?, checking_started_at=?, updated_at=?
|
||||||
WHERE id=?
|
WHERE id=?
|
||||||
`, IPChecking, timeToDB(now.Add(leaseTTL)), timeToDB(now), ipID)
|
`, IPChecking, timeToDB(now.Add(leaseTTL)), timeToDB(now), timeToDB(now), ipID)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -194,16 +206,36 @@ func (d *DB) SetAggregating(ctx context.Context, ipID int64) error {
|
|||||||
|
|
||||||
// FinishIP records the aggregated result and marks the IP done or failed.
|
// FinishIP records the aggregated result and marks the IP done or failed.
|
||||||
func (d *DB) FinishIP(ctx context.Context, ipID int64, result string) error {
|
func (d *DB) FinishIP(ctx context.Context, ipID int64, result string) error {
|
||||||
|
return d.FinishIPExpected(ctx, ipID, result, -1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FinishIPExpected is FinishIP that also records, in the address's run, how
|
||||||
|
// many checks were expected at the verdict (expected < 0: unknown) and
|
||||||
|
// finalizes the run if this was its last open address.
|
||||||
|
func (d *DB) FinishIPExpected(ctx context.Context, ipID int64, result string, expected int) error {
|
||||||
state := IPDone
|
state := IPDone
|
||||||
if result == ResultFail {
|
if result == ResultFail {
|
||||||
state = IPFailed
|
state = IPFailed
|
||||||
}
|
}
|
||||||
|
tx, err := d.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
now := timeToDB(Now())
|
now := timeToDB(Now())
|
||||||
_, err := d.ExecContext(ctx, `
|
if _, err := tx.ExecContext(ctx, `
|
||||||
UPDATE ip_queue SET state=?, overall_result=?, aggregated_at=?, updated_at=?
|
UPDATE ip_queue SET state=?, overall_result=?, aggregated_at=?, updated_at=?
|
||||||
WHERE id=?
|
WHERE id=?
|
||||||
`, state, result, now, now, ipID)
|
`, state, result, now, now, ipID); err != nil {
|
||||||
return err
|
return err
|
||||||
|
}
|
||||||
|
if err := upsertRunResultTx(ctx, tx, ipID, result, expected, now); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := finalizeRunsTx(ctx, tx, now); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Commit()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReleaseFIP records that the floating IP has been disassociated and frees
|
// ReleaseFIP records that the floating IP has been disassociated and frees
|
||||||
@@ -254,6 +286,9 @@ func (d *DB) MarkFIPOccupied(ctx context.Context, ipID int64, validatorID string
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if err := finalizeRunsTx(ctx, tx, now); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
return tx.Commit()
|
return tx.Commit()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -295,7 +330,7 @@ func (d *DB) RequeueOrFail(ctx context.Context, ipID int64, validatorID string,
|
|||||||
UPDATE ip_queue SET
|
UPDATE ip_queue SET
|
||||||
state=?, owner_validator_id=NULL, fip_id='', retry_count=?, attempt_number=attempt_number+1,
|
state=?, owner_validator_id=NULL, fip_id='', retry_count=?, attempt_number=attempt_number+1,
|
||||||
cycle_id=?, lease_expires_at=NULL, egress_complete=0,
|
cycle_id=?, lease_expires_at=NULL, egress_complete=0,
|
||||||
overall_result='', assigned_at=NULL, fip_associated_at=NULL, updated_at=?
|
overall_result='', assigned_at=NULL, checking_started_at=NULL, fip_associated_at=NULL, updated_at=?
|
||||||
WHERE id=?
|
WHERE id=?
|
||||||
`, nextState, retryCount, cycle, now, ipID)
|
`, nextState, retryCount, cycle, now, ipID)
|
||||||
} else {
|
} else {
|
||||||
@@ -304,6 +339,12 @@ func (d *DB) RequeueOrFail(ctx context.Context, ipID int64, validatorID string,
|
|||||||
state=?, retry_count=?, overall_result=?, aggregated_at=?, updated_at=?
|
state=?, retry_count=?, overall_result=?, aggregated_at=?, updated_at=?
|
||||||
WHERE id=?
|
WHERE id=?
|
||||||
`, nextState, retryCount, ResultFail, now, now, ipID)
|
`, nextState, retryCount, ResultFail, now, now, ipID)
|
||||||
|
if err == nil {
|
||||||
|
err = upsertRunResultTx(ctx, tx, ipID, ResultFail, -1, now)
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
err = finalizeRunsTx(ctx, tx, now)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -317,6 +358,178 @@ func (d *DB) RequeueOrFail(ctx context.Context, ipID int64, validatorID string,
|
|||||||
return tx.Commit()
|
return tx.Commit()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SelfCheckFailure is the outcome of FailSelfCheck.
|
||||||
|
type SelfCheckFailure struct {
|
||||||
|
// Failures is the number of failed self-checks in the address's current
|
||||||
|
// series, this one included.
|
||||||
|
Failures int
|
||||||
|
// Failed: the ceiling was reached and the address got the verdict fail.
|
||||||
|
Failed bool
|
||||||
|
// Validators lists the validators that failed the self-check in this
|
||||||
|
// series, oldest first (with repeats if one failed it more than once).
|
||||||
|
Validators []string
|
||||||
|
// NewRound: the address was queued again, and every working validator had
|
||||||
|
// already failed it in the round, so the round was reset — the exclusions
|
||||||
|
// no longer apply (always false when Failed).
|
||||||
|
NewRound bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// FailSelfCheck handles a failed self-check of the address ipID held by
|
||||||
|
// validatorID, in one transaction: it records the failure in
|
||||||
|
// ip_self_check_failures and in ip_queue.sc_failures, then
|
||||||
|
//
|
||||||
|
// - if sc_failures reached maxAttempts: marks the address failed with the
|
||||||
|
// verdict fail;
|
||||||
|
// - otherwise sends it back to the queue without touching retry_count (a
|
||||||
|
// failed self-check has its own ceiling, unlike a failed association or
|
||||||
|
// an expired lease, see RequeueOrFail). The validator is excluded from
|
||||||
|
// this address for the rest of the round (ClaimNextQueued). If no
|
||||||
|
// working validator (idle, assigned, checking) is left without a failure
|
||||||
|
// in the round, a new round starts: the exclusions lapse and the retry
|
||||||
|
// follows the usual rules, so with fewer validators than maxAttempts the
|
||||||
|
// address never gets stuck in the queue.
|
||||||
|
//
|
||||||
|
// The validator is freed in the same transaction. Returns ErrInvalidState if
|
||||||
|
// the address is not awaiting_self_check on this validator (a late report).
|
||||||
|
func (d *DB) FailSelfCheck(ctx context.Context, ipID int64, validatorID, detail string, maxAttempts int) (SelfCheckFailure, error) {
|
||||||
|
var out SelfCheckFailure
|
||||||
|
tx, err := d.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
|
||||||
|
var registryID, cycle, roundStart int64
|
||||||
|
var runID sql.NullInt64
|
||||||
|
var attempt, failures int
|
||||||
|
err = tx.QueryRowContext(ctx, `
|
||||||
|
SELECT registry_id, run_id, cycle_id, attempt_number, sc_failures, sc_round_start_cycle
|
||||||
|
FROM ip_queue WHERE id=? AND state=? AND owner_validator_id=?
|
||||||
|
`, ipID, IPAwaitingSelfCheck, validatorID).Scan(®istryID, &runID, &cycle, &attempt, &failures, &roundStart)
|
||||||
|
if err == sql.ErrNoRows {
|
||||||
|
return out, fmt.Errorf("ip_id %d is not awaiting self-check on %s: %w", ipID, validatorID, ErrInvalidState)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
|
||||||
|
now := timeToDB(Now())
|
||||||
|
if _, err := tx.ExecContext(ctx, `
|
||||||
|
INSERT INTO ip_self_check_failures (registry_id, run_id, cycle_id, attempt_number, validator_id, failed_at, detail)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`, registryID, runID, cycle, attempt, validatorID, now, detail); err != nil {
|
||||||
|
return out, fmt.Errorf("record self-check failure: %w", err)
|
||||||
|
}
|
||||||
|
failures++
|
||||||
|
out.Failures = failures
|
||||||
|
|
||||||
|
rows, err := tx.QueryContext(ctx, `
|
||||||
|
SELECT validator_id FROM (
|
||||||
|
SELECT id, validator_id FROM ip_self_check_failures WHERE registry_id=? ORDER BY id DESC LIMIT ?
|
||||||
|
) ORDER BY id
|
||||||
|
`, registryID, failures)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
for rows.Next() {
|
||||||
|
var v string
|
||||||
|
if err := rows.Scan(&v); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
out.Validators = append(out.Validators, v)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
|
||||||
|
if failures >= maxAttempts {
|
||||||
|
out.Failed = true
|
||||||
|
if _, err := tx.ExecContext(ctx, `
|
||||||
|
UPDATE ip_queue SET
|
||||||
|
state=?, sc_failures=?, overall_result=?, aggregated_at=?, updated_at=?
|
||||||
|
WHERE id=?
|
||||||
|
`, IPFailed, failures, ResultFail, now, now, ipID); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if err := upsertRunResultTx(ctx, tx, ipID, ResultFail, -1, now); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if err := finalizeRunsTx(ctx, tx, now); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
newCycle, err := nextRegistryCycleTx(ctx, tx, registryID, now)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
var left int
|
||||||
|
if err := tx.QueryRowContext(ctx, `
|
||||||
|
SELECT COUNT(*) FROM validators v
|
||||||
|
WHERE v.state IN (?, ?, ?) AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM ip_self_check_failures f
|
||||||
|
WHERE f.registry_id=? AND f.validator_id=v.validator_id AND f.cycle_id>=?)
|
||||||
|
`, ValidatorIdle, ValidatorAssigned, ValidatorChecking, registryID, roundStart).Scan(&left); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if left == 0 {
|
||||||
|
out.NewRound = true
|
||||||
|
roundStart = int64(newCycle)
|
||||||
|
}
|
||||||
|
if _, err := tx.ExecContext(ctx, `
|
||||||
|
UPDATE ip_queue SET
|
||||||
|
state=?, owner_validator_id=NULL, fip_id='', attempt_number=attempt_number+1,
|
||||||
|
cycle_id=?, sc_failures=?, sc_round_start_cycle=?, lease_expires_at=NULL, egress_complete=0,
|
||||||
|
overall_result='', assigned_at=NULL, checking_started_at=NULL, fip_associated_at=NULL, updated_at=?
|
||||||
|
WHERE id=?
|
||||||
|
`, IPQueued, newCycle, failures, roundStart, now, ipID); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := tx.ExecContext(ctx, freeValidatorSQL, now, validatorID, ipID); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
return out, tx.Commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetIPRunID returns the check run the queue row belongs to (0 if none).
|
||||||
|
func (d *DB) GetIPRunID(ctx context.Context, ipID int64) (int64, error) {
|
||||||
|
var runID sql.NullInt64
|
||||||
|
if err := d.QueryRowContext(ctx, `SELECT run_id FROM ip_queue WHERE id=?`, ipID).Scan(&runID); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return runID.Int64, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListSelfCheckFailedOn returns the distinct validators whose self-check of
|
||||||
|
// the address failed, in alphabetical order: over the whole history of the
|
||||||
|
// address, or, if runID > 0, only the failures that happened in that run.
|
||||||
|
func (d *DB) ListSelfCheckFailedOn(ctx context.Context, registryID, runID int64) ([]string, error) {
|
||||||
|
q := `SELECT DISTINCT validator_id FROM ip_self_check_failures WHERE registry_id=?`
|
||||||
|
args := []any{registryID}
|
||||||
|
if runID > 0 {
|
||||||
|
q += ` AND run_id=?`
|
||||||
|
args = append(args, runID)
|
||||||
|
}
|
||||||
|
rows, err := d.QueryContext(ctx, q+` ORDER BY validator_id`, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := []string{}
|
||||||
|
for rows.Next() {
|
||||||
|
var v string
|
||||||
|
if err := rows.Scan(&v); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, v)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
// SubmitIPs is the single admin entry point for both "add new addresses to
|
// SubmitIPs is the single admin entry point for both "add new addresses to
|
||||||
// the queue" and "force a re-check of an already-finished address" — the
|
// the queue" and "force a re-check of an already-finished address" — the
|
||||||
// same list can freely mix both. Addresses are processed in one
|
// same list can freely mix both. Addresses are processed in one
|
||||||
@@ -325,7 +538,9 @@ func (d *DB) RequeueOrFail(ctx context.Context, ipID int64, validatorID string,
|
|||||||
// - unknown address: inserted as a new queued row.
|
// - unknown address: inserted as a new queued row.
|
||||||
// - address currently done/failed/occupied: reset to queued (new attempt,
|
// - address currently done/failed/occupied: reset to queued (new attempt,
|
||||||
// retry_count cleared — this is a deliberate admin-triggered restart,
|
// retry_count cleared — this is a deliberate admin-triggered restart,
|
||||||
// not a system retry).
|
// not a system retry). It also starts a new series of self-check
|
||||||
|
// failures (sc_failures=0, validators that failed it before are no
|
||||||
|
// longer excluded); the history in ip_self_check_failures stays.
|
||||||
// - address currently queued (not yet claimed): left in state=queued,
|
// - address currently queued (not yet claimed): left in state=queued,
|
||||||
// only its sequence is updated.
|
// only its sequence is updated.
|
||||||
// - address currently mid-check (assigning_fip / awaiting_self_check /
|
// - address currently mid-check (assigning_fip / awaiting_self_check /
|
||||||
@@ -337,6 +552,12 @@ func (d *DB) RequeueOrFail(ctx context.Context, ipID int64, validatorID string,
|
|||||||
// sequence, so a batch's relative order is preserved and, critically,
|
// sequence, so a batch's relative order is preserved and, critically,
|
||||||
// resubmitting the same list later reproduces the same relative order.
|
// resubmitting the same list later reproduces the same relative order.
|
||||||
func (d *DB) SubmitIPs(ctx context.Context, addresses []string) (SubmitIPsResult, error) {
|
func (d *DB) SubmitIPs(ctx context.Context, addresses []string) (SubmitIPsResult, error) {
|
||||||
|
return d.SubmitIPsAs(ctx, addresses, RunManual)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SubmitIPsAs is SubmitIPs that names the kind of run it opens when no run is
|
||||||
|
// open (RunManual or RunAuto); an already open run is joined whatever the kind.
|
||||||
|
func (d *DB) SubmitIPsAs(ctx context.Context, addresses []string, kind string) (SubmitIPsResult, error) {
|
||||||
var result SubmitIPsResult
|
var result SubmitIPsResult
|
||||||
if len(addresses) == 0 {
|
if len(addresses) == 0 {
|
||||||
return result, fmt.Errorf("addresses must not be empty: %w", ErrValidation)
|
return result, fmt.Errorf("addresses must not be empty: %w", ErrValidation)
|
||||||
@@ -354,6 +575,17 @@ func (d *DB) SubmitIPs(ctx context.Context, addresses []string) (SubmitIPsResult
|
|||||||
}
|
}
|
||||||
|
|
||||||
now := timeToDB(Now())
|
now := timeToDB(Now())
|
||||||
|
runID := int64(0)
|
||||||
|
ensureRun := func() (int64, error) {
|
||||||
|
if runID == 0 {
|
||||||
|
id, err := openRunTx(ctx, tx, kind, now)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
runID = id
|
||||||
|
}
|
||||||
|
return runID, nil
|
||||||
|
}
|
||||||
for i, addr := range addresses {
|
for i, addr := range addresses {
|
||||||
seq := base + i
|
seq := base + i
|
||||||
|
|
||||||
@@ -369,10 +601,14 @@ func (d *DB) SubmitIPs(ctx context.Context, addresses []string) (SubmitIPsResult
|
|||||||
if cErr != nil {
|
if cErr != nil {
|
||||||
return result, cErr
|
return result, cErr
|
||||||
}
|
}
|
||||||
|
rid, rErr := ensureRun()
|
||||||
|
if rErr != nil {
|
||||||
|
return result, rErr
|
||||||
|
}
|
||||||
if _, err := tx.ExecContext(ctx, `
|
if _, err := tx.ExecContext(ctx, `
|
||||||
INSERT INTO ip_queue (ip_address, sequence, state, registry_id, cycle_id, created_at, updated_at)
|
INSERT INTO ip_queue (ip_address, sequence, state, registry_id, cycle_id, run_id, sc_round_start_cycle, created_at, updated_at)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
`, addr, seq, IPQueued, registryID, cycle, now, now); err != nil {
|
`, addr, seq, IPQueued, registryID, cycle, rid, cycle, now, now); err != nil {
|
||||||
return result, fmt.Errorf("insert %s: %w", addr, err)
|
return result, fmt.Errorf("insert %s: %w", addr, err)
|
||||||
}
|
}
|
||||||
result.Added = append(result.Added, addr)
|
result.Added = append(result.Added, addr)
|
||||||
@@ -389,14 +625,18 @@ func (d *DB) SubmitIPs(ctx context.Context, addresses []string) (SubmitIPsResult
|
|||||||
if cErr != nil {
|
if cErr != nil {
|
||||||
return result, cErr
|
return result, cErr
|
||||||
}
|
}
|
||||||
|
rid, rErr := ensureRun()
|
||||||
|
if rErr != nil {
|
||||||
|
return result, rErr
|
||||||
|
}
|
||||||
if _, err := tx.ExecContext(ctx, `
|
if _, err := tx.ExecContext(ctx, `
|
||||||
UPDATE ip_queue SET
|
UPDATE ip_queue SET
|
||||||
state=?, sequence=?, owner_validator_id=NULL, fip_id='', retry_count=0,
|
state=?, sequence=?, owner_validator_id=NULL, fip_id='', retry_count=0,
|
||||||
attempt_number=attempt_number+1, cycle_id=?, lease_expires_at=NULL, egress_complete=0,
|
attempt_number=attempt_number+1, cycle_id=?, lease_expires_at=NULL, egress_complete=0,
|
||||||
overall_result='',
|
overall_result='', run_id=?, sc_failures=0, sc_round_start_cycle=?,
|
||||||
assigned_at=NULL, fip_associated_at=NULL, aggregated_at=NULL, fip_released_at=NULL, updated_at=?
|
assigned_at=NULL, checking_started_at=NULL, fip_associated_at=NULL, aggregated_at=NULL, fip_released_at=NULL, updated_at=?
|
||||||
WHERE ip_address=?
|
WHERE ip_address=?
|
||||||
`, IPQueued, seq, cycle, now, addr); err != nil {
|
`, IPQueued, seq, cycle, rid, cycle, now, addr); err != nil {
|
||||||
return result, fmt.Errorf("requeue %s: %w", addr, err)
|
return result, fmt.Errorf("requeue %s: %w", addr, err)
|
||||||
}
|
}
|
||||||
result.Requeued = append(result.Requeued, addr)
|
result.Requeued = append(result.Requeued, addr)
|
||||||
@@ -431,7 +671,12 @@ func (d *DB) SubmitIPs(ctx context.Context, addresses []string) (SubmitIPsResult
|
|||||||
// closed by the single-connection transactional UPDATE below).
|
// closed by the single-connection transactional UPDATE below).
|
||||||
func (d *DB) CancelIP(ctx context.Context, ipID int64) error {
|
func (d *DB) CancelIP(ctx context.Context, ipID int64) error {
|
||||||
now := timeToDB(Now())
|
now := timeToDB(Now())
|
||||||
res, err := d.ExecContext(ctx, `
|
tx, err := d.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
res, err := tx.ExecContext(ctx, `
|
||||||
UPDATE ip_queue SET
|
UPDATE ip_queue SET
|
||||||
state=?, overall_result=?, aggregated_at=?, owner_validator_id=NULL, fip_id='',
|
state=?, overall_result=?, aggregated_at=?, owner_validator_id=NULL, fip_id='',
|
||||||
lease_expires_at=NULL, updated_at=?
|
lease_expires_at=NULL, updated_at=?
|
||||||
@@ -443,7 +688,13 @@ func (d *DB) CancelIP(ctx context.Context, ipID int64) error {
|
|||||||
if n, _ := res.RowsAffected(); n == 0 {
|
if n, _ := res.RowsAffected(); n == 0 {
|
||||||
return fmt.Errorf("ip_id %d already finished: %w", ipID, ErrInvalidState)
|
return fmt.Errorf("ip_id %d already finished: %w", ipID, ErrInvalidState)
|
||||||
}
|
}
|
||||||
return nil
|
if err := upsertRunResultTx(ctx, tx, ipID, ResultCancelled, -1, now); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := finalizeRunsTx(ctx, tx, now); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Commit()
|
||||||
}
|
}
|
||||||
|
|
||||||
// DeleteIP permanently removes an ip_queue row, along with its full check
|
// DeleteIP permanently removes an ip_queue row, along with its full check
|
||||||
@@ -463,6 +714,9 @@ func (d *DB) DeleteIP(ctx context.Context, ipID int64) error {
|
|||||||
if err := deleteIPTx(ctx, tx, ipID); err != nil {
|
if err := deleteIPTx(ctx, tx, ipID); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if err := finalizeRunsTx(ctx, tx, timeToDB(Now())); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
return tx.Commit()
|
return tx.Commit()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -497,6 +751,9 @@ func (d *DB) DeleteIPs(ctx context.Context, addresses []string) (DeleteIPsResult
|
|||||||
result.Deleted = append(result.Deleted, addr)
|
result.Deleted = append(result.Deleted, addr)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := finalizeRunsTx(ctx, tx, timeToDB(Now())); err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
if err := tx.Commit(); err != nil {
|
if err := tx.Commit(); err != nil {
|
||||||
return result, err
|
return result, err
|
||||||
}
|
}
|
||||||
@@ -592,6 +849,9 @@ func (d *DB) ClearAllIPs(ctx context.Context) ([]string, error) {
|
|||||||
if _, err := tx.ExecContext(ctx, `DELETE FROM ip_queue`); err != nil {
|
if _, err := tx.ExecContext(ctx, `DELETE FROM ip_queue`); err != nil {
|
||||||
return nil, fmt.Errorf("delete ip_queue rows: %w", err)
|
return nil, fmt.Errorf("delete ip_queue rows: %w", err)
|
||||||
}
|
}
|
||||||
|
if err := finalizeRunsTx(ctx, tx, now); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
if err := tx.Commit(); err != nil {
|
if err := tx.Commit(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -835,6 +1095,24 @@ func (d *DB) ListChecking(ctx context.Context) ([]IPQueueItem, error) {
|
|||||||
return scanIPQueueItems(rows)
|
return scanIPQueueItems(rows)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ListCheckingForSite returns the addresses in the checking state that the
|
||||||
|
// given prober site still has to probe: those for which it has not yet
|
||||||
|
// reported completion in the current attempt. Without this filter a prober
|
||||||
|
// would re-probe every checking address on every poll until the verdict.
|
||||||
|
func (d *DB) ListCheckingForSite(ctx context.Context, siteIndex int) ([]IPQueueItem, error) {
|
||||||
|
rows, err := d.QueryContext(ctx, ipQueueSelect+`
|
||||||
|
WHERE state=? AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM ip_site_checks s
|
||||||
|
WHERE s.ip_id=ip_queue.id AND s.attempt_number=ip_queue.attempt_number
|
||||||
|
AND s.site_idx=? AND s.complete=1)
|
||||||
|
ORDER BY sequence`, IPChecking, siteIndex)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
return scanIPQueueItems(rows)
|
||||||
|
}
|
||||||
|
|
||||||
// ListExpiredLeases returns non-terminal IPs whose lease has expired —
|
// ListExpiredLeases returns non-terminal IPs whose lease has expired —
|
||||||
// candidates for the lease sweep (crash recovery + stuck-validator reclaim).
|
// candidates for the lease sweep (crash recovery + stuck-validator reclaim).
|
||||||
func (d *DB) ListExpiredLeases(ctx context.Context, now time.Time) ([]IPQueueItem, error) {
|
func (d *DB) ListExpiredLeases(ctx context.Context, now time.Time) ([]IPQueueItem, error) {
|
||||||
@@ -851,7 +1129,7 @@ func (d *DB) ListExpiredLeases(ctx context.Context, now time.Time) ([]IPQueueIte
|
|||||||
const ipQueueSelect = `
|
const ipQueueSelect = `
|
||||||
SELECT id, ip_address, sequence, state, owner_validator_id, fip_id, attempt_number, retry_count,
|
SELECT id, ip_address, sequence, state, owner_validator_id, fip_id, attempt_number, retry_count,
|
||||||
lease_expires_at, egress_complete, overall_result,
|
lease_expires_at, egress_complete, overall_result,
|
||||||
assigned_at, fip_associated_at, aggregated_at, fip_released_at,
|
assigned_at, checking_started_at, fip_associated_at, aggregated_at, fip_released_at,
|
||||||
registry_id, cycle_id, created_at, updated_at
|
registry_id, cycle_id, created_at, updated_at
|
||||||
FROM ip_queue
|
FROM ip_queue
|
||||||
`
|
`
|
||||||
@@ -871,14 +1149,14 @@ func scanIPQueueItems(rows *sql.Rows) ([]IPQueueItem, error) {
|
|||||||
func scanIPQueueItem(row rowScanner) (*IPQueueItem, error) {
|
func scanIPQueueItem(row rowScanner) (*IPQueueItem, error) {
|
||||||
var item IPQueueItem
|
var item IPQueueItem
|
||||||
var owner sql.NullString
|
var owner sql.NullString
|
||||||
var leaseExpires, assignedAt, fipAssociatedAt, aggregatedAt, fipReleasedAt sql.NullString
|
var leaseExpires, assignedAt, checkingStartedAt, fipAssociatedAt, aggregatedAt, fipReleasedAt sql.NullString
|
||||||
var registryID sql.NullInt64
|
var registryID sql.NullInt64
|
||||||
var createdAt, updatedAt string
|
var createdAt, updatedAt string
|
||||||
if err := row.Scan(
|
if err := row.Scan(
|
||||||
&item.ID, &item.IPAddress, &item.Sequence, &item.State, &owner, &item.FIPID,
|
&item.ID, &item.IPAddress, &item.Sequence, &item.State, &owner, &item.FIPID,
|
||||||
&item.AttemptNumber, &item.RetryCount, &leaseExpires,
|
&item.AttemptNumber, &item.RetryCount, &leaseExpires,
|
||||||
&item.EgressComplete,
|
&item.EgressComplete,
|
||||||
&item.OverallResult, &assignedAt, &fipAssociatedAt, &aggregatedAt, &fipReleasedAt,
|
&item.OverallResult, &assignedAt, &checkingStartedAt, &fipAssociatedAt, &aggregatedAt, &fipReleasedAt,
|
||||||
®istryID, &item.CycleID, &createdAt, &updatedAt,
|
®istryID, &item.CycleID, &createdAt, &updatedAt,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -896,6 +1174,9 @@ func scanIPQueueItem(row rowScanner) (*IPQueueItem, error) {
|
|||||||
if item.AssignedAt, err = nullStringToTimePtr(assignedAt); err != nil {
|
if item.AssignedAt, err = nullStringToTimePtr(assignedAt); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if item.CheckingStartedAt, err = nullStringToTimePtr(checkingStartedAt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
if item.FIPAssociatedAt, err = nullStringToTimePtr(fipAssociatedAt); err != nil {
|
if item.FIPAssociatedAt, err = nullStringToTimePtr(fipAssociatedAt); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net/netip"
|
||||||
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -56,6 +58,28 @@ type RegistrySummary struct {
|
|||||||
LastCheckedAt *time.Time
|
LastCheckedAt *time.Time
|
||||||
InQueue bool
|
InQueue bool
|
||||||
CurrentState string
|
CurrentState string
|
||||||
|
|
||||||
|
// LastCycleID is the newest cycle_id with recorded checks (0 if none).
|
||||||
|
// Egress and Ingress count that cycle's recorded checks per level.
|
||||||
|
LastCycleID int
|
||||||
|
Egress LevelResult
|
||||||
|
Ingress LevelResult
|
||||||
|
}
|
||||||
|
|
||||||
|
// TypeStat counts the recorded checks of one check family (see CheckFamily)
|
||||||
|
// within a level: Total checks, OK of them successful.
|
||||||
|
type TypeStat struct {
|
||||||
|
Type string
|
||||||
|
Total int
|
||||||
|
OK int
|
||||||
|
}
|
||||||
|
|
||||||
|
// LevelResult is the "OK of Total" rollup of one level (egress or ingress) of
|
||||||
|
// a cycle, with the same counts split by check family, sorted by Type.
|
||||||
|
type LevelResult struct {
|
||||||
|
Total int
|
||||||
|
OK int
|
||||||
|
ByType []TypeStat
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListRegistry returns every address ever submitted, newest first-seen
|
// ListRegistry returns every address ever submitted, newest first-seen
|
||||||
@@ -87,6 +111,9 @@ func (d *DB) ListRegistry(ctx context.Context) ([]RegistrySummary, error) {
|
|||||||
}
|
}
|
||||||
out[i] = s
|
out[i] = s
|
||||||
}
|
}
|
||||||
|
if err := d.fillRegistryLevels(ctx, out); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,6 +121,34 @@ func (d *DB) ListRegistry(ctx context.Context) ([]RegistrySummary, error) {
|
|||||||
type RegistryFilter struct {
|
type RegistryFilter struct {
|
||||||
Query string // substring of ip_address
|
Query string // substring of ip_address
|
||||||
LastResult string // pass|partial|fail|cancelled — same meaning as RegistrySummary.LastResult
|
LastResult string // pass|partial|fail|cancelled — same meaning as RegistrySummary.LastResult
|
||||||
|
RunID int64 // only addresses that have a result in this run
|
||||||
|
Subnet string // only addresses inside this CIDR
|
||||||
|
}
|
||||||
|
|
||||||
|
// subnetIDs returns the registry ids of the addresses inside prefix. SQLite
|
||||||
|
// has no CIDR operators, so the registry's addresses are filtered here.
|
||||||
|
func (d *DB) subnetIDs(ctx context.Context, cidr string) ([]any, error) {
|
||||||
|
p, err := netip.ParsePrefix(cidr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("subnet %q: %v: %w", cidr, err, ErrValidation)
|
||||||
|
}
|
||||||
|
rows, err := d.QueryContext(ctx, `SELECT id, ip_address FROM ip_registry`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var ids []any
|
||||||
|
for rows.Next() {
|
||||||
|
var id int64
|
||||||
|
var ip string
|
||||||
|
if err := rows.Scan(&id, &ip); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if a, err := netip.ParseAddr(ip); err == nil && p.Contains(a) {
|
||||||
|
ids = append(ids, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ids, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
// lastResultCond is the SQL form of fillRegistrySummary's LastResult rule,
|
// lastResultCond is the SQL form of fillRegistrySummary's LastResult rule,
|
||||||
@@ -129,6 +184,22 @@ func (d *DB) ListRegistryPage(ctx context.Context, f RegistryFilter, limit, offs
|
|||||||
conds = append(conds, lastResultCond)
|
conds = append(conds, lastResultCond)
|
||||||
args = append(args, f.LastResult, f.LastResult)
|
args = append(args, f.LastResult, f.LastResult)
|
||||||
}
|
}
|
||||||
|
if f.RunID > 0 {
|
||||||
|
conds = append(conds, "r.id IN (SELECT registry_id FROM run_results WHERE run_id = ?)")
|
||||||
|
args = append(args, f.RunID)
|
||||||
|
}
|
||||||
|
if f.Subnet != "" {
|
||||||
|
ids, err := d.subnetIDs(ctx, f.Subnet)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
if len(ids) == 0 {
|
||||||
|
conds = append(conds, "0 = 1")
|
||||||
|
} else {
|
||||||
|
conds = append(conds, "r.id IN ("+strings.TrimSuffix(strings.Repeat("?,", len(ids)), ",")+")")
|
||||||
|
args = append(args, ids...)
|
||||||
|
}
|
||||||
|
}
|
||||||
from := ` FROM ip_registry r LEFT JOIN ip_queue q ON q.registry_id = r.id `
|
from := ` FROM ip_registry r LEFT JOIN ip_queue q ON q.registry_id = r.id `
|
||||||
where := ""
|
where := ""
|
||||||
if len(conds) > 0 {
|
if len(conds) > 0 {
|
||||||
@@ -165,6 +236,9 @@ func (d *DB) ListRegistryPage(ctx context.Context, f RegistryFilter, limit, offs
|
|||||||
}
|
}
|
||||||
out[i] = s
|
out[i] = s
|
||||||
}
|
}
|
||||||
|
if err := d.fillRegistryLevels(ctx, out); err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
return out, total, nil
|
return out, total, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -186,6 +260,11 @@ func (d *DB) GetRegistryByAddress(ctx context.Context, address string) (*Registr
|
|||||||
if err := d.fillRegistrySummary(ctx, s); err != nil {
|
if err := d.fillRegistrySummary(ctx, s); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
one := []RegistrySummary{*s}
|
||||||
|
if err := d.fillRegistryLevels(ctx, one); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
*s = one[0]
|
||||||
return s, nil
|
return s, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -253,6 +332,98 @@ func (d *DB) fillRegistrySummary(ctx context.Context, s *RegistrySummary) error
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// registryLevelsChunk bounds the number of registry ids per query, well under
|
||||||
|
// SQLite's bound-variable limit.
|
||||||
|
const registryLevelsChunk = 500
|
||||||
|
|
||||||
|
// registryLevelsQuery is the grouped query of fillRegistryLevels for n
|
||||||
|
// registry ids: per address, the counts of its newest cycle by source and
|
||||||
|
// check type.
|
||||||
|
func registryLevelsQuery(n int) string {
|
||||||
|
return `
|
||||||
|
SELECT c.registry_id, m.cid, c.source, c.check_type, COUNT(*), COALESCE(SUM(c.success), 0)
|
||||||
|
FROM checks c
|
||||||
|
JOIN (SELECT registry_id, MAX(cycle_id) AS cid FROM checks
|
||||||
|
WHERE registry_id IN (` + strings.TrimSuffix(strings.Repeat("?,", n), ",") + `)
|
||||||
|
GROUP BY registry_id) m
|
||||||
|
ON m.registry_id = c.registry_id AND m.cid = c.cycle_id
|
||||||
|
GROUP BY c.registry_id, m.cid, c.source, c.check_type
|
||||||
|
`
|
||||||
|
}
|
||||||
|
|
||||||
|
// fillRegistryLevels sets LastCycleID, Egress and Ingress on every summary in
|
||||||
|
// 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
|
||||||
|
// runs one grouped query per chunk of addresses, not one per address, over
|
||||||
|
// idx_checks_registry_cycle. Checks whose source is neither egress nor an
|
||||||
|
// inbound site are not counted. The counts follow the recorded rows only, so
|
||||||
|
// they can differ from LastResult, which also treats missing results as
|
||||||
|
// failures.
|
||||||
|
func (d *DB) fillRegistryLevels(ctx context.Context, sums []RegistrySummary) error {
|
||||||
|
pos := make(map[int64]int, len(sums))
|
||||||
|
for i := range sums {
|
||||||
|
pos[sums[i].ID] = i
|
||||||
|
}
|
||||||
|
type key struct {
|
||||||
|
id int64
|
||||||
|
level, family string
|
||||||
|
}
|
||||||
|
for start := 0; start < len(sums); start += registryLevelsChunk {
|
||||||
|
end := min(start+registryLevelsChunk, len(sums))
|
||||||
|
args := make([]any, 0, end-start)
|
||||||
|
for _, s := range sums[start:end] {
|
||||||
|
args = append(args, s.ID)
|
||||||
|
}
|
||||||
|
rows, err := d.QueryContext(ctx, registryLevelsQuery(len(args)), args...)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
stats := map[key]*TypeStat{}
|
||||||
|
for rows.Next() {
|
||||||
|
var id int64
|
||||||
|
var cid, total, ok int
|
||||||
|
var source, checkType string
|
||||||
|
if err := rows.Scan(&id, &cid, &source, &checkType, &total, &ok); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
sums[pos[id]].LastCycleID = cid
|
||||||
|
level := CheckLevel(source)
|
||||||
|
if level == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
k := key{id, level, CheckFamily(checkType)}
|
||||||
|
st := stats[k]
|
||||||
|
if st == nil {
|
||||||
|
st = &TypeStat{Type: k.family}
|
||||||
|
stats[k] = st
|
||||||
|
}
|
||||||
|
st.Total += total
|
||||||
|
st.OK += ok
|
||||||
|
}
|
||||||
|
err = rows.Err()
|
||||||
|
rows.Close()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for k, st := range stats {
|
||||||
|
lr := &sums[pos[k.id]].Egress
|
||||||
|
if k.level == LevelIngress {
|
||||||
|
lr = &sums[pos[k.id]].Ingress
|
||||||
|
}
|
||||||
|
lr.Total += st.Total
|
||||||
|
lr.OK += st.OK
|
||||||
|
lr.ByType = append(lr.ByType, *st)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i := range sums {
|
||||||
|
for _, lr := range []*LevelResult{&sums[i].Egress, &sums[i].Ingress} {
|
||||||
|
sort.Slice(lr.ByType, func(a, b int) bool { return lr.ByType[a].Type < lr.ByType[b].Type })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// lastCycleResultFromChecks classifies the most recent cycle recorded for
|
// lastCycleResultFromChecks classifies the most recent cycle recorded for
|
||||||
// registryID directly from its checks rows: pass if every recorded check
|
// registryID directly from its checks rows: pass if every recorded check
|
||||||
// succeeded, fail if every one failed, partial on a mix. Returns "" if no
|
// succeeded, fail if every one failed, partial on a mix. Returns "" if no
|
||||||
|
|||||||
@@ -0,0 +1,169 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCheckLevelAndFamily(t *testing.T) {
|
||||||
|
for source, want := range map[string]string{
|
||||||
|
"egress": LevelEgress, "inbound-site-1": LevelIngress, "inbound-site-12": LevelIngress,
|
||||||
|
"": "", "other": "",
|
||||||
|
} {
|
||||||
|
if got := CheckLevel(source); got != want {
|
||||||
|
t.Errorf("CheckLevel(%q) = %q, want %q", source, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for ct, want := range map[string]string{
|
||||||
|
"https": "https", "icmp": "icmp", "ssh": "ssh",
|
||||||
|
"tcp-22": "tcp", "tcp-443": "tcp", "tls-443": "tls", "dns": "dns", "-x": "-x",
|
||||||
|
} {
|
||||||
|
if got := CheckFamily(ct); got != want {
|
||||||
|
t.Errorf("CheckFamily(%q) = %q, want %q", ct, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// addCheck records one check for the address's current queue row.
|
||||||
|
func addCheck(t *testing.T, d *DB, addr, source, checkType, target string, success bool) {
|
||||||
|
t.Helper()
|
||||||
|
ctx := t.Context()
|
||||||
|
ip, err := d.GetIPByAddress(ctx, addr)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get %s: %v", addr, err)
|
||||||
|
}
|
||||||
|
if err := d.UpsertCheck(ctx, Check{
|
||||||
|
IPID: ip.ID, IPAddress: addr, AttemptNumber: ip.AttemptNumber,
|
||||||
|
Source: source, CheckType: checkType, Target: target,
|
||||||
|
Success: success, CheckedAt: Now(),
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("upsert check: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistryLevelsGroupByTypeAndLevel(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
if _, err := d.SubmitIPs(ctx, []string{"1.2.3.4"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
a := "1.2.3.4"
|
||||||
|
// Egress: https 2 of 3, icmp 1 of 1.
|
||||||
|
addCheck(t, d, a, SourceEgress, "https", "https://a.test", true)
|
||||||
|
addCheck(t, d, a, SourceEgress, "https", "https://b.test", true)
|
||||||
|
addCheck(t, d, a, SourceEgress, "https", "https://c.test", false)
|
||||||
|
addCheck(t, d, a, SourceEgress, "icmp", "a.test", true)
|
||||||
|
// Ingress from two sites: tcp-22 and tcp-443 are one family; tls, ssh,
|
||||||
|
// icmp and a type unknown today ("dns") are listed on their own.
|
||||||
|
for site := 1; site <= 2; site++ {
|
||||||
|
src := InboundSource(site)
|
||||||
|
addCheck(t, d, a, src, "tcp-22", a, true)
|
||||||
|
addCheck(t, d, a, src, "tcp-443", a, site == 1)
|
||||||
|
addCheck(t, d, a, src, "tls-443", a, true)
|
||||||
|
addCheck(t, d, a, src, "ssh", a, false)
|
||||||
|
addCheck(t, d, a, src, "icmp", a, true)
|
||||||
|
addCheck(t, d, a, src, "dns", a, true)
|
||||||
|
}
|
||||||
|
// A source that is neither egress nor an inbound site is not counted.
|
||||||
|
addCheck(t, d, a, "manual", "https", "x", true)
|
||||||
|
|
||||||
|
s, err := d.GetRegistryByAddress(ctx, a)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
wantEgress := LevelResult{Total: 4, OK: 3, ByType: []TypeStat{
|
||||||
|
{"https", 3, 2}, {"icmp", 1, 1},
|
||||||
|
}}
|
||||||
|
wantIngress := LevelResult{Total: 12, OK: 9, ByType: []TypeStat{
|
||||||
|
{"dns", 2, 2}, {"icmp", 2, 2}, {"ssh", 2, 0}, {"tcp", 4, 3}, {"tls", 2, 2},
|
||||||
|
}}
|
||||||
|
if !reflect.DeepEqual(s.Egress, wantEgress) {
|
||||||
|
t.Errorf("egress = %+v, want %+v", s.Egress, wantEgress)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(s.Ingress, wantIngress) {
|
||||||
|
t.Errorf("ingress = %+v, want %+v", s.Ingress, wantIngress)
|
||||||
|
}
|
||||||
|
if s.LastCycleID != 1 {
|
||||||
|
t.Errorf("LastCycleID = %d, want 1", s.LastCycleID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistryLevelsNoChecksAreZero(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
if _, err := d.SubmitIPs(ctx, []string{"1.2.3.4"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
s, err := d.GetRegistryByAddress(ctx, "1.2.3.4")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if s.LastCycleID != 0 || s.Egress.Total != 0 || s.Ingress.Total != 0 || len(s.Egress.ByType) != 0 {
|
||||||
|
t.Fatalf("expected empty levels, got %+v", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The counts follow the newest cycle, also after the queue row is deleted,
|
||||||
|
// and one grouped query serves several addresses without mixing them up.
|
||||||
|
func TestRegistryLevelsLatestCycleAndManyAddresses(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
if _, err := d.SubmitIPs(ctx, []string{"1.1.1.1", "2.2.2.2"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
addCheck(t, d, "1.1.1.1", SourceEgress, "https", "t1", false)
|
||||||
|
addCheck(t, d, "2.2.2.2", SourceEgress, "https", "t1", true)
|
||||||
|
addCheck(t, d, "2.2.2.2", InboundSource(1), "tcp-22", "2.2.2.2", true)
|
||||||
|
|
||||||
|
// New cycle for 1.1.1.1: delete and submit again.
|
||||||
|
ip, err := d.GetIPByAddress(ctx, "1.1.1.1")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := d.DeleteIP(ctx, ip.ID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := d.SubmitIPs(ctx, []string{"1.1.1.1"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
addCheck(t, d, "1.1.1.1", SourceEgress, "icmp", "t2", true)
|
||||||
|
addCheck(t, d, "1.1.1.1", SourceEgress, "https", "t2", true)
|
||||||
|
|
||||||
|
all, err := d.ListRegistry(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got := map[string]RegistrySummary{}
|
||||||
|
for _, s := range all {
|
||||||
|
got[s.IPAddress] = s
|
||||||
|
}
|
||||||
|
a := got["1.1.1.1"]
|
||||||
|
if a.LastCycleID != 2 || a.Egress.Total != 2 || a.Egress.OK != 2 || a.Ingress.Total != 0 {
|
||||||
|
t.Errorf("1.1.1.1: %+v", a)
|
||||||
|
}
|
||||||
|
b := got["2.2.2.2"]
|
||||||
|
if b.LastCycleID != 1 || b.Egress.Total != 1 || b.Ingress.Total != 1 || b.Ingress.OK != 1 {
|
||||||
|
t.Errorf("2.2.2.2: %+v", b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Page and single lookups agree with the full list.
|
||||||
|
page, _, err := d.ListRegistryPage(ctx, RegistryFilter{}, 10, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, s := range page {
|
||||||
|
if !reflect.DeepEqual(s.Egress, got[s.IPAddress].Egress) || !reflect.DeepEqual(s.Ingress, got[s.IPAddress].Ingress) {
|
||||||
|
t.Errorf("page differs from list for %s", s.IPAddress)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete the queue row of 2.2.2.2: the counts stay (history outlives it).
|
||||||
|
ip2, _ := d.GetIPByAddress(ctx, "2.2.2.2")
|
||||||
|
if err := d.DeleteIP(ctx, ip2.ID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
s, err := d.GetRegistryByAddress(ctx, "2.2.2.2")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if s.Egress.Total != 1 || s.Ingress.Total != 1 {
|
||||||
|
t.Errorf("after delete: %+v", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,387 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
"net/netip"
|
||||||
|
"sort"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Run kinds and states. A run groups the cycles of one launch of checks — see
|
||||||
|
// migrations/0011_check_runs.sql.
|
||||||
|
const (
|
||||||
|
RunManual = "manual"
|
||||||
|
RunAuto = "auto"
|
||||||
|
|
||||||
|
RunOpen = "open"
|
||||||
|
RunFinalized = "finalized"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CheckRun is one launch of checks. FinalizedAt is nil while it is open.
|
||||||
|
type CheckRun struct {
|
||||||
|
ID int64
|
||||||
|
Kind string
|
||||||
|
State string
|
||||||
|
StartedAt time.Time
|
||||||
|
FinalizedAt *time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// RunCounts is the verdict tally of a run.
|
||||||
|
type RunCounts struct {
|
||||||
|
Addresses int
|
||||||
|
Pass int
|
||||||
|
Partial int
|
||||||
|
Fail int
|
||||||
|
Cancelled int
|
||||||
|
}
|
||||||
|
|
||||||
|
// RunSummary is a run with its verdict tally, for the run selector. Pending
|
||||||
|
// is the number of its queue rows still being processed (open runs only).
|
||||||
|
type RunSummary struct {
|
||||||
|
CheckRun
|
||||||
|
RunCounts
|
||||||
|
Pending int
|
||||||
|
Total int
|
||||||
|
}
|
||||||
|
|
||||||
|
// openRunTx returns the id of the open run, creating one of the given kind if
|
||||||
|
// none is open. Called when addresses enter the queue: while a run is open
|
||||||
|
// everything submitted or re-checked joins it.
|
||||||
|
func openRunTx(ctx context.Context, tx *sql.Tx, kind, now string) (int64, error) {
|
||||||
|
var id int64
|
||||||
|
err := tx.QueryRowContext(ctx, `SELECT id FROM check_runs WHERE state=? ORDER BY id DESC LIMIT 1`, RunOpen).Scan(&id)
|
||||||
|
if err == nil {
|
||||||
|
return id, nil
|
||||||
|
}
|
||||||
|
if err != sql.ErrNoRows {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if kind == "" {
|
||||||
|
kind = RunManual
|
||||||
|
}
|
||||||
|
res, err := tx.ExecContext(ctx, `INSERT INTO check_runs (kind, state, started_at) VALUES (?, ?, ?)`, kind, RunOpen, now)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("open run: %w", err)
|
||||||
|
}
|
||||||
|
return res.LastInsertId()
|
||||||
|
}
|
||||||
|
|
||||||
|
// finalizeRunsTx finalizes every open run that has no queue row left in a
|
||||||
|
// non-terminal state, and drops finalized runs that ended up with no results
|
||||||
|
// at all (everything was deleted before any verdict). Called wherever a queue
|
||||||
|
// row reaches a terminal state or disappears.
|
||||||
|
func finalizeRunsTx(ctx context.Context, tx *sql.Tx, now string) error {
|
||||||
|
if _, err := tx.ExecContext(ctx, `
|
||||||
|
UPDATE check_runs SET state=?, finalized_at=COALESCE(
|
||||||
|
(SELECT MAX(aggregated_at) FROM run_results WHERE run_id=check_runs.id), ?)
|
||||||
|
WHERE state=? AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM ip_queue q WHERE q.run_id=check_runs.id AND q.state NOT IN (?, ?, ?))
|
||||||
|
`, RunFinalized, now, RunOpen, IPDone, IPFailed, IPOccupied); err != nil {
|
||||||
|
return fmt.Errorf("finalize runs: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := tx.ExecContext(ctx, `
|
||||||
|
DELETE FROM check_runs WHERE state=? AND NOT EXISTS (SELECT 1 FROM run_results r WHERE r.run_id=check_runs.id)
|
||||||
|
`, RunFinalized); err != nil {
|
||||||
|
return fmt.Errorf("drop empty runs: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FinalizeRuns finalizes runs whose addresses are all done. The orchestrator
|
||||||
|
// calls it every tick as a safety net; the terminal transitions already do it.
|
||||||
|
func (d *DB) FinalizeRuns(ctx context.Context) error {
|
||||||
|
tx, err := d.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
if err := finalizeRunsTx(ctx, tx, timeToDB(Now())); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
// upsertRunResultTx stores the verdict of the address's current cycle in its
|
||||||
|
// run. A re-check inside an open run replaces the earlier result. expected < 0
|
||||||
|
// means unknown. Rows without a run (queue rows that predate runs and never
|
||||||
|
// got one) are skipped.
|
||||||
|
func upsertRunResultTx(ctx context.Context, tx *sql.Tx, ipID int64, verdict string, expected int, now string) error {
|
||||||
|
var exp sql.NullInt64
|
||||||
|
if expected >= 0 {
|
||||||
|
exp = sql.NullInt64{Int64: int64(expected), Valid: true}
|
||||||
|
}
|
||||||
|
_, err := tx.ExecContext(ctx, `
|
||||||
|
INSERT INTO run_results (run_id, registry_id, ip_address, cycle_id, verdict, aggregated_at, expected_checks, recorded_checks)
|
||||||
|
SELECT q.run_id, q.registry_id, q.ip_address, q.cycle_id, ?, ?, ?,
|
||||||
|
(SELECT COUNT(*) FROM checks c WHERE c.registry_id=q.registry_id AND c.cycle_id=q.cycle_id)
|
||||||
|
FROM ip_queue q WHERE q.id=? AND q.run_id IS NOT NULL
|
||||||
|
ON CONFLICT(run_id, registry_id) DO UPDATE SET
|
||||||
|
cycle_id=excluded.cycle_id, verdict=excluded.verdict, verdict_derived=0,
|
||||||
|
aggregated_at=excluded.aggregated_at, expected_checks=excluded.expected_checks,
|
||||||
|
recorded_checks=excluded.recorded_checks
|
||||||
|
`, verdict, now, exp, ipID)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("record run result: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// adoptOrphanQueueRows gives every live queue row without a run (rows that
|
||||||
|
// predate runs) the open run, creating one. Runs once after migrating.
|
||||||
|
func (d *DB) adoptOrphanQueueRows(ctx context.Context) error {
|
||||||
|
tx, err := d.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
var n int
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM ip_queue WHERE run_id IS NULL AND state NOT IN (?, ?, ?)`,
|
||||||
|
IPDone, IPFailed, IPOccupied).Scan(&n); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
now := timeToDB(Now())
|
||||||
|
id, err := openRunTx(ctx, tx, RunManual, now)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := tx.ExecContext(ctx, `UPDATE ip_queue SET run_id=? WHERE run_id IS NULL AND state NOT IN (?, ?, ?)`,
|
||||||
|
id, IPDone, IPFailed, IPOccupied); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListRuns returns every run, newest first, with its verdict tally.
|
||||||
|
func (d *DB) ListRuns(ctx context.Context) ([]RunSummary, error) {
|
||||||
|
rows, err := d.QueryContext(ctx, `
|
||||||
|
SELECT r.id, r.kind, r.state, r.started_at, r.finalized_at,
|
||||||
|
COALESCE(SUM(CASE WHEN x.verdict IS NOT NULL THEN 1 ELSE 0 END), 0),
|
||||||
|
COALESCE(SUM(CASE WHEN x.verdict='pass' THEN 1 ELSE 0 END), 0),
|
||||||
|
COALESCE(SUM(CASE WHEN x.verdict='partial' THEN 1 ELSE 0 END), 0),
|
||||||
|
COALESCE(SUM(CASE WHEN x.verdict='fail' THEN 1 ELSE 0 END), 0),
|
||||||
|
COALESCE(SUM(CASE WHEN x.verdict='cancelled' THEN 1 ELSE 0 END), 0),
|
||||||
|
(SELECT COUNT(*) FROM ip_queue q WHERE q.run_id=r.id),
|
||||||
|
(SELECT COUNT(*) FROM ip_queue q WHERE q.run_id=r.id AND q.state NOT IN (?, ?, ?))
|
||||||
|
FROM check_runs r LEFT JOIN run_results x ON x.run_id=r.id
|
||||||
|
GROUP BY r.id ORDER BY r.id DESC
|
||||||
|
`, IPDone, IPFailed, IPOccupied)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var out []RunSummary
|
||||||
|
for rows.Next() {
|
||||||
|
var s RunSummary
|
||||||
|
var started string
|
||||||
|
var finalized sql.NullString
|
||||||
|
if err := rows.Scan(&s.ID, &s.Kind, &s.State, &started, &finalized,
|
||||||
|
&s.Addresses, &s.Pass, &s.Partial, &s.Fail, &s.Cancelled, &s.Total, &s.Pending); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if s.StartedAt, err = dbToTime(started); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if s.FinalizedAt, err = nullStringToTimePtr(finalized); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, s)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetRun returns one run, or ErrNotFound.
|
||||||
|
func (d *DB) GetRun(ctx context.Context, id int64) (*CheckRun, error) {
|
||||||
|
var r CheckRun
|
||||||
|
var started string
|
||||||
|
var finalized sql.NullString
|
||||||
|
err := d.QueryRowContext(ctx, `SELECT id, kind, state, started_at, finalized_at FROM check_runs WHERE id=?`, id).
|
||||||
|
Scan(&r.ID, &r.Kind, &r.State, &started, &finalized)
|
||||||
|
if err == sql.ErrNoRows {
|
||||||
|
return nil, fmt.Errorf("run %d: %w", id, ErrNotFound)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if r.StartedAt, err = dbToTime(started); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if r.FinalizedAt, err = nullStringToTimePtr(finalized); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &r, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RunResult is one address's result in a run.
|
||||||
|
type RunResult struct {
|
||||||
|
RegistryID int64
|
||||||
|
IPAddress string
|
||||||
|
CycleID int
|
||||||
|
Verdict string
|
||||||
|
Derived bool
|
||||||
|
AggregatedAt time.Time
|
||||||
|
ExpectedChecks int // -1 when unknown
|
||||||
|
RecordedChecks int
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListRunResults returns the results of a run in address order of insertion.
|
||||||
|
func (d *DB) ListRunResults(ctx context.Context, runID int64) ([]RunResult, error) {
|
||||||
|
rows, err := d.QueryContext(ctx, `
|
||||||
|
SELECT registry_id, ip_address, cycle_id, verdict, verdict_derived, aggregated_at, expected_checks, recorded_checks
|
||||||
|
FROM run_results WHERE run_id=? ORDER BY registry_id`, runID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var out []RunResult
|
||||||
|
for rows.Next() {
|
||||||
|
var r RunResult
|
||||||
|
var agg string
|
||||||
|
var exp sql.NullInt64
|
||||||
|
if err := rows.Scan(&r.RegistryID, &r.IPAddress, &r.CycleID, &r.Verdict, &r.Derived, &agg, &exp, &r.RecordedChecks); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if r.AggregatedAt, err = dbToTime(agg); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
r.ExpectedChecks = -1
|
||||||
|
if exp.Valid {
|
||||||
|
r.ExpectedChecks = int(exp.Int64)
|
||||||
|
}
|
||||||
|
out = append(out, r)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// RunCheck is one stored check of a run's result cycle, with what the
|
||||||
|
// analytics needs to place it.
|
||||||
|
type RunCheck struct {
|
||||||
|
RegistryID int64
|
||||||
|
Source string
|
||||||
|
CheckType string
|
||||||
|
Target string
|
||||||
|
Success bool
|
||||||
|
ValidatorID string
|
||||||
|
Detail string
|
||||||
|
RecordedAt time.Time
|
||||||
|
AfterVerdict bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// EachRunCheck calls fn for every check of the cycles that make up the run's
|
||||||
|
// results (the latest cycle of each address in the run), in one pass over the
|
||||||
|
// run_id index. fn must not call back into the DB (one connection).
|
||||||
|
func (d *DB) EachRunCheck(ctx context.Context, runID int64, fn func(RunCheck)) error {
|
||||||
|
rows, err := d.QueryContext(ctx, `
|
||||||
|
SELECT c.registry_id, c.source, c.check_type, c.target, c.success, c.validator_id, c.detail,
|
||||||
|
COALESCE(c.recorded_at, c.created_at), c.after_verdict
|
||||||
|
FROM checks c JOIN run_results r ON r.run_id=c.run_id AND r.registry_id=c.registry_id AND r.cycle_id=c.cycle_id
|
||||||
|
WHERE c.run_id=?`, runID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
for rows.Next() {
|
||||||
|
var c RunCheck
|
||||||
|
var rec string
|
||||||
|
if err := rows.Scan(&c.RegistryID, &c.Source, &c.CheckType, &c.Target, &c.Success, &c.ValidatorID, &c.Detail, &rec, &c.AfterVerdict); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if c.RecordedAt, err = dbToTime(rec); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fn(c)
|
||||||
|
}
|
||||||
|
return rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// RunDataVersion changes whenever a check of the run is written, so a cache of
|
||||||
|
// computed analytics can tell when it is stale.
|
||||||
|
func (d *DB) RunDataVersion(ctx context.Context, runID int64) (string, error) {
|
||||||
|
var maxID, n sql.NullInt64
|
||||||
|
var rec sql.NullString
|
||||||
|
if err := d.QueryRowContext(ctx, `SELECT MAX(id), COUNT(*), MAX(recorded_at) FROM checks WHERE run_id=?`, runID).Scan(&maxID, &n, &rec); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
var res sql.NullString
|
||||||
|
if err := d.QueryRowContext(ctx, `SELECT MAX(aggregated_at) FROM run_results WHERE run_id=?`, runID).Scan(&res); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%d/%d/%s/%s", maxID.Int64, n.Int64, rec.String, res.String), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Subnet is one entry of the administrator's subnet list.
|
||||||
|
type Subnet struct {
|
||||||
|
CIDR string
|
||||||
|
Label string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListSubnets returns the configured subnets, sorted by prefix.
|
||||||
|
func (d *DB) ListSubnets(ctx context.Context) ([]Subnet, error) {
|
||||||
|
rows, err := d.QueryContext(ctx, `SELECT cidr, label FROM subnets`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var out []Subnet
|
||||||
|
for rows.Next() {
|
||||||
|
var s Subnet
|
||||||
|
if err := rows.Scan(&s.CIDR, &s.Label); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, s)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
sort.Slice(out, func(i, j int) bool {
|
||||||
|
a, _ := netip.ParsePrefix(out[i].CIDR)
|
||||||
|
b, _ := netip.ParsePrefix(out[j].CIDR)
|
||||||
|
if a.Addr() != b.Addr() {
|
||||||
|
return a.Addr().Less(b.Addr())
|
||||||
|
}
|
||||||
|
return a.Bits() < b.Bits()
|
||||||
|
})
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReplaceSubnets replaces the whole subnet list. Every entry must be a valid
|
||||||
|
// CIDR; entries are stored in canonical form (host bits cleared) and
|
||||||
|
// duplicates collapse.
|
||||||
|
func (d *DB) ReplaceSubnets(ctx context.Context, subnets []Subnet) error {
|
||||||
|
canon := map[string]string{}
|
||||||
|
for _, s := range subnets {
|
||||||
|
p, err := netip.ParsePrefix(s.CIDR)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("subnet %q: %v: %w", s.CIDR, err, ErrValidation)
|
||||||
|
}
|
||||||
|
canon[p.Masked().String()] = s.Label
|
||||||
|
}
|
||||||
|
tx, err := d.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
if _, err := tx.ExecContext(ctx, `DELETE FROM subnets`); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for cidr, label := range canon {
|
||||||
|
if _, err := tx.ExecContext(ctx, `INSERT INTO subnets (cidr, label) VALUES (?, ?)`, cidr, label); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return tx.Commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
// CountRecheckedInRun returns how many addresses have more than one cycle of
|
||||||
|
// checks inside the run (re-checked while the run was open).
|
||||||
|
func (d *DB) CountRecheckedInRun(ctx context.Context, runID int64) (int, error) {
|
||||||
|
var n int
|
||||||
|
err := d.QueryRowContext(ctx, `
|
||||||
|
SELECT COUNT(*) FROM (SELECT registry_id FROM checks WHERE run_id=? GROUP BY registry_id HAVING COUNT(DISTINCT cycle_id) > 1)
|
||||||
|
`, runID).Scan(&n)
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
@@ -0,0 +1,389 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func submit(t *testing.T, d *DB, kind string, addrs ...string) {
|
||||||
|
t.Helper()
|
||||||
|
if _, err := d.SubmitIPsAs(context.Background(), addrs, kind); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func finish(t *testing.T, d *DB, addr, verdict string, expected int) {
|
||||||
|
t.Helper()
|
||||||
|
ctx := context.Background()
|
||||||
|
ip, err := d.GetIPByAddress(ctx, addr)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := d.FinishIPExpected(ctx, ip.ID, verdict, expected); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func runs(t *testing.T, d *DB) []RunSummary {
|
||||||
|
t.Helper()
|
||||||
|
r, err := d.ListRuns(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
// An address entering an idle queue opens a run; everything submitted while it
|
||||||
|
// is open joins it; it is finalized when the last address is done.
|
||||||
|
func TestRunOpensJoinsAndFinalizes(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
submit(t, d, RunAuto, "1.1.1.1", "2.2.2.2")
|
||||||
|
submit(t, d, RunManual, "3.3.3.3") // joins the open run, kind stays auto
|
||||||
|
|
||||||
|
rs := runs(t, d)
|
||||||
|
if len(rs) != 1 || rs[0].State != RunOpen || rs[0].Kind != RunAuto || rs[0].Total != 3 || rs[0].Pending != 3 {
|
||||||
|
t.Fatalf("expected one open auto run with 3 pending rows: %+v", rs)
|
||||||
|
}
|
||||||
|
a, _ := d.GetIPByAddress(ctx, "1.1.1.1")
|
||||||
|
c, _ := d.GetIPByAddress(ctx, "3.3.3.3")
|
||||||
|
if a.ID == 0 || c.ID == 0 {
|
||||||
|
t.Fatal("rows missing")
|
||||||
|
}
|
||||||
|
|
||||||
|
finish(t, d, "1.1.1.1", ResultPass, 22)
|
||||||
|
finish(t, d, "2.2.2.2", ResultPartial, 22)
|
||||||
|
if rs = runs(t, d); rs[0].State != RunOpen || rs[0].Addresses != 2 || rs[0].Pending != 1 {
|
||||||
|
t.Fatalf("one address still pending, the run stays open: %+v", rs[0])
|
||||||
|
}
|
||||||
|
finish(t, d, "3.3.3.3", ResultFail, -1)
|
||||||
|
|
||||||
|
rs = runs(t, d)
|
||||||
|
if rs[0].State != RunFinalized || rs[0].FinalizedAt == nil || rs[0].Pass != 1 || rs[0].Partial != 1 || rs[0].Fail != 1 || rs[0].Addresses != 3 {
|
||||||
|
t.Fatalf("expected a finalized run with the three verdicts: %+v", rs[0])
|
||||||
|
}
|
||||||
|
res, err := d.ListRunResults(ctx, rs[0].ID)
|
||||||
|
if err != nil || len(res) != 3 {
|
||||||
|
t.Fatalf("results: %v %v", res, err)
|
||||||
|
}
|
||||||
|
byIP := map[string]RunResult{}
|
||||||
|
for _, r := range res {
|
||||||
|
byIP[r.IPAddress] = r
|
||||||
|
}
|
||||||
|
if byIP["1.1.1.1"].ExpectedChecks != 22 || byIP["3.3.3.3"].ExpectedChecks != -1 || byIP["2.2.2.2"].Verdict != ResultPartial {
|
||||||
|
t.Fatalf("results: %+v", byIP)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A re-check after the run is finalized opens a new run and leaves the old one
|
||||||
|
// as it was; the old cycle's checks keep their run.
|
||||||
|
func TestRecheckAfterFinalizeOpensNewRun(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
ip := checkingIP(t, d, "1.1.1.1")
|
||||||
|
if _, err := d.UpsertCheckIfOpen(ctx, checkOf(ip, "icmp", true)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
finish(t, d, "1.1.1.1", ResultPass, 1)
|
||||||
|
first := runs(t, d)[0]
|
||||||
|
if first.State != RunFinalized {
|
||||||
|
t.Fatalf("expected finalized: %+v", first)
|
||||||
|
}
|
||||||
|
|
||||||
|
submit(t, d, RunManual, "1.1.1.1") // re-check of a finished address
|
||||||
|
rs := runs(t, d)
|
||||||
|
if len(rs) != 2 || rs[0].State != RunOpen || rs[0].ID == first.ID {
|
||||||
|
t.Fatalf("a re-check after the run ended must open a new run: %+v", rs)
|
||||||
|
}
|
||||||
|
ip, _ = d.GetIPByAddress(ctx, "1.1.1.1")
|
||||||
|
if err := d.SetChecking(ctx, ip.ID, time.Minute); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ip, _ = d.GetIP(ctx, ip.ID)
|
||||||
|
if _, err := d.UpsertCheckIfOpen(ctx, checkOf(ip, "icmp", false)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
finish(t, d, "1.1.1.1", ResultFail, 1)
|
||||||
|
|
||||||
|
var n1, n2 int
|
||||||
|
d.QueryRowContext(ctx, `SELECT COUNT(*) FROM checks WHERE run_id=?`, first.ID).Scan(&n1)
|
||||||
|
d.QueryRowContext(ctx, `SELECT COUNT(*) FROM checks WHERE run_id=?`, rs[0].ID).Scan(&n2)
|
||||||
|
if n1 != 1 || n2 != 1 {
|
||||||
|
t.Fatalf("each run keeps its own cycle's check: %d %d", n1, n2)
|
||||||
|
}
|
||||||
|
old, _ := d.ListRunResults(ctx, first.ID)
|
||||||
|
cur, _ := d.ListRunResults(ctx, rs[0].ID)
|
||||||
|
if len(old) != 1 || old[0].Verdict != ResultPass || old[0].CycleID != 1 || len(cur) != 1 || cur[0].Verdict != ResultFail || cur[0].CycleID != 2 {
|
||||||
|
t.Fatalf("results must not cross: old=%+v cur=%+v", old, cur)
|
||||||
|
}
|
||||||
|
// The checks of a run are the ones of its result cycle, nothing else.
|
||||||
|
var got []RunCheck
|
||||||
|
if err := d.EachRunCheck(ctx, first.ID, func(c RunCheck) { got = append(got, c) }); err != nil || len(got) != 1 || !got[0].Success {
|
||||||
|
t.Fatalf("run 1 checks: %+v %v", got, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A re-check while the run is still open joins it and replaces the address's
|
||||||
|
// result, so a run holds one result per address.
|
||||||
|
func TestRecheckInsideOpenRunReplacesResult(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
submit(t, d, RunManual, "1.1.1.1", "2.2.2.2")
|
||||||
|
finish(t, d, "1.1.1.1", ResultFail, 1)
|
||||||
|
submit(t, d, RunManual, "1.1.1.1") // while 2.2.2.2 is still pending
|
||||||
|
finish(t, d, "1.1.1.1", ResultPass, 1)
|
||||||
|
finish(t, d, "2.2.2.2", ResultPass, 1)
|
||||||
|
|
||||||
|
rs := runs(t, d)
|
||||||
|
if len(rs) != 1 || rs[0].Addresses != 2 || rs[0].Pass != 2 || rs[0].Fail != 0 {
|
||||||
|
t.Fatalf("expected one run with the latest verdicts: %+v", rs)
|
||||||
|
}
|
||||||
|
res, _ := d.ListRunResults(ctx, rs[0].ID)
|
||||||
|
for _, r := range res {
|
||||||
|
if r.IPAddress == "1.1.1.1" && r.CycleID != 2 {
|
||||||
|
t.Fatalf("the re-checked address must show its latest cycle: %+v", r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if n, err := d.CountRecheckedInRun(ctx, rs[0].ID); err != nil || n != 0 {
|
||||||
|
t.Fatalf("no checks stored, so no re-check counted: %d %v", n, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunEndsWhenQueueIsClearedOrDeleted(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
submit(t, d, RunManual, "1.1.1.1", "2.2.2.2")
|
||||||
|
finish(t, d, "1.1.1.1", ResultPass, 1)
|
||||||
|
if _, err := d.ClearAllIPs(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
rs := runs(t, d)
|
||||||
|
if len(rs) != 1 || rs[0].State != RunFinalized || rs[0].Addresses != 1 {
|
||||||
|
t.Fatalf("clearing ends the run with what it has: %+v", rs)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The next submission is a new run, not a join of the ended one.
|
||||||
|
submit(t, d, RunManual, "3.3.3.3")
|
||||||
|
if rs = runs(t, d); len(rs) != 2 || rs[0].State != RunOpen {
|
||||||
|
t.Fatalf("expected a new open run: %+v", rs)
|
||||||
|
}
|
||||||
|
// A run with no result at all disappears when its rows are deleted.
|
||||||
|
ip, _ := d.GetIPByAddress(ctx, "3.3.3.3")
|
||||||
|
if err := d.DeleteIP(ctx, ip.ID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if rs = runs(t, d); len(rs) != 1 {
|
||||||
|
t.Fatalf("an empty run must be dropped: %+v", rs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCancelAndRetryFailureRecordResults(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
submit(t, d, RunManual, "1.1.1.1", "2.2.2.2")
|
||||||
|
a, _ := d.GetIPByAddress(ctx, "1.1.1.1")
|
||||||
|
if err := d.CancelIP(ctx, a.ID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
b, _ := d.GetIPByAddress(ctx, "2.2.2.2")
|
||||||
|
if err := d.RequeueOrFail(ctx, b.ID, "", 0); err != nil { // retries exhausted at once
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
rs := runs(t, d)
|
||||||
|
if rs[0].State != RunFinalized || rs[0].Cancelled != 1 || rs[0].Fail != 1 {
|
||||||
|
t.Fatalf("cancelled and failed addresses are results of the run: %+v", rs[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ingress checks name the validator that held the address.
|
||||||
|
func TestIngressCheckTakesValidatorOfTheAddress(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
if err := d.RegisterValidator(ctx, "validator-7", "host", "port", "v"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ip := checkingIP(t, d, "1.1.1.1")
|
||||||
|
if _, err := d.ExecContext(ctx, `UPDATE ip_queue SET owner_validator_id='validator-7' WHERE id=?`, ip.ID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := d.UpsertCheckIfOpen(ctx, checkOf(ip, "icmp", true)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var v string
|
||||||
|
if err := d.QueryRowContext(ctx, `SELECT validator_id FROM checks WHERE ip_id=?`, ip.ID).Scan(&v); err != nil || v != "validator-7" {
|
||||||
|
t.Fatalf("validator of an ingress check = %q err=%v", v, err)
|
||||||
|
}
|
||||||
|
// An explicit validator (egress checks) is kept.
|
||||||
|
c := checkOf(ip, "https", true)
|
||||||
|
c.Source, c.ValidatorID, c.Target = SourceEgress, "validator-9", "https://x"
|
||||||
|
if _, err := d.UpsertCheckIfOpen(ctx, c); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := d.QueryRowContext(ctx, `SELECT validator_id FROM checks WHERE ip_id=? AND source='egress'`, ip.ID).Scan(&v); err != nil || v != "validator-9" {
|
||||||
|
t.Fatalf("egress validator = %q err=%v", v, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSubnetsReplaceAndValidate(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
if err := d.ReplaceSubnets(ctx, []Subnet{{CIDR: "10.1.2.3/24", Label: "a"}, {CIDR: "10.0.0.0/8"}, {CIDR: "10.1.2.0/24", Label: "dup"}}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got, err := d.ListSubnets(ctx)
|
||||||
|
if err != nil || len(got) != 2 || got[0].CIDR != "10.0.0.0/8" || got[1].CIDR != "10.1.2.0/24" {
|
||||||
|
t.Fatalf("subnets must be canonical, de-duplicated and sorted by prefix: %+v %v", got, err)
|
||||||
|
}
|
||||||
|
if err := d.ReplaceSubnets(ctx, []Subnet{{CIDR: "nonsense"}}); !errors.Is(err, ErrValidation) {
|
||||||
|
t.Fatalf("expected ErrValidation, got %v", err)
|
||||||
|
}
|
||||||
|
if got, _ := d.ListSubnets(ctx); len(got) != 2 {
|
||||||
|
t.Fatalf("a rejected list must leave the old one: %+v", got)
|
||||||
|
}
|
||||||
|
if err := d.ReplaceSubnets(ctx, nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got, _ := d.ListSubnets(ctx); len(got) != 0 {
|
||||||
|
t.Fatalf("an empty list clears: %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistryFilterByRunAndSubnet(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
submit(t, d, RunManual, "10.0.0.1", "10.0.0.2", "10.0.1.1")
|
||||||
|
for _, a := range []string{"10.0.0.1", "10.0.0.2", "10.0.1.1"} {
|
||||||
|
finish(t, d, a, ResultPass, -1)
|
||||||
|
}
|
||||||
|
runID := runs(t, d)[0].ID
|
||||||
|
submit(t, d, RunManual, "10.0.0.2") // second run holds only this address
|
||||||
|
finish(t, d, "10.0.0.2", ResultFail, -1)
|
||||||
|
secondID := runs(t, d)[0].ID
|
||||||
|
|
||||||
|
count := func(f RegistryFilter) int {
|
||||||
|
t.Helper()
|
||||||
|
_, total, err := d.ListRegistryPage(ctx, f, 50, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return total
|
||||||
|
}
|
||||||
|
if n := count(RegistryFilter{RunID: runID}); n != 3 {
|
||||||
|
t.Errorf("run 1: %d", n)
|
||||||
|
}
|
||||||
|
if n := count(RegistryFilter{RunID: secondID}); n != 1 {
|
||||||
|
t.Errorf("run 2: %d", n)
|
||||||
|
}
|
||||||
|
if n := count(RegistryFilter{Subnet: "10.0.0.0/24"}); n != 2 {
|
||||||
|
t.Errorf("subnet /24: %d", n)
|
||||||
|
}
|
||||||
|
if n := count(RegistryFilter{RunID: secondID, Subnet: "10.0.1.0/24"}); n != 0 {
|
||||||
|
t.Errorf("run 2 and the other subnet: %d", n)
|
||||||
|
}
|
||||||
|
if n := count(RegistryFilter{Subnet: "192.168.0.0/16"}); n != 0 {
|
||||||
|
t.Errorf("subnet with no address: %d", n)
|
||||||
|
}
|
||||||
|
if _, _, err := d.ListRegistryPage(ctx, RegistryFilter{Subnet: "x"}, 10, 0); !errors.Is(err, ErrValidation) {
|
||||||
|
t.Errorf("bad subnet: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Migration 0011 on a database of version 10: runs are cut at pauses of more
|
||||||
|
// than an hour, results come from the queue row or the checks, ingress checks
|
||||||
|
// get their validator from the fip_associated event, and live queue rows
|
||||||
|
// without a run are adopted into an open run when the database is opened.
|
||||||
|
func TestMigration0011BuildsRunsFromExistingData(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
path := filepath.Join(t.TempDir(), "old.db")
|
||||||
|
raw, err := sql.Open("sqlite", path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
raw.SetMaxOpenConns(1)
|
||||||
|
for _, m := range migrations {
|
||||||
|
if m.version > 10 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if _, err := raw.ExecContext(ctx, m.sql); err != nil {
|
||||||
|
t.Fatalf("migration %d: %v", m.version, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
raw.ExecContext(ctx, `PRAGMA user_version=10`)
|
||||||
|
exec := func(q string, args ...any) {
|
||||||
|
t.Helper()
|
||||||
|
if _, err := raw.ExecContext(ctx, q, args...); err != nil {
|
||||||
|
t.Fatalf("seed: %v\n%s", err, q)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const ts = "2026-10-02T13:00:00Z"
|
||||||
|
for i, ip := range []string{"1.1.1.1", "2.2.2.2", "3.3.3.3"} {
|
||||||
|
exec(`INSERT INTO ip_registry (id, ip_address, first_seen_at, last_seen_at, next_cycle, created_at, updated_at) VALUES (?, ?, ?, ?, 3, ?, ?)`, i+1, ip, ts, ts, ts, ts)
|
||||||
|
}
|
||||||
|
// 1.1.1.1 and 2.2.2.2 finish minutes apart (run 1); 1.1.1.1 is checked
|
||||||
|
// again three hours later (run 2). 3.3.3.3 is still in the queue.
|
||||||
|
exec(`INSERT INTO ip_queue (id, ip_address, sequence, state, overall_result, aggregated_at, registry_id, cycle_id, created_at, updated_at)
|
||||||
|
VALUES (1, '1.1.1.1', 1, 'done', 'fail', '2026-10-02T16:00:30Z', 1, 2, ?, ?), (2, '2.2.2.2', 2, 'done', 'pass', '2026-10-02T13:05:30Z', 2, 1, ?, ?),
|
||||||
|
(3, '3.3.3.3', 3, 'checking', '', NULL, 3, 1, ?, ?)`, ts, ts, ts, ts, ts, ts)
|
||||||
|
chk := func(reg, cyc int, src, typ string, ok int, at string) {
|
||||||
|
exec(`INSERT INTO checks (registry_id, cycle_id, ip_id, ip_address, attempt_number, validator_id, source, check_type, target, success, checked_at, created_at)
|
||||||
|
VALUES (?, ?, ?, 'x', 1, '', ?, ?, 't', ?, ?, ?)`, reg, cyc, reg, src, typ, ok, at, at)
|
||||||
|
}
|
||||||
|
chk(1, 1, "egress", "https", 1, "2026-10-02T13:00:10Z")
|
||||||
|
chk(1, 1, "inbound-site-1", "icmp", 1, "2026-10-02T13:00:20Z")
|
||||||
|
chk(2, 1, "egress", "https", 1, "2026-10-02T13:05:00Z")
|
||||||
|
chk(1, 2, "egress", "https", 0, "2026-10-02T16:00:10Z")
|
||||||
|
exec(`INSERT INTO events (source_type, source_id, ip_id, event_type, payload, occurred_at, registry_id, cycle_id) VALUES
|
||||||
|
('control-api', '', 1, 'fip_associated', '{"fip_id":"f","validator_id":"vkiplab-v5"}', ?, 1, 1),
|
||||||
|
('control-api', '', 2, 'aggregated', '{"result":"pass","checks":1,"passed":1,"missing":1}', ?, 2, 1)`, ts, ts)
|
||||||
|
raw.Close()
|
||||||
|
|
||||||
|
d, err := Open(ctx, path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open (runs migration 11): %v", err)
|
||||||
|
}
|
||||||
|
defer d.Close()
|
||||||
|
|
||||||
|
rs := runs(t, d)
|
||||||
|
// run 1 and run 2 from the checks, plus the open run that adopted 3.3.3.3
|
||||||
|
if len(rs) != 3 {
|
||||||
|
t.Fatalf("expected 3 runs, got %+v", rs)
|
||||||
|
}
|
||||||
|
var first, second, open RunSummary
|
||||||
|
for _, r := range rs {
|
||||||
|
switch {
|
||||||
|
case r.State == RunOpen:
|
||||||
|
open = r
|
||||||
|
case r.Addresses == 2:
|
||||||
|
first = r
|
||||||
|
default:
|
||||||
|
second = r
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if first.Pass != 2 || first.Fail != 0 || second.Fail != 1 || second.Addresses != 1 || open.Total != 1 {
|
||||||
|
t.Fatalf("runs: first=%+v second=%+v open=%+v", first, second, open)
|
||||||
|
}
|
||||||
|
res, _ := d.ListRunResults(ctx, first.ID)
|
||||||
|
for _, r := range res {
|
||||||
|
if r.IPAddress == "1.1.1.1" && (r.CycleID != 1 || r.Verdict != ResultPass || !r.Derived) {
|
||||||
|
// the queue row holds the later cycle, so this one is derived from its checks
|
||||||
|
t.Errorf("1.1.1.1 in the first run: %+v", r)
|
||||||
|
}
|
||||||
|
if r.IPAddress == "2.2.2.2" && (r.ExpectedChecks != 2 || r.RecordedChecks != 1 || r.Verdict != ResultPass || r.Derived) {
|
||||||
|
t.Errorf("result from the aggregated event: %+v", r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res2, _ := d.ListRunResults(ctx, second.ID)
|
||||||
|
if len(res2) != 1 || res2[0].CycleID != 2 || res2[0].Verdict != ResultFail || res2[0].Derived {
|
||||||
|
t.Errorf("second run result: %+v", res2)
|
||||||
|
}
|
||||||
|
var v string
|
||||||
|
if err := d.QueryRowContext(ctx, `SELECT validator_id FROM checks WHERE source='inbound-site-1'`).Scan(&v); err != nil || v != "vkiplab-v5" {
|
||||||
|
t.Errorf("ingress validator = %q err=%v", v, err)
|
||||||
|
}
|
||||||
|
var unset int
|
||||||
|
d.QueryRowContext(ctx, `SELECT COUNT(*) FROM checks WHERE run_id IS NULL`).Scan(&unset)
|
||||||
|
if unset != 0 {
|
||||||
|
t.Errorf("%d checks without a run", unset)
|
||||||
|
}
|
||||||
|
var ver int
|
||||||
|
d.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&ver)
|
||||||
|
if ver != 12 {
|
||||||
|
t.Errorf("user_version = %d", ver)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
"sort"
|
"sort"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -350,6 +351,33 @@ func TestMigration0009Indexes(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestRegistryLevelsQueryUsesIndex guards against a full scan of checks: both
|
||||||
|
// the per-address MAX(cycle_id) and the join back must go through
|
||||||
|
// idx_checks_registry_cycle.
|
||||||
|
func TestRegistryLevelsQueryUsesIndex(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
rows, err := d.QueryContext(ctx, "EXPLAIN QUERY PLAN "+registryLevelsQuery(3), 1, 2, 3)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var plan string
|
||||||
|
for rows.Next() {
|
||||||
|
var id, parent, unused int
|
||||||
|
var detail string
|
||||||
|
if err := rows.Scan(&id, &parent, &unused, &detail); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
plan += detail + "\n"
|
||||||
|
if strings.HasPrefix(detail, "SCAN") && strings.Contains(detail, "checks") {
|
||||||
|
t.Errorf("full scan of checks in plan:\n%s", plan)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !strings.Contains(plan, "idx_checks_registry_cycle") {
|
||||||
|
t.Errorf("expected idx_checks_registry_cycle in plan:\n%s", plan)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestScaleSmoke6440 pushes a realistic project size through the hot paths
|
// TestScaleSmoke6440 pushes a realistic project size through the hot paths
|
||||||
// with a loose time bound: the point is the absence of O(n^2) / N+1 work, not
|
// with a loose time bound: the point is the absence of O(n^2) / N+1 work, not
|
||||||
// a benchmark.
|
// a benchmark.
|
||||||
@@ -369,11 +397,36 @@ func TestScaleSmoke6440(t *testing.T) {
|
|||||||
}
|
}
|
||||||
submitDur := time.Since(start)
|
submitDur := time.Since(start)
|
||||||
|
|
||||||
|
// A realistic check set for the addresses of the registry page below:
|
||||||
|
// 12 egress and 18 ingress checks each.
|
||||||
|
for _, addr := range addrs[3000:3100] {
|
||||||
|
ip, err := d.GetIPByAddress(ctx, addr)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get %s: %v", addr, err)
|
||||||
|
}
|
||||||
|
for i := 0; i < 30; i++ {
|
||||||
|
source, checkType := SourceEgress, []string{"https", "icmp"}[i%2]
|
||||||
|
if i >= 12 {
|
||||||
|
source, checkType = InboundSource(i%3+1), fmt.Sprintf("tcp-%d", 20+i)
|
||||||
|
}
|
||||||
|
if err := d.UpsertCheck(ctx, Check{
|
||||||
|
IPID: ip.ID, IPAddress: addr, AttemptNumber: ip.AttemptNumber,
|
||||||
|
Source: source, CheckType: checkType, Target: fmt.Sprintf("t%d", i),
|
||||||
|
Success: i%5 != 0, CheckedAt: Now(),
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("upsert check: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
start = time.Now()
|
start = time.Now()
|
||||||
page, total, err := d.ListRegistryPage(ctx, RegistryFilter{}, 100, 3000)
|
page, total, err := d.ListRegistryPage(ctx, RegistryFilter{}, 100, 3000)
|
||||||
if err != nil || total != 6440 || len(page) != 100 {
|
if err != nil || total != 6440 || len(page) != 100 {
|
||||||
t.Fatalf("registry page: total=%d len=%d err=%v", total, len(page), err)
|
t.Fatalf("registry page: total=%d len=%d err=%v", total, len(page), err)
|
||||||
}
|
}
|
||||||
|
if e, i := page[0].Egress.Total, page[0].Ingress.Total; e != 12 || i != 18 {
|
||||||
|
t.Fatalf("levels of the first page row: egress=%d ingress=%d", e, i)
|
||||||
|
}
|
||||||
if _, total, err = d.ListRegistryPage(ctx, RegistryFilter{LastResult: ResultPass}, 100, 0); err != nil || total != 0 {
|
if _, total, err = d.ListRegistryPage(ctx, RegistryFilter{LastResult: ResultPass}, 100, 0); err != nil || total != 0 {
|
||||||
t.Fatalf("registry last_result filter: total=%d err=%v", total, err)
|
t.Fatalf("registry last_result filter: total=%d err=%v", total, err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,190 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"cloudipvalidator/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
// claimAwaitingSelfCheck claims the next address for the validator and brings
|
||||||
|
// it to awaiting_self_check, as the orchestrator does after the association.
|
||||||
|
func claimAwaitingSelfCheck(t *testing.T, ctx context.Context, d *DB, validatorID string) *IPQueueItem {
|
||||||
|
t.Helper()
|
||||||
|
item, err := d.ClaimNextQueued(ctx, validatorID, time.Minute)
|
||||||
|
if err != nil || item == nil {
|
||||||
|
t.Fatalf("claim for %s: item=%+v err=%v", validatorID, item, err)
|
||||||
|
}
|
||||||
|
if err := d.SetFIPAssociated(ctx, item.ID, "fip-"+item.IPAddress, time.Minute); err != nil {
|
||||||
|
t.Fatalf("set fip associated: %v", err)
|
||||||
|
}
|
||||||
|
return item
|
||||||
|
}
|
||||||
|
|
||||||
|
// A validator that failed the self-check of an address is not given that
|
||||||
|
// address again, takes the next one instead, and another validator takes the
|
||||||
|
// excluded one; the exclusion covers that address only.
|
||||||
|
func TestClaimSkipsAddressExcludedForValidator(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
if err := d.SeedQueue(ctx, []string{"1.1.1.1", "2.2.2.2"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, v := range []string{"v1", "v2"} {
|
||||||
|
if err := d.AdminCreateValidator(ctx, v, "port-"+v); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
first := claimAwaitingSelfCheck(t, ctx, d, "v1")
|
||||||
|
if first.IPAddress != "1.1.1.1" {
|
||||||
|
t.Fatalf("expected 1.1.1.1 first, got %s", first.IPAddress)
|
||||||
|
}
|
||||||
|
res, err := d.FailSelfCheck(ctx, first.ID, "v1", "ip echo timeout", 5)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("fail self-check: %v", err)
|
||||||
|
}
|
||||||
|
if res.Failed || res.NewRound || res.Failures != 1 {
|
||||||
|
t.Fatalf("expected a plain retry after the first failure, got %+v", res)
|
||||||
|
}
|
||||||
|
back, _ := d.GetIP(ctx, first.ID)
|
||||||
|
if back.State != IPQueued || back.RetryCount != 0 {
|
||||||
|
t.Fatalf("expected queued with retry_count untouched, got state=%s retry_count=%d", back.State, back.RetryCount)
|
||||||
|
}
|
||||||
|
if v, _ := d.GetValidator(ctx, "v1"); v.State != ValidatorIdle {
|
||||||
|
t.Fatalf("expected v1 freed to idle, got %s", v.State)
|
||||||
|
}
|
||||||
|
|
||||||
|
// v1 skips 1.1.1.1 (still ahead in the queue) and takes 2.2.2.2.
|
||||||
|
second, err := d.ClaimNextQueued(ctx, "v1", time.Minute)
|
||||||
|
if err != nil || second == nil || second.IPAddress != "2.2.2.2" {
|
||||||
|
t.Fatalf("expected v1 to take 2.2.2.2, got %+v err=%v", second, err)
|
||||||
|
}
|
||||||
|
// v2 takes the excluded address.
|
||||||
|
other, err := d.ClaimNextQueued(ctx, "v2", time.Minute)
|
||||||
|
if err != nil || other == nil || other.IPAddress != "1.1.1.1" {
|
||||||
|
t.Fatalf("expected v2 to take 1.1.1.1, got %+v err=%v", other, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// When every working validator has failed the address in the round, a new
|
||||||
|
// round starts and the exclusions lapse; an unreachable validator does not
|
||||||
|
// count as working.
|
||||||
|
func TestSelfCheckNewRoundLiftsExclusions(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
if err := d.SeedQueue(ctx, []string{"1.1.1.1"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, v := range []string{"v1", "v2"} {
|
||||||
|
if err := d.AdminCreateValidator(ctx, v, "port-"+v); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := d.Exec(`UPDATE validators SET state=? WHERE validator_id='v2'`, ValidatorUnreachable); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
item := claimAwaitingSelfCheck(t, ctx, d, "v1")
|
||||||
|
res, err := d.FailSelfCheck(ctx, item.ID, "v1", "x", 5)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !res.NewRound {
|
||||||
|
t.Fatalf("expected a new round (the only working validator failed it), got %+v", res)
|
||||||
|
}
|
||||||
|
again, err := d.ClaimNextQueued(ctx, "v1", time.Minute)
|
||||||
|
if err != nil || again == nil || again.IPAddress != "1.1.1.1" {
|
||||||
|
t.Fatalf("expected v1 to get the address again in the new round, got %+v err=%v", again, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reaching the ceiling gives the verdict fail; a re-submission starts a new
|
||||||
|
// series (counter and exclusions) but keeps the failure history.
|
||||||
|
func TestSelfCheckCeilingAndResubmit(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
if err := d.SeedQueue(ctx, []string{"1.1.1.1"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, v := range []string{"v1", "v2"} {
|
||||||
|
if err := d.AdminCreateValidator(ctx, v, "port-"+v); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
item := claimAwaitingSelfCheck(t, ctx, d, "v1")
|
||||||
|
if res, err := d.FailSelfCheck(ctx, item.ID, "v1", "x", 2); err != nil || res.Failed {
|
||||||
|
t.Fatalf("below the ceiling: res=%+v err=%v", res, err)
|
||||||
|
}
|
||||||
|
item = claimAwaitingSelfCheck(t, ctx, d, "v2")
|
||||||
|
res, err := d.FailSelfCheck(ctx, item.ID, "v2", "y", 2)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !res.Failed || res.Failures != 2 || len(res.Validators) != 2 || res.Validators[0] != "v1" || res.Validators[1] != "v2" {
|
||||||
|
t.Fatalf("expected fail at the ceiling on v1, v2, got %+v", res)
|
||||||
|
}
|
||||||
|
ip, _ := d.GetIP(ctx, item.ID)
|
||||||
|
if ip.State != IPFailed || ip.OverallResult != ResultFail {
|
||||||
|
t.Fatalf("expected failed/fail, got %s/%s", ip.State, ip.OverallResult)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := d.SubmitIPs(ctx, []string{"1.1.1.1"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var failures int
|
||||||
|
if err := d.QueryRow(`SELECT sc_failures FROM ip_queue WHERE id=?`, item.ID).Scan(&failures); err != nil || failures != 0 {
|
||||||
|
t.Fatalf("expected the series reset to 0, got %d err=%v", failures, err)
|
||||||
|
}
|
||||||
|
if got, err := d.ListSelfCheckFailedOn(ctx, ip.RegistryID, 0); err != nil || len(got) != 2 || got[0] != "v1" || got[1] != "v2" {
|
||||||
|
t.Fatalf("expected the history kept (v1, v2), got %v err=%v", got, err)
|
||||||
|
}
|
||||||
|
// v1 failed it before the re-submission, but is no longer excluded.
|
||||||
|
if again, err := d.ClaimNextQueued(ctx, "v1", time.Minute); err != nil || again == nil {
|
||||||
|
t.Fatalf("expected v1 to claim the re-submitted address, got %+v err=%v", again, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A late report for an address the validator does not hold is refused.
|
||||||
|
func TestFailSelfCheckRequiresAwaitingSelfCheckOnValidator(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
if err := d.SeedQueue(ctx, []string{"1.1.1.1"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, v := range []string{"v1", "v2"} {
|
||||||
|
if err := d.AdminCreateValidator(ctx, v, "port-"+v); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item := claimAwaitingSelfCheck(t, ctx, d, "v1")
|
||||||
|
if _, err := d.FailSelfCheck(ctx, item.ID, "v2", "late", 5); !errors.Is(err, ErrInvalidState) {
|
||||||
|
t.Fatalf("expected ErrInvalidState for another validator, got %v", err)
|
||||||
|
}
|
||||||
|
cur, _ := d.GetIP(ctx, item.ID)
|
||||||
|
if got, _ := d.ListSelfCheckFailedOn(ctx, cur.RegistryID, 0); len(got) != 0 {
|
||||||
|
t.Fatalf("a refused report must leave no history, got %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSelfCheckMaxAttemptsSetting(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
if err := d.BootstrapFromConfig(ctx, &config.ControlAPI{}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if s, err := d.GetSettings(ctx); err != nil || s.SelfCheckMaxAttempts != 5 {
|
||||||
|
t.Fatalf("expected default 5, got %+v err=%v", s, err)
|
||||||
|
}
|
||||||
|
for _, bad := range []int{0, -1, 51} {
|
||||||
|
if err := d.SetSelfCheckMaxAttempts(ctx, bad); !errors.Is(err, ErrValidation) {
|
||||||
|
t.Fatalf("expected ErrValidation for %d, got %v", bad, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, ok := range []int{1, 50} {
|
||||||
|
if err := d.SetSelfCheckMaxAttempts(ctx, ok); err != nil {
|
||||||
|
t.Fatalf("set %d: %v", ok, err)
|
||||||
|
}
|
||||||
|
if s, _ := d.GetSettings(ctx); s.SelfCheckMaxAttempts != ok {
|
||||||
|
t.Fatalf("expected %d, got %d", ok, s.SelfCheckMaxAttempts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,8 +13,8 @@ func (d *DB) GetSettings(ctx context.Context) (Settings, error) {
|
|||||||
var s Settings
|
var s Settings
|
||||||
var createdAt, updatedAt string
|
var createdAt, updatedAt string
|
||||||
err := d.QueryRowContext(ctx, `
|
err := d.QueryRowContext(ctx, `
|
||||||
SELECT fip_settle_seconds, history_retention_cycles, created_at, updated_at FROM settings WHERE id=1
|
SELECT fip_settle_seconds, history_retention_cycles, self_check_max_attempts, created_at, updated_at FROM settings WHERE id=1
|
||||||
`).Scan(&s.FIPSettleSeconds, &s.HistoryRetentionCycles, &createdAt, &updatedAt)
|
`).Scan(&s.FIPSettleSeconds, &s.HistoryRetentionCycles, &s.SelfCheckMaxAttempts, &createdAt, &updatedAt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Settings{}, err
|
return Settings{}, err
|
||||||
}
|
}
|
||||||
@@ -58,3 +58,17 @@ func (d *DB) SetHistoryRetentionCycles(ctx context.Context, cycles int) error {
|
|||||||
`, cycles, now)
|
`, cycles, now)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetSelfCheckMaxAttempts persists the ceiling of failed self-checks per
|
||||||
|
// address (1..MaxSelfCheckMaxAttempts). It applies from the next failed
|
||||||
|
// self-check, without a restart.
|
||||||
|
func (d *DB) SetSelfCheckMaxAttempts(ctx context.Context, attempts int) error {
|
||||||
|
if attempts < MinSelfCheckMaxAttempts || attempts > MaxSelfCheckMaxAttempts {
|
||||||
|
return fmt.Errorf("self_check_max_attempts must be in %d..%d: %w", MinSelfCheckMaxAttempts, MaxSelfCheckMaxAttempts, ErrValidation)
|
||||||
|
}
|
||||||
|
now := timeToDB(Now())
|
||||||
|
_, err := d.ExecContext(ctx, `
|
||||||
|
UPDATE settings SET self_check_max_attempts=?, updated_at=? WHERE id=1
|
||||||
|
`, attempts, now)
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// checkingIP submits one address and moves it to the checking state.
|
||||||
|
func checkingIP(t *testing.T, d *DB, addr string) *IPQueueItem {
|
||||||
|
t.Helper()
|
||||||
|
ctx := context.Background()
|
||||||
|
if _, err := d.SubmitIPs(ctx, []string{addr}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ip, err := d.GetIPByAddress(ctx, addr)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := d.SetChecking(ctx, ip.ID, time.Minute); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ip, err = d.GetIP(ctx, ip.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return ip
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkOf(ip *IPQueueItem, ct string, ok bool) Check {
|
||||||
|
return Check{IPID: ip.ID, IPAddress: ip.IPAddress, AttemptNumber: ip.AttemptNumber,
|
||||||
|
Source: InboundSource(1), CheckType: ct, Target: ip.IPAddress, Success: ok, CheckedAt: Now()}
|
||||||
|
}
|
||||||
|
|
||||||
|
func storedSuccess(t *testing.T, d *DB, ip *IPQueueItem, ct string) (success bool, found bool) {
|
||||||
|
t.Helper()
|
||||||
|
err := d.QueryRowContext(context.Background(),
|
||||||
|
`SELECT success FROM checks WHERE ip_id=? AND check_type=?`, ip.ID, ct).Scan(&success)
|
||||||
|
if err == sql.ErrNoRows {
|
||||||
|
return false, false
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return success, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Results are accepted while the address is being checked (also repeated ones,
|
||||||
|
// idempotently) and refused from the moment the verdict is being computed.
|
||||||
|
func TestUpsertCheckIfOpenFreezesAtVerdict(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
ip := checkingIP(t, d, "1.2.3.4")
|
||||||
|
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
if ok, err := d.UpsertCheckIfOpen(ctx, checkOf(ip, "tcp-22", true)); err != nil || !ok {
|
||||||
|
t.Fatalf("write %d while checking: ok=%v err=%v", i, ok, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var n int
|
||||||
|
if err := d.QueryRowContext(ctx, `SELECT COUNT(*) FROM checks WHERE ip_id=?`, ip.ID).Scan(&n); err != nil || n != 1 {
|
||||||
|
t.Fatalf("expected one row after repeated write, got %d err=%v", n, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// An older attempt's result does not touch the current attempt.
|
||||||
|
old := checkOf(ip, "icmp", true)
|
||||||
|
old.AttemptNumber = ip.AttemptNumber - 1
|
||||||
|
if ok, err := d.UpsertCheckIfOpen(ctx, old); err != nil || ok {
|
||||||
|
t.Fatalf("stale attempt must be dropped: ok=%v err=%v", ok, err)
|
||||||
|
}
|
||||||
|
if _, found := storedSuccess(t, d, ip, "icmp"); found {
|
||||||
|
t.Fatal("stale attempt wrote a row")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := d.SetAggregating(ctx, ip.ID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// Neither a new check nor a change of an existing one gets through.
|
||||||
|
if ok, err := d.UpsertCheckIfOpen(ctx, checkOf(ip, "ssh", false)); err != nil || ok {
|
||||||
|
t.Fatalf("new check while aggregating must be dropped: ok=%v err=%v", ok, err)
|
||||||
|
}
|
||||||
|
if ok, err := d.UpsertCheckIfOpen(ctx, checkOf(ip, "tcp-22", false)); err != nil || ok {
|
||||||
|
t.Fatalf("overwrite while aggregating must be dropped: ok=%v err=%v", ok, err)
|
||||||
|
}
|
||||||
|
if err := d.FinishIP(ctx, ip.ID, ResultPass); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ok, err := d.UpsertCheckIfOpen(ctx, checkOf(ip, "tcp-22", false)); err != nil || ok {
|
||||||
|
t.Fatalf("overwrite after the verdict must be dropped: ok=%v err=%v", ok, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if s, found := storedSuccess(t, d, ip, "tcp-22"); !found || !s {
|
||||||
|
t.Fatalf("stored tcp-22 changed after the verdict: found=%v success=%v", found, s)
|
||||||
|
}
|
||||||
|
if _, found := storedSuccess(t, d, ip, "ssh"); found {
|
||||||
|
t.Fatal("a check written after the verdict")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// recorded_at is the server's own write time and moves on every accepted write.
|
||||||
|
func TestUpsertCheckIfOpenSetsRecordedAt(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
ip := checkingIP(t, d, "1.2.3.4")
|
||||||
|
if _, err := d.UpsertCheckIfOpen(ctx, checkOf(ip, "icmp", true)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var first string
|
||||||
|
if err := d.QueryRowContext(ctx, `SELECT recorded_at FROM checks WHERE ip_id=?`, ip.ID).Scan(&first); err != nil || first == "" {
|
||||||
|
t.Fatalf("recorded_at not set: %q %v", first, err)
|
||||||
|
}
|
||||||
|
time.Sleep(5 * time.Millisecond)
|
||||||
|
if _, err := d.UpsertCheckIfOpen(ctx, checkOf(ip, "icmp", false)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var second, created string
|
||||||
|
if err := d.QueryRowContext(ctx, `SELECT recorded_at, created_at FROM checks WHERE ip_id=?`, ip.ID).Scan(&second, &created); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if second <= first || created != first {
|
||||||
|
t.Fatalf("recorded_at must advance, created_at stay: first=%s second=%s created=%s", first, second, created)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A prober site is handed an address until it reports it complete in the
|
||||||
|
// current attempt; other sites are unaffected; a new attempt hands it out again.
|
||||||
|
func TestListCheckingForSite(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
a := checkingIP(t, d, "1.1.1.1")
|
||||||
|
b := checkingIP(t, d, "2.2.2.2")
|
||||||
|
|
||||||
|
names := func(items []IPQueueItem) string {
|
||||||
|
s := ""
|
||||||
|
for _, it := range items {
|
||||||
|
s += it.IPAddress + " "
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
for site := 1; site <= 2; site++ {
|
||||||
|
items, err := d.ListCheckingForSite(ctx, site)
|
||||||
|
if err != nil || len(items) != 2 {
|
||||||
|
t.Fatalf("site %d before any report: %q err=%v", site, names(items), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := d.SetSiteComplete(ctx, a.ID, 1); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if items, _ := d.ListCheckingForSite(ctx, 1); names(items) != "2.2.2.2 " {
|
||||||
|
t.Fatalf("site 1 after completing 1.1.1.1: %q", names(items))
|
||||||
|
}
|
||||||
|
if items, _ := d.ListCheckingForSite(ctx, 2); len(items) != 2 {
|
||||||
|
t.Fatalf("site 2 must still get both: %q", names(items))
|
||||||
|
}
|
||||||
|
|
||||||
|
// A retry starts a new attempt: site 1 has to probe the address again.
|
||||||
|
if err := d.RequeueOrFail(ctx, a.ID, "", 3); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := d.SetChecking(ctx, a.ID, time.Minute); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if items, _ := d.ListCheckingForSite(ctx, 1); len(items) != 2 {
|
||||||
|
t.Fatalf("site 1 after a new attempt: %q", names(items))
|
||||||
|
}
|
||||||
|
_ = b
|
||||||
|
}
|
||||||
|
|
||||||
|
// The aggregation window counts from the start of checking; a retry clears it.
|
||||||
|
func TestCheckingStartedAt(t *testing.T) {
|
||||||
|
d, ctx := newTestDB(t)
|
||||||
|
ip := checkingIP(t, d, "1.2.3.4")
|
||||||
|
if ip.CheckingStartedAt == nil || time.Since(*ip.CheckingStartedAt) > time.Minute {
|
||||||
|
t.Fatalf("checking_started_at not set: %v", ip.CheckingStartedAt)
|
||||||
|
}
|
||||||
|
if err := d.RequeueOrFail(ctx, ip.ID, "", 3); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ip, err := d.GetIP(ctx, ip.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ip.CheckingStartedAt != nil {
|
||||||
|
t.Fatalf("checking_started_at must be cleared on requeue, got %v", ip.CheckingStartedAt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Migration 0010 flags the rows of an existing database that were written
|
||||||
|
// after their address's verdict, and leaves the others alone.
|
||||||
|
func TestMigration0010MarksRowsAfterVerdict(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
path := filepath.Join(t.TempDir(), "old.db")
|
||||||
|
raw, err := sql.Open("sqlite", path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
raw.SetMaxOpenConns(1)
|
||||||
|
for _, m := range migrations {
|
||||||
|
if m.version > 9 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if _, err := raw.ExecContext(ctx, m.sql); err != nil {
|
||||||
|
t.Fatalf("migration %d: %v", m.version, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := raw.ExecContext(ctx, `PRAGMA user_version=9`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, q := range []string{
|
||||||
|
`INSERT INTO ip_registry (id, ip_address, first_seen_at, last_seen_at, next_cycle, created_at, updated_at)
|
||||||
|
VALUES (1, '1.2.3.4', '2026-10-02T13:00:00Z', '2026-10-02T13:00:00Z', 2, '2026-10-02T13:00:00Z', '2026-10-02T13:00:00Z')`,
|
||||||
|
`INSERT INTO ip_queue (id, ip_address, sequence, state, overall_result, aggregated_at, registry_id, cycle_id, created_at, updated_at)
|
||||||
|
VALUES (1, '1.2.3.4', 1, 'done', 'pass', '2026-10-02T13:48:45.659Z', 1, 1, '2026-10-02T13:00:00Z', '2026-10-02T13:00:00Z')`,
|
||||||
|
// before the verdict, and (with a longer fraction) after it
|
||||||
|
`INSERT INTO checks (registry_id, cycle_id, ip_id, ip_address, attempt_number, validator_id, source, check_type, target, success, checked_at, created_at)
|
||||||
|
VALUES (1, 1, 1, '1.2.3.4', 1, '', 'inbound-site-1', 'icmp', '1.2.3.4', 1, '2026-10-02T13:48:40.100000000Z', '2026-10-02T13:48:40.2Z')`,
|
||||||
|
`INSERT INTO checks (registry_id, cycle_id, ip_id, ip_address, attempt_number, validator_id, source, check_type, target, success, checked_at, created_at)
|
||||||
|
VALUES (1, 1, 1, '1.2.3.4', 1, '', 'inbound-site-1', 'ssh', '1.2.3.4', 0, '2026-10-02T13:48:45.730314288Z', '2026-10-02T13:48:40.3Z')`,
|
||||||
|
} {
|
||||||
|
if _, err := raw.ExecContext(ctx, q); err != nil {
|
||||||
|
t.Fatalf("seed: %v\n%s", err, q)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
raw.Close()
|
||||||
|
|
||||||
|
d, err := Open(ctx, path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open (runs migration 10): %v", err)
|
||||||
|
}
|
||||||
|
defer d.Close()
|
||||||
|
flag := func(ct string) (after int, recorded, created string) {
|
||||||
|
if err := d.QueryRowContext(ctx, `SELECT after_verdict, recorded_at, created_at FROM checks WHERE check_type=?`, ct).Scan(&after, &recorded, &created); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if a, rec, cr := flag("icmp"); a != 0 || rec != cr {
|
||||||
|
t.Errorf("icmp: after_verdict=%d recorded=%s created=%s", a, rec, cr)
|
||||||
|
}
|
||||||
|
if a, rec, cr := flag("ssh"); a != 1 || rec != cr {
|
||||||
|
t.Errorf("ssh: after_verdict=%d recorded=%s created=%s", a, rec, cr)
|
||||||
|
}
|
||||||
|
var ver int
|
||||||
|
if err := d.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&ver); err != nil || ver != 12 {
|
||||||
|
t.Errorf("user_version=%d err=%v", ver, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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"] != 34 || counts["agent"] != 5 || counts["open"] != 8 {
|
if counts["admin"] != 41 || counts["agent"] != 5 || counts["open"] != 8 {
|
||||||
t.Fatalf("access counts = %v, want admin=34 agent=5 open=8", counts)
|
t.Fatalf("access counts = %v, want admin=41 agent=5 open=8", counts)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,6 +23,15 @@ type okResponse struct {
|
|||||||
OK bool `json:"ok"`
|
OK bool `json:"ok"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// resultsResponse answers the result-submission endpoints. Ignored counts the
|
||||||
|
// submitted checks that were dropped because the address already has its
|
||||||
|
// verdict (or the result belongs to an earlier attempt); the sender must not
|
||||||
|
// retry them.
|
||||||
|
type resultsResponse struct {
|
||||||
|
OK bool `json:"ok"`
|
||||||
|
Ignored int `json:"ignored,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
type observedIPResponse struct {
|
type observedIPResponse struct {
|
||||||
IP string `json:"ip"`
|
IP string `json:"ip"`
|
||||||
Source string `json:"source"`
|
Source string `json:"source"`
|
||||||
|
|||||||
@@ -93,6 +93,24 @@ type registryDTO struct {
|
|||||||
LastCheckedAt *time.Time `json:"last_checked_at"`
|
LastCheckedAt *time.Time `json:"last_checked_at"`
|
||||||
InQueue bool `json:"in_queue"`
|
InQueue bool `json:"in_queue"`
|
||||||
CurrentState string `json:"current_state"`
|
CurrentState string `json:"current_state"`
|
||||||
|
// LastCycleID is the cycle counted by Egress and Ingress (0 = no checks).
|
||||||
|
LastCycleID int `json:"last_cycle_id"`
|
||||||
|
Egress levelResultDTO `json:"egress"`
|
||||||
|
Ingress levelResultDTO `json:"ingress"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// levelResultDTO is "ok of total" recorded checks of one level in the last
|
||||||
|
// cycle, split by check family (tcp-22 and tcp-443 are both "tcp").
|
||||||
|
type levelResultDTO struct {
|
||||||
|
Total int `json:"total"`
|
||||||
|
OK int `json:"ok"`
|
||||||
|
ByType []typeStatDTO `json:"by_type"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type typeStatDTO struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
OK int `json:"ok"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type validatorDTO struct {
|
type validatorDTO struct {
|
||||||
@@ -144,12 +162,21 @@ type putCheckTypeRequest struct {
|
|||||||
Targets []string `json:"targets"`
|
Targets []string `json:"targets"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// orchestratorSettingsDTO doubles as both the GET response and the PUT
|
// orchestratorSettingsDTO is the GET response for
|
||||||
// request body for /api/v1/admin/config/orchestrator — a single-field DTO,
|
// /api/v1/admin/config/orchestrator.
|
||||||
// same shape both ways, like putSiteRequest/siteDTO.
|
|
||||||
type orchestratorSettingsDTO struct {
|
type orchestratorSettingsDTO struct {
|
||||||
FIPSettleSeconds int `json:"fip_settle_seconds"`
|
FIPSettleSeconds int `json:"fip_settle_seconds"`
|
||||||
HistoryRetentionCycles int `json:"history_retention_cycles"`
|
HistoryRetentionCycles int `json:"history_retention_cycles"`
|
||||||
|
SelfCheckMaxAttempts int `json:"self_check_max_attempts"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// putOrchestratorSettingsRequest is the PUT body. SelfCheckMaxAttempts is a
|
||||||
|
// pointer so that a client written before the field existed (it sends only
|
||||||
|
// the first two) leaves the ceiling unchanged instead of failing validation.
|
||||||
|
type putOrchestratorSettingsRequest struct {
|
||||||
|
FIPSettleSeconds int `json:"fip_settle_seconds"`
|
||||||
|
HistoryRetentionCycles int `json:"history_retention_cycles"`
|
||||||
|
SelfCheckMaxAttempts *int `json:"self_check_max_attempts"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// inboundChecksDTO doubles as both the GET response and the PUT request
|
// inboundChecksDTO doubles as both the GET response and the PUT request
|
||||||
|
|||||||
@@ -178,11 +178,23 @@ func (s *Server) handleAdminIPDetail(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeError(w, http.StatusInternalServerError, err.Error())
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// Self-check failures of this address in its current run.
|
||||||
|
runID, err := s.DB.GetIPRunID(r.Context(), item.ID)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
failedOn, err := s.DB.ListSelfCheckFailedOn(r.Context(), item.RegistryID, runID)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
writeJSON(w, http.StatusOK, struct {
|
writeJSON(w, http.StatusOK, struct {
|
||||||
IP *db.IPQueueItem `json:"ip"`
|
IP *db.IPQueueItem `json:"ip"`
|
||||||
Checks []db.Check `json:"checks"`
|
Checks []db.Check `json:"checks"`
|
||||||
Events []db.Event `json:"events"`
|
Events []db.Event `json:"events"`
|
||||||
}{item, checks, events})
|
SelfCheckFailedOn []string `json:"self_check_failed_on"`
|
||||||
|
}{item, checks, events, failedOn})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleAdminValidators(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleAdminValidators(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|||||||
@@ -149,6 +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{}
|
||||||
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 {
|
||||||
@@ -159,7 +160,7 @@ func (s *Server) handleAgentResults(w http.ResponseWriter, r *http.Request) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
checkedAt = db.Now()
|
checkedAt = db.Now()
|
||||||
}
|
}
|
||||||
err = s.Orch.RecordCheck(r.Context(), db.Check{
|
written, err := s.Orch.RecordCheckIfOpen(r.Context(), 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,
|
||||||
@@ -168,8 +169,11 @@ func (s *Server) handleAgentResults(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeError(w, http.StatusInternalServerError, err.Error())
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if !written {
|
||||||
|
dropped[item.ID]++
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, okResponse{OK: true})
|
}
|
||||||
|
writeJSON(w, http.StatusOK, s.reportDropped(r.Context(), "validator-agent", id, db.SourceEgress, dropped))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleAgentComplete(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleAgentComplete(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|||||||
@@ -0,0 +1,284 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/csv"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"cloudipvalidator/internal/analytics"
|
||||||
|
"cloudipvalidator/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// analyticsRunDTO is one entry of the run selector.
|
||||||
|
type analyticsRunDTO struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
State string `json:"state"`
|
||||||
|
StartedAt time.Time `json:"started_at"`
|
||||||
|
FinalizedAt *time.Time `json:"finalized_at"`
|
||||||
|
Addresses int `json:"addresses"`
|
||||||
|
Pass int `json:"pass"`
|
||||||
|
Partial int `json:"partial"`
|
||||||
|
Fail int `json:"fail"`
|
||||||
|
Cancelled int `json:"cancelled"`
|
||||||
|
// Total is the number of queue rows of the run, Pending those still being
|
||||||
|
// processed (only an open run has any).
|
||||||
|
Total int `json:"total"`
|
||||||
|
Pending int `json:"pending"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type subnetDTO struct {
|
||||||
|
CIDR string `json:"cidr"`
|
||||||
|
Label string `json:"label,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type subnetsDTO struct {
|
||||||
|
Subnets []subnetDTO `json:"subnets"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// analyticsCache keeps the computed analysis of finalized runs. An entry is
|
||||||
|
// valid while the run's data version (checks written, results) is unchanged;
|
||||||
|
// the subnet list is part of the key because it changes the grouping.
|
||||||
|
type analyticsCache struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
entries map[int64]analyticsEntry
|
||||||
|
}
|
||||||
|
|
||||||
|
type analyticsEntry struct {
|
||||||
|
version string
|
||||||
|
an *analytics.Analysis
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleAnalyticsRuns(w http.ResponseWriter, r *http.Request) {
|
||||||
|
runs, err := s.DB.ListRuns(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
writeDBError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out := make([]analyticsRunDTO, 0, len(runs))
|
||||||
|
for _, x := range runs {
|
||||||
|
out = append(out, analyticsRunDTO{
|
||||||
|
ID: x.ID, Kind: x.Kind, State: x.State, StartedAt: x.StartedAt, FinalizedAt: x.FinalizedAt,
|
||||||
|
Addresses: x.Addresses, Pass: x.Pass, Partial: x.Partial, Fail: x.Fail, Cancelled: x.Cancelled,
|
||||||
|
Total: x.Total, Pending: x.Pending,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// analysisFor returns the analysis of the run named by the {id} of the path;
|
||||||
|
// see analysisByID.
|
||||||
|
func (s *Server) analysisFor(w http.ResponseWriter, r *http.Request) *analytics.Analysis {
|
||||||
|
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||||
|
if err != nil || id <= 0 {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid run id")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return s.analysisByID(w, r, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// analysisByID returns the analysis of a finalized run, from the cache when
|
||||||
|
// the run's data has not changed since it was computed. It writes the error
|
||||||
|
// response itself and returns nil when it cannot.
|
||||||
|
func (s *Server) analysisByID(w http.ResponseWriter, r *http.Request, id int64) *analytics.Analysis {
|
||||||
|
ctx := r.Context()
|
||||||
|
run, err := s.DB.GetRun(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
writeDBError(w, err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if run.State != db.RunFinalized {
|
||||||
|
writeError(w, http.StatusConflict, "run is still open: analytics are available for finished runs")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
data, err := s.DB.RunDataVersion(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
writeDBError(w, err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
subnets, err := s.DB.ListSubnets(ctx)
|
||||||
|
if err != nil {
|
||||||
|
writeDBError(w, err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var sb strings.Builder
|
||||||
|
for _, x := range subnets {
|
||||||
|
sb.WriteString(x.CIDR + "|" + x.Label + ";")
|
||||||
|
}
|
||||||
|
version := data + "#" + sb.String()
|
||||||
|
|
||||||
|
s.analytics.mu.Lock()
|
||||||
|
defer s.analytics.mu.Unlock()
|
||||||
|
if e, ok := s.analytics.entries[id]; ok && e.version == version {
|
||||||
|
return e.an
|
||||||
|
}
|
||||||
|
an, err := analytics.Load(ctx, s.DB, id)
|
||||||
|
if err != nil {
|
||||||
|
writeDBError(w, err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if s.analytics.entries == nil {
|
||||||
|
s.analytics.entries = map[int64]analyticsEntry{}
|
||||||
|
}
|
||||||
|
s.analytics.entries[id] = analyticsEntry{version: version, an: an}
|
||||||
|
return an
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleAnalyticsRun(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if an := s.analysisFor(w, r); an != nil {
|
||||||
|
writeJSON(w, http.StatusOK, an.Report)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var nonSlug = regexp.MustCompile(`[^a-z0-9]+`)
|
||||||
|
|
||||||
|
// handleAnalyticsList serves the address table behind one indicator
|
||||||
|
// (kind = egress_https_any|egress_https_all|ingress_ssh_any|ingress_ssh_all),
|
||||||
|
// the addresses of one verdict (kind = verdict_pass|verdict_partial|verdict_fail)
|
||||||
|
// or one ingress error class (kind = error, ?class=...), as JSON or, with
|
||||||
|
// ?format=csv, as a downloadable CSV file.
|
||||||
|
func (s *Server) handleAnalyticsList(w http.ResponseWriter, r *http.Request) {
|
||||||
|
an := s.analysisFor(w, r)
|
||||||
|
if an == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
kind, class := r.PathValue("kind"), r.URL.Query().Get("class")
|
||||||
|
list, err := an.List(kind, class)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusNotFound, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.URL.Query().Get("format") != "csv" {
|
||||||
|
writeJSON(w, http.StatusOK, list)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name := kind
|
||||||
|
if kind == analytics.ListError {
|
||||||
|
if slug := strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(class), "-"), "-"); slug != "" {
|
||||||
|
name += "-" + slug
|
||||||
|
} else {
|
||||||
|
name += "-class"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writeCSV(w, list.Columns, list.Rows, fmt.Sprintf("%s_run%s.csv", name, r.PathValue("id")))
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeCSV sends a table as a downloadable CSV file.
|
||||||
|
func writeCSV(w http.ResponseWriter, columns []string, rows [][]string, filename string) {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
buf.WriteString("\xef\xbb\xbf") // UTF-8 BOM, so Excel opens the file as UTF-8
|
||||||
|
cw := csv.NewWriter(&buf)
|
||||||
|
cw.UseCRLF = true
|
||||||
|
_ = cw.Write(columns)
|
||||||
|
_ = cw.WriteAll(rows)
|
||||||
|
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||||
|
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
_, _ = w.Write(buf.Bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
// compareFor loads the two runs named by ?base=A&target=B (the older and the
|
||||||
|
// newer one) and compares them. It writes the error response itself and
|
||||||
|
// returns nil when it cannot: 400 for a missing or malformed id or the same
|
||||||
|
// run twice, 404 for an unknown run, 409 for one that is still open.
|
||||||
|
func (s *Server) compareFor(w http.ResponseWriter, r *http.Request) (c *analytics.Comparison, base, target int64) {
|
||||||
|
ids := [2]int64{}
|
||||||
|
for i, name := range []string{"base", "target"} {
|
||||||
|
id, err := strconv.ParseInt(r.URL.Query().Get(name), 10, 64)
|
||||||
|
if err != nil || id <= 0 {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid or missing "+name+" run id")
|
||||||
|
return nil, 0, 0
|
||||||
|
}
|
||||||
|
ids[i] = id
|
||||||
|
}
|
||||||
|
if ids[0] == ids[1] {
|
||||||
|
writeError(w, http.StatusBadRequest, "base and target must be different runs")
|
||||||
|
return nil, 0, 0
|
||||||
|
}
|
||||||
|
a := s.analysisByID(w, r, ids[0])
|
||||||
|
if a == nil {
|
||||||
|
return nil, 0, 0
|
||||||
|
}
|
||||||
|
b := s.analysisByID(w, r, ids[1])
|
||||||
|
if b == nil {
|
||||||
|
return nil, 0, 0
|
||||||
|
}
|
||||||
|
return analytics.Compare(a, b), ids[0], ids[1]
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleAnalyticsCompare serves the comparison of two finished runs:
|
||||||
|
// ?base=A (older) &target=B (newer).
|
||||||
|
func (s *Server) handleAnalyticsCompare(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if c, _, _ := s.compareFor(w, r); c != nil {
|
||||||
|
writeJSON(w, http.StatusOK, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleAnalyticsCompareList serves the address table of one group of the
|
||||||
|
// comparison (new|left|common|changed|same|entered|exited), narrowed by
|
||||||
|
// ?indicator=... and ?from=...&to=... (verdicts), as JSON or, with
|
||||||
|
// ?format=csv, as a downloadable CSV file.
|
||||||
|
func (s *Server) handleAnalyticsCompareList(w http.ResponseWriter, r *http.Request) {
|
||||||
|
c, base, target := s.compareFor(w, r)
|
||||||
|
if c == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
q := r.URL.Query()
|
||||||
|
group := r.PathValue("group")
|
||||||
|
f := analytics.CompareFilter{Indicator: q.Get("indicator"), From: q.Get("from"), To: q.Get("to")}
|
||||||
|
list, err := c.List(group, f)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusNotFound, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if q.Get("format") != "csv" {
|
||||||
|
writeJSON(w, http.StatusOK, list)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name := "compare_" + group
|
||||||
|
if f.Indicator != "" {
|
||||||
|
name += "_" + f.Indicator
|
||||||
|
}
|
||||||
|
if f.From != "" {
|
||||||
|
name += "_" + f.From + "-" + f.To
|
||||||
|
}
|
||||||
|
writeCSV(w, list.Columns, list.Rows, fmt.Sprintf("%s_run%d-%d.csv", name, base, target))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleConfigGetSubnets(w http.ResponseWriter, r *http.Request) {
|
||||||
|
list, err := s.DB.ListSubnets(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
writeDBError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out := subnetsDTO{Subnets: make([]subnetDTO, 0, len(list))}
|
||||||
|
for _, x := range list {
|
||||||
|
out.Subnets = append(out.Subnets, subnetDTO{CIDR: x.CIDR, Label: x.Label})
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleConfigPutSubnets replaces the whole subnet list. The list groups the
|
||||||
|
// addresses on the analytics page; with none configured they group by /24.
|
||||||
|
func (s *Server) handleConfigPutSubnets(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req subnetsDTO
|
||||||
|
if err := readJSON(r, &req); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid body: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
in := make([]db.Subnet, 0, len(req.Subnets))
|
||||||
|
for _, x := range req.Subnets {
|
||||||
|
in = append(in, db.Subnet{CIDR: strings.TrimSpace(x.CIDR), Label: x.Label})
|
||||||
|
}
|
||||||
|
if err := s.DB.ReplaceSubnets(r.Context(), in); err != nil {
|
||||||
|
writeDBError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.handleConfigGetSubnets(w, r)
|
||||||
|
}
|
||||||
@@ -0,0 +1,409 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"cloudipvalidator/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// finishedRun builds one finished run of two addresses through the real
|
||||||
|
// queue paths and returns its id: 9.9.9.1 passes, 9.9.9.2 has a failed ssh.
|
||||||
|
func finishedRun(t *testing.T, d *db.DB) int64 {
|
||||||
|
t.Helper()
|
||||||
|
ctx := context.Background()
|
||||||
|
if _, err := d.SubmitIPsAs(ctx, []string{"9.9.9.1", "9.9.9.2"}, db.RunManual); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, addr := range []string{"9.9.9.1", "9.9.9.2"} {
|
||||||
|
ip, err := d.GetIPByAddress(ctx, addr)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := d.SetChecking(ctx, ip.ID, time.Minute); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ip, _ = d.GetIP(ctx, ip.ID)
|
||||||
|
put := func(src, typ, target, detail string, ok bool) {
|
||||||
|
if _, err := d.UpsertCheckIfOpen(ctx, db.Check{IPID: ip.ID, IPAddress: addr, AttemptNumber: ip.AttemptNumber,
|
||||||
|
ValidatorID: "vkiplab-v1", Source: src, CheckType: typ, Target: target, Success: ok, Detail: detail, CheckedAt: db.Now()}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
put(db.SourceEgress, "https", "https://a.test", "", true)
|
||||||
|
put(db.InboundSource(1), "icmp", addr, "", true)
|
||||||
|
sshOK := addr == "9.9.9.1"
|
||||||
|
put(db.InboundSource(1), "ssh", addr, "dial tcp: i/o timeout", sshOK)
|
||||||
|
verdict := db.ResultPass
|
||||||
|
if !sshOK {
|
||||||
|
verdict = db.ResultPartial
|
||||||
|
}
|
||||||
|
if err := d.FinishIPExpected(ctx, ip.ID, verdict, 3); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rs, err := d.ListRuns(ctx)
|
||||||
|
if err != nil || len(rs) != 1 || rs[0].State != db.RunFinalized {
|
||||||
|
t.Fatalf("expected one finalized run: %+v %v", rs, err)
|
||||||
|
}
|
||||||
|
return rs[0].ID
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAnalyticsEndpoints(t *testing.T) {
|
||||||
|
fc, d, _, _ := newConfigTestHarness(t)
|
||||||
|
fc.do(http.MethodPut, "/api/v1/admin/config/sites/1", putSiteRequest{SiteID: "rxmsk"})
|
||||||
|
id := finishedRun(t, d)
|
||||||
|
base := "/api/v1/admin/analytics/runs"
|
||||||
|
|
||||||
|
resp, body := fc.do(http.MethodGet, base, nil)
|
||||||
|
var list []analyticsRunDTO
|
||||||
|
if resp.StatusCode != http.StatusOK || json.Unmarshal(body, &list) != nil || len(list) != 1 ||
|
||||||
|
list[0].State != "finalized" || list[0].Addresses != 2 || list[0].Pass != 1 || list[0].Partial != 1 {
|
||||||
|
t.Fatalf("runs: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, body = fc.do(http.MethodGet, base+"/"+itoa64(id), nil)
|
||||||
|
var rep struct {
|
||||||
|
Summary struct {
|
||||||
|
Addresses int `json:"addresses"`
|
||||||
|
IngressSSHAny int `json:"ingress_ssh_any_failed"`
|
||||||
|
IngressSSHAll int `json:"ingress_ssh_all_failed"`
|
||||||
|
} `json:"summary"`
|
||||||
|
Errors []struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Count int `json:"count"`
|
||||||
|
} `json:"errors"`
|
||||||
|
Sites struct {
|
||||||
|
Rows []struct {
|
||||||
|
Site string `json:"site"`
|
||||||
|
} `json:"rows"`
|
||||||
|
} `json:"sites"`
|
||||||
|
}
|
||||||
|
if resp.StatusCode != http.StatusOK || json.Unmarshal(body, &rep) != nil || rep.Summary.Addresses != 2 ||
|
||||||
|
rep.Summary.IngressSSHAny != 1 || rep.Summary.IngressSSHAll != 1 ||
|
||||||
|
len(rep.Errors) != 1 || rep.Errors[0].Name != "SSH: таймаут" || len(rep.Sites.Rows) != 1 || rep.Sites.Rows[0].Site != "rxmsk" {
|
||||||
|
t.Fatalf("report: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The list as JSON and as a CSV file with BOM and a download name.
|
||||||
|
resp, body = fc.do(http.MethodGet, base+"/"+itoa64(id)+"/lists/ingress_ssh_any", nil)
|
||||||
|
var l struct {
|
||||||
|
Columns []string `json:"columns"`
|
||||||
|
Rows [][]string `json:"rows"`
|
||||||
|
}
|
||||||
|
if resp.StatusCode != http.StatusOK || json.Unmarshal(body, &l) != nil || len(l.Rows) != 1 || l.Rows[0][0] != "9.9.9.2" {
|
||||||
|
t.Fatalf("list: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
resp, body = fc.do(http.MethodGet, base+"/"+itoa64(id)+"/lists/ingress_ssh_any?format=csv", nil)
|
||||||
|
if resp.StatusCode != http.StatusOK || !strings.HasPrefix(string(body), "\xef\xbb\xbf") ||
|
||||||
|
!strings.Contains(string(body), "9.9.9.2") || !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/csv") ||
|
||||||
|
!strings.Contains(resp.Header.Get("Content-Disposition"), `attachment; filename="ingress_ssh_any_run`+itoa64(id)+`.csv"`) {
|
||||||
|
t.Fatalf("csv: %d %v %q", resp.StatusCode, resp.Header, body)
|
||||||
|
}
|
||||||
|
// A verdict list: 9.9.9.2 is the only partial address.
|
||||||
|
resp, body = fc.do(http.MethodGet, base+"/"+itoa64(id)+"/lists/verdict_partial", nil)
|
||||||
|
if resp.StatusCode != http.StatusOK || json.Unmarshal(body, &l) != nil || len(l.Rows) != 1 || l.Rows[0][0] != "9.9.9.2" || l.Columns[len(l.Columns)-1] != "Причина" {
|
||||||
|
t.Fatalf("verdict list: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
resp, body = fc.do(http.MethodGet, base+"/"+itoa64(id)+"/lists/verdict_partial?format=csv", nil)
|
||||||
|
if resp.StatusCode != http.StatusOK || !strings.Contains(string(body), "9.9.9.2") ||
|
||||||
|
!strings.Contains(resp.Header.Get("Content-Disposition"), `attachment; filename="verdict_partial_run`+itoa64(id)+`.csv"`) {
|
||||||
|
t.Fatalf("verdict csv: %d %v %q", resp.StatusCode, resp.Header, body)
|
||||||
|
}
|
||||||
|
q := url.Values{"class": {"SSH: таймаут"}, "format": {"csv"}}
|
||||||
|
resp, body = fc.do(http.MethodGet, base+"/"+itoa64(id)+"/lists/error?"+q.Encode(), nil)
|
||||||
|
if resp.StatusCode != http.StatusOK || !strings.Contains(resp.Header.Get("Content-Disposition"), "error-ssh_run") {
|
||||||
|
t.Fatalf("error csv: %d %v %q", resp.StatusCode, resp.Header, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
for path, want := range map[string]int{
|
||||||
|
base + "/" + itoa64(id) + "/lists/error": http.StatusNotFound, // class missing
|
||||||
|
base + "/" + itoa64(id) + "/lists/nonsense": http.StatusNotFound,
|
||||||
|
base + "/" + itoa64(id) + "/lists/verdict_cancelled": http.StatusNotFound,
|
||||||
|
base + "/9999": http.StatusNotFound,
|
||||||
|
base + "/abc": http.StatusBadRequest,
|
||||||
|
base + "/9999/lists/ingress_ssh_any": http.StatusNotFound,
|
||||||
|
} {
|
||||||
|
if resp, body := fc.do(http.MethodGet, path, nil); resp.StatusCode != want {
|
||||||
|
t.Errorf("%s: %d %s, want %d", path, resp.StatusCode, body, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// secondRun builds the run after finishedRun's and returns its id: 9.9.9.1 is
|
||||||
|
// not in it, 9.9.9.2 is checked again and passes now, 9.9.9.3 is new and has a
|
||||||
|
// failed ssh. Against the first run: one new, one left, one changed address.
|
||||||
|
func secondRun(t *testing.T, d *db.DB) int64 {
|
||||||
|
t.Helper()
|
||||||
|
ctx := context.Background()
|
||||||
|
if _, err := d.SubmitIPsAs(ctx, []string{"9.9.9.2", "9.9.9.3"}, db.RunManual); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, addr := range []string{"9.9.9.2", "9.9.9.3"} {
|
||||||
|
ip, err := d.GetIPByAddress(ctx, addr)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := d.SetChecking(ctx, ip.ID, time.Minute); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ip, _ = d.GetIP(ctx, ip.ID)
|
||||||
|
put := func(src, typ, target string, ok bool) {
|
||||||
|
if _, err := d.UpsertCheckIfOpen(ctx, db.Check{IPID: ip.ID, IPAddress: addr, AttemptNumber: ip.AttemptNumber,
|
||||||
|
ValidatorID: "vkiplab-v1", Source: src, CheckType: typ, Target: target, Success: ok, Detail: "dial tcp: i/o timeout", CheckedAt: db.Now()}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
put(db.SourceEgress, "https", "https://a.test", true)
|
||||||
|
put(db.InboundSource(1), "icmp", addr, true)
|
||||||
|
sshOK := addr == "9.9.9.2"
|
||||||
|
put(db.InboundSource(1), "ssh", addr, sshOK)
|
||||||
|
verdict := db.ResultPass
|
||||||
|
if !sshOK {
|
||||||
|
verdict = db.ResultPartial
|
||||||
|
}
|
||||||
|
if err := d.FinishIPExpected(ctx, ip.ID, verdict, 3); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rs, err := d.ListRuns(ctx)
|
||||||
|
if err != nil || len(rs) != 2 || rs[0].State != db.RunFinalized {
|
||||||
|
t.Fatalf("expected two finalized runs: %+v %v", rs, err)
|
||||||
|
}
|
||||||
|
return rs[0].ID
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAnalyticsCompareEndpoints(t *testing.T) {
|
||||||
|
fc, d, _, _ := newConfigTestHarness(t)
|
||||||
|
fc.do(http.MethodPut, "/api/v1/admin/config/sites/1", putSiteRequest{SiteID: "rxmsk"})
|
||||||
|
a := finishedRun(t, d)
|
||||||
|
b := secondRun(t, d)
|
||||||
|
cmp := "/api/v1/admin/analytics/compare"
|
||||||
|
q := "?base=" + itoa64(a) + "&target=" + itoa64(b)
|
||||||
|
|
||||||
|
resp, body := fc.do(http.MethodGet, cmp+q, nil)
|
||||||
|
var rep struct {
|
||||||
|
Runs struct {
|
||||||
|
Base struct{ ID, Addresses int64 } `json:"base"`
|
||||||
|
Target struct{ ID, Addresses int64 } `json:"target"`
|
||||||
|
} `json:"runs"`
|
||||||
|
Groups struct {
|
||||||
|
New, Left, Common, Changed, Same int
|
||||||
|
} `json:"groups"`
|
||||||
|
Indicators []struct {
|
||||||
|
Key string
|
||||||
|
|
||||||
|
Base, Target, Delta, New, Left, Entered, Exited int
|
||||||
|
} `json:"indicators"`
|
||||||
|
Transitions struct {
|
||||||
|
Matrix [][]int `json:"matrix"`
|
||||||
|
} `json:"transitions"`
|
||||||
|
}
|
||||||
|
if resp.StatusCode != http.StatusOK || json.Unmarshal(body, &rep) != nil || rep.Runs.Base.ID != a || rep.Runs.Target.ID != b ||
|
||||||
|
rep.Runs.Base.Addresses != 2 || rep.Runs.Target.Addresses != 2 ||
|
||||||
|
rep.Groups.New != 1 || rep.Groups.Left != 1 || rep.Groups.Common != 1 || rep.Groups.Changed != 1 || rep.Groups.Same != 0 ||
|
||||||
|
len(rep.Indicators) != 7 || len(rep.Transitions.Matrix) != 3 || rep.Transitions.Matrix[1][0] != 1 {
|
||||||
|
t.Fatalf("compare: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
for _, ind := range rep.Indicators {
|
||||||
|
if ind.Delta != ind.New-ind.Left+ind.Entered-ind.Exited || ind.Delta != ind.Target-ind.Base {
|
||||||
|
t.Errorf("indicator %s: %+v", ind.Key, ind)
|
||||||
|
}
|
||||||
|
if ind.Key == "ingress_ssh_any" && (ind.Base != 1 || ind.Target != 1 || ind.New != 1 || ind.Exited != 1) {
|
||||||
|
t.Errorf("ssh any: %+v", ind)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lists: JSON, then CSV with BOM and the name of the file.
|
||||||
|
var l struct {
|
||||||
|
Group string `json:"group"`
|
||||||
|
Columns []string `json:"columns"`
|
||||||
|
Rows [][]string `json:"rows"`
|
||||||
|
}
|
||||||
|
resp, body = fc.do(http.MethodGet, cmp+"/lists/changed"+q, nil)
|
||||||
|
if resp.StatusCode != http.StatusOK || json.Unmarshal(body, &l) != nil || l.Group != "changed" || len(l.Rows) != 1 ||
|
||||||
|
l.Rows[0][0] != "9.9.9.2" || !strings.HasPrefix(l.Rows[0][2], "partial → pass") {
|
||||||
|
t.Fatalf("changed list: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
resp, body = fc.do(http.MethodGet, cmp+"/lists/new"+q+"&indicator=verdict_partial", nil)
|
||||||
|
if resp.StatusCode != http.StatusOK || json.Unmarshal(body, &l) != nil || len(l.Rows) != 1 || l.Rows[0][0] != "9.9.9.3" {
|
||||||
|
t.Fatalf("new list: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
resp, body = fc.do(http.MethodGet, cmp+"/lists/left"+q+"&indicator=verdict_pass", nil)
|
||||||
|
if resp.StatusCode != http.StatusOK || json.Unmarshal(body, &l) != nil || len(l.Rows) != 1 || l.Rows[0][0] != "9.9.9.1" {
|
||||||
|
t.Fatalf("left list: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
resp, body = fc.do(http.MethodGet, cmp+"/lists/common"+q+"&from=partial&to=pass", nil)
|
||||||
|
if resp.StatusCode != http.StatusOK || json.Unmarshal(body, &l) != nil || len(l.Rows) != 1 || l.Rows[0][0] != "9.9.9.2" {
|
||||||
|
t.Fatalf("matrix cell list: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
resp, body = fc.do(http.MethodGet, cmp+"/lists/exited"+q+"&indicator=ingress_ssh_any", nil)
|
||||||
|
if resp.StatusCode != http.StatusOK || json.Unmarshal(body, &l) != nil || len(l.Rows) != 1 || l.Rows[0][0] != "9.9.9.2" {
|
||||||
|
t.Fatalf("exited list: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
resp, body = fc.do(http.MethodGet, cmp+"/lists/changed"+q+"&format=csv", nil)
|
||||||
|
if resp.StatusCode != http.StatusOK || !strings.HasPrefix(string(body), "\xef\xbb\xbf") || !strings.Contains(string(body), "9.9.9.2") ||
|
||||||
|
!strings.HasPrefix(resp.Header.Get("Content-Type"), "text/csv") ||
|
||||||
|
!strings.Contains(resp.Header.Get("Content-Disposition"), `attachment; filename="compare_changed_run`+itoa64(a)+"-"+itoa64(b)+`.csv"`) {
|
||||||
|
t.Fatalf("csv: %d %v %q", resp.StatusCode, resp.Header, body)
|
||||||
|
}
|
||||||
|
resp, body = fc.do(http.MethodGet, cmp+"/lists/new"+q+"&indicator=verdict_partial&format=csv", nil)
|
||||||
|
if !strings.Contains(resp.Header.Get("Content-Disposition"), `filename="compare_new_verdict_partial_run`+itoa64(a)+"-"+itoa64(b)+`.csv"`) {
|
||||||
|
t.Fatalf("csv with an indicator: %d %v %q", resp.StatusCode, resp.Header, body)
|
||||||
|
}
|
||||||
|
resp, body = fc.do(http.MethodGet, cmp+"/lists/common"+q+"&from=partial&to=pass&format=csv", nil)
|
||||||
|
if !strings.Contains(resp.Header.Get("Content-Disposition"), `filename="compare_common_partial-pass_run`+itoa64(a)+"-"+itoa64(b)+`.csv"`) {
|
||||||
|
t.Fatalf("csv with verdicts: %d %v %q", resp.StatusCode, resp.Header, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The order is the caller's: swapped, the new address is the one that left.
|
||||||
|
swapped := "?base=" + itoa64(b) + "&target=" + itoa64(a)
|
||||||
|
resp, body = fc.do(http.MethodGet, cmp+"/lists/new"+swapped, nil)
|
||||||
|
if resp.StatusCode != http.StatusOK || json.Unmarshal(body, &l) != nil || len(l.Rows) != 1 || l.Rows[0][0] != "9.9.9.1" {
|
||||||
|
t.Fatalf("swapped: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
// An open run cannot be compared.
|
||||||
|
if _, err := d.SubmitIPs(context.Background(), []string{"9.9.9.9"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
rs, _ := d.ListRuns(context.Background())
|
||||||
|
open := itoa64(rs[0].ID)
|
||||||
|
if rs[0].State == db.RunFinalized {
|
||||||
|
t.Fatalf("expected an open run: %+v", rs[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
ida, idb := itoa64(a), itoa64(b)
|
||||||
|
for _, c := range []struct {
|
||||||
|
path string
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{cmp, http.StatusBadRequest}, // no ids
|
||||||
|
{cmp + "?base=" + ida, http.StatusBadRequest},
|
||||||
|
{cmp + "?target=" + ida, http.StatusBadRequest},
|
||||||
|
{cmp + "?base=abc&target=" + ida, http.StatusBadRequest},
|
||||||
|
{cmp + "?base=0&target=" + ida, http.StatusBadRequest},
|
||||||
|
{cmp + "?base=" + ida + "&target=" + ida, http.StatusBadRequest}, // the same run twice
|
||||||
|
{cmp + "/lists/changed?base=" + ida + "&target=" + ida, http.StatusBadRequest},
|
||||||
|
{cmp + "/lists/changed", http.StatusBadRequest},
|
||||||
|
{cmp + "?base=9999&target=" + ida, http.StatusNotFound},
|
||||||
|
{cmp + "?base=" + ida + "&target=9999", http.StatusNotFound},
|
||||||
|
{cmp + "?base=" + ida + "&target=" + open, http.StatusConflict},
|
||||||
|
{cmp + "/lists/changed?base=" + open + "&target=" + idb, http.StatusConflict},
|
||||||
|
{cmp + "/lists/nonsense" + q, http.StatusNotFound},
|
||||||
|
{cmp + "/lists/new" + q + "&indicator=nonsense", http.StatusNotFound},
|
||||||
|
{cmp + "/lists/entered" + q, http.StatusNotFound}, // an indicator is required
|
||||||
|
{cmp + "/lists/common" + q + "&from=pass", http.StatusNotFound},
|
||||||
|
{cmp + "/lists/common" + q + "&from=pass&to=cancelled", http.StatusNotFound},
|
||||||
|
} {
|
||||||
|
if resp, body := fc.do(http.MethodGet, c.path, nil); resp.StatusCode != c.want {
|
||||||
|
t.Errorf("%s: %d %s, want %d", c.path, resp.StatusCode, body, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// An open run has no analytics yet.
|
||||||
|
func TestAnalyticsOfOpenRunIsRefused(t *testing.T) {
|
||||||
|
fc, d, _, _ := newConfigTestHarness(t)
|
||||||
|
if _, err := d.SubmitIPs(context.Background(), []string{"9.9.9.1"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
rs, _ := d.ListRuns(context.Background())
|
||||||
|
resp, body := fc.do(http.MethodGet, "/api/v1/admin/analytics/runs/"+itoa64(rs[0].ID), nil)
|
||||||
|
if resp.StatusCode != http.StatusConflict {
|
||||||
|
t.Fatalf("open run: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The result is cached while the run is unchanged and recomputed when a
|
||||||
|
// check of the run is written or the subnet list changes.
|
||||||
|
func TestAnalyticsCacheFollowsData(t *testing.T) {
|
||||||
|
fc, d, _, _ := newConfigTestHarness(t)
|
||||||
|
id := finishedRun(t, d)
|
||||||
|
path := "/api/v1/admin/analytics/runs/" + itoa64(id)
|
||||||
|
subnetsOf := func() []string {
|
||||||
|
_, body := fc.do(http.MethodGet, path, nil)
|
||||||
|
var rep struct {
|
||||||
|
Subnets []struct {
|
||||||
|
CIDR string `json:"cidr"`
|
||||||
|
} `json:"subnets"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(body, &rep); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var out []string
|
||||||
|
for _, s := range rep.Subnets {
|
||||||
|
out = append(out, s.CIDR)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
if got := subnetsOf(); len(got) != 1 || got[0] != "9.9.9.0/24" {
|
||||||
|
t.Fatalf("without a list addresses group by /24: %v", got)
|
||||||
|
}
|
||||||
|
resp, body := fc.do(http.MethodPut, "/api/v1/admin/config/subnets", subnetsDTO{Subnets: []subnetDTO{{CIDR: "9.9.0.0/16", Label: "девятые"}}})
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
t.Fatalf("put subnets: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
if got := subnetsOf(); len(got) != 1 || got[0] != "9.9.0.0/16" {
|
||||||
|
t.Fatalf("a changed subnet list must change the report: %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSubnetsConfigEndpoints(t *testing.T) {
|
||||||
|
fc, _, _, _ := newConfigTestHarness(t)
|
||||||
|
resp, body := fc.do(http.MethodPut, "/api/v1/admin/config/subnets", subnetsDTO{Subnets: []subnetDTO{{CIDR: " 10.1.2.3/24 ", Label: "a"}, {CIDR: "10.0.0.0/8"}}})
|
||||||
|
var got subnetsDTO
|
||||||
|
if resp.StatusCode != http.StatusOK || json.Unmarshal(body, &got) != nil || len(got.Subnets) != 2 || got.Subnets[0].CIDR != "10.0.0.0/8" || got.Subnets[1].CIDR != "10.1.2.0/24" {
|
||||||
|
t.Fatalf("put: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
if resp, _ = fc.do(http.MethodPut, "/api/v1/admin/config/subnets", subnetsDTO{Subnets: []subnetDTO{{CIDR: "garbage"}}}); resp.StatusCode != http.StatusBadRequest {
|
||||||
|
t.Fatalf("garbage must be a 400, got %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
resp, body = fc.do(http.MethodGet, "/api/v1/admin/config/subnets", nil)
|
||||||
|
if resp.StatusCode != http.StatusOK || json.Unmarshal(body, &got) != nil || len(got.Subnets) != 2 {
|
||||||
|
t.Fatalf("a rejected list must leave the old one: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistryRunAndSubnetFilters(t *testing.T) {
|
||||||
|
fc, d, _, _ := newConfigTestHarness(t)
|
||||||
|
id := finishedRun(t, d)
|
||||||
|
// an address outside the run
|
||||||
|
if _, err := d.SubmitIPs(context.Background(), []string{"8.8.8.8"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
count := func(q string) int {
|
||||||
|
t.Helper()
|
||||||
|
resp, body := fc.do(http.MethodGet, "/api/v1/admin/registry?limit=50&"+q, nil)
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
t.Fatalf("%s: %d %s", q, resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
var p registryPageResponse
|
||||||
|
if err := json.Unmarshal(body, &p); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return p.Total
|
||||||
|
}
|
||||||
|
if n := count("run=" + itoa64(id)); n != 2 {
|
||||||
|
t.Errorf("run filter: %d", n)
|
||||||
|
}
|
||||||
|
if n := count("subnet=" + url.QueryEscape("9.9.9.0/24")); n != 2 {
|
||||||
|
t.Errorf("subnet filter: %d", n)
|
||||||
|
}
|
||||||
|
if n := count("run=" + itoa64(id) + "&subnet=" + url.QueryEscape("8.8.8.0/24")); n != 0 {
|
||||||
|
t.Errorf("run and subnet together: %d", n)
|
||||||
|
}
|
||||||
|
for _, bad := range []string{"run=abc", "run=0", "subnet=nonsense"} {
|
||||||
|
if resp, _ := fc.do(http.MethodGet, "/api/v1/admin/registry?limit=5&"+bad, nil); resp.StatusCode != http.StatusBadRequest {
|
||||||
|
t.Errorf("%s: %d, want 400", bad, resp.StatusCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func itoa64(n int64) string { return strconv.FormatInt(n, 10) }
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
@@ -203,6 +204,7 @@ func (s *Server) handleConfigGetOrchestratorSettings(w http.ResponseWriter, r *h
|
|||||||
writeJSON(w, http.StatusOK, orchestratorSettingsDTO{
|
writeJSON(w, http.StatusOK, orchestratorSettingsDTO{
|
||||||
FIPSettleSeconds: settings.FIPSettleSeconds,
|
FIPSettleSeconds: settings.FIPSettleSeconds,
|
||||||
HistoryRetentionCycles: settings.HistoryRetentionCycles,
|
HistoryRetentionCycles: settings.HistoryRetentionCycles,
|
||||||
|
SelfCheckMaxAttempts: settings.SelfCheckMaxAttempts,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -211,11 +213,17 @@ func (s *Server) handleConfigGetOrchestratorSettings(w http.ResponseWriter, r *h
|
|||||||
// needs cross-field validation against the static lease_ttl_seconds/
|
// needs cross-field validation against the static lease_ttl_seconds/
|
||||||
// self_check_timeout_seconds config, which only the orchestrator has.
|
// self_check_timeout_seconds config, which only the orchestrator has.
|
||||||
func (s *Server) handleConfigPutOrchestratorSettings(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleConfigPutOrchestratorSettings(w http.ResponseWriter, r *http.Request) {
|
||||||
var req orchestratorSettingsDTO
|
var req putOrchestratorSettingsRequest
|
||||||
if err := readJSON(r, &req); err != nil {
|
if err := readJSON(r, &req); err != nil {
|
||||||
writeError(w, http.StatusBadRequest, "invalid body: "+err.Error())
|
writeError(w, http.StatusBadRequest, "invalid body: "+err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// Checked before anything is saved, so a bad ceiling does not leave the
|
||||||
|
// other two settings half-applied. An omitted field keeps the current value.
|
||||||
|
if a := req.SelfCheckMaxAttempts; a != nil && (*a < db.MinSelfCheckMaxAttempts || *a > db.MaxSelfCheckMaxAttempts) {
|
||||||
|
writeError(w, http.StatusBadRequest, fmt.Sprintf("self_check_max_attempts must be in %d..%d", db.MinSelfCheckMaxAttempts, db.MaxSelfCheckMaxAttempts))
|
||||||
|
return
|
||||||
|
}
|
||||||
if err := s.Orch.SetFIPSettleSeconds(r.Context(), req.FIPSettleSeconds); err != nil {
|
if err := s.Orch.SetFIPSettleSeconds(r.Context(), req.FIPSettleSeconds); err != nil {
|
||||||
writeDBError(w, err)
|
writeDBError(w, err)
|
||||||
return
|
return
|
||||||
@@ -224,9 +232,22 @@ func (s *Server) handleConfigPutOrchestratorSettings(w http.ResponseWriter, r *h
|
|||||||
writeDBError(w, err)
|
writeDBError(w, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if req.SelfCheckMaxAttempts != nil {
|
||||||
|
if err := s.DB.SetSelfCheckMaxAttempts(r.Context(), *req.SelfCheckMaxAttempts); err != nil {
|
||||||
|
writeDBError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Answer with what is stored now, so an omitted ceiling shows its current value.
|
||||||
|
settings, err := s.DB.GetSettings(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
writeDBError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
writeJSON(w, http.StatusOK, orchestratorSettingsDTO{
|
writeJSON(w, http.StatusOK, orchestratorSettingsDTO{
|
||||||
FIPSettleSeconds: req.FIPSettleSeconds,
|
FIPSettleSeconds: settings.FIPSettleSeconds,
|
||||||
HistoryRetentionCycles: req.HistoryRetentionCycles,
|
HistoryRetentionCycles: settings.HistoryRetentionCycles,
|
||||||
|
SelfCheckMaxAttempts: settings.SelfCheckMaxAttempts,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -426,19 +426,32 @@ func TestOrchestratorSettingsGetPut(t *testing.T) {
|
|||||||
if err := json.Unmarshal(body, &got); err != nil {
|
if err := json.Unmarshal(body, &got); err != nil {
|
||||||
t.Fatalf("unmarshal get response: %v", err)
|
t.Fatalf("unmarshal get response: %v", err)
|
||||||
}
|
}
|
||||||
if got.FIPSettleSeconds != 0 {
|
if got.FIPSettleSeconds != 0 || got.SelfCheckMaxAttempts != 5 {
|
||||||
t.Fatalf("expected default 0, got %+v", got)
|
t.Fatalf("expected defaults 0 and 5, got %+v", got)
|
||||||
}
|
}
|
||||||
|
|
||||||
resp, body = fc.do(http.MethodPut, "/api/v1/admin/config/orchestrator", orchestratorSettingsDTO{FIPSettleSeconds: 20})
|
resp, body = fc.do(http.MethodPut, "/api/v1/admin/config/orchestrator", putOrchestratorSettingsRequest{FIPSettleSeconds: 20})
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
t.Fatalf("put settings: status=%d body=%s", resp.StatusCode, body)
|
t.Fatalf("put settings: status=%d body=%s", resp.StatusCode, body)
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(body, &got); err != nil {
|
if err := json.Unmarshal(body, &got); err != nil {
|
||||||
t.Fatalf("unmarshal put response: %v", err)
|
t.Fatalf("unmarshal put response: %v", err)
|
||||||
}
|
}
|
||||||
if got.FIPSettleSeconds != 20 {
|
if got.FIPSettleSeconds != 20 || got.SelfCheckMaxAttempts != 5 {
|
||||||
t.Fatalf("expected 20, got %+v", got)
|
t.Fatalf("expected 20 with the omitted ceiling kept at 5, got %+v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
eight := 8
|
||||||
|
resp, body = fc.do(http.MethodPut, "/api/v1/admin/config/orchestrator", putOrchestratorSettingsRequest{FIPSettleSeconds: 20, SelfCheckMaxAttempts: &eight})
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
t.Fatalf("put settings with ceiling: status=%d body=%s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
for _, bad := range []int{0, 51} {
|
||||||
|
bad := bad
|
||||||
|
resp, body = fc.do(http.MethodPut, "/api/v1/admin/config/orchestrator", putOrchestratorSettingsRequest{FIPSettleSeconds: 20, SelfCheckMaxAttempts: &bad})
|
||||||
|
if resp.StatusCode != http.StatusBadRequest {
|
||||||
|
t.Fatalf("expected 400 for self_check_max_attempts=%d, status=%d body=%s", bad, resp.StatusCode, body)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
resp, body = fc.do(http.MethodGet, "/api/v1/admin/config/orchestrator", nil)
|
resp, body = fc.do(http.MethodGet, "/api/v1/admin/config/orchestrator", nil)
|
||||||
@@ -448,8 +461,8 @@ func TestOrchestratorSettingsGetPut(t *testing.T) {
|
|||||||
if err := json.Unmarshal(body, &got); err != nil {
|
if err := json.Unmarshal(body, &got); err != nil {
|
||||||
t.Fatalf("unmarshal get-after-put response: %v", err)
|
t.Fatalf("unmarshal get-after-put response: %v", err)
|
||||||
}
|
}
|
||||||
if got.FIPSettleSeconds != 20 {
|
if got.FIPSettleSeconds != 20 || got.SelfCheckMaxAttempts != 8 {
|
||||||
t.Fatalf("expected 20 to persist, got %+v", got)
|
t.Fatalf("expected 20 and 8 to persist, got %+v", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -459,12 +472,12 @@ func TestOrchestratorSettingsPutValidation(t *testing.T) {
|
|||||||
fc, _, _, _ := newConfigTestHarness(t)
|
fc, _, _, _ := newConfigTestHarness(t)
|
||||||
// newConfigTestHarness: LeaseTTLSeconds=180, SelfCheckTimeoutSeconds=10.
|
// newConfigTestHarness: LeaseTTLSeconds=180, SelfCheckTimeoutSeconds=10.
|
||||||
|
|
||||||
resp, body := fc.do(http.MethodPut, "/api/v1/admin/config/orchestrator", orchestratorSettingsDTO{FIPSettleSeconds: 175})
|
resp, body := fc.do(http.MethodPut, "/api/v1/admin/config/orchestrator", putOrchestratorSettingsRequest{FIPSettleSeconds: 175})
|
||||||
if resp.StatusCode != http.StatusBadRequest {
|
if resp.StatusCode != http.StatusBadRequest {
|
||||||
t.Fatalf("expected 400 for settle seconds too close to lease ttl, status=%d body=%s", resp.StatusCode, body)
|
t.Fatalf("expected 400 for settle seconds too close to lease ttl, status=%d body=%s", resp.StatusCode, body)
|
||||||
}
|
}
|
||||||
|
|
||||||
resp, body = fc.do(http.MethodPut, "/api/v1/admin/config/orchestrator", orchestratorSettingsDTO{FIPSettleSeconds: -1})
|
resp, body = fc.do(http.MethodPut, "/api/v1/admin/config/orchestrator", putOrchestratorSettingsRequest{FIPSettleSeconds: -1})
|
||||||
if resp.StatusCode != http.StatusBadRequest {
|
if resp.StatusCode != http.StatusBadRequest {
|
||||||
t.Fatalf("expected 400 for negative settle seconds, status=%d body=%s", resp.StatusCode, body)
|
t.Fatalf("expected 400 for negative settle seconds, status=%d body=%s", resp.StatusCode, body)
|
||||||
}
|
}
|
||||||
@@ -479,7 +492,7 @@ func TestFIPSettleDelayGatesAssignmentEndpoint(t *testing.T) {
|
|||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
mock.Seed("fip-1", "9.9.9.9", "svc-project")
|
mock.Seed("fip-1", "9.9.9.9", "svc-project")
|
||||||
|
|
||||||
resp, body := fc.do(http.MethodPut, "/api/v1/admin/config/orchestrator", orchestratorSettingsDTO{FIPSettleSeconds: 1})
|
resp, body := fc.do(http.MethodPut, "/api/v1/admin/config/orchestrator", putOrchestratorSettingsRequest{FIPSettleSeconds: 1})
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
t.Fatalf("put settings: status=%d body=%s", resp.StatusCode, body)
|
t.Fatalf("put settings: status=%d body=%s", resp.StatusCode, body)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -41,9 +43,12 @@ func (s *Server) handleProberHeartbeat(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSON(w, http.StatusOK, okResponse{OK: true})
|
writeJSON(w, http.StatusOK, okResponse{OK: true})
|
||||||
}
|
}
|
||||||
|
|
||||||
// handleProberAssignments returns every IP currently in the checking
|
// handleProberAssignments returns every IP currently in the checking state
|
||||||
// state — probers work the whole active set each poll, not one IP at a
|
// that this site has not yet finished probing in the current attempt —
|
||||||
// time, since multiple validators run in parallel.
|
// probers work the whole active set each poll, not one IP at a time, since
|
||||||
|
// multiple validators run in parallel. An address is handed out until the
|
||||||
|
// site reports it complete, then no more: one probe round per site per
|
||||||
|
// attempt, so results are written once and never overwritten.
|
||||||
func (s *Server) handleProberAssignments(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleProberAssignments(w http.ResponseWriter, r *http.Request) {
|
||||||
siteID := r.PathValue("site_id")
|
siteID := r.PathValue("site_id")
|
||||||
idx, err := s.Orch.SiteIndexForID(r.Context(), siteID)
|
idx, err := s.Orch.SiteIndexForID(r.Context(), siteID)
|
||||||
@@ -55,7 +60,7 @@ func (s *Server) handleProberAssignments(w http.ResponseWriter, r *http.Request)
|
|||||||
writeError(w, http.StatusNotFound, "unknown site_id: "+siteID)
|
writeError(w, http.StatusNotFound, "unknown site_id: "+siteID)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
items, err := s.DB.ListChecking(r.Context())
|
items, err := s.DB.ListCheckingForSite(r.Context(), idx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeError(w, http.StatusInternalServerError, err.Error())
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
return
|
return
|
||||||
@@ -93,6 +98,7 @@ func (s *Server) handleProberResults(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
completed := map[int64]bool{}
|
completed := map[int64]bool{}
|
||||||
|
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 {
|
||||||
@@ -103,7 +109,7 @@ func (s *Server) handleProberResults(w http.ResponseWriter, r *http.Request) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
checkedAt = db.Now()
|
checkedAt = db.Now()
|
||||||
}
|
}
|
||||||
err = s.Orch.RecordCheck(r.Context(), db.Check{
|
written, err := s.Orch.RecordCheckIfOpen(r.Context(), 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,
|
||||||
@@ -112,6 +118,10 @@ func (s *Server) handleProberResults(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeError(w, http.StatusInternalServerError, err.Error())
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if !written {
|
||||||
|
dropped[item.ID]++
|
||||||
|
continue
|
||||||
|
}
|
||||||
if res.Complete {
|
if res.Complete {
|
||||||
completed[res.IPID] = true
|
completed[res.IPID] = true
|
||||||
}
|
}
|
||||||
@@ -122,5 +132,20 @@ func (s *Server) handleProberResults(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, okResponse{OK: true})
|
writeJSON(w, http.StatusOK, s.reportDropped(r.Context(), "prober", siteID, db.InboundSource(siteIndex), dropped))
|
||||||
|
}
|
||||||
|
|
||||||
|
// reportDropped records one result_dropped event per address whose submitted
|
||||||
|
// checks were refused (the verdict already exists, or the attempt is old) and
|
||||||
|
// builds the response. The events are the audit trail of how often senders
|
||||||
|
// are late; in a healthy run there are none.
|
||||||
|
func (s *Server) reportDropped(ctx context.Context, sourceType, sourceID, checkSource string, dropped map[int64]int) resultsResponse {
|
||||||
|
total := 0
|
||||||
|
for ipID, n := range dropped {
|
||||||
|
total += n
|
||||||
|
id := ipID
|
||||||
|
s.Orch.RecordEvent(ctx, sourceType, sourceID, &id, "result_dropped",
|
||||||
|
fmt.Sprintf(`{"source":%q,"dropped":%d}`, checkSource, n))
|
||||||
|
}
|
||||||
|
return resultsResponse{OK: true, Ignored: total}
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,7 @@ package httpapi
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/netip"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -22,7 +23,21 @@ func (s *Server) handleAdminRegistry(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeError(w, http.StatusBadRequest, err.Error())
|
writeError(w, http.StatusBadRequest, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
filter := db.RegistryFilter{Query: strings.TrimSpace(q.Get("q")), LastResult: q.Get("last_result")}
|
filter := db.RegistryFilter{Query: strings.TrimSpace(q.Get("q")), LastResult: q.Get("last_result"), Subnet: strings.TrimSpace(q.Get("subnet"))}
|
||||||
|
if filter.Subnet != "" {
|
||||||
|
if _, err := netip.ParsePrefix(filter.Subnet); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid subnet "+strconv.Quote(filter.Subnet)+" (a CIDR such as 203.0.113.0/24 is expected)")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if v := q.Get("run"); v != "" {
|
||||||
|
id, err := strconv.ParseInt(v, 10, 64)
|
||||||
|
if err != nil || id <= 0 {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid run "+strconv.Quote(v))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
filter.RunID = id
|
||||||
|
}
|
||||||
if filter.LastResult != "" && !db.IsValidResult(filter.LastResult) {
|
if filter.LastResult != "" && !db.IsValidResult(filter.LastResult) {
|
||||||
writeError(w, http.StatusBadRequest, "invalid last_result "+strconv.Quote(filter.LastResult)+" (valid: pass, partial, fail, cancelled)")
|
writeError(w, http.StatusBadRequest, "invalid last_result "+strconv.Quote(filter.LastResult)+" (valid: pass, partial, fail, cancelled)")
|
||||||
return
|
return
|
||||||
@@ -66,10 +81,17 @@ func (s *Server) handleAdminRegistryHistory(w http.ResponseWriter, r *http.Reque
|
|||||||
writeError(w, http.StatusInternalServerError, err.Error())
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// Self-check failures over every run of the address.
|
||||||
|
failedOn, err := s.DB.ListSelfCheckFailedOn(r.Context(), summary.ID, 0)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
writeJSON(w, http.StatusOK, struct {
|
writeJSON(w, http.StatusOK, struct {
|
||||||
Registry registryDTO `json:"registry"`
|
Registry registryDTO `json:"registry"`
|
||||||
Checks []db.Check `json:"checks"`
|
Checks []db.Check `json:"checks"`
|
||||||
}{registrySummaryToDTO(*summary), checks})
|
SelfCheckFailedOn []string `json:"self_check_failed_on"`
|
||||||
|
}{registrySummaryToDTO(*summary), checks, failedOn})
|
||||||
}
|
}
|
||||||
|
|
||||||
func registrySummaryToDTO(s db.RegistrySummary) registryDTO {
|
func registrySummaryToDTO(s db.RegistrySummary) registryDTO {
|
||||||
@@ -82,5 +104,16 @@ func registrySummaryToDTO(s db.RegistrySummary) registryDTO {
|
|||||||
LastCheckedAt: s.LastCheckedAt,
|
LastCheckedAt: s.LastCheckedAt,
|
||||||
InQueue: s.InQueue,
|
InQueue: s.InQueue,
|
||||||
CurrentState: s.CurrentState,
|
CurrentState: s.CurrentState,
|
||||||
|
LastCycleID: s.LastCycleID,
|
||||||
|
Egress: levelResultToDTO(s.Egress),
|
||||||
|
Ingress: levelResultToDTO(s.Ingress),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func levelResultToDTO(l db.LevelResult) levelResultDTO {
|
||||||
|
out := levelResultDTO{Total: l.Total, OK: l.OK, ByType: make([]typeStatDTO, len(l.ByType))}
|
||||||
|
for i, t := range l.ByType {
|
||||||
|
out.ByType[i] = typeStatDTO{Type: t.Type, Total: t.Total, OK: t.OK}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"reflect"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -149,3 +151,119 @@ func TestRegistryHistoryOutlivesIPDeletion(t *testing.T) {
|
|||||||
t.Fatalf("expected a single registry entry for the address, got %+v", all)
|
t.Fatalf("expected a single registry entry for the address, got %+v", all)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestAdminRegistryLevels proves the registry endpoints report the last
|
||||||
|
// cycle's recorded checks as "ok of total" per level (egress / ingress) and
|
||||||
|
// per check family, and that by_type is an empty list, not null, when a
|
||||||
|
// level has no checks.
|
||||||
|
func TestAdminRegistryLevels(t *testing.T) {
|
||||||
|
fc, d, _, _ := newConfigTestHarness(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
if _, err := d.SubmitIPs(ctx, []string{"7.7.7.7", "8.8.8.8"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ip, err := d.GetIPByAddress(ctx, "7.7.7.7")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, c := range []struct {
|
||||||
|
source, typ, target string
|
||||||
|
ok bool
|
||||||
|
}{
|
||||||
|
{db.SourceEgress, "https", "https://a.test", true},
|
||||||
|
{db.SourceEgress, "https", "https://b.test", false},
|
||||||
|
{db.SourceEgress, "icmp", "a.test", true},
|
||||||
|
{db.InboundSource(1), "tcp-22", "7.7.7.7", true},
|
||||||
|
{db.InboundSource(1), "tcp-443", "7.7.7.7", true},
|
||||||
|
{db.InboundSource(2), "tcp-22", "7.7.7.7", false},
|
||||||
|
} {
|
||||||
|
if err := d.UpsertCheck(ctx, db.Check{
|
||||||
|
IPID: ip.ID, IPAddress: "7.7.7.7", AttemptNumber: ip.AttemptNumber,
|
||||||
|
Source: c.source, CheckType: c.typ, Target: c.target, Success: c.ok, CheckedAt: db.Now(),
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, body := fc.do(http.MethodGet, "/api/v1/admin/registry/7.7.7.7", nil)
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
t.Fatalf("detail: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
var detail struct {
|
||||||
|
Registry registryDTO `json:"registry"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(body, &detail); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r := detail.Registry
|
||||||
|
if r.LastCycleID != 1 {
|
||||||
|
t.Errorf("last_cycle_id = %d", r.LastCycleID)
|
||||||
|
}
|
||||||
|
wantEgress := levelResultDTO{Total: 3, OK: 2, ByType: []typeStatDTO{{"https", 2, 1}, {"icmp", 1, 1}}}
|
||||||
|
wantIngress := levelResultDTO{Total: 3, OK: 2, ByType: []typeStatDTO{{"tcp", 3, 2}}}
|
||||||
|
if !reflect.DeepEqual(r.Egress, wantEgress) || !reflect.DeepEqual(r.Ingress, wantIngress) {
|
||||||
|
t.Errorf("egress=%+v ingress=%+v", r.Egress, r.Ingress)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The paginated list carries the same fields; an address without checks
|
||||||
|
// serialises empty levels as {"total":0,"ok":0,"by_type":[]}.
|
||||||
|
_, body = fc.do(http.MethodGet, "/api/v1/admin/registry?limit=10", nil)
|
||||||
|
var page registryPageResponse
|
||||||
|
if err := json.Unmarshal(body, &page); err != nil || len(page.Items) != 2 {
|
||||||
|
t.Fatalf("list: %v %s", err, body)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(page.Items[0].Egress, wantEgress) {
|
||||||
|
t.Errorf("list egress = %+v", page.Items[0].Egress)
|
||||||
|
}
|
||||||
|
if !bytes.Contains(body, []byte(`"egress":{"total":0,"ok":0,"by_type":[]}`)) {
|
||||||
|
t.Errorf("empty level must serialise by_type as [], got %s", body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSelfCheckFailedOnInAddressEndpoints proves GET /admin/ips/{ip} and GET
|
||||||
|
// /admin/registry/{ip} list the validators whose self-check of the address
|
||||||
|
// failed ([] when none).
|
||||||
|
func TestSelfCheckFailedOnInAddressEndpoints(t *testing.T) {
|
||||||
|
fc, d, orch, mock := newConfigTestHarness(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
mock.Seed("fip-1", "9.9.9.9", "svc-project")
|
||||||
|
fc.do(http.MethodPost, "/api/v1/admin/config/validators", createValidatorRequest{ValidatorID: "validator-1", OSPortID: "port-1"})
|
||||||
|
fc.do(http.MethodPost, "/api/v1/agents/register", registerAgentRequest{ValidatorID: "validator-1"})
|
||||||
|
fc.do(http.MethodPost, "/api/v1/admin/ips", submitIPsRequest{Addresses: []string{"9.9.9.9"}})
|
||||||
|
|
||||||
|
failedOn := func(path string) []string {
|
||||||
|
t.Helper()
|
||||||
|
resp, body := fc.do(http.MethodGet, path, nil)
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
t.Fatalf("get %s: status=%d body=%s", path, resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
var got struct {
|
||||||
|
SelfCheckFailedOn []string `json:"self_check_failed_on"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(body, &got); err != nil {
|
||||||
|
t.Fatalf("unmarshal %s: %v", path, err)
|
||||||
|
}
|
||||||
|
if got.SelfCheckFailedOn == nil {
|
||||||
|
t.Fatalf("%s: self_check_failed_on must be [] rather than null, body=%s", path, body)
|
||||||
|
}
|
||||||
|
return got.SelfCheckFailedOn
|
||||||
|
}
|
||||||
|
if got := failedOn("/api/v1/admin/ips/9.9.9.9"); len(got) != 0 {
|
||||||
|
t.Fatalf("expected no failures yet, got %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
orch.Tick(ctx) // claim + associate -> awaiting_self_check
|
||||||
|
ip, err := d.GetIPByAddress(ctx, "9.9.9.9")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := orch.SelfCheckResult(ctx, "validator-1", ip.ID, false, "ip echo timeout"); err != nil {
|
||||||
|
t.Fatalf("self-check result: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, path := range []string{"/api/v1/admin/ips/9.9.9.9", "/api/v1/admin/registry/9.9.9.9"} {
|
||||||
|
if got := failedOn(path); !reflect.DeepEqual(got, []string{"validator-1"}) {
|
||||||
|
t.Fatalf("%s: expected [validator-1], got %v", path, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"cloudipvalidator/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// setupCheckingIP stands up two sites and one validator and leaves 9.9.9.9 in
|
||||||
|
// the checking state.
|
||||||
|
func setupCheckingIP(t *testing.T) (*fakeClient, *db.DB, *db.IPQueueItem) {
|
||||||
|
t.Helper()
|
||||||
|
fc, d, orch, mock := newConfigTestHarness(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
mock.Seed("fip-1", "9.9.9.9", "svc-project")
|
||||||
|
fc.do(http.MethodPut, "/api/v1/admin/config/sites/1", putSiteRequest{SiteID: "site-1"})
|
||||||
|
fc.do(http.MethodPut, "/api/v1/admin/config/sites/2", putSiteRequest{SiteID: "site-2"})
|
||||||
|
fc.do(http.MethodPost, "/api/v1/admin/config/validators", createValidatorRequest{ValidatorID: "validator-1", OSPortID: "port-1"})
|
||||||
|
fc.do(http.MethodPost, "/api/v1/agents/register", registerAgentRequest{ValidatorID: "validator-1"})
|
||||||
|
fc.do(http.MethodPost, "/api/v1/admin/ips", submitIPsRequest{Addresses: []string{"9.9.9.9"}})
|
||||||
|
orch.Tick(ctx)
|
||||||
|
_, body := fc.do(http.MethodGet, "/api/v1/agents/validator-1/assignment", nil)
|
||||||
|
var a assignmentResponse
|
||||||
|
if err := json.Unmarshal(body, &a); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
fc.do(http.MethodPost, "/api/v1/agents/validator-1/self-check", selfCheckRequest{IPID: a.IPID, DetectedEgress: "9.9.9.9", Success: true, Detail: "matched"})
|
||||||
|
fc.do(http.MethodPost, "/api/v1/probers/register", registerProberRequest{SiteID: "site-1"})
|
||||||
|
fc.do(http.MethodPost, "/api/v1/probers/register", registerProberRequest{SiteID: "site-2"})
|
||||||
|
ip, err := d.GetIP(ctx, a.IPID)
|
||||||
|
if err != nil || ip.State != db.IPChecking {
|
||||||
|
t.Fatalf("expected checking: %v %+v", err, ip)
|
||||||
|
}
|
||||||
|
return fc, d, ip
|
||||||
|
}
|
||||||
|
|
||||||
|
func proberAssignmentsFor(t *testing.T, fc *fakeClient, site string) []proberAssignment {
|
||||||
|
t.Helper()
|
||||||
|
resp, body := fc.do(http.MethodGet, "/api/v1/probers/"+site+"/assignments", nil)
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
t.Fatalf("%s assignments: %d %s", site, resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
var out []proberAssignment
|
||||||
|
if err := json.Unmarshal(body, &out); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func proberResult(ip *db.IPQueueItem, ct string, ok, complete bool) proberResultDTO {
|
||||||
|
return proberResultDTO{IPID: ip.ID, IPAddress: ip.IPAddress, CheckType: ct, Success: ok,
|
||||||
|
CheckedAt: time.Now().UTC().Format(time.RFC3339Nano), Complete: complete}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A prober site gets an address until it has reported it complete, then not
|
||||||
|
// again; the other site still gets it.
|
||||||
|
func TestProberAssignmentsOncePerSite(t *testing.T) {
|
||||||
|
fc, _, ip := setupCheckingIP(t)
|
||||||
|
|
||||||
|
if len(proberAssignmentsFor(t, fc, "site-1")) != 1 || len(proberAssignmentsFor(t, fc, "site-2")) != 1 {
|
||||||
|
t.Fatal("both sites must get the address before reporting")
|
||||||
|
}
|
||||||
|
resp, body := fc.do(http.MethodPost, "/api/v1/probers/site-1/results", proberResultsRequest{
|
||||||
|
Results: []proberResultDTO{proberResult(ip, "tcp-22", true, false), proberResult(ip, "icmp", true, true)},
|
||||||
|
})
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
t.Fatalf("results: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
if got := proberAssignmentsFor(t, fc, "site-1"); len(got) != 0 {
|
||||||
|
t.Fatalf("site-1 must not get the address again after completing it: %+v", got)
|
||||||
|
}
|
||||||
|
if got := proberAssignmentsFor(t, fc, "site-2"); len(got) != 1 {
|
||||||
|
t.Fatalf("site-2 still has to probe the address: %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Results that arrive after the verdict are refused with ignored>0, leave the
|
||||||
|
// stored checks untouched and leave a result_dropped event behind; the same
|
||||||
|
// for the validator agent's results.
|
||||||
|
func TestResultsAfterVerdictAreIgnored(t *testing.T) {
|
||||||
|
fc, d, ip := setupCheckingIP(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
fc.do(http.MethodPost, "/api/v1/probers/site-1/results", proberResultsRequest{
|
||||||
|
Results: []proberResultDTO{proberResult(ip, "tcp-22", true, true)},
|
||||||
|
})
|
||||||
|
fc.do(http.MethodPost, "/api/v1/agents/validator-1/results", agentResultsRequest{
|
||||||
|
Results: []checkResultDTO{{IPID: ip.ID, CheckType: "https", Target: "https://example.test", Success: true, CheckedAt: time.Now().UTC().Format(time.RFC3339Nano)}},
|
||||||
|
})
|
||||||
|
if err := d.SetAggregating(ctx, ip.ID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := d.FinishIP(ctx, ip.ID, db.ResultPartial); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// prober: one new check and one that would flip a stored success
|
||||||
|
resp, body := fc.do(http.MethodPost, "/api/v1/probers/site-1/results", proberResultsRequest{
|
||||||
|
Results: []proberResultDTO{proberResult(ip, "tcp-22", false, false), proberResult(ip, "ssh", false, true)},
|
||||||
|
})
|
||||||
|
var rr resultsResponse
|
||||||
|
if resp.StatusCode != http.StatusOK || json.Unmarshal(body, &rr) != nil || !rr.OK || rr.Ignored != 2 {
|
||||||
|
t.Fatalf("prober late results: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
// agent
|
||||||
|
resp, body = fc.do(http.MethodPost, "/api/v1/agents/validator-1/results", agentResultsRequest{
|
||||||
|
Results: []checkResultDTO{{IPID: ip.ID, CheckType: "https", Target: "https://example.test", Success: false, CheckedAt: time.Now().UTC().Format(time.RFC3339Nano)}},
|
||||||
|
})
|
||||||
|
if resp.StatusCode != http.StatusOK || json.Unmarshal(body, &rr) != nil || rr.Ignored != 1 {
|
||||||
|
t.Fatalf("agent late results: %d %s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
rows, err := d.ListChecksForAttempt(ctx, ip.ID, ip.AttemptNumber)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(rows) != 2 {
|
||||||
|
t.Fatalf("expected the 2 checks written before the verdict, got %d", len(rows))
|
||||||
|
}
|
||||||
|
for _, c := range rows {
|
||||||
|
if !c.Success {
|
||||||
|
t.Errorf("%s/%s changed after the verdict", c.Source, c.CheckType)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var dropped int
|
||||||
|
if err := d.QueryRowContext(ctx, `SELECT COUNT(*) FROM events WHERE event_type='result_dropped' AND ip_id=?`, ip.ID).Scan(&dropped); err != nil || dropped != 2 {
|
||||||
|
t.Fatalf("expected 2 result_dropped events (prober, agent), got %d err=%v", dropped, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -65,6 +65,13 @@ func (s *Server) routeTable() []route {
|
|||||||
{"POST /api/v1/admin/auto-cycle/stop", s.handleAdminStopAutoCycle, accessAdmin},
|
{"POST /api/v1/admin/auto-cycle/stop", s.handleAdminStopAutoCycle, accessAdmin},
|
||||||
{"GET /api/v1/admin/registry", s.handleAdminRegistry, accessAdmin},
|
{"GET /api/v1/admin/registry", s.handleAdminRegistry, accessAdmin},
|
||||||
{"GET /api/v1/admin/registry/{ip}", s.handleAdminRegistryHistory, accessAdmin},
|
{"GET /api/v1/admin/registry/{ip}", s.handleAdminRegistryHistory, accessAdmin},
|
||||||
|
{"GET /api/v1/admin/analytics/runs", s.handleAnalyticsRuns, accessAdmin},
|
||||||
|
{"GET /api/v1/admin/analytics/runs/{id}", s.handleAnalyticsRun, accessAdmin},
|
||||||
|
{"GET /api/v1/admin/analytics/runs/{id}/lists/{kind}", s.handleAnalyticsList, accessAdmin},
|
||||||
|
{"GET /api/v1/admin/analytics/compare", s.handleAnalyticsCompare, accessAdmin},
|
||||||
|
{"GET /api/v1/admin/analytics/compare/lists/{group}", s.handleAnalyticsCompareList, accessAdmin},
|
||||||
|
{"GET /api/v1/admin/config/subnets", s.handleConfigGetSubnets, accessAdmin},
|
||||||
|
{"PUT /api/v1/admin/config/subnets", s.handleConfigPutSubnets, accessAdmin},
|
||||||
{"GET /api/v1/admin/config/validators", s.handleConfigListValidators, accessAdmin},
|
{"GET /api/v1/admin/config/validators", s.handleConfigListValidators, accessAdmin},
|
||||||
{"POST /api/v1/admin/config/validators", s.handleConfigCreateValidator, accessAdmin},
|
{"POST /api/v1/admin/config/validators", s.handleConfigCreateValidator, accessAdmin},
|
||||||
{"PUT /api/v1/admin/config/validators/{id}", s.handleConfigUpdateValidator, accessAdmin},
|
{"PUT /api/v1/admin/config/validators/{id}", s.handleConfigUpdateValidator, accessAdmin},
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ type Server struct {
|
|||||||
Orch *orchestrator.Orchestrator
|
Orch *orchestrator.Orchestrator
|
||||||
Log *slog.Logger
|
Log *slog.Logger
|
||||||
Auth Authenticator
|
Auth Authenticator
|
||||||
|
|
||||||
|
analytics analyticsCache
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(d *db.DB, o *orchestrator.Orchestrator, log *slog.Logger) *Server {
|
func New(d *db.DB, o *orchestrator.Orchestrator, log *slog.Logger) *Server {
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -128,6 +129,9 @@ func (o *Orchestrator) Tick(ctx context.Context) {
|
|||||||
if err := o.sweepExpiredLeases(ctx); err != nil {
|
if err := o.sweepExpiredLeases(ctx); err != nil {
|
||||||
o.Log.Error("sweep expired leases", "err", err)
|
o.Log.Error("sweep expired leases", "err", err)
|
||||||
}
|
}
|
||||||
|
if err := o.DB.FinalizeRuns(ctx); err != nil {
|
||||||
|
o.Log.Error("finalize runs", "err", err)
|
||||||
|
}
|
||||||
if !o.Async {
|
if !o.Async {
|
||||||
o.wg.Wait()
|
o.wg.Wait()
|
||||||
}
|
}
|
||||||
@@ -240,9 +244,9 @@ func (o *Orchestrator) SelfCheckResult(ctx context.Context, validatorID string,
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
// Detach the floating IP before the address goes back to the queue.
|
// Detach the floating IP before the address goes back to the queue.
|
||||||
// requeueOrFail frees the validator in the database but knows nothing
|
// The database side (db.FailSelfCheck) frees the validator but knows
|
||||||
// about the cloud: a floating IP left on the validator's port makes
|
// nothing about the cloud: a floating IP left on the validator's port
|
||||||
// every later association on that port fail with 409 ("fixed IP
|
// makes every later association on that port fail with 409 ("fixed IP
|
||||||
// already has a floating IP"). Best-effort, like the other release
|
// already has a floating IP"). Best-effort, like the other release
|
||||||
// paths — the database state must be freed even if Neutron hiccups.
|
// paths — the database state must be freed even if Neutron hiccups.
|
||||||
if item.FIPID != "" {
|
if item.FIPID != "" {
|
||||||
@@ -250,20 +254,48 @@ func (o *Orchestrator) SelfCheckResult(ctx context.Context, validatorID string,
|
|||||||
o.Log.Error("disassociate fip after failed self-check", "ip_id", ipID, "fip_id", item.FIPID, "err", err)
|
o.Log.Error("disassociate fip after failed self-check", "ip_id", ipID, "fip_id", item.FIPID, "err", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if item.RetryCount+1 > o.Cfg.MaxSelfCheckRetries {
|
return o.failSelfCheck(ctx, item, validatorID, detail)
|
||||||
o.requeueOrFail(ctx, ipID, validatorID, "self-check failed: "+detail)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
// Retry association without fully requeuing: re-drive the same
|
|
||||||
// claim by cycling back through requeue/claim keeps the logic in
|
|
||||||
// one place at the cost of the IP briefly returning to `queued`.
|
|
||||||
o.requeueOrFail(ctx, ipID, validatorID, "self-check failed, retrying: "+detail)
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return o.DB.SetChecking(ctx, ipID, o.leaseTTL())
|
return o.DB.SetChecking(ctx, ipID, o.leaseTTL())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// failSelfCheck records a failed self-check and decides what happens to the
|
||||||
|
// address (see db.FailSelfCheck): the ceiling self_check_max_attempts is read
|
||||||
|
// from the settings on every failure, so a change applies to the next one. The
|
||||||
|
// retry_count / max_retries pair is not involved: a failed self-check has its
|
||||||
|
// own ceiling, and the validator that failed it is not handed this address
|
||||||
|
// again in the current round (db.ClaimNextQueued). The validator itself stays
|
||||||
|
// in service.
|
||||||
|
func (o *Orchestrator) failSelfCheck(ctx context.Context, item *db.IPQueueItem, validatorID, detail string) error {
|
||||||
|
settings, err := o.DB.GetSettings(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
res, err := o.DB.FailSelfCheck(ctx, item.ID, validatorID, detail, settings.SelfCheckMaxAttempts)
|
||||||
|
if errors.Is(err, db.ErrInvalidState) {
|
||||||
|
o.Log.Warn("ignoring failed self-check for an address the validator does not hold",
|
||||||
|
"validator", validatorID, "ip_id", item.ID)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if res.Failed {
|
||||||
|
o.event(ctx, "control-api", "", &item.ID, "retry_or_fail",
|
||||||
|
fmt.Sprintf(`{"reason":%q}`, fmt.Sprintf("self-check failed %d times (on %s), giving up: %s",
|
||||||
|
res.Failures, strings.Join(res.Validators, ", "), detail)))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
o.event(ctx, "control-api", "", &item.ID, "retry_or_fail",
|
||||||
|
fmt.Sprintf(`{"reason":%q}`, "self-check failed, retrying: "+detail))
|
||||||
|
if !res.NewRound {
|
||||||
|
o.event(ctx, "control-api", "", &item.ID, "validator_excluded",
|
||||||
|
fmt.Sprintf(`{"validator_id":%q,"failures":%d}`, validatorID, res.Failures))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// AssignmentForValidator returns the check config for a validator's current
|
// AssignmentForValidator returns the check config for a validator's current
|
||||||
// IP if it's ready to be worked on (awaiting_self_check or checking),
|
// IP if it's ready to be worked on (awaiting_self_check or checking),
|
||||||
// or nil if the validator has nothing to do right now. The check config is
|
// or nil if the validator has nothing to do right now. The check config is
|
||||||
@@ -354,8 +386,20 @@ func (o *Orchestrator) SiteIndexForID(ctx context.Context, siteID string) (int,
|
|||||||
// RecordCheck upserts a single check result and, if it represents a
|
// RecordCheck upserts a single check result and, if it represents a
|
||||||
// completion signal (egress or a given site's full port+icmp sweep),
|
// completion signal (egress or a given site's full port+icmp sweep),
|
||||||
// updates the corresponding *_complete flag.
|
// updates the corresponding *_complete flag.
|
||||||
|
// RecordCheckIfOpen stores one result for an address that is still being
|
||||||
|
// checked. It returns false when the result was dropped because the address
|
||||||
|
// already has (or is computing) its verdict, or the result belongs to an
|
||||||
|
// earlier attempt: checks are frozen at the verdict so that the verdict and
|
||||||
|
// the stored checks always agree.
|
||||||
|
func (o *Orchestrator) RecordCheckIfOpen(ctx context.Context, c db.Check) (bool, error) {
|
||||||
|
return o.DB.UpsertCheckIfOpen(ctx, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RecordCheck is RecordCheckIfOpen for callers that do not need to know
|
||||||
|
// 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 {
|
||||||
return o.DB.UpsertCheck(ctx, c)
|
_, err := o.RecordCheckIfOpen(ctx, c)
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *Orchestrator) MarkEgressComplete(ctx context.Context, ipID int64) error {
|
func (o *Orchestrator) MarkEgressComplete(ctx context.Context, ipID int64) error {
|
||||||
@@ -664,7 +708,15 @@ func (o *Orchestrator) sweepCheckingWindow(ctx context.Context) error {
|
|||||||
// reported in ip_site_checks), with no need to wait on a prober that will
|
// reported in ip_site_checks), with no need to wait on a prober that will
|
||||||
// never exist, and no cap on how many sites can be configured.
|
// never exist, and no cap on how many sites can be configured.
|
||||||
func (o *Orchestrator) isReadyToAggregate(ctx context.Context, item db.IPQueueItem, deadline time.Time, sites []db.Site) (bool, error) {
|
func (o *Orchestrator) isReadyToAggregate(ctx context.Context, item db.IPQueueItem, deadline time.Time, sites []db.Site) (bool, error) {
|
||||||
if item.AssignedAt != nil && item.AssignedAt.Before(deadline) {
|
// The window counts from the start of checking, not from the assignment:
|
||||||
|
// assigned_at also covers floating-IP association, the settle pause and the
|
||||||
|
// self-check, which would leave only a few seconds for the checks. Rows from
|
||||||
|
// before checking_started_at existed fall back to assigned_at.
|
||||||
|
started := item.CheckingStartedAt
|
||||||
|
if started == nil {
|
||||||
|
started = item.AssignedAt
|
||||||
|
}
|
||||||
|
if started != nil && started.Before(deadline) {
|
||||||
return true, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
if !item.EgressComplete {
|
if !item.EgressComplete {
|
||||||
@@ -695,36 +747,15 @@ func (o *Orchestrator) aggregateAndRelease(ctx context.Context, item db.IPQueueI
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("expected check count: %w", err)
|
return fmt.Errorf("expected check count: %w", err)
|
||||||
}
|
}
|
||||||
passCount := 0
|
result, passCount, missing := computeVerdict(checks, expected, o.Agg.MissingCountsAsFail)
|
||||||
for _, c := range checks {
|
egress, ingress := countByLevel(checks)
|
||||||
if c.Success {
|
|
||||||
passCount++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
missing := expected - len(checks)
|
|
||||||
if missing < 0 {
|
|
||||||
missing = 0
|
|
||||||
}
|
|
||||||
failCount := (len(checks) - passCount) + missing
|
|
||||||
|
|
||||||
var result string
|
if err := o.DB.FinishIPExpected(ctx, item.ID, result, expected); err != nil {
|
||||||
switch {
|
|
||||||
case passCount > 0 && failCount == 0:
|
|
||||||
result = db.ResultPass
|
|
||||||
case passCount == 0:
|
|
||||||
result = db.ResultFail
|
|
||||||
default:
|
|
||||||
result = db.ResultPartial
|
|
||||||
}
|
|
||||||
if missing > 0 && o.Agg.MissingCountsAsFail && result == db.ResultPass {
|
|
||||||
result = db.ResultPartial
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := o.DB.FinishIP(ctx, item.ID, result); err != nil {
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
o.event(ctx, "control-api", "", &item.ID, "aggregated",
|
o.event(ctx, "control-api", "", &item.ID, "aggregated",
|
||||||
fmt.Sprintf(`{"result":%q,"checks":%d,"passed":%d,"missing":%d}`, result, len(checks), passCount, missing))
|
fmt.Sprintf(`{"result":%q,"checks":%d,"passed":%d,"missing":%d,"egress":%d,"ingress":%d}`,
|
||||||
|
result, len(checks), passCount, missing, egress, ingress))
|
||||||
|
|
||||||
if settings, err := o.DB.GetSettings(ctx); err != nil {
|
if settings, err := o.DB.GetSettings(ctx); err != nil {
|
||||||
o.Log.Error("get settings for history retention", "ip_id", item.ID, "err", err)
|
o.Log.Error("get settings for history retention", "ip_id", item.ID, "err", err)
|
||||||
@@ -751,6 +782,52 @@ func (o *Orchestrator) aggregateAndRelease(ctx context.Context, item db.IPQueueI
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// computeVerdict is the single rule that turns an address's stored checks into
|
||||||
|
// its overall result. Egress and ingress checks count alike, one check one
|
||||||
|
// vote. A check that was expected but has no stored row counts as a failure,
|
||||||
|
// so an incomplete set can never be "pass". The verdict is a pure function of
|
||||||
|
// the stored checks and the expected count: recomputing it later from the
|
||||||
|
// same rows gives the same result.
|
||||||
|
func computeVerdict(checks []db.Check, expected int, missingCountsAsFail bool) (result string, passCount, missing int) {
|
||||||
|
for _, c := range checks {
|
||||||
|
if c.Success {
|
||||||
|
passCount++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
missing = expected - len(checks)
|
||||||
|
if missing < 0 {
|
||||||
|
missing = 0
|
||||||
|
}
|
||||||
|
failCount := (len(checks) - passCount) + missing
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case passCount > 0 && failCount == 0:
|
||||||
|
result = db.ResultPass
|
||||||
|
case passCount == 0:
|
||||||
|
result = db.ResultFail
|
||||||
|
default:
|
||||||
|
result = db.ResultPartial
|
||||||
|
}
|
||||||
|
if missing > 0 && missingCountsAsFail && result == db.ResultPass {
|
||||||
|
result = db.ResultPartial
|
||||||
|
}
|
||||||
|
return result, passCount, missing
|
||||||
|
}
|
||||||
|
|
||||||
|
// countByLevel counts checks per level (egress, ingress), for the audit
|
||||||
|
// payload of the aggregated event.
|
||||||
|
func countByLevel(checks []db.Check) (egress, ingress int) {
|
||||||
|
for _, c := range checks {
|
||||||
|
switch db.CheckLevel(c.Source) {
|
||||||
|
case db.LevelEgress:
|
||||||
|
egress++
|
||||||
|
case db.LevelIngress:
|
||||||
|
ingress++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return egress, ingress
|
||||||
|
}
|
||||||
|
|
||||||
// expectedCheckCount is the number of check rows a fully-reported IP should
|
// expectedCheckCount is the number of check rows a fully-reported IP should
|
||||||
// have: one per (egress check-type x target) plus one per (site x inbound
|
// have: one per (egress check-type x target) plus one per (site x inbound
|
||||||
// port/icmp probe). Reads the current check_types/targets/sites/inbound
|
// port/icmp probe). Reads the current check_types/targets/sites/inbound
|
||||||
|
|||||||
@@ -1162,3 +1162,169 @@ func TestLateFailedSelfCheckIsIgnored(t *testing.T) {
|
|||||||
t.Fatalf("a late report changed the address state to %s", cur.State)
|
t.Fatalf("a late report changed the address state to %s", cur.State)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// reportSelfChecks answers the self-check of every address that is waiting for
|
||||||
|
// one: a validator in failing reports a failure, any other a success.
|
||||||
|
func reportSelfChecks(t *testing.T, ctx context.Context, o *Orchestrator, d *db.DB, failing ...string) {
|
||||||
|
t.Helper()
|
||||||
|
fails := map[string]bool{}
|
||||||
|
for _, v := range failing {
|
||||||
|
fails[v] = true
|
||||||
|
}
|
||||||
|
validators, err := d.ListValidators(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, v := range validators {
|
||||||
|
if v.CurrentIPID == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ip, err := d.GetIP(ctx, *v.CurrentIPID)
|
||||||
|
if err != nil || ip.State != db.IPAwaitingSelfCheck {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := o.SelfCheckResult(ctx, v.ValidatorID, ip.ID, !fails[v.ValidatorID], "ip echo timeout"); err != nil {
|
||||||
|
t.Fatalf("self-check result of %s: %v", v.ValidatorID, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func registerValidators(t *testing.T, ctx context.Context, d *db.DB, ids ...string) {
|
||||||
|
t.Helper()
|
||||||
|
for i, id := range ids {
|
||||||
|
if err := d.RegisterValidator(ctx, id, "h", fmt.Sprintf("port-%d", i+1), "v"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func eventTypes(t *testing.T, ctx context.Context, d *db.DB, ipID int64) map[string]int {
|
||||||
|
t.Helper()
|
||||||
|
events, err := d.ListEventsForIP(ctx, ipID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
out := map[string]int{}
|
||||||
|
for _, e := range events {
|
||||||
|
out[e.EventType]++
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// The incident: v1 fails the self-check of 1.1.1.1. The address must not go
|
||||||
|
// back to v1; another validator takes it and passes, while v1 keeps taking
|
||||||
|
// other addresses.
|
||||||
|
func TestSelfCheckFailureExcludesValidatorForThatAddress(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
o, d, mock := newTestOrchestrator(t, 180)
|
||||||
|
for i, a := range []string{"1.1.1.1", "2.2.2.2", "3.3.3.3"} {
|
||||||
|
mock.Seed(fmt.Sprintf("fip-%d", i+1), a, "svc-project")
|
||||||
|
}
|
||||||
|
registerValidators(t, ctx, d, "v1", "v2", "v3")
|
||||||
|
if err := d.SeedQueue(ctx, []string{"1.1.1.1", "2.2.2.2"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
o.Tick(ctx) // v1 -> 1.1.1.1, v2 -> 2.2.2.2, v3 stays idle
|
||||||
|
reportSelfChecks(t, ctx, o, d, "v1")
|
||||||
|
a1, _ := d.GetIPByAddress(ctx, "1.1.1.1")
|
||||||
|
if a1.State != db.IPQueued || a1.RetryCount != 0 {
|
||||||
|
t.Fatalf("expected 1.1.1.1 back in the queue with retry_count 0, got %s/%d", a1.State, a1.RetryCount)
|
||||||
|
}
|
||||||
|
if v1, _ := d.GetValidator(ctx, "v1"); v1.State != db.ValidatorIdle {
|
||||||
|
t.Fatalf("v1 must stay in service, got %s", v1.State)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := d.SubmitIPs(ctx, []string{"3.3.3.3"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
o.Tick(ctx) // v1 skips 1.1.1.1 and takes 3.3.3.3; v3 takes 1.1.1.1
|
||||||
|
a1, _ = d.GetIPByAddress(ctx, "1.1.1.1")
|
||||||
|
a3, _ := d.GetIPByAddress(ctx, "3.3.3.3")
|
||||||
|
if a1.OwnerValidatorID == nil || *a1.OwnerValidatorID != "v3" {
|
||||||
|
t.Fatalf("expected 1.1.1.1 on v3, got %v", a1.OwnerValidatorID)
|
||||||
|
}
|
||||||
|
if a3.OwnerValidatorID == nil || *a3.OwnerValidatorID != "v1" {
|
||||||
|
t.Fatalf("expected 3.3.3.3 on v1, got %v", a3.OwnerValidatorID)
|
||||||
|
}
|
||||||
|
|
||||||
|
reportSelfChecks(t, ctx, o, d) // v1 passes this time: the others are fine
|
||||||
|
a1, _ = d.GetIPByAddress(ctx, "1.1.1.1")
|
||||||
|
a3, _ = d.GetIPByAddress(ctx, "3.3.3.3")
|
||||||
|
if a1.State != db.IPChecking || a3.State != db.IPChecking {
|
||||||
|
t.Fatalf("expected both addresses to pass the self-check, got %s and %s", a1.State, a3.State)
|
||||||
|
}
|
||||||
|
if got, _ := d.ListSelfCheckFailedOn(ctx, a1.RegistryID, 0); len(got) != 1 || got[0] != "v1" {
|
||||||
|
t.Fatalf("expected self-check failures on v1 only, got %v", got)
|
||||||
|
}
|
||||||
|
if ev := eventTypes(t, ctx, d, a1.ID); ev["validator_excluded"] != 1 {
|
||||||
|
t.Fatalf("expected one validator_excluded event, got %v", ev)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The ceiling does not depend on the number of validators and is read at each
|
||||||
|
// failure: the address fails once it is reached, not earlier, even though the
|
||||||
|
// third validator never tried it.
|
||||||
|
func TestSelfCheckCeilingGivesFailAndFollowsSetting(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
o, d, mock := newTestOrchestrator(t, 180)
|
||||||
|
mock.Seed("fip-1", "1.1.1.1", "svc-project")
|
||||||
|
registerValidators(t, ctx, d, "v1", "v2", "v3")
|
||||||
|
if err := d.SeedQueue(ctx, []string{"1.1.1.1"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
o.Tick(ctx)
|
||||||
|
reportSelfChecks(t, ctx, o, d, "v1", "v2", "v3")
|
||||||
|
if ip, _ := d.GetIPByAddress(ctx, "1.1.1.1"); ip.State != db.IPQueued {
|
||||||
|
t.Fatalf("expected queued after the first failure (ceiling 5), got %s", ip.State)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := d.SetSelfCheckMaxAttempts(ctx, 2); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
o.Tick(ctx)
|
||||||
|
reportSelfChecks(t, ctx, o, d, "v1", "v2", "v3")
|
||||||
|
ip, _ := d.GetIPByAddress(ctx, "1.1.1.1")
|
||||||
|
if ip.State != db.IPFailed || ip.OverallResult != db.ResultFail || ip.RetryCount != 0 {
|
||||||
|
t.Fatalf("expected failed/fail at the lowered ceiling 2, got %s/%s retry_count=%d", ip.State, ip.OverallResult, ip.RetryCount)
|
||||||
|
}
|
||||||
|
if got, _ := d.ListSelfCheckFailedOn(ctx, ip.RegistryID, 0); len(got) != 2 {
|
||||||
|
t.Fatalf("expected failures on two validators, got %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// With fewer working validators than the ceiling (down to a single one) the
|
||||||
|
// retries continue on the validators in a new round, up to the ceiling; the
|
||||||
|
// address never gets stuck in the queue.
|
||||||
|
func TestSelfCheckFewerValidatorsThanCeilingRetriesUntilCeiling(t *testing.T) {
|
||||||
|
for _, validators := range [][]string{{"v1"}, {"v1", "v2"}} {
|
||||||
|
ctx := context.Background()
|
||||||
|
o, d, mock := newTestOrchestrator(t, 180)
|
||||||
|
mock.Seed("fip-1", "1.1.1.1", "svc-project")
|
||||||
|
registerValidators(t, ctx, d, validators...)
|
||||||
|
if err := d.SeedQueue(ctx, []string{"1.1.1.1"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := d.SetSelfCheckMaxAttempts(ctx, 5); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for attempt := 1; attempt <= 5; attempt++ {
|
||||||
|
o.Tick(ctx)
|
||||||
|
ip, _ := d.GetIPByAddress(ctx, "1.1.1.1")
|
||||||
|
if ip.State != db.IPAwaitingSelfCheck {
|
||||||
|
t.Fatalf("%d validators, attempt %d: expected the address to be handed out, got %s", len(validators), attempt, ip.State)
|
||||||
|
}
|
||||||
|
reportSelfChecks(t, ctx, o, d, validators...)
|
||||||
|
ip, _ = d.GetIPByAddress(ctx, "1.1.1.1")
|
||||||
|
want := db.IPQueued
|
||||||
|
if attempt == 5 {
|
||||||
|
want = db.IPFailed
|
||||||
|
}
|
||||||
|
if ip.State != want {
|
||||||
|
t.Fatalf("%d validators, after failure %d: expected %s, got %s", len(validators), attempt, want, ip.State)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -282,7 +282,11 @@ func (o *Orchestrator) doScan(ctx context.Context, opts ScanOptions) (scanResult
|
|||||||
return res, err
|
return res, err
|
||||||
}
|
}
|
||||||
chunk := free[off:min(off+scanChunkSize, len(free))]
|
chunk := free[off:min(off+scanChunkSize, len(free))]
|
||||||
r, err := o.DB.SubmitIPs(ctx, chunk)
|
kind := db.RunManual
|
||||||
|
if opts.ClearFirst {
|
||||||
|
kind = db.RunAuto // the auto-cycle's scan; a manual scan never clears first
|
||||||
|
}
|
||||||
|
r, err := o.DB.SubmitIPsAs(ctx, chunk, kind)
|
||||||
res.submit.Added = append(res.submit.Added, r.Added...)
|
res.submit.Added = append(res.submit.Added, r.Added...)
|
||||||
res.submit.Requeued = append(res.submit.Requeued, r.Requeued...)
|
res.submit.Requeued = append(res.submit.Requeued, r.Requeued...)
|
||||||
res.submit.Reordered = append(res.submit.Reordered, r.Reordered...)
|
res.submit.Reordered = append(res.submit.Reordered, r.Reordered...)
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
package orchestrator
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"cloudipvalidator/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
func chk(src, ct string, ok bool) db.Check {
|
||||||
|
return db.Check{Source: src, CheckType: ct, Success: ok}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestComputeVerdict(t *testing.T) {
|
||||||
|
in1 := db.InboundSource(1)
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
checks []db.Check
|
||||||
|
expected int
|
||||||
|
want string
|
||||||
|
missing int
|
||||||
|
}{
|
||||||
|
{"all pass, complete", []db.Check{chk(db.SourceEgress, "https", true), chk(in1, "icmp", true)}, 2, db.ResultPass, 0},
|
||||||
|
{"egress failure", []db.Check{chk(db.SourceEgress, "https", false), chk(in1, "icmp", true)}, 2, db.ResultPartial, 0},
|
||||||
|
{"ingress failure", []db.Check{chk(db.SourceEgress, "https", true), chk(in1, "ssh", false)}, 2, db.ResultPartial, 0},
|
||||||
|
{"all recorded pass but one missing", []db.Check{chk(db.SourceEgress, "https", true)}, 2, db.ResultPartial, 1},
|
||||||
|
{"all fail", []db.Check{chk(db.SourceEgress, "https", false), chk(in1, "icmp", false)}, 2, db.ResultFail, 0},
|
||||||
|
{"nothing recorded", nil, 2, db.ResultFail, 2},
|
||||||
|
{"more recorded than expected", []db.Check{chk(db.SourceEgress, "https", true), chk(in1, "icmp", true)}, 1, db.ResultPass, 0},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
got, _, missing := computeVerdict(c.checks, c.expected, true)
|
||||||
|
if got != c.want || missing != c.missing {
|
||||||
|
t.Errorf("%s: got %s missing=%d, want %s missing=%d", c.name, got, missing, c.want, c.missing)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The window starts when checking starts: an address handed out long ago but
|
||||||
|
// that only just began checking must not be cut off.
|
||||||
|
func TestAggregationWindowCountsFromCheckingStart(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
o, _, _ := newTestOrchestrator(t, 180)
|
||||||
|
deadline := time.Now().Add(-120 * time.Second)
|
||||||
|
long, recent := time.Now().Add(-10*time.Minute), time.Now()
|
||||||
|
|
||||||
|
item := db.IPQueueItem{AssignedAt: &long, CheckingStartedAt: &recent}
|
||||||
|
ready, err := o.isReadyToAggregate(ctx, item, deadline, nil)
|
||||||
|
if err != nil || ready {
|
||||||
|
t.Fatalf("recent checking start must not be cut off by an old assignment: ready=%v err=%v", ready, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
started := time.Now().Add(-3 * time.Minute)
|
||||||
|
item.CheckingStartedAt = &started
|
||||||
|
if ready, err := o.isReadyToAggregate(ctx, item, deadline, nil); err != nil || !ready {
|
||||||
|
t.Fatalf("window elapsed since checking start: ready=%v err=%v", ready, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rows from before checking_started_at existed fall back to assigned_at.
|
||||||
|
item.CheckingStartedAt = nil
|
||||||
|
if ready, err := o.isReadyToAggregate(ctx, item, deadline, nil); err != nil || !ready {
|
||||||
|
t.Fatalf("fallback to assigned_at: ready=%v err=%v", ready, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// After the verdict nothing can change the stored checks, and the verdict is
|
||||||
|
// exactly what the stored checks give when computed again.
|
||||||
|
func TestVerdictMatchesStoredChecksAndLateResultIsDropped(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
o, d, mock := newTestOrchestrator(t, 180)
|
||||||
|
mock.Seed("fip-1", "1.2.3.4", "svc-project")
|
||||||
|
_ = d.RegisterValidator(ctx, "validator-1", "host-1", "port-1", "v0.1")
|
||||||
|
_ = d.SeedQueue(ctx, []string{"1.2.3.4"})
|
||||||
|
|
||||||
|
o.Tick(ctx)
|
||||||
|
ip, _ := d.GetIPByAddress(ctx, "1.2.3.4")
|
||||||
|
_ = o.SelfCheckResult(ctx, "validator-1", ip.ID, true, "ok")
|
||||||
|
ip, _ = d.GetIP(ctx, ip.ID)
|
||||||
|
|
||||||
|
rec := func(src, ct string, ok bool) bool {
|
||||||
|
t.Helper()
|
||||||
|
written, err := o.RecordCheckIfOpen(ctx, db.Check{
|
||||||
|
IPID: ip.ID, IPAddress: ip.IPAddress, AttemptNumber: ip.AttemptNumber, ValidatorID: "validator-1",
|
||||||
|
Source: src, CheckType: ct, Target: "t", Success: ok, CheckedAt: db.Now(),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return written
|
||||||
|
}
|
||||||
|
if !rec(db.SourceEgress, "https", true) || !rec(db.InboundSource(1), "tcp-22", false) {
|
||||||
|
t.Fatal("results while checking must be stored")
|
||||||
|
}
|
||||||
|
_ = o.MarkEgressComplete(ctx, ip.ID)
|
||||||
|
o.Cfg.CheckingWindowSeconds = 0
|
||||||
|
time.Sleep(5 * time.Millisecond)
|
||||||
|
o.Tick(ctx)
|
||||||
|
|
||||||
|
ip, _ = d.GetIP(ctx, ip.ID)
|
||||||
|
if ip.State != db.IPDone {
|
||||||
|
t.Fatalf("expected done, got %s", ip.State)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A late result: a new check, and an attempt to flip a stored one.
|
||||||
|
if rec(db.InboundSource(2), "icmp", true) {
|
||||||
|
t.Fatal("new check after the verdict was stored")
|
||||||
|
}
|
||||||
|
if rec(db.InboundSource(1), "tcp-22", true) {
|
||||||
|
t.Fatal("overwrite after the verdict was accepted")
|
||||||
|
}
|
||||||
|
|
||||||
|
stored, err := d.ListChecksForAttempt(ctx, ip.ID, ip.AttemptNumber)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(stored) != 2 {
|
||||||
|
t.Fatalf("stored checks changed after the verdict: %d rows", len(stored))
|
||||||
|
}
|
||||||
|
expected, err := o.expectedCheckCount(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got, _, _ := computeVerdict(stored, expected, o.Agg.MissingCountsAsFail); got != ip.OverallResult {
|
||||||
|
t.Fatalf("recomputed verdict %s differs from stored %s", got, ip.OverallResult)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user