Validator agent: retry outbound HTTPS up to 3 times, traceroute on failure
A failed HTTPS check is retried (3 attempts, 2 s apart). If all attempts fail, the agent runs traceroute -4 -n to the target's IPv4 address in a separate process, polls it every 5 s (90 s limit) and posts the full output as a traceroute_result event for the address. The agent waits for traces before reporting completion, while the floating IP is attached. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1536723196
commit
5c75ece8b1
15 files changed
+465
-10
No files matched your search
@@ -48,7 +48,7 @@ docker compose up -d --build # весь стенд на одной
|
|||||||
**Остальные компоненты**
|
**Остальные компоненты**
|
||||||
| Компонент | Ключи |
|
| Компонент | Ключи |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `validator-agent` | `validator_id`, `control_api_url`, `control_api_token_env` (`CONTROL_API_AGENT_TOKEN`), `poll_interval_seconds`, `self_check.*` (таймаут, `methods` — `ip_echo`/`control_api`, `ip_echo_urls`), `checks.*` (таймауты HTTPS/ICMP, число ICMP-пакетов, `ssh.*`) |
|
| `validator-agent` | `validator_id`, `control_api_url`, `control_api_token_env` (`CONTROL_API_AGENT_TOKEN`), `poll_interval_seconds`, `self_check.*` (таймаут, `methods` — `ip_echo`/`control_api`, `ip_echo_urls`), `checks.*` (таймауты HTTPS/ICMP, число ICMP-пакетов, `https_attempts`, `https_retry_delay_seconds`, `traceroute.*`, `ssh.*`) |
|
||||||
| `prober` | `site_id`, `control_api_url`, `control_api_token_env` (`CONTROL_API_AGENT_TOKEN`), `poll_interval_seconds`, `checks.*` (таймауты TCP/ICMP, число ICMP-пакетов) |
|
| `prober` | `site_id`, `control_api_url`, `control_api_token_env` (`CONTROL_API_AGENT_TOKEN`), `poll_interval_seconds`, `checks.*` (таймауты TCP/ICMP, число ICMP-пакетов) |
|
||||||
| `admin-dashboard` | `server.listen_addr` (`:8090`), `control_api.base_url`, `control_api.timeout_seconds`, `control_api.token_env` (`ADMIN_DASHBOARD_CONTROL_API_TOKEN`), `auth.username_env` / `password_env` / `session_secret_env` (`ADMIN_DASHBOARD_USERNAME` / `_PASSWORD` / `_SESSION_SECRET`), `auth.session_ttl_minutes` (480), `overview.last_completed_count` (20), `overview.poll_interval_seconds` (5) |
|
| `admin-dashboard` | `server.listen_addr` (`:8090`), `control_api.base_url`, `control_api.timeout_seconds`, `control_api.token_env` (`ADMIN_DASHBOARD_CONTROL_API_TOKEN`), `auth.username_env` / `password_env` / `session_secret_env` (`ADMIN_DASHBOARD_USERNAME` / `_PASSWORD` / `_SESSION_SECRET`), `auth.session_ttl_minutes` (480), `overview.last_completed_count` (20), `overview.poll_interval_seconds` (5) |
|
||||||
|
|
||||||
@@ -95,6 +95,10 @@ docs/ документация и планы доработок
|
|||||||
- Оператор может отменить проверку (`failed` + `cancelled`), перепроверить завершённый адрес (возврат в `queued`) или удалить адрес из очереди.
|
- Оператор может отменить проверку (`failed` + `cancelled`), перепроверить завершённый адрес (возврат в `queued`) или удалить адрес из очереди.
|
||||||
- Адреса обрабатываются в порядке `sequence`; каждый свободный валидатор получает следующий `queued`-адрес под лизинг. Истёкший лизинг возвращает адрес в очередь, после `max_retries` — в `failed`.
|
- Адреса обрабатываются в порядке `sequence`; каждый свободный валидатор получает следующий `queued`-адрес под лизинг. Истёкший лизинг возвращает адрес в очередь, после `max_retries` — в `failed`.
|
||||||
|
|
||||||
|
**Исходящая HTTPS-проверка**
|
||||||
|
- `GET` на URL цели; успех — ответ с кодом < 400 после редиректов. До `https_attempts` попыток (по умолчанию 3, пауза `https_retry_delay_seconds` = 2 с); в БД одна итоговая запись, номер попытки в `detail`.
|
||||||
|
- Если все попытки провалились — агент в отдельном процессе запускает `traceroute -4 -n` до IPv4-адреса FQDN, опрашивает его статус каждые `traceroute.poll_interval_seconds` (5 с), лимит `traceroute.timeout_seconds` (90 с). Полный вывод пишется в журнал событий адреса (`traceroute_result`: target, host, ip, status `completed`/`timeout`/`error`, output). Агент завершает проверку адреса только после всех трассировок; на вердикт трассировка не влияет.
|
||||||
|
|
||||||
**Итоговый результат**
|
**Итоговый результат**
|
||||||
- `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`).
|
||||||
@@ -208,6 +212,8 @@ scripts/run-local-e2e.sh # сквозной прог
|
|||||||
|
|
||||||
| Дата | Веха | Документ |
|
| Дата | Веха | Документ |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
|
| 2026-11-02 | Пересобран `bin/validator-agent`; ansible-роль доставки проверяет новые переменные env-файла (предупреждение) и после запуска — наличие `traceroute` и новых параметров в конфиге агента | [план](docs/changes/2026-11-02_22-40_ansible-agent-traceroute-rollout-plan.md) · [итог](docs/changes/2026-11-02_22-40_ansible-agent-traceroute-rollout-summary.md) · [Ansible](deploy/ansible/README.md) |
|
||||||
|
| 2026-11-02 | Исходящий HTTPS: до 3 попыток на цель; при провале всех — асинхронная трассировка `traceroute -4 -n` (опрос статуса раз в 5 с), подробный вывод в журнал событий адреса (`traceroute_result`) | [план](docs/changes/2026-11-02_22-21_https-retry-traceroute-plan.md) · [итог](docs/changes/2026-11-02_22-21_https-retry-traceroute-summary.md) |
|
||||||
| 2026-10-08 | Окно со списком адресов: столбцы «Подсеть» и «Метка подсети» (из списка подсетей администратора), сводка по подсетям с фильтром; «прочие» → «вне списка подсетей» | [план](docs/changes/2026-10-08_12-56_dialog-subnet-column-plan.md) · [итог](docs/changes/2026-10-08_12-56_dialog-subnet-column-summary.md) · [USAGE](docs/USAGE.md#реестр-адресов-и-глубина-истории) |
|
| 2026-10-08 | Окно со списком адресов: столбцы «Подсеть» и «Метка подсети» (из списка подсетей администратора), сводка по подсетям с фильтром; «прочие» → «вне списка подсетей» | [план](docs/changes/2026-10-08_12-56_dialog-subnet-column-plan.md) · [итог](docs/changes/2026-10-08_12-56_dialog-subnet-column-summary.md) · [USAGE](docs/USAGE.md#реестр-адресов-и-глубина-истории) |
|
||||||
| 2026-10-08 | Реестр: индикатор «Всегда проходили» — число адресов без единого провала проверок выбранного направления за период; клик — список и CSV; API `registry/always-pass` | [план](docs/changes/2026-10-08_12-23_registry-always-pass-indicator-plan.md) · [итог](docs/changes/2026-10-08_12-23_registry-always-pass-indicator-summary.md) · [USAGE](docs/USAGE.md#реестр-адресов-и-глубина-истории) · [API](docs/API.md#get-apiv1adminregistryalways-pass) |
|
| 2026-10-08 | Реестр: индикатор «Всегда проходили» — число адресов без единого провала проверок выбранного направления за период; клик — список и CSV; API `registry/always-pass` | [план](docs/changes/2026-10-08_12-23_registry-always-pass-indicator-plan.md) · [итог](docs/changes/2026-10-08_12-23_registry-always-pass-indicator-summary.md) · [USAGE](docs/USAGE.md#реестр-адресов-и-глубина-истории) · [API](docs/API.md#get-apiv1adminregistryalways-pass) |
|
||||||
| 2026-10-08 | График «Динамика по запускам» переведён на vendored Chart.js 4.5.1 (офлайн, MIT); данные и API без изменений | [план](docs/changes/2026-10-08_12-00_registry-trend-chartjs-plan.md) · [итог](docs/changes/2026-10-08_12-00_registry-trend-chartjs-summary.md) |
|
| 2026-10-08 | График «Динамика по запускам» переведён на vendored Chart.js 4.5.1 (офлайн, MIT); данные и API без изменений | [план](docs/changes/2026-10-08_12-00_registry-trend-chartjs-plan.md) · [итог](docs/changes/2026-10-08_12-00_registry-trend-chartjs-summary.md) |
|
||||||
|
|||||||
@@ -39,6 +39,16 @@ self_check:
|
|||||||
|
|
||||||
checks:
|
checks:
|
||||||
https_timeout_seconds: 10
|
https_timeout_seconds: 10
|
||||||
|
# Attempts per HTTPS URL (first + retries) and pause between them.
|
||||||
|
https_attempts: 3
|
||||||
|
https_retry_delay_seconds: 2
|
||||||
|
# Background traceroute (IPv4) after an HTTPS check fails on all attempts;
|
||||||
|
# result goes to the address event log as "traceroute_result".
|
||||||
|
traceroute:
|
||||||
|
enabled: true
|
||||||
|
timeout_seconds: 90
|
||||||
|
max_hops: 30
|
||||||
|
poll_interval_seconds: 5
|
||||||
icmp_timeout_seconds: 5
|
icmp_timeout_seconds: 5
|
||||||
icmp_count: 3
|
icmp_count: 3
|
||||||
ssh:
|
ssh:
|
||||||
|
|||||||
@@ -23,6 +23,12 @@ VALIDATOR_AGENT_POLL_INTERVAL_SECONDS=5
|
|||||||
|
|
||||||
# Исходящие проверки.
|
# Исходящие проверки.
|
||||||
VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS=10
|
VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS=10
|
||||||
|
VALIDATOR_AGENT_HTTPS_ATTEMPTS=3
|
||||||
|
VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS=2
|
||||||
|
VALIDATOR_AGENT_TRACEROUTE_ENABLED=true
|
||||||
|
VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS=90
|
||||||
|
VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS=30
|
||||||
|
VALIDATOR_AGENT_TRACEROUTE_POLL_INTERVAL_SECONDS=5
|
||||||
VALIDATOR_AGENT_ICMP_TIMEOUT_SECONDS=5
|
VALIDATOR_AGENT_ICMP_TIMEOUT_SECONDS=5
|
||||||
VALIDATOR_AGENT_ICMP_COUNT=3
|
VALIDATOR_AGENT_ICMP_COUNT=3
|
||||||
VALIDATOR_AGENT_SSH_ENABLED=false
|
VALIDATOR_AGENT_SSH_ENABLED=false
|
||||||
|
|||||||
@@ -102,6 +102,12 @@ services:
|
|||||||
VALIDATOR_AGENT_SELF_CHECK_TIMEOUT_SECONDS: "${VALIDATOR_AGENT_SELF_CHECK_TIMEOUT_SECONDS:-10}"
|
VALIDATOR_AGENT_SELF_CHECK_TIMEOUT_SECONDS: "${VALIDATOR_AGENT_SELF_CHECK_TIMEOUT_SECONDS:-10}"
|
||||||
VALIDATOR_AGENT_SELF_CHECK_METHODS: "${VALIDATOR_AGENT_SELF_CHECK_METHODS:-[ip_echo]}"
|
VALIDATOR_AGENT_SELF_CHECK_METHODS: "${VALIDATOR_AGENT_SELF_CHECK_METHODS:-[ip_echo]}"
|
||||||
VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS: "${VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS:-10}"
|
VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS: "${VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS:-10}"
|
||||||
|
VALIDATOR_AGENT_HTTPS_ATTEMPTS: "${VALIDATOR_AGENT_HTTPS_ATTEMPTS:-3}"
|
||||||
|
VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS: "${VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS:-2}"
|
||||||
|
VALIDATOR_AGENT_TRACEROUTE_ENABLED: "${VALIDATOR_AGENT_TRACEROUTE_ENABLED:-true}"
|
||||||
|
VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS: "${VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS:-90}"
|
||||||
|
VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS: "${VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS:-30}"
|
||||||
|
VALIDATOR_AGENT_TRACEROUTE_POLL_INTERVAL_SECONDS: "${VALIDATOR_AGENT_TRACEROUTE_POLL_INTERVAL_SECONDS:-5}"
|
||||||
VALIDATOR_AGENT_ICMP_TIMEOUT_SECONDS: "${VALIDATOR_AGENT_ICMP_TIMEOUT_SECONDS:-5}"
|
VALIDATOR_AGENT_ICMP_TIMEOUT_SECONDS: "${VALIDATOR_AGENT_ICMP_TIMEOUT_SECONDS:-5}"
|
||||||
VALIDATOR_AGENT_ICMP_COUNT: "${VALIDATOR_AGENT_ICMP_COUNT:-3}"
|
VALIDATOR_AGENT_ICMP_COUNT: "${VALIDATOR_AGENT_ICMP_COUNT:-3}"
|
||||||
VALIDATOR_AGENT_SSH_ENABLED: "${VALIDATOR_AGENT_SSH_ENABLED:-false}"
|
VALIDATOR_AGENT_SSH_ENABLED: "${VALIDATOR_AGENT_SSH_ENABLED:-false}"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
FROM alpine:3.20
|
FROM alpine:3.20
|
||||||
|
|
||||||
RUN apk add --no-cache gettext
|
RUN apk add --no-cache gettext traceroute
|
||||||
|
|
||||||
COPY bin/validator-agent /usr/local/bin/validator-agent
|
COPY bin/validator-agent /usr/local/bin/validator-agent
|
||||||
COPY deploy/docker/validator-agent/validator-agent.yaml.tmpl /etc/validator-agent/validator-agent.yaml.tmpl
|
COPY deploy/docker/validator-agent/validator-agent.yaml.tmpl /etc/validator-agent/validator-agent.yaml.tmpl
|
||||||
|
|||||||
@@ -8,6 +8,12 @@ export VALIDATOR_AGENT_POLL_INTERVAL_SECONDS="${VALIDATOR_AGENT_POLL_INTERVAL_SE
|
|||||||
export VALIDATOR_AGENT_SELF_CHECK_TIMEOUT_SECONDS="${VALIDATOR_AGENT_SELF_CHECK_TIMEOUT_SECONDS:-10}"
|
export VALIDATOR_AGENT_SELF_CHECK_TIMEOUT_SECONDS="${VALIDATOR_AGENT_SELF_CHECK_TIMEOUT_SECONDS:-10}"
|
||||||
export VALIDATOR_AGENT_SELF_CHECK_METHODS="${VALIDATOR_AGENT_SELF_CHECK_METHODS:-[ip_echo]}"
|
export VALIDATOR_AGENT_SELF_CHECK_METHODS="${VALIDATOR_AGENT_SELF_CHECK_METHODS:-[ip_echo]}"
|
||||||
export VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS="${VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS:-10}"
|
export VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS="${VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS:-10}"
|
||||||
|
export VALIDATOR_AGENT_HTTPS_ATTEMPTS="${VALIDATOR_AGENT_HTTPS_ATTEMPTS:-3}"
|
||||||
|
export VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS="${VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS:-2}"
|
||||||
|
export VALIDATOR_AGENT_TRACEROUTE_ENABLED="${VALIDATOR_AGENT_TRACEROUTE_ENABLED:-true}"
|
||||||
|
export VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS="${VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS:-90}"
|
||||||
|
export VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS="${VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS:-30}"
|
||||||
|
export VALIDATOR_AGENT_TRACEROUTE_POLL_INTERVAL_SECONDS="${VALIDATOR_AGENT_TRACEROUTE_POLL_INTERVAL_SECONDS:-5}"
|
||||||
export VALIDATOR_AGENT_ICMP_TIMEOUT_SECONDS="${VALIDATOR_AGENT_ICMP_TIMEOUT_SECONDS:-5}"
|
export VALIDATOR_AGENT_ICMP_TIMEOUT_SECONDS="${VALIDATOR_AGENT_ICMP_TIMEOUT_SECONDS:-5}"
|
||||||
export VALIDATOR_AGENT_ICMP_COUNT="${VALIDATOR_AGENT_ICMP_COUNT:-3}"
|
export VALIDATOR_AGENT_ICMP_COUNT="${VALIDATOR_AGENT_ICMP_COUNT:-3}"
|
||||||
export VALIDATOR_AGENT_SSH_ENABLED="${VALIDATOR_AGENT_SSH_ENABLED:-false}"
|
export VALIDATOR_AGENT_SSH_ENABLED="${VALIDATOR_AGENT_SSH_ENABLED:-false}"
|
||||||
@@ -17,7 +23,7 @@ export VALIDATOR_AGENT_SSH_TIMEOUT_SECONDS="${VALIDATOR_AGENT_SSH_TIMEOUT_SECOND
|
|||||||
# NOT templated into the YAML: the binary reads them straight from this
|
# NOT templated into the YAML: the binary reads them straight from this
|
||||||
# container's environment (names default in the config loader), so secrets
|
# container's environment (names default in the config loader), so secrets
|
||||||
# never land in a file inside the container.
|
# never land in a file inside the container.
|
||||||
envsubst '${VALIDATOR_AGENT_VALIDATOR_ID} ${VALIDATOR_AGENT_CONTROL_API_URL} ${VALIDATOR_AGENT_POLL_INTERVAL_SECONDS} ${VALIDATOR_AGENT_SELF_CHECK_TIMEOUT_SECONDS} ${VALIDATOR_AGENT_SELF_CHECK_METHODS} ${VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS} ${VALIDATOR_AGENT_ICMP_TIMEOUT_SECONDS} ${VALIDATOR_AGENT_ICMP_COUNT} ${VALIDATOR_AGENT_SSH_ENABLED} ${VALIDATOR_AGENT_SSH_TIMEOUT_SECONDS}' \
|
envsubst '${VALIDATOR_AGENT_VALIDATOR_ID} ${VALIDATOR_AGENT_CONTROL_API_URL} ${VALIDATOR_AGENT_POLL_INTERVAL_SECONDS} ${VALIDATOR_AGENT_SELF_CHECK_TIMEOUT_SECONDS} ${VALIDATOR_AGENT_SELF_CHECK_METHODS} ${VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS} ${VALIDATOR_AGENT_HTTPS_ATTEMPTS} ${VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS} ${VALIDATOR_AGENT_TRACEROUTE_ENABLED} ${VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS} ${VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS} ${VALIDATOR_AGENT_TRACEROUTE_POLL_INTERVAL_SECONDS} ${VALIDATOR_AGENT_ICMP_TIMEOUT_SECONDS} ${VALIDATOR_AGENT_ICMP_COUNT} ${VALIDATOR_AGENT_SSH_ENABLED} ${VALIDATOR_AGENT_SSH_TIMEOUT_SECONDS}' \
|
||||||
< /etc/validator-agent/validator-agent.yaml.tmpl > /etc/validator-agent/validator-agent.yaml
|
< /etc/validator-agent/validator-agent.yaml.tmpl > /etc/validator-agent/validator-agent.yaml
|
||||||
|
|
||||||
exec /usr/local/bin/validator-agent -config /etc/validator-agent/validator-agent.yaml
|
exec /usr/local/bin/validator-agent -config /etc/validator-agent/validator-agent.yaml
|
||||||
@@ -8,6 +8,13 @@ self_check:
|
|||||||
|
|
||||||
checks:
|
checks:
|
||||||
https_timeout_seconds: ${VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS}
|
https_timeout_seconds: ${VALIDATOR_AGENT_HTTPS_TIMEOUT_SECONDS}
|
||||||
|
https_attempts: ${VALIDATOR_AGENT_HTTPS_ATTEMPTS}
|
||||||
|
https_retry_delay_seconds: ${VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS}
|
||||||
|
traceroute:
|
||||||
|
enabled: ${VALIDATOR_AGENT_TRACEROUTE_ENABLED}
|
||||||
|
timeout_seconds: ${VALIDATOR_AGENT_TRACEROUTE_TIMEOUT_SECONDS}
|
||||||
|
max_hops: ${VALIDATOR_AGENT_TRACEROUTE_MAX_HOPS}
|
||||||
|
poll_interval_seconds: ${VALIDATOR_AGENT_TRACEROUTE_POLL_INTERVAL_SECONDS}
|
||||||
icmp_timeout_seconds: ${VALIDATOR_AGENT_ICMP_TIMEOUT_SECONDS}
|
icmp_timeout_seconds: ${VALIDATOR_AGENT_ICMP_TIMEOUT_SECONDS}
|
||||||
icmp_count: ${VALIDATOR_AGENT_ICMP_COUNT}
|
icmp_count: ${VALIDATOR_AGENT_ICMP_COUNT}
|
||||||
ssh:
|
ssh:
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# План: повтор исходящей HTTPS-проверки и трассировка при провале
|
||||||
|
|
||||||
|
## Цель
|
||||||
|
|
||||||
|
Исходящая HTTPS-проверка до FQDN не должна проваливаться из-за единичного сбоя. Если FQDN недоступен после всех попыток, в журнал событий по адресу пишется трассировка маршрута до этого узла.
|
||||||
|
|
||||||
|
## Поведение
|
||||||
|
|
||||||
|
1. **Повтор HTTPS.** До одного URL делается до 3 попыток (первая + 2 повтора), пауза между попытками 2 с.
|
||||||
|
- Успех на любой попытке → проверка успешна, остальные попытки не выполняются.
|
||||||
|
- В БД по-прежнему одна строка на (адрес, тип, цель) — итоговая. В `detail` указывается номер попытки, например `ok (attempt 2/3)` или `unexpected status 403 (3/3 attempts failed)`. `latency_ms` — у последней попытки.
|
||||||
|
2. **Трассировка.** Если все 3 попытки провалились:
|
||||||
|
- FQDN из URL разрешается в IPv4-адрес силами агента (первый A-адрес). Если имя не разрешилось, трассировка не запускается, в журнал пишется событие с ошибкой DNS.
|
||||||
|
- Запускается отдельный процесс `traceroute -4 -n -q 1 -w 2 -m 30 <IPv4>`: только IPv4, без разрешения имён узлов.
|
||||||
|
- Процесс работает асинхронно: агент сразу переходит к следующим проверкам. Статус процесса опрашивается каждые 5 с (параметр `poll_interval_seconds`).
|
||||||
|
- Общий лимит на одну трассировку — 90 с, по истечении процесс завершается, в событие попадает частичный вывод с пометкой `timeout`.
|
||||||
|
3. **Журнал событий.** По каждой трассировке агент отправляет событие `traceroute_result` по адресу (`ip_id`) через существующий `POST /api/v1/agents/{id}/events`. Payload (JSON):
|
||||||
|
`{"target":"https://…","host":"github.com","ip":"140.82.121.4","status":"completed|timeout|error","duration_ms":…,"output":"<полный вывод traceroute>","error":"…"}`
|
||||||
|
4. **Порядок завершения.** Перед `complete` агент дожидается окончания всех запущенных трассировок (в пределах их лимита). Причина: после `complete` control-api отвязывает floating IP, и трассировка ушла бы уже не с проверяемого адреса. На вердикт трассировка не влияет.
|
||||||
|
|
||||||
|
## Изменения
|
||||||
|
|
||||||
|
| Файл | Что меняется |
|
||||||
|
|---|---|
|
||||||
|
| `internal/config/config.go` | В `AgentChecks`: `https_attempts` (по умолчанию 3), `https_retry_delay_seconds` (2), блок `traceroute` с `enabled` (true), `timeout_seconds` (90), `max_hops` (30), `poll_interval_seconds` (5). |
|
||||||
|
| `internal/checkrunner/https.go` | Обёртка с повторами вокруг текущей HTTPS-проверки. |
|
||||||
|
| `internal/checkrunner/traceroute.go` (новый) | Разрешение имени в IPv4, запуск `traceroute` через `exec.CommandContext`, опрос статуса, сбор вывода. |
|
||||||
|
| `internal/agentcore/agentcore.go` | `runChecks`: запуск трассировки в фоне при провале HTTPS, ожидание всех трассировок перед `postComplete`, отправка события. |
|
||||||
|
| `deploy/docker/validator-agent/Dockerfile` | `apk add traceroute` (полноценная утилита вместо busybox). |
|
||||||
|
| `deploy/docker/validator-agent/validator-agent.yaml.tmpl`, `configs/validator-agent.example.yaml`, `.env.example` | Новые параметры. |
|
||||||
|
| `README.md` | Описание повторов и трассировки. |
|
||||||
|
|
||||||
|
Изменений на стороне control-api, БД и дашборда нет: событие ложится в существующую таблицу `events` и видно в журнале по адресу.
|
||||||
|
|
||||||
|
## Требования к окружению
|
||||||
|
|
||||||
|
- Контейнеру агента уже выдаётся `NET_RAW` (нужен для ICMP), этого достаточно для `traceroute`.
|
||||||
|
- Образ агента нужно пересобрать и выкатить на валидаторы.
|
||||||
|
|
||||||
|
## Тесты
|
||||||
|
|
||||||
|
Минимально: один тест на повторы HTTPS (сервер отвечает 500, затем 200 → успех со 2-й попытки) и один на разбор URL → хост для трассировки.
|
||||||
|
|
||||||
|
## Риски
|
||||||
|
|
||||||
|
- Время обработки адреса растёт: до 2 повторов × таймаут на каждый провальный FQDN плюс до 90 с на трассировку (трассировки идут параллельно с остальными проверками).
|
||||||
|
- Если провайдер блокирует UDP/ICMP, трассировка покажет `* * *` — это ожидаемо и тоже информативно.
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# Итог: повтор исходящей HTTPS-проверки и трассировка при провале
|
||||||
|
|
||||||
|
План: [2026-11-02_22-21_https-retry-traceroute-plan.md](2026-11-02_22-21_https-retry-traceroute-plan.md)
|
||||||
|
|
||||||
|
## Что сделано
|
||||||
|
|
||||||
|
- **Повтор HTTPS** (`internal/checkrunner/https.go`, `HTTPSWithRetry`): до 3 попыток на URL, пауза 2 с, остановка на первом успехе. В БД одна итоговая запись. `detail`: `ok (attempt N/3)` или `<ошибка> (3/3 attempts failed)`, `latency_ms` — последней попытки.
|
||||||
|
- **Трассировка** (`internal/checkrunner/traceroute.go`, новый):
|
||||||
|
- FQDN разрешается в первый IPv4-адрес (если цель уже IPv4 — используется она); ошибка DNS → событие со статусом `error`, процесс не запускается.
|
||||||
|
- Отдельный процесс `traceroute -4 -n -q 1 -w 2 -m 30 <IPv4>`; статус опрашивается каждые 5 с; лимит 90 с, по истечении процесс убивается (`timeout`, частичный вывод сохраняется).
|
||||||
|
- **Агент** (`internal/agentcore/agentcore.go`): при провале HTTPS трассировка запускается в фоне, остальные проверки идут дальше. Перед `complete` агент ждёт все трассировки (иначе Floating IP будет отвязан). Результат — событие `traceroute_result` в журнале адреса, payload: `target`, `host`, `ip`, `status`, `duration_ms`, `output`, `error`.
|
||||||
|
- **Конфиг** (`internal/config/config.go`): `checks.https_attempts` (3), `checks.https_retry_delay_seconds` (2), `checks.traceroute.enabled` (true), `timeout_seconds` (90), `max_hops` (30), `poll_interval_seconds` (5).
|
||||||
|
- **Деплой**: в образ агента добавлен пакет `traceroute`; новые переменные `VALIDATOR_AGENT_HTTPS_ATTEMPTS`, `VALIDATOR_AGENT_HTTPS_RETRY_DELAY_SECONDS`, `VALIDATOR_AGENT_TRACEROUTE_{ENABLED,TIMEOUT_SECONDS,MAX_HOPS,POLL_INTERVAL_SECONDS}` в entrypoint, шаблоне конфига, `docker-compose.yml`, ansible env example; обновлены `configs/validator-agent.example.yaml` и его копия в `rxprod-compose/sources/`.
|
||||||
|
- **Тесты** (`internal/checkrunner/retry_trace_test.go`): успех со 2-й попытки (500 → 200) и разбор URL в хост.
|
||||||
|
|
||||||
|
control-api, схема БД и дашборд не менялись.
|
||||||
|
|
||||||
|
## Проверка
|
||||||
|
|
||||||
|
- `go build ./...`, `go vet`, `gofmt` — чисто; тесты `checkrunner`, `agentcore`, `config` проходят.
|
||||||
|
- Ручной прогон трассировки до `https://github.com` на хосте разработки: статус `completed`, вывод в IPv4 без имён, завершение зафиксировано на опросе через 5 с.
|
||||||
|
|
||||||
|
## Что нужно для внедрения
|
||||||
|
|
||||||
|
- Пересобрать бинарь и образ `validator-agent` и выкатить на валидаторы. Без пересборки образа `traceroute` в контейнере отсутствует, события получат `error: start traceroute: …`.
|
||||||
|
- `NET_RAW` контейнеру уже выдаётся, дополнительных прав не нужно.
|
||||||
|
- Время обработки адреса с недоступным FQDN растёт: +2 повтора с таймаутом и до 90 с на трассировку.
|
||||||
|
|
||||||
|
## Не сделано
|
||||||
|
|
||||||
|
- `deploy/docker/RUN.txt` и `docs/SETUP.md` не дополнены новыми переменными (работают значения по умолчанию).
|
||||||
@@ -19,6 +19,7 @@ import (
|
|||||||
neturl "net/url"
|
neturl "net/url"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -402,12 +403,16 @@ func fetchIPEcho(ctx context.Context, url string) (string, error) {
|
|||||||
|
|
||||||
func (a *Agent) runChecks(ctx context.Context, assignment assignmentResp) {
|
func (a *Agent) runChecks(ctx context.Context, assignment assignmentResp) {
|
||||||
var results []checkResultDTO
|
var results []checkResultDTO
|
||||||
|
var traces sync.WaitGroup
|
||||||
for _, ct := range assignment.CheckConfig {
|
for _, ct := range assignment.CheckConfig {
|
||||||
for _, target := range ct.Targets {
|
for _, target := range ct.Targets {
|
||||||
var fn func(context.Context) checkrunner.Result
|
var fn func(context.Context) checkrunner.Result
|
||||||
switch ct.Type {
|
switch ct.Type {
|
||||||
case "https":
|
case "https":
|
||||||
fn = checkrunner.HTTPS(target, time.Duration(a.cfg.Checks.HTTPSTimeoutSeconds)*time.Second)
|
fn = checkrunner.HTTPSWithRetry(target,
|
||||||
|
time.Duration(a.cfg.Checks.HTTPSTimeoutSeconds)*time.Second,
|
||||||
|
a.cfg.Checks.HTTPSAttempts,
|
||||||
|
time.Duration(a.cfg.Checks.HTTPSRetryDelaySeconds)*time.Second)
|
||||||
case "icmp":
|
case "icmp":
|
||||||
fn = checkrunner.ICMPEcho(hostOnly(target), a.cfg.Checks.ICMPCount, time.Duration(a.cfg.Checks.ICMPTimeoutSeconds)*time.Second)
|
fn = checkrunner.ICMPEcho(hostOnly(target), a.cfg.Checks.ICMPCount, time.Duration(a.cfg.Checks.ICMPTimeoutSeconds)*time.Second)
|
||||||
case "ssh":
|
case "ssh":
|
||||||
@@ -435,13 +440,53 @@ func (a *Agent) runChecks(ctx context.Context, assignment assignmentResp) {
|
|||||||
// Report progressively rather than batching until the end, so
|
// Report progressively rather than batching until the end, so
|
||||||
// a crash mid-run doesn't lose already-completed check results.
|
// a crash mid-run doesn't lose already-completed check results.
|
||||||
a.postResults(ctx, []checkResultDTO{results[len(results)-1]})
|
a.postResults(ctx, []checkResultDTO{results[len(results)-1]})
|
||||||
|
|
||||||
|
if ct.Type == "https" && !res.Success && a.cfg.Checks.Traceroute.IsEnabled() {
|
||||||
|
traces.Add(1)
|
||||||
|
go func(target string) {
|
||||||
|
defer traces.Done()
|
||||||
|
a.runTraceroute(ctx, assignment.IPID, target)
|
||||||
|
}(target)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Wait for traces before complete: after complete the control-api
|
||||||
|
// detaches the floating IP and the trace would leave from another address.
|
||||||
|
traces.Wait()
|
||||||
|
|
||||||
a.postComplete(ctx, assignment.IPID)
|
a.postComplete(ctx, assignment.IPID)
|
||||||
a.lastHandledIPID = assignment.IPID
|
a.lastHandledIPID = assignment.IPID
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// runTraceroute traces the route to target's host and posts the outcome as a
|
||||||
|
// traceroute_result event. It never affects the verdict.
|
||||||
|
func (a *Agent) runTraceroute(ctx context.Context, ipID int64, target string) {
|
||||||
|
tc := a.cfg.Checks.Traceroute
|
||||||
|
a.log.Info("traceroute start", "target", target)
|
||||||
|
r := <-checkrunner.StartTraceroute(ctx, target, checkrunner.TraceConfig{
|
||||||
|
Timeout: time.Duration(tc.TimeoutSeconds) * time.Second,
|
||||||
|
MaxHops: tc.MaxHops,
|
||||||
|
PollInterval: time.Duration(tc.PollIntervalSeconds) * time.Second,
|
||||||
|
})
|
||||||
|
a.log.Info("traceroute finish", "target", target, "ip", r.IP, "status", r.Status, "duration_ms", r.DurationMS)
|
||||||
|
|
||||||
|
payload, err := json.Marshal(struct {
|
||||||
|
Target string `json:"target"`
|
||||||
|
Host string `json:"host"`
|
||||||
|
IP string `json:"ip"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
DurationMS int64 `json:"duration_ms"`
|
||||||
|
Output string `json:"output"`
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
|
}{r.Target, r.Host, r.IP, r.Status, r.DurationMS, r.Output, r.Error})
|
||||||
|
if err != nil {
|
||||||
|
a.log.Error("marshal traceroute event", "err", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
a.postEvent(ctx, ipID, "traceroute_result", string(payload))
|
||||||
|
}
|
||||||
|
|
||||||
type checkResultDTO struct {
|
type checkResultDTO struct {
|
||||||
IPID int64 `json:"ip_id"`
|
IPID int64 `json:"ip_id"`
|
||||||
CheckType string `json:"check_type"`
|
CheckType string `json:"check_type"`
|
||||||
|
|||||||
@@ -9,12 +9,15 @@ import (
|
|||||||
|
|
||||||
// HTTPS performs a GET against target (expected to be a full URL, e.g.
|
// HTTPS performs a GET against target (expected to be a full URL, e.g.
|
||||||
// https://github.com) and reports success for any response with status
|
// https://github.com) and reports success for any response with status
|
||||||
// < 400. It never follows the check to a different host on a check-type
|
// < 400. Redirects are followed by the default http.Client policy.
|
||||||
// boundary — redirects within the same request are followed by the
|
// It makes a single attempt; use HTTPSWithRetry for retries.
|
||||||
// standard http.Client default policy, which is what we want for
|
|
||||||
// reachability checks.
|
|
||||||
func HTTPS(target string, timeout time.Duration) func(ctx context.Context) Result {
|
func HTTPS(target string, timeout time.Duration) func(ctx context.Context) Result {
|
||||||
return run("https", target, func(ctx context.Context) error {
|
return run("https", target, func(ctx context.Context) error {
|
||||||
|
return httpsOnce(ctx, &http.Client{Timeout: timeout}, target, timeout)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func httpsOnce(ctx context.Context, client *http.Client, target string, timeout time.Duration) error {
|
||||||
ctx, cancel := context.WithTimeout(ctx, timeout)
|
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
@@ -22,7 +25,6 @@ func HTTPS(target string, timeout time.Duration) func(ctx context.Context) Resul
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("build request: %w", err)
|
return fmt.Errorf("build request: %w", err)
|
||||||
}
|
}
|
||||||
client := &http.Client{Timeout: timeout}
|
|
||||||
resp, err := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -32,5 +34,41 @@ func HTTPS(target string, timeout time.Duration) func(ctx context.Context) Resul
|
|||||||
return fmt.Errorf("unexpected status %d", resp.StatusCode)
|
return fmt.Errorf("unexpected status %d", resp.StatusCode)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
}
|
||||||
|
|
||||||
|
// HTTPSWithRetry makes up to attempts tries, pausing delay between them, and
|
||||||
|
// stops at the first success. The result is a single Result: Detail carries
|
||||||
|
// the attempt number, LatencyMS is that of the last attempt.
|
||||||
|
func HTTPSWithRetry(target string, timeout time.Duration, attempts int, delay time.Duration) func(ctx context.Context) Result {
|
||||||
|
return httpsWithRetry(&http.Client{Timeout: timeout}, target, timeout, attempts, delay)
|
||||||
|
}
|
||||||
|
|
||||||
|
func httpsWithRetry(client *http.Client, target string, timeout time.Duration, attempts int, delay time.Duration) func(ctx context.Context) Result {
|
||||||
|
if attempts < 1 {
|
||||||
|
attempts = 1
|
||||||
|
}
|
||||||
|
return func(ctx context.Context) Result {
|
||||||
|
var res Result
|
||||||
|
for n := 1; n <= attempts; n++ {
|
||||||
|
res = run("https", target, func(ctx context.Context) error {
|
||||||
|
return httpsOnce(ctx, client, target, timeout)
|
||||||
|
})(ctx)
|
||||||
|
if res.Success {
|
||||||
|
res.Detail = fmt.Sprintf("ok (attempt %d/%d)", n, attempts)
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
if n == attempts || ctx.Err() != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
case <-time.After(delay):
|
||||||
|
}
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res.Detail = fmt.Sprintf("%s (%d/%d attempts failed)", res.Detail, attempts, attempts)
|
||||||
|
return res
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package checkrunner
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestHTTPSRetrySucceedsOnSecondAttempt(t *testing.T) {
|
||||||
|
var n atomic.Int32
|
||||||
|
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if n.Add(1) == 1 {
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
res := httpsWithRetry(srv.Client(), srv.URL, 2*time.Second, 3, 10*time.Millisecond)(context.Background())
|
||||||
|
if !res.Success || res.Detail != "ok (attempt 2/3)" {
|
||||||
|
t.Fatalf("got success=%v detail=%q", res.Success, res.Detail)
|
||||||
|
}
|
||||||
|
if n.Load() != 2 {
|
||||||
|
t.Fatalf("expected 2 requests, got %d", n.Load())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHostFromTarget(t *testing.T) {
|
||||||
|
cases := map[string]string{
|
||||||
|
"https://github.com": "github.com",
|
||||||
|
"https://github.com:8443/x": "github.com",
|
||||||
|
"http://1.2.3.4/path?q=1": "1.2.3.4",
|
||||||
|
"example.org": "example.org",
|
||||||
|
"example.org:443": "example.org",
|
||||||
|
}
|
||||||
|
for in, want := range cases {
|
||||||
|
if got := HostFromTarget(in); got != want {
|
||||||
|
t.Errorf("HostFromTarget(%q)=%q want %q", in, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
package checkrunner
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
neturl "net/url"
|
||||||
|
"os/exec"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Traceroute statuses.
|
||||||
|
const (
|
||||||
|
TraceCompleted = "completed"
|
||||||
|
TraceTimeout = "timeout"
|
||||||
|
TraceError = "error"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TraceResult is the outcome of one traceroute run.
|
||||||
|
type TraceResult struct {
|
||||||
|
Target string
|
||||||
|
Host string
|
||||||
|
IP string
|
||||||
|
Status string
|
||||||
|
DurationMS int64
|
||||||
|
Output string
|
||||||
|
Error string
|
||||||
|
}
|
||||||
|
|
||||||
|
// TraceConfig holds traceroute run parameters.
|
||||||
|
type TraceConfig struct {
|
||||||
|
Timeout time.Duration
|
||||||
|
MaxHops int
|
||||||
|
PollInterval time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// HostFromTarget extracts the host from a URL; if the target has no scheme
|
||||||
|
// (or does not parse) the raw value is used with any port/path stripped.
|
||||||
|
func HostFromTarget(target string) string {
|
||||||
|
if u, err := neturl.Parse(target); err == nil && u.Hostname() != "" {
|
||||||
|
return u.Hostname()
|
||||||
|
}
|
||||||
|
if u, err := neturl.Parse("//" + target); err == nil && u.Hostname() != "" {
|
||||||
|
return u.Hostname()
|
||||||
|
}
|
||||||
|
return target
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartTraceroute runs the trace in the background and returns a channel
|
||||||
|
// that yields exactly one result.
|
||||||
|
func StartTraceroute(ctx context.Context, target string, cfg TraceConfig) <-chan TraceResult {
|
||||||
|
ch := make(chan TraceResult, 1)
|
||||||
|
go func() { ch <- Traceroute(ctx, target, cfg) }()
|
||||||
|
return ch
|
||||||
|
}
|
||||||
|
|
||||||
|
// Traceroute resolves the host of target to IPv4 and runs the traceroute
|
||||||
|
// binary, polling its status every cfg.PollInterval until it exits or
|
||||||
|
// cfg.Timeout elapses (then the process is killed and partial output kept).
|
||||||
|
func Traceroute(ctx context.Context, target string, cfg TraceConfig) TraceResult {
|
||||||
|
start := time.Now()
|
||||||
|
res := TraceResult{Target: target, Host: HostFromTarget(target)}
|
||||||
|
finish := func() TraceResult {
|
||||||
|
res.DurationMS = time.Since(start).Milliseconds()
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.PollInterval <= 0 {
|
||||||
|
cfg.PollInterval = 5 * time.Second
|
||||||
|
}
|
||||||
|
if cfg.Timeout <= 0 {
|
||||||
|
cfg.Timeout = 90 * time.Second
|
||||||
|
}
|
||||||
|
if cfg.MaxHops <= 0 {
|
||||||
|
cfg.MaxHops = 30
|
||||||
|
}
|
||||||
|
|
||||||
|
if ip := net.ParseIP(res.Host); ip != nil && ip.To4() != nil {
|
||||||
|
res.IP = ip.To4().String()
|
||||||
|
} else {
|
||||||
|
rctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||||
|
ips, err := net.DefaultResolver.LookupIP(rctx, "ip4", res.Host)
|
||||||
|
cancel()
|
||||||
|
if err != nil || len(ips) == 0 {
|
||||||
|
res.Status = TraceError
|
||||||
|
if err == nil {
|
||||||
|
err = fmt.Errorf("no A records")
|
||||||
|
}
|
||||||
|
res.Error = "dns: " + err.Error()
|
||||||
|
return finish()
|
||||||
|
}
|
||||||
|
res.IP = ips[0].String()
|
||||||
|
}
|
||||||
|
|
||||||
|
var buf lockedBuffer
|
||||||
|
cmd := exec.Command("traceroute", "-4", "-n", "-q", "1", "-w", "2", "-m", strconv.Itoa(cfg.MaxHops), res.IP)
|
||||||
|
cmd.Stdout = &buf
|
||||||
|
cmd.Stderr = &buf
|
||||||
|
if err := cmd.Start(); err != nil {
|
||||||
|
res.Status = TraceError
|
||||||
|
res.Error = "start traceroute: " + err.Error()
|
||||||
|
return finish()
|
||||||
|
}
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go func() { done <- cmd.Wait() }()
|
||||||
|
|
||||||
|
ticker := time.NewTicker(cfg.PollInterval)
|
||||||
|
defer ticker.Stop()
|
||||||
|
deadline := time.NewTimer(cfg.Timeout)
|
||||||
|
defer deadline.Stop()
|
||||||
|
|
||||||
|
kill := func(status, msg string) {
|
||||||
|
_ = cmd.Process.Kill()
|
||||||
|
<-done
|
||||||
|
res.Status = status
|
||||||
|
res.Error = msg
|
||||||
|
}
|
||||||
|
|
||||||
|
loop:
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ticker.C:
|
||||||
|
// Status poll: the process state is checked only on a tick.
|
||||||
|
select {
|
||||||
|
case err := <-done:
|
||||||
|
if err != nil {
|
||||||
|
res.Status = TraceError
|
||||||
|
res.Error = err.Error()
|
||||||
|
} else {
|
||||||
|
res.Status = TraceCompleted
|
||||||
|
}
|
||||||
|
break loop
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
case <-deadline.C:
|
||||||
|
kill(TraceTimeout, fmt.Sprintf("traceroute exceeded %s", cfg.Timeout))
|
||||||
|
break loop
|
||||||
|
case <-ctx.Done():
|
||||||
|
kill(TraceError, "cancelled: "+ctx.Err().Error())
|
||||||
|
break loop
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res.Output = buf.String()
|
||||||
|
return finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
type lockedBuffer struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
b bytes.Buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *lockedBuffer) Write(p []byte) (int, error) {
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
return l.b.Write(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *lockedBuffer) String() string {
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
return l.b.String()
|
||||||
|
}
|
||||||
@@ -265,8 +265,26 @@ type AgentChecks struct {
|
|||||||
ICMPTimeoutSeconds int `yaml:"icmp_timeout_seconds"`
|
ICMPTimeoutSeconds int `yaml:"icmp_timeout_seconds"`
|
||||||
ICMPCount int `yaml:"icmp_count"`
|
ICMPCount int `yaml:"icmp_count"`
|
||||||
SSH SSHCfg `yaml:"ssh"`
|
SSH SSHCfg `yaml:"ssh"`
|
||||||
|
|
||||||
|
// HTTPSAttempts is the number of tries per HTTPS URL (first + retries).
|
||||||
|
HTTPSAttempts int `yaml:"https_attempts"`
|
||||||
|
HTTPSRetryDelaySeconds int `yaml:"https_retry_delay_seconds"`
|
||||||
|
|
||||||
|
Traceroute TracerouteCfg `yaml:"traceroute"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TracerouteCfg controls the background traceroute run after a failed HTTPS
|
||||||
|
// check. Enabled is a pointer so that an absent key means "enabled".
|
||||||
|
type TracerouteCfg struct {
|
||||||
|
Enabled *bool `yaml:"enabled"`
|
||||||
|
TimeoutSeconds int `yaml:"timeout_seconds"`
|
||||||
|
MaxHops int `yaml:"max_hops"`
|
||||||
|
PollIntervalSeconds int `yaml:"poll_interval_seconds"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsEnabled reports whether traceroute is on (default true).
|
||||||
|
func (t TracerouteCfg) IsEnabled() bool { return t.Enabled == nil || *t.Enabled }
|
||||||
|
|
||||||
type SSHCfg struct {
|
type SSHCfg struct {
|
||||||
Enabled bool `yaml:"enabled"`
|
Enabled bool `yaml:"enabled"`
|
||||||
TimeoutSeconds int `yaml:"timeout_seconds"`
|
TimeoutSeconds int `yaml:"timeout_seconds"`
|
||||||
@@ -306,6 +324,21 @@ func LoadValidatorAgent(path string) (*ValidatorAgent, error) {
|
|||||||
if c.Checks.ICMPCount == 0 {
|
if c.Checks.ICMPCount == 0 {
|
||||||
c.Checks.ICMPCount = 3
|
c.Checks.ICMPCount = 3
|
||||||
}
|
}
|
||||||
|
if c.Checks.HTTPSAttempts <= 0 {
|
||||||
|
c.Checks.HTTPSAttempts = 3
|
||||||
|
}
|
||||||
|
if c.Checks.HTTPSRetryDelaySeconds <= 0 {
|
||||||
|
c.Checks.HTTPSRetryDelaySeconds = 2
|
||||||
|
}
|
||||||
|
if c.Checks.Traceroute.TimeoutSeconds <= 0 {
|
||||||
|
c.Checks.Traceroute.TimeoutSeconds = 90
|
||||||
|
}
|
||||||
|
if c.Checks.Traceroute.MaxHops <= 0 {
|
||||||
|
c.Checks.Traceroute.MaxHops = 30
|
||||||
|
}
|
||||||
|
if c.Checks.Traceroute.PollIntervalSeconds <= 0 {
|
||||||
|
c.Checks.Traceroute.PollIntervalSeconds = 5
|
||||||
|
}
|
||||||
if c.Checks.SSH.TimeoutSeconds == 0 {
|
if c.Checks.SSH.TimeoutSeconds == 0 {
|
||||||
c.Checks.SSH.TimeoutSeconds = 5
|
c.Checks.SSH.TimeoutSeconds = 5
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,6 +39,16 @@ self_check:
|
|||||||
|
|
||||||
checks:
|
checks:
|
||||||
https_timeout_seconds: 10
|
https_timeout_seconds: 10
|
||||||
|
# Attempts per HTTPS URL (first + retries) and pause between them.
|
||||||
|
https_attempts: 3
|
||||||
|
https_retry_delay_seconds: 2
|
||||||
|
# Background traceroute (IPv4) after an HTTPS check fails on all attempts;
|
||||||
|
# result goes to the address event log as "traceroute_result".
|
||||||
|
traceroute:
|
||||||
|
enabled: true
|
||||||
|
timeout_seconds: 90
|
||||||
|
max_hops: 30
|
||||||
|
poll_interval_seconds: 5
|
||||||
icmp_timeout_seconds: 5
|
icmp_timeout_seconds: 5
|
||||||
icmp_count: 3
|
icmp_count: 3
|
||||||
ssh:
|
ssh:
|
||||||
|
|||||||
Reference in new issue
Block a user