chore: reap docker events, cut per-cycle work, use mkswap --file [P1/P2]
1. docker events was leaking zombies. docker_events_loop spawned the child, read its stdout to EOF and returned without calling wait(). Dropping a Child does not reap it, so every reconnect - which happens whenever Docker restarts or the stream ends - left a defunct process behind for the lifetime of the daemon. The reader loop moved into its own function so the wait happens on every exit path, and the exit status is logged rather than discarded. 2. sysctl status still decided ownership with contains(). The destructive paths were fixed earlier, but inspect_sysctl_tuning kept first.contains(MANAGED_MARKER) in the disabled branch, so a file whose first line merely embedded the marker was reported as managed. Diagnostic-only, but it contradicted the rule the rest of the module follows. Now an exact match on the trimmed first line. 3. Swap was reconciled at the traffic interval. ensure_swap ran every reconcile_interval_secs, default 15, and each run spawns swapon --show, sysctl reads, the persistence check and the final verify. A swapfile, its fstab entry and vm.swappiness change when an operator changes them and at no other time, so this was process spawning for state that does not drift. Swap now runs on its own 300-second schedule; traffic and firewall keep the configured interval. The startup reconcile is unchanged, so a fresh daemon still converges immediately. 4. The event log recorded routine success. Every successful cycle appended a line, and appending means reading the whole file, rewriting it and truncating. At 15 seconds that is roughly 17k entries a day, and the entries worth reading were buried among them. Only transitions are written now: a new failure, a failure whose message changed, and the recovery after one. set_ok and set_err report whether the state actually changed, which is what makes that possible. journald still has the full per-cycle picture through the tracing output. 5. Swapfile creation is one command. mkswap --file <path> --size <N>M creates and formats the file, replacing the fallocate → dd fallback → chmod → mkswap chain: four processes, three failure branches, and a window where the file existed but was not yet formatted. util-linux on Debian 13 also handles filesystem-specific requirements - Btrfs in particular - that raw fallocate does not. fallocate, dd and chmod drop out of the required host tools when swap is enabled. cargo test --workspace: 183 + 4 passed. clippy -D warnings clean.
This commit is contained in:
@@ -465,7 +465,7 @@ Status обязан показывать наличие таблицы/chain/п
|
||||
Демон использует два триггера:
|
||||
|
||||
1. Docker events: `docker events --filter event=start --format '{{.Actor.Attributes.name}}'`. Имя сверяется с `amnezia.container_names`, после чего выполняется ожидание готовности интерфейса и reconcile traffic + firewall. Если поток событий завершился, он перезапускается через 10 секунд.
|
||||
2. Таймер: периодический reconcile каждые `traffic.reconcile_interval_secs`, но не чаще одного раза в 5 секунд.
|
||||
2. Таймер: периодический reconcile каждые `traffic.reconcile_interval_secs`, но не чаще одного раза в 5 секунд. Он применяется к `traffic` и `firewall`; `swap` идёт по собственному расписанию — раз в 5 минут. Swapfile, запись в `/etc/fstab` и `vm.swappiness` меняются только тогда, когда их меняет оператор, а проверка на traffic-интервале означала несколько вызовов `swapon --show` и `sysctl` каждые 15 секунд ради состояния, которое само по себе не дрейфует.
|
||||
|
||||
Таймер обязателен. События могут быть пропущены при рестарте демона, рестарте Docker или транзиентных ошибках.
|
||||
|
||||
@@ -485,6 +485,8 @@ Status обязан показывать наличие таблицы/chain/п
|
||||
- `/run/awg2-harness/last_action.state` — последний успех и последняя ошибка;
|
||||
- `/run/awg2-harness/events.log` — журнал событий, ограниченный 1000 строками и 256 KiB.
|
||||
|
||||
В `events.log` пишутся только **переходы состояния**: первое появление ошибки, изменение текста ошибки и восстановление после неё. Рутинный успех не пишется. Раньше каждый успешный цикл добавлял строку — при интервале 15 секунд это порядка 17 тысяч записей в сутки, каждая с полным чтением, дополнением и перезаписью файла, и на их фоне терялись записи, ради которых журнал и читают. Полная поцикловая картина остаётся в journald через tracing.
|
||||
|
||||
## 14. Блокировки
|
||||
|
||||
Одновременно может выполняться только один reconcile каждого вида — по всем подкомандам и задачам демона.
|
||||
@@ -592,7 +594,7 @@ Production-путь перезагрузки — внешний бинарь/с
|
||||
|
||||
При `swap.enabled = true` AWG2 Harness владеет состоянием swap на хосте эксклюзивно. Целевое состояние — ровно одна активная swap-запись: `swap.path`. Все прочие активные swap выключаются через `swapoff`, а их записи убираются из `/etc/fstab`. Операция обязана быть идемпотентной.
|
||||
|
||||
Создание файла: `fallocate`, при неудаче — fallback на `dd`.
|
||||
Создание файла: `mkswap --file <path> --size <N>M` — одна команда, которая и создаёт файл, и форматирует его. Прежняя цепочка `fallocate` → fallback `dd` → `chmod` → `mkswap` давала четыре процесса, три ветки отказа и промежуток, в котором файл уже существовал, но ещё не был отформатирован. `util-linux` в Debian 13 дополнительно учитывает требования конкретных ФС (в частности Btrfs), которых голый `fallocate` не знает. Из обязательных host tools при `swap.enabled = true` соответственно ушли `fallocate`, `dd` и `chmod`.
|
||||
|
||||
### Владение swapfile
|
||||
|
||||
|
||||
Reference in New Issue
Block a user