From cfa01cf5e293349ce09b79acd862e083b9a1bccd Mon Sep 17 00:00:00 2001 From: rchac Date: Mon, 23 Mar 2026 02:24:20 +0000 Subject: [PATCH] changes --- .../v2.0/libreqos-backend-architecture-es.md | 10 + docs-es/v2.0/node-manager-ui-es.md | 1 + docs-es/v2.0/treeguard-es.md | 38 +- docs-es/v2.0/troubleshooting-es.md | 14 +- docs/v2.0/libreqos-backend-architecture.md | 10 + docs/v2.0/node-manager-ui.md | 1 + docs/v2.0/treeguard.md | 38 +- docs/v2.0/troubleshooting.md | 18 +- src/LibreQoS.py | 944 +++--- src/bakery_integration_test.py | 171 +- src/rust/Cargo.lock | 71 +- src/rust/Cargo.toml | 4 + src/rust/lqos_bakery/src/commands.rs | 99 +- src/rust/lqos_bakery/src/diff/circuits.rs | 137 +- src/rust/lqos_bakery/src/lib.rs | 2855 ++++++++++++++++- src/rust/lqos_bakery/src/qdisc_handles.rs | 21 - src/rust/lqos_bakery/src/utils.rs | 419 ++- src/rust/lqos_bus/src/bus/request.rs | 19 + src/rust/lqos_config/Cargo.toml | 2 + src/rust/lqos_config/src/authentication.rs | 383 ++- src/rust/lqos_config/src/lib.rs | 9 +- src/rust/lqos_config/src/network_json.rs | 2 + .../src/network_json/network_json_node.rs | 1 + .../network_json/network_json_transport.rs | 3 + src/rust/lqos_config/src/planner.rs | 698 ++++ src/rust/lqos_overrides/src/overrides_file.rs | 69 +- src/rust/lqos_python/src/lib.rs | 506 ++- .../lqos_queue_tracker/src/tracking/mod.rs | 37 +- src/rust/lqosd/Cargo.toml | 3 + src/rust/lqosd/src/main.rs | 17 +- src/rust/lqosd/src/node_manager.rs | 1 + src/rust/lqosd/src/node_manager/auth.rs | 732 ++++- .../src/dashlets/bakery_apply_summary.js | 56 +- .../js_build/src/dashlets/bakery_capacity.js | 255 +- .../js_build/src/dashlets/bakery_shared.js | 7 + .../src/dashlets/treeguard_controls.js | 14 +- .../node_manager/js_build/src/first-run.js | 19 +- .../src/node_manager/js_build/src/index.js | 8 + .../src/node_manager/js_build/src/login.js | 19 +- .../dashboard/dashboard_editor.js | 20 +- .../src/lq_js_common/dashboard/layout.js | 176 +- .../src/node_manager/js_build/src/template.js | 5 +- .../src/node_manager/js_build/src/tree.js | 14 + .../src/node_manager/local_api/directories.rs | 2 +- .../local_api/network_tree_lite.rs | 3 + src/rust/lqosd/src/node_manager/run.rs | 2 + .../src/node_manager/static2/first-run.html | 5 + .../lqosd/src/node_manager/static2/login.html | 2 +- .../src/node_manager/static2/template.html | 3 +- .../lqosd/src/node_manager/ws/messages.rs | 15 + .../src/node_manager/ws/ticker/bakery.rs | 13 + src/rust/lqosd/src/reload_lock.rs | 36 - .../lqosd/src/shaped_devices_tracker/mod.rs | 58 +- src/rust/lqosd/src/throughput_tracker/mod.rs | 35 +- src/rust/lqosd/src/treeguard/actor.rs | 2221 +++++++------ src/rust/lqosd/src/treeguard/bakery.rs | 38 +- src/rust/lqosd/src/treeguard/decisions.rs | 14 +- src/rust/lqosd/src/treeguard/errors.rs | 4 + src/rust/lqosd/src/treeguard/mod.rs | 1 - src/rust/lqosd/src/treeguard/overrides.rs | 46 +- src/rust/lqosd/src/treeguard/reload.rs | 219 -- src/rust/lqosd/src/treeguard/status.rs | 4 + src/rust/lqusers/Cargo.toml | 2 + src/rust/lqusers/src/main.rs | 17 + src/scheduler.py | 47 +- 65 files changed, 8218 insertions(+), 2495 deletions(-) create mode 100644 src/rust/lqos_config/src/planner.rs delete mode 100644 src/rust/lqosd/src/reload_lock.rs delete mode 100644 src/rust/lqosd/src/treeguard/reload.rs diff --git a/docs-es/v2.0/libreqos-backend-architecture-es.md b/docs-es/v2.0/libreqos-backend-architecture-es.md index 5222ef74..741bceff 100644 --- a/docs-es/v2.0/libreqos-backend-architecture-es.md +++ b/docs-es/v2.0/libreqos-backend-architecture-es.md @@ -242,6 +242,7 @@ Efecto práctico: |---|---|---|---| | Cambio solo de IP de circuito | Sí | No | Actualización de mapeo puede aplicarse sin reconstruir árbol | | Cambio de velocidad de circuito/sitio (subconjunto) | Sí | A veces | Depende del impacto estructural y class handles disponibles | +| Virtualización runtime de nodos TreeGuard (subárbol soportado / ruta de rebalanceo top-level) | Sí | No | Bakery ahora la aplica como un plan runtime vivo: nodos no top-level usan reparent/prune/restore, y nodos top-level soportados usan una ruta de rebalanceo y migración entre colas | | Cambios masivos en todos los circuitos | A veces | Frecuente | Límites de escala y cardinalidad de transacciones | | Re-parent/reestructura topológica | Rara vez | Sí | Restricciones de mutación de subárbol HTB | | Alta/baja de circuitos | Sí (pequeño/mediano) | A veces | Límites de handles y fronteras de corrección en el diff | @@ -269,6 +270,15 @@ flowchart TD 3. Esperar mayor riesgo cuando coinciden muchos circuitos y muchos cambios estructurales. 4. Diseñar la cadencia operativa para priorizar cambios incrementalmente seguros. +### 7.4 Guardrails de seguridad para recargas completas + +Las recargas completas actuales de Bakery aplican dos verificaciones conservadoras de seguridad antes y durante reconstrucciones grandes de colas: + +1. Un preflight de qdisc estima los qdisc planificados por interfaz y además separa qdisc de infraestructura, hojas `cake` y hojas `fq_codel`. +2. Ese mismo preflight aplica una proyección conservadora de memoria y bloquea de forma estricta las recargas completas claramente inseguras antes de arrancar `tc -batch`. +3. Durante la aplicación chunked de una recarga completa, Bakery vuelve a revisar la memoria del host en los límites de chunk y aborta el resto de la aplicación si la memoria disponible cae por debajo de su piso de seguridad. +4. Estos guardrails están sesgados intencionalmente hacia falsos positivos en recargas grandes para fallar temprano con diagnósticos en lugar de entrar en una espiral OOM. + ## 8) Límites de Diseño para Operadores ### 8.1 Límites de observabilidad diff --git a/docs-es/v2.0/node-manager-ui-es.md b/docs-es/v2.0/node-manager-ui-es.md index 850cf65e..b00b1997 100644 --- a/docs-es/v2.0/node-manager-ui-es.md +++ b/docs-es/v2.0/node-manager-ui-es.md @@ -9,6 +9,7 @@ Esta página documenta las vistas clave de la WebUI (Node Manager) y su comporta - El contenido puede variar según versión y funciones habilitadas. - Executive Summary ofrece una vista operativa compacta para redes grandes, con páginas de detalle para heatmaps y rankings ejecutivos. - Bakery ofrece una pestaña dedicada para el estado de aplicación de colas, eventos recientes de Bakery, resultados de seguridad/preflight de qdisc y el gráfico existente de actividad de circuitos. +- El preflight de qdisc de Bakery ahora presenta los qdisc planificados por interfaz como barras compactas de uso con badges del tipo de qdisc, además de una tabla separada de límites/memoria para presupuesto seguro, límite del kernel, memoria estimada de qdisc, memoria disponible actual y margen sobre el piso de seguridad. - Algunos gráficos pueden tardar un poco en poblarse al abrir una pestaña por primera vez, especialmente en sistemas ocupados o inmediatamente después de reiniciar servicios. - Durante un full reload de Bakery, las tarjetas de conteo de colas mantienen los últimos valores conocidos de HTB/CAKE/fq-codel y los marcan como `Reloading` en lugar de mostrar ceros momentáneamente. diff --git a/docs-es/v2.0/treeguard-es.md b/docs-es/v2.0/treeguard-es.md index 606ce238..ddacdd7f 100644 --- a/docs-es/v2.0/treeguard-es.md +++ b/docs-es/v2.0/treeguard-es.md @@ -32,11 +32,19 @@ TreeGuard evalúa utilización, frescura de RTT, guardrails de CPU y guardrails Comportamiento de alto nivel: 1. Bajo condiciones sostenidas de baja carga, TreeGuard puede cambiar una dirección de `cake` a `fq_codel`. -2. Si sube la utilización, los guardrails RTT/QoO no son seguros o se cumplen condiciones de reversión, TreeGuard vuelve a `cake`. +2. Si sube la utilización, los guardrails de QoO no son seguros o se cumplen condiciones de reversión, TreeGuard vuelve hacia la política SQM base del circuito. 3. Las decisiones pueden ser independientes por dirección cuando `independent_directions = true`. Esto crea un perfil dinámico en el que direcciones cargadas favorecen `cake diffserv4`, mientras direcciones de baja carga pueden usar `fq_codel` cuando las condiciones son seguras. +La política SQM base proviene de la intención del operador, no de defaults internos de TreeGuard. En la práctica, TreeGuard parte de la política efectiva configurada para cada circuito y solo persiste su propio overlay temporal cuando necesita diferir de esa base. + +Regla importante de política base: + +1. Si la política SQM base de una dirección es `cake`, TreeGuard puede cambiar temporalmente esa dirección a `fq_codel` y luego volver a la base. +2. Si la política SQM base de una dirección es `fq_codel`, TreeGuard no conmuta esa dirección de circuito hacia `cake`. +3. La virtualización de enlaces sigue disponible independientemente de la política SQM base del circuito. + ## Configuración (`/etc/lqos.conf`) La configuración de TreeGuard vive bajo `[treeguard]` y sus sub-secciones: @@ -80,20 +88,38 @@ enabled = true ## Overrides y Notas Operativas -Cuando está habilitado y no está en dry-run, TreeGuard puede persistir decisiones en: +Cuando está habilitado y no está en dry-run, TreeGuard puede persistir decisiones SQM de circuitos en: - `lqos_overrides.treeguard.json` TreeGuard está diseñado para no pelear con overrides del operador. Si existen overrides del operador para entidades enroladas, TreeGuard omite esas entidades y reporta advertencias. -Las decisiones de virtualización de nodos de TreeGuard son overrides de tiempo de ejecución. El -scheduler no las materializa de vuelta en el `network.json` base, por lo que deshabilitar o limpiar -TreeGuard no reescribe permanentemente la topología definida por el operador. +Las decisiones de virtualización de nodos de TreeGuard son operaciones de Bakery solo en tiempo de +ejecución. El scheduler no las materializa de vuelta en el `network.json` base, y tampoco se +persisten como entradas TreeGuard `set_node_virtual` dentro de la entrada efectiva de shaping. En +v1 son efímeras: un reinicio del daemon devuelve el árbol físico a la topología base definida por +el operador hasta que TreeGuard vuelva a decidir. -TreeGuard también se niega a gestionar nodos que ya estén marcados con `"virtual": true` en el `network.json` base. Si existen overrides viejos de TreeGuard para esos nodos, TreeGuard limpia su propia capa de overrides y vuelve a respetar la definición base de la topología. +Las decisiones SQM por circuito de TreeGuard también son overrides de tiempo de ejecución. El scheduler no materializa los cambios SQM propiedad de TreeGuard de vuelta en el `ShapedDevices.csv` base, por lo que limpiar TreeGuard no reescribe permanentemente la política SQM definida por el operador. + +TreeGuard también se niega a gestionar nodos que ya estén marcados con `"virtual": true` en el `network.json` base. Si existen overrides legados de TreeGuard para esos nodos, TreeGuard limpia ese estado legado y vuelve a respetar la definición base de la topología. Para la gestión SQM por circuito, TreeGuard trata los valores duplicados de `device_id` como colisiones de identidad inseguras. Si el mismo `device_id` aparece en más de un circuito dentro de `ShapedDevices.csv`, TreeGuard omite esos circuitos afectados y limpia cualquier override SQM de TreeGuard asociado a esos `device_id` duplicados. +Si la telemetría RTT no está disponible temporalmente después de un reinicio, TreeGuard no trata la ausencia de RTT por sí sola como evidencia para revertir direcciones en `fq_codel`. Siguen aplicando otros guardrails como utilización, QoO y presión de CPU. + +TreeGuard también aplica un presupuesto global conservador de cambios SQM por tick. En poblaciones muy grandes de circuitos enrolados, los cambios SQM excedentes se difieren a ticks posteriores en lugar de saturar Bakery en una sola pasada. + +Para escalar mejor, TreeGuard ya no reconstruye la membresía de circuitos desde `ShapedDevices.csv` en cada tick de circuitos. Ahora mantiene un inventario por circuito en caché derivado de `ShapedDevices.csv`, lee la telemetría viva por circuito desde el snapshot compartido de rollup por circuito actualizado una vez por segundo, y reparte las evaluaciones SQM grandes con `all_circuits = true` a lo largo de múltiples ticks en lugar de reescanear todos los circuitos enrolados cada segundo. + +En la práctica esto significa: + +1. La virtualización de enlaces sigue la cadencia normal de ticks de TreeGuard. +2. La evaluación SQM de circuitos para enrolamientos pequeños sigue completándose rápidamente. +3. Los enrolamientos muy grandes con `all_circuits` se recorren de forma incremental a lo largo de varios ticks, con un objetivo de barrido completo de alrededor de 15 segundos en vez de intentar un escaneo completo por segundo. +4. La virtualización de nodos de TreeGuard ahora usa rutas vivas de planificación/aplicación en Bakery en lugar de forzar una recarga completa de LibreQoS o de Bakery. +5. La virtualización runtime soportada de nodos top-level ahora usa un plan de rebalanceo/migración en Bakery que puede promover sitios hijos y circuitos directos entre raíces de cola, preservando la jerarquía lógica para reportes. + La actividad reciente de TreeGuard está disponible en dos lugares: - Las vistas de estado/actividad de TreeGuard en la WebUI. diff --git a/docs-es/v2.0/troubleshooting-es.md b/docs-es/v2.0/troubleshooting-es.md index 80112b0b..0dc21a88 100644 --- a/docs-es/v2.0/troubleshooting-es.md +++ b/docs-es/v2.0/troubleshooting-es.md @@ -46,14 +46,17 @@ Incluya también: ### La contraseña de usuario no funciona -Elimine el archivo de usuarios: +Los builds actuales: +- migran automáticamente archivos de autenticación antiguos +- redirigen `/login.html` a `/first-run.html` cuando no existen usuarios ```bash -sudo rm /opt/libreqos/src/lqusers.toml -sudo systemctl restart lqosd lqos_scheduler +sudo systemctl restart lqosd ``` -Luego abra: `IP_CAJA:9123/index.html`. +Si el usuario/contraseña correctos siguen fallando, pruebe primero con ese reinicio. + +Elimine `lqusers.toml` solo si desea reiniciar el acceso o si el archivo está corrupto y no se puede reparar. Después de eliminarlo, reinicie `lqosd` y abra `IP_CAJA:9123/login.html`; la WebUI debería redirigirlo automáticamente al flujo de primer inicio. ### No hay WebUI en x.x.x.x:9123 @@ -216,7 +219,8 @@ WebUI muestra códigos legibles por máquina para triage rápido. |---|---|---|---| | `MAPPED_CIRCUIT_LIMIT` | Bakery está forzando límite de circuitos mapeados. | Estado de licencia Insight y `journalctl -u lqosd` con requested/allowed/dropped. | Reducir circuitos mapeados o actualizar licencia/límites. | | `TC_U16_OVERFLOW` | IDs minor de clases/colas excedieron rango u16 de tc en una cola CPU. | `journalctl -u lqos_scheduler -u lqosd`, profundidad topológica y distribución por colas. | Aumentar paralelismo de colas y/o simplificar/rebalancear jerarquía. | -| `TC_QDISC_CAPACITY` | Los qdisc autoasignados planificados exceden el presupuesto seguro por interfaz antes de aplicar. | Conteos estimados de qdisc por interfaz en el contexto del urgent issue, `journalctl -u lqos_scheduler -u lqosd`, configuración `on_a_stick` y `monitor_only`. | Reducir la carga planificada de qdisc para esta ejecución (por ejemplo menos circuitos/dispositivos en la forma de prueba) antes de reintentar; no confiar en una aplicación parcial. | +| `TC_QDISC_CAPACITY` | Los qdisc autoasignados planificados exceden el presupuesto seguro por interfaz o el preflight conservador de seguridad de memoria de Bakery antes de aplicar. | Conteos estimados por interfaz, desglose por tipo de qdisc y campos de memoria en el contexto del urgent issue, `journalctl -u lqos_scheduler -u lqosd`, configuración `on_a_stick` y `monitor_only`. | Reducir la carga planificada de qdisc para esta ejecución (por ejemplo menos circuitos/dispositivos en la forma de prueba) antes de reintentar; no confiar en una aplicación parcial. | +| `BAKERY_MEMORY_GUARD` | Un full reload chunked de Bakery fue detenido a mitad de aplicación porque la memoria disponible del host cayó por debajo del piso de seguridad. | `journalctl -u lqosd`, memoria disponible/total en el contexto del urgent issue y progreso reciente de aplicación de Bakery. | Tratar la ejecución como fallida, reducir presión de memoria o huella de colas y reintentar solo cuando el host esté estable. | | `XDP_IP_MAPPING_CAPACITY` | Los mapeos IP requeridos exceden la capacidad actual del mapa XDP en el kernel. | Forma de `ShapedDevices.csv`, mezcla IPv4/IPv6, supuesto de un dispositivo frente a varios dispositivos, `journalctl -u lqos_scheduler -u lqosd`. | Reducir mapeos requeridos de inmediato (por ejemplo menos dispositivos o prueba IPv4-only), o aumentar la capacidad del mapa del kernel en un cambio coordinado. | | `XDP_IP_MAPPING_APPLY_FAILED` | Uno o más inserts de mapeo IP fallaron durante la aplicación. | `journalctl -u lqos_scheduler -u lqosd` para ejemplos resumidos y conteos de fallo. | Corregir la causa del fallo y volver a ejecutar; no confiar en shaping parcial. | diff --git a/docs/v2.0/libreqos-backend-architecture.md b/docs/v2.0/libreqos-backend-architecture.md index c35c1114..b4382b3d 100644 --- a/docs/v2.0/libreqos-backend-architecture.md +++ b/docs/v2.0/libreqos-backend-architecture.md @@ -248,6 +248,7 @@ Practical effect: |---|---|---|---| | Circuit IP-only change | Yes | No | Mapping update can often be applied without tree rebuild | | Circuit/site speed change (subset) | Yes | Sometimes | Depends on structural impact and available class handles | +| TreeGuard runtime node virtualization (supported subtree/top-level rebalance path) | Yes | No | Bakery now applies it as a live runtime plan: non-top-level nodes use reparent/prune/restore, and supported top-level nodes use a rebalance + cross-queue migration path | | Bulk all-circuit changes | Sometimes | Often | Scale and transaction/cardinality limits | | Topology re-parent/restructure | Rarely | Yes | HTB subtree mutation constraints | | Add/remove circuits | Yes (small/moderate) | Sometimes | Handle availability and diff correctness boundaries | @@ -275,6 +276,15 @@ flowchart TD 3. Expect higher risk when many circuits and many structure-affecting changes happen together. 4. Build operations cadence around incremental-safe updates by default. +### 7.4 Full-reload safety guards + +Current Bakery full reloads apply two conservative safety checks before and during large queue rebuilds: + +1. A qdisc preflight estimates planned qdiscs per interface and also separates infrastructure, `cake`, and `fq_codel` leaf qdiscs. +2. That same preflight applies a conservative memory forecast and hard-blocks clearly unsafe full reloads before `tc -batch` starts. +3. During chunked full reload apply, Bakery re-checks host memory at chunk boundaries and aborts the remaining apply if available memory drops below its safety floor. +4. These guards are intentionally biased toward false positives on large reloads so the system fails early with diagnostics instead of spiraling into an OOM event. + ## 8) Design Boundaries for Operators ### 8.1 Observability boundaries diff --git a/docs/v2.0/node-manager-ui.md b/docs/v2.0/node-manager-ui.md index e36e9510..478634c5 100644 --- a/docs/v2.0/node-manager-ui.md +++ b/docs/v2.0/node-manager-ui.md @@ -9,6 +9,7 @@ This page documents key WebUI (Node Manager) views and operational behavior in t - Dashboard content can vary by version and enabled features. - Executive Summary provides a compact operational view for large networks, with drilldown pages for executive heatmaps and leaderboards. - Bakery provides dedicated status for queue apply state, recent Bakery events, qdisc safety/preflight results, and the existing circuit-activity graph. +- Bakery qdisc preflight now presents per-interface planned qdiscs as compact usage bars with qdisc-kind mix badges, plus a separate limits/memory table for safe budget, kernel limit, estimated qdisc memory, current available memory, and safety-floor headroom. - Some charts may take a short time to populate after first opening a tab, especially on busy systems or immediately after a service restart. - During a Bakery full reload, queue-count cards keep showing the last known HTB/CAKE/fq-codel values and mark them as `Reloading` instead of briefly zeroing them. diff --git a/docs/v2.0/treeguard.md b/docs/v2.0/treeguard.md index d5b48c71..d4868171 100644 --- a/docs/v2.0/treeguard.md +++ b/docs/v2.0/treeguard.md @@ -32,11 +32,19 @@ TreeGuard evaluates utilization, RTT freshness, CPU guardrails, and optional QoO High-level behavior: 1. For sustained low-load conditions, TreeGuard may switch a direction from `cake` to `fq_codel`. -2. If utilization rises, RTT/QoO guardrails are unsafe, or revert conditions are met, TreeGuard switches back to `cake`. +2. If utilization rises, QoO guardrails are unsafe, or revert conditions are met, TreeGuard switches back toward the circuit's base SQM policy. 3. Decisions can be independent per direction when `independent_directions = true`. This gives a dynamic profile where loaded directions favor `cake diffserv4`, while low-load directions can use `fq_codel` when conditions are safe. +The base SQM policy comes from operator intent, not from TreeGuard defaults. In practice, TreeGuard starts from the effective configured policy for each circuit and only persists its own temporary overlay when it needs to differ from that base. + +Important base-policy rule: + +1. If a direction's base SQM policy is `cake`, TreeGuard may temporarily switch that direction to `fq_codel` and later return it to base. +2. If a direction's base SQM policy is `fq_codel`, TreeGuard does not circuit-switch that direction to `cake`. +3. Link virtualization remains available regardless of the circuit SQM base policy. + ## Configuration (`/etc/lqos.conf`) TreeGuard config lives under `[treeguard]` and sub-sections: @@ -80,20 +88,38 @@ enabled = true ## Overrides and Operational Notes -When enabled and not dry-run, TreeGuard may persist decisions to: +When enabled and not dry-run, TreeGuard may persist circuit SQM decisions to: - `lqos_overrides.treeguard.json` TreeGuard is designed to avoid fighting operator-owned overrides. If operator overrides exist for enrolled entities, TreeGuard skips those entities and reports warnings. -TreeGuard virtual-node decisions are runtime overrides. They are not materialized back into the -base `network.json` by the scheduler, so disabling or clearing TreeGuard does not permanently -rewrite operator-authored topology. +TreeGuard virtual-node decisions are runtime-only Bakery operations. They are not materialized back +into the base `network.json` by the scheduler, and they are not persisted as TreeGuard-owned +`set_node_virtual` entries in the effective shaping input. In v1 they are ephemeral: a daemon +restart returns the physical tree to the base operator-defined topology until TreeGuard decides +again. -TreeGuard also refuses to manage nodes that are already marked `"virtual": true` in the base `network.json`. If stale TreeGuard-owned node-virtualization overrides exist for those nodes, TreeGuard clears its own override layer and falls back to the base topology definition. +TreeGuard circuit SQM decisions are also runtime overrides. The scheduler does not materialize TreeGuard-owned SQM changes back into the base `ShapedDevices.csv`, so clearing TreeGuard does not permanently rewrite operator-authored circuit SQM policy. + +TreeGuard also refuses to manage nodes that are already marked `"virtual": true` in the base `network.json`. If stale legacy TreeGuard-owned node-virtualization overrides exist for those nodes, TreeGuard clears that legacy override state and falls back to the base topology definition. For circuit SQM management, TreeGuard treats duplicate `device_id` values as unsafe identity collisions. If the same `device_id` appears in more than one circuit in `ShapedDevices.csv`, TreeGuard skips those affected circuits and clears any TreeGuard-owned SQM overrides for those duplicate device IDs. +If RTT telemetry is temporarily unavailable after a restart, TreeGuard does not treat missing RTT alone as evidence that it should revert `fq_codel` directions. Other guardrails such as utilization, QoO, and CPU pressure still apply. + +TreeGuard also applies a conservative global per-tick circuit SQM change budget. On very large enrolled populations, excess circuit SQM changes are deferred to later ticks instead of stampeding Bakery in one pass. + +For scale, TreeGuard no longer rebuilds circuit membership from `ShapedDevices.csv` on every circuit tick. It now keeps a cached per-circuit inventory derived from `ShapedDevices.csv`, reads per-circuit live telemetry from the shared once-per-second circuit rollup snapshot, and spreads large `all_circuits = true` SQM evaluations across multiple ticks instead of rescanning every enrolled circuit every second. + +In practice, this means: + +1. Link virtualization still follows the normal TreeGuard tick cadence. +2. Circuit SQM evaluation for small enrollments still completes quickly. +3. Very large `all_circuits` enrollments are swept incrementally over multiple ticks, with a target full sweep around 15 seconds instead of attempting a full per-second scan. +4. TreeGuard node virtualization now goes through Bakery live runtime planning/apply paths instead of forcing a LibreQoS reload or Bakery full reload. +5. Supported top-level runtime virtualization now uses a Bakery-side rebalance/migration plan that can promote child sites and direct circuits across queue roots while preserving the logical hierarchy for reporting. + Recent TreeGuard activity is available in two places: - The WebUI TreeGuard status/activity views. diff --git a/docs/v2.0/troubleshooting.md b/docs/v2.0/troubleshooting.md index af4b142e..f35ea2d2 100644 --- a/docs/v2.0/troubleshooting.md +++ b/docs/v2.0/troubleshooting.md @@ -48,13 +48,16 @@ And include: ### User password not working -Delete the lqusers file: -``` -sudo rm /opt/libreqos/src/lqusers.toml -sudo systemctl restart lqosd lqos_scheduler +Current builds will: +- migrate older auth files automatically +- redirect `/login.html` to `/first-run.html` when no users exist + +If the correct username/password still fails, first restart `lqosd` and try again: +```bash +sudo systemctl restart lqosd ``` -Then visit: BOX_IP:9123/index.html -This will allow you to set up the user again from scratch using the WebUI. + +Only remove `lqusers.toml` if you are intentionally resetting access or if the file is corrupt and cannot be repaired. After removing it, restart `lqosd` and open `BOX_IP:9123/login.html`; the WebUI should redirect you to first-run setup automatically. ### No WebUI at x.x.x.x:9123 @@ -236,7 +239,8 @@ WebUI urgent issues include machine-readable codes. Use them to triage quickly. |---|---|---|---| | `MAPPED_CIRCUIT_LIMIT` | Bakery is enforcing a mapped-circuit limit. | Insight license status, `journalctl -u lqosd` for requested/allowed/dropped counts. | Reduce mapped circuits immediately or update license/limits. | | `TC_U16_OVERFLOW` | Queue/class minor IDs exceeded the Linux tc u16 range on a CPU queue. | `journalctl -u lqos_scheduler -u lqosd`, topology depth/queue distribution. | Increase queue count and/or simplify/rebalance hierarchy (for example with integration strategy or root promotion changes). | -| `TC_QDISC_CAPACITY` | Planned auto-allocated qdiscs exceed the per-interface safe budget before apply. | Estimated per-interface qdisc counts in the urgent issue context, `journalctl -u lqos_scheduler -u lqosd`, `on_a_stick` and `monitor_only` config. | Reduce the planned qdisc load for this run (for example fewer circuits/devices in the test shape) before retrying; do not trust partial apply. | +| `TC_QDISC_CAPACITY` | Planned auto-allocated qdiscs exceed the per-interface safe budget or Bakery's conservative memory-safety preflight before apply. | Estimated per-interface qdisc counts, qdisc-kind breakdown, and memory fields in the urgent issue context, `journalctl -u lqos_scheduler -u lqosd`, `on_a_stick` and `monitor_only` config. | Reduce the planned qdisc load for this run (for example fewer circuits/devices in the test shape) before retrying; do not trust partial apply. | +| `BAKERY_MEMORY_GUARD` | A chunked Bakery full reload was stopped mid-apply because available host memory fell below the safety floor. | `journalctl -u lqosd`, available/total memory in the urgent issue context, and recent Bakery apply progress. | Treat the run as failed, reduce memory pressure or queue footprint, and retry only after the host is stable. | | `XDP_IP_MAPPING_CAPACITY` | Required IP mappings exceed the current XDP kernel map capacity. | `ShapedDevices.csv` row shape, IPv4/IPv6 mix, one-device-vs-many-device assumptions, `journalctl -u lqos_scheduler -u lqosd`. | Reduce required mappings immediately (for example fewer devices or IPv4-only test shape), or raise kernel map capacity in a coordinated change. | | `XDP_IP_MAPPING_APPLY_FAILED` | One or more IP mapping inserts failed during apply. | `journalctl -u lqos_scheduler -u lqosd` for summarized failure examples and counts. | Fix the underlying mapping failure, then rerun; do not trust partial shaping. | diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 63b9d471..4f0d988c 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -40,6 +40,8 @@ from liblqos_python import is_lqosd_alive, clear_ip_mappings, delete_ip_mapping, run_shell_commands_as_sudo, generated_pn_download_mbps, generated_pn_upload_mbps, queues_available_override, \ on_a_stick, get_tree_weights, get_weights, is_network_flat, get_libreqos_directory, enable_insight_topology, \ is_insight_enabled, scheduler_error, xdp_ip_mapping_capacity, \ + plan_top_level_cpu_bins, \ + plan_class_identities, \ fast_queues_fq_codel, \ shaping_cpu_count, \ Bakery @@ -112,6 +114,128 @@ def get_network_json_path(): # Either insight not enabled, or file doesn't exist return os.path.join(base_dir, "network.json") + +def get_planner_state_path(): + return os.path.join(get_libreqos_directory(), "planner_state.json") + + +def _load_json_dict(path): + try: + with open(path, "r") as infile: + data = json.load(infile) + if isinstance(data, dict): + return data + except Exception: + pass + return {} + + +def load_planner_state(state_path=None, planner_module=None): + if state_path is None: + state_path = get_planner_state_path() + if planner_module is not None: + try: + state = planner_module.load_state(state_path) + if isinstance(state, dict): + return state + except Exception: + pass + return _load_json_dict(state_path) + + +def save_planner_state(state, state_path=None, planner_module=None): + if state_path is None: + state_path = get_planner_state_path() + if planner_module is not None: + planner_module.save_state(state_path, state) + return + + parent = os.path.dirname(state_path) + if parent: + os.makedirs(parent, exist_ok=True) + temp_path = state_path + ".tmp" + with open(temp_path, "w") as outfile: + json.dump(state, outfile, indent=2, sort_keys=True) + os.replace(temp_path, state_path) + + +def _parse_int_token(value): + if value is None: + return None + try: + if isinstance(value, int): + return value + token = str(value).strip() + if not token: + return None + if token.lower().startswith("0x"): + return int(token, 16) + return int(token) + except Exception: + return None + + +def planner_circuit_identity_key(circuit): + circuit_id = str(circuit.get("circuitID", "") or "").strip() + if not circuit_id: + raise ValueError("Missing circuitID is unsupported for planner identity") + return circuit_id + + +def load_minor_state_from_queuing_structure(path=None): + if path is None: + path = os.path.join(get_libreqos_directory(), "queuingStructure.json") + data = _load_json_dict(path) + network = data.get("Network") + if not isinstance(network, dict): + return {"sites": {}, "circuits": {}} + + sites = {} + circuits = {} + + def walk(node_map, trail=()): + for node_name, node in sorted(node_map.items()): + if not isinstance(node, dict): + continue + node_path = trail + (node_name,) + site_key = "/".join(node_path) + parent_path = "/".join(trail) + queue = _parse_int_token(node.get("cpuNum")) + class_minor = _parse_int_token(node.get("classMinor")) + class_major = _parse_int_token(node.get("classMajor")) + up_class_major = _parse_int_token(node.get("up_classMajor")) + if queue is not None and class_minor is not None: + sites[site_key] = { + "class_minor": class_minor, + "queue": queue + 1, + "parent_path": parent_path, + "class_major": class_major, + "up_class_major": up_class_major, + } + + if isinstance(node.get("circuits"), list): + for circuit in node.get("circuits", []): + if not isinstance(circuit, dict): + continue + circuit_id = circuit.get("circuitID") + circuit_minor = _parse_int_token(circuit.get("classMinor")) + if queue is None or circuit_id is None or circuit_minor is None: + continue + circuits[str(circuit_id)] = { + "class_minor": circuit_minor, + "queue": queue + 1, + "parent_node": circuit.get("ParentNode", node_name), + "class_major": _parse_int_token(circuit.get("classMajor")), + "up_class_major": _parse_int_token(circuit.get("up_classMajor")), + } + + children = node.get("children") + if isinstance(children, dict): + walk(children, node_path) + + walk(network) + return {"sites": sites, "circuits": circuits} + def calculateR2q(maxRateInMbps): # So we've learned that r2q defaults to 10, and is used to calculate quantum. Quantum is rateInBytes/r2q by # default. This default gives errors at high rates, and tc clamps the quantum to 200000. Setting a high quantum @@ -551,42 +675,11 @@ def loadSubscriberCircuits(shapedDevicesFile): counterForCircuitsWithoutParentNodes += 1 subscriberCircuits.append(thisCircuit) circuitsById[circuitID] = thisCircuit - # If there is nothing in the circuit ID field else: - # Copy deviceName to circuitName if none defined already - if circuitName == "": - circuitName = deviceName - if ParentNode == "": - ParentNode = "none" - #ParentNode = ParentNode.strip() - deviceListForCircuit = [] - thisDevice = { - "deviceID": deviceID, - "deviceName": deviceName, - "mac": mac, - "ipv4s": ipv4_subnets_and_hosts, - "ipv6s": ipv6_subnets_and_hosts, - } - deviceListForCircuit.append(thisDevice) - thisCircuit = { - "circuitID": circuitID, - "circuitName": circuitName, - "ParentNode": ParentNode, - "devices": deviceListForCircuit, - "minDownload": float(downloadMin), - "minUpload": float(uploadMin), - "maxDownload": float(downloadMax), - "maxUpload": float(uploadMax), - "classid": '', - "comment": comment - } - if sqm_override_token != '': - thisCircuit['sqm'] = sqm_override_token - if thisCircuit['ParentNode'] == 'none': - thisCircuit['idForCircuitsWithoutParentNodes'] = counterForCircuitsWithoutParentNodes - dictForCircuitsWithoutParentNodes[counterForCircuitsWithoutParentNodes] = ((float(downloadMax))+(float(uploadMax))) - counterForCircuitsWithoutParentNodes += 1 - subscriberCircuits.append(thisCircuit) + raise ValueError( + "Missing circuitID is unsupported in ShapedDevices.csv " + f"(deviceID={deviceID}, deviceName={deviceName}, parent={ParentNode})" + ) return (subscriberCircuits, dictForCircuitsWithoutParentNodes) def refreshShapers(): @@ -834,10 +927,10 @@ def refreshShapers(): except ImportError: bin_planner = None # Store planner state directly in lqos_directory (no hidden subdirs) - state_path = os.path.join(get_libreqos_directory(), "planner_state.json") + state_path = get_planner_state_path() state = {} if bin_planner is not None: - state = bin_planner.load_state(state_path) + state = load_planner_state(state_path, bin_planner) now_ts = time.time() prev_assign = {} last_change_ts = {} @@ -903,7 +996,7 @@ def refreshShapers(): state["assignments"][iid] = b try: print(f"Saving planner state to {state_path} (generated PNs)") - bin_planner.save_state(state_path, state) + save_planner_state(state, state_path, bin_planner) except Exception as e: warnings.warn(f"Failed to save planner state at {state_path}: {e}", stacklevel=2) @@ -1058,26 +1151,34 @@ def refreshShapers(): print("Parsing network structure and tallying devices") parentNodes = [] minorByCPUpreloaded = {} - knownClassIDs = [] nodes_requiring_min_squashing = {} - # Persisted circuit minor assignments for stability across reloads - circuit_state_from_disk = {} - circuit_state_updated = {} - used_minors_by_queue = {cpu + 1: set() for cpu in range(queuesAvailable)} # Track minor counter by CPU. This way we can have > 32000 hosts (htb has u16 limit to minor handle) # Minor numbers start at 3 to reserve 1 for root qdisc and 2 for default class # With CIRCUIT_PADDING, we leave gaps between nodes to allow future circuit additions # without disrupting existing ClassID assignments. This maintains stability across reloads. for x in range(queuesAvailable): minorByCPUpreloaded[x+1] = 3 - def traverseNetwork(data, depth, major, minorByCPU, queue, parentClassID, upParentClassID, parentMaxDL, parentMaxUL, parentMinDL, parentMinUL): - # ClassID Assignment Strategy: - # - Nodes and circuits are processed in alphabetical order for stability - # - Each node gets a unique minor number that increments sequentially - # - After processing all circuits for a node, we add CIRCUIT_PADDING to the minor counter - # - This creates gaps that allow adding new circuits without affecting other ClassIDs - # - Children are also sorted before recursive processing to ensure deterministic traversal - # For top-level binpacked keys (CpueQueueN), enforce numeric ordering of N + def report_minor_overflow(queue, minor): + msg = f"Minor class ID overflow on CPU {queue}: {minor} exceeds TC's u16 limit (65535). Consider increasing queue count or restructuring network hierarchy." + logging.error(msg) + try: + ctx = json.dumps({"cpu": queue, "minor": minor}) + submit_urgent_issue("LibreQoS", "Error", "TC_U16_OVERFLOW", msg, ctx, f"TC_U16_OVERFLOW_CPU_{queue}") + except Exception: + pass + raise ValueError(msg) + + def ensure_minor_capacity(queue, minor): + if minor > 0xFFFF: + report_minor_overflow(queue, minor) + + def next_free_minor(start_minor, reserved): + candidate = max(3, start_minor) + while candidate in reserved: + candidate += 1 + return candidate + + def sorted_node_keys(data, depth): keys = list(data.keys()) if depth == 0 and len(keys) > 0 and all(k.startswith("CpueQueue") for k in keys): try: @@ -1086,227 +1187,7 @@ def refreshShapers(): keys = sorted(keys) else: keys = sorted(keys) - for node in keys: - #if data[node]['type'] == "virtual": - # print(node + " is a virtual node. Skipping.") - # if depth == 0: - # parentClassID = hex(major) + ':' - # upParentClassID = hex(major+stickOffset) + ':' - # data[node]['parentClassID'] = parentClassID - # data[node]['up_parentClassID'] = upParentClassID - # data[node]['classMajor'] = hex(major) - # data[node]['up_classMajor'] = hex(major + stickOffset) - # data[node]['classMinor'] = hex(minorByCPU[queue]) - # data[node]['cpuNum'] = hex(queue-1) - # data[node]['up_cpuNum'] = hex(queue-1+stickOffset) - # traverseNetwork(data[node]['children'], depth, major, minorByCPU, queue, parentClassID, upParentClassID, parentMaxDL, parentMaxUL) - # continue - circuitsForThisNetworkNode = [] - nodeClassID = hex(major) + ':' + hex(minorByCPU[queue]) - upNodeClassID = hex(major+stickOffset) + ':' + hex(minorByCPU[queue]) - data[node]['classid'] = nodeClassID - data[node]['up_classid'] = upNodeClassID - if depth == 0: - parentClassID = hex(major) + ':' - upParentClassID = hex(major+stickOffset) + ':' - data[node]['parentClassID'] = parentClassID - data[node]['up_parentClassID'] = upParentClassID - # If in monitorOnlyMode, override bandwidth rates to where no shaping will actually occur - if monitor_mode_only() == True: - data[node]['downloadBandwidthMbps'] = 100000 - data[node]['uploadBandwidthMbps'] = 100000 - data[node]['downloadBandwidthMbpsMin'] = 100000 - data[node]['uploadBandwidthMbpsMin'] = 100000 - # If not in monitorOnlyMode - else: - # Cap based on this node's max bandwidth, or parent node's max bandwidth, whichever is lower - data[node]['downloadBandwidthMbps'] = min(data[node]['downloadBandwidthMbps'],parentMaxDL) - data[node]['uploadBandwidthMbps'] = min(data[node]['uploadBandwidthMbps'],parentMaxUL) - data[node]['downloadBandwidthMbpsMin'] = min(data[node]['downloadBandwidthMbpsMin'], data[node]['downloadBandwidthMbps'], parentMinDL) - data[node]['uploadBandwidthMbpsMin'] = min(data[node]['uploadBandwidthMbpsMin'], data[node]['uploadBandwidthMbps'], parentMinUL) - # Calculations are done in findBandwidthMins() to determine optimal HTB rates (mins) and ceils (maxs) - data[node]['classMajor'] = hex(major) - data[node]['up_classMajor'] = hex(major + stickOffset) - data[node]['classMinor'] = hex(minorByCPU[queue]) - data[node]['cpuNum'] = hex(queue-1) - data[node]['up_cpuNum'] = hex(queue-1+stickOffset) - used_minors_by_queue.setdefault(queue, set()).add(minorByCPU[queue]) - thisParentNode = { - "parentNodeName": node, - "classID": nodeClassID, - "maxDownload": data[node]['downloadBandwidthMbps'], - "maxUpload": data[node]['uploadBandwidthMbps'], - } - parentNodes.append(thisParentNode) - minorByCPU[queue] = minorByCPU[queue] + 1 - # Check for overflow - TC uses u16 for minor class ID (max 65535) - if minorByCPU[queue] > 0xFFFF: - msg = f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds TC's u16 limit (65535). Consider increasing queue count or restructuring network hierarchy." - logging.error(msg) - try: - ctx = json.dumps({"cpu": queue, "minor": minorByCPU[queue]}) - submit_urgent_issue("LibreQoS", "Error", "TC_U16_OVERFLOW", msg, ctx, f"TC_U16_OVERFLOW_CPU_{queue}") - except Exception: - pass - raise ValueError(f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds limit of 65535") - # If a device from ShapedDevices.csv lists this node as its Parent Node, attach it as a leaf to this node HTB - if node in circuits_by_parent_node: - # If mins of circuits combined exceed min of parent node - set to 1 - override_min_down = None - override_min_up = None - if monitor_mode_only() == False: - if (circuit_min_down_combined_by_parent_node[node] > data[node]['downloadBandwidthMbpsMin']) or (circuit_min_up_combined_by_parent_node[node] > data[node]['uploadBandwidthMbpsMin']): - override_min_down = 1 - override_min_up = 1 - logging.info("The combined minimums of circuits in Parent Node [" + node + "] exceeded that of the parent node. Reducing these circuits' minimums to 1 now.", stacklevel=2) - if ((override_min_down * len(circuits_by_parent_node[node])) > data[node]['downloadBandwidthMbpsMin']) or ((override_min_up * len(circuits_by_parent_node[node])) > data[node]['uploadBandwidthMbpsMin']): - logging.info("Even with this change, minimums will exceed the min rate of the parent node. Using 10 kbps as the minimum for these circuits instead.", stacklevel=2) - nodes_requiring_min_squashing[node] = True - # Sort circuits by name for stable ordering - sorted_circuits = sorted(circuits_by_parent_node[node], - key=lambda c: c.get('circuitName', c.get('circuitID', ''))) - for circuit in sorted_circuits: - if node == circuit['ParentNode']: - if monitor_mode_only() == False: - if circuit['maxDownload'] > data[node]['downloadBandwidthMbps']: - logging.info("downloadMax of Circuit ID [" + circuit['circuitID'] + "] exceeded that of its parent node. Reducing to that of its parent node now.", stacklevel=2) - if circuit['maxUpload'] > data[node]['uploadBandwidthMbps']: - logging.info("uploadMax of Circuit ID [" + circuit['circuitID'] + "] exceeded that of its parent node. Reducing to that of its parent node now.", stacklevel=2) - parentString = hex(major) + ':' - # Attempt to reuse a stored minor for stability (only if parent/bin unchanged and not colliding) - reuse_minor = None - try: - circuit_id_str = str(circuit.get('circuitID')) - stored_entry = circuit_state_from_disk.get(circuit_id_str, {}) if isinstance(circuit_state_from_disk, dict) else {} - stored_minor = stored_entry.get("class_minor") - stored_queue = stored_entry.get("queue") - stored_parent = stored_entry.get("parent_node") - if stored_minor is not None and stored_queue is not None and stored_parent is not None: - try: - stored_minor = int(stored_minor) - except Exception: - stored_minor = None - try: - stored_queue = int(stored_queue) - except Exception: - stored_queue = None - if stored_minor is not None and stored_queue == queue and stored_parent == circuit['ParentNode']: - if stored_minor not in used_minors_by_queue.setdefault(queue, set()): - reuse_minor = stored_minor - except Exception: - pass - - candidate_minor = reuse_minor if reuse_minor is not None else minorByCPU[queue] - reserved = used_minors_by_queue.setdefault(queue, set()) - while candidate_minor in reserved: - candidate_minor += 1 - - flowIDstring = hex(major) + ':' + hex(candidate_minor) - upFlowIDstring = hex(major + stickOffset) + ':' + hex(candidate_minor) - circuit['classid'] = flowIDstring - circuit['up_classid'] = upFlowIDstring - logging.info("Added up_classid to circuit: " + circuit['up_classid']) - # Create circuit dictionary to be added to network structure, eventually output as queuingStructure.json - maxDownload = min(circuit['maxDownload'],data[node]['downloadBandwidthMbps']) - maxUpload = min(circuit['maxUpload'],data[node]['uploadBandwidthMbps']) - if override_min_down: - circuit['minDownload'] = 1 - if override_min_up: - circuit['minUpload'] = 1 - minDownload = min(circuit['minDownload'],maxDownload) - minUpload = min(circuit['minUpload'],maxUpload) - thisNewCircuitItemForNetwork = { - 'maxDownload' : maxDownload, - 'maxUpload' : maxUpload, - 'minDownload' : minDownload, - 'minUpload' : minUpload, - "circuitID": circuit['circuitID'], - "circuitName": circuit['circuitName'], - "ParentNode": circuit['ParentNode'], - "logicalParentNode": circuit.get('logicalParentNode', circuit['ParentNode']), - "devices": circuit['devices'], - "classid": flowIDstring, - "up_classid" : upFlowIDstring, - "classMajor": hex(major), - "up_classMajor" : hex(major + stickOffset), - "classMinor": hex(candidate_minor), - "comment": circuit['comment'] - } - # Attach the planner weight used by the planner/UI summary - # Priority: explicit weight -> fallback to maxDownload - try: - cid = str(circuit.get('circuitID','')) - w = None - if cid in weight_by_circuit_id: - w = float(weight_by_circuit_id[cid]) - if w is None: - w = float(maxDownload) - # Treat 1000 as a sentinel default from Insight; use maxDownload instead - if abs(w - 1000.0) < 1e-6: - w = float(maxDownload) - # If the circuit's configured rate equals the generated PN default, - # ignore it for weight purposes. - try: - default_rate = float(generated_pn_download_mbps()) - if abs(float(maxDownload) - default_rate) < 1e-6: - w = 0.0 - except Exception: - pass - thisNewCircuitItemForNetwork['planner_weight'] = w - except Exception: - pass - # Preserve optional per-circuit SQM override for downstream bakery call - if 'sqm' in circuit and circuit['sqm']: - thisNewCircuitItemForNetwork['sqm'] = circuit['sqm'] - # Generate TC commands to be executed later - thisNewCircuitItemForNetwork['devices'] = circuit['devices'] - circuitsForThisNetworkNode.append(thisNewCircuitItemForNetwork) - reserved.add(candidate_minor) - minorByCPU[queue] = max(minorByCPU[queue], candidate_minor) + 1 - try: - # Record the assigned minor for future stability - circuit_state_updated[str(circuit.get('circuitID'))] = { - "class_minor": candidate_minor, - "queue": queue, - "parent_node": circuit['ParentNode'], - "class_major": major, - "up_class_major": major + stickOffset, - } - except Exception: - pass - if len(circuitsForThisNetworkNode) > 0: - data[node]['circuits'] = circuitsForThisNetworkNode - - # Add padding for future circuit additions (applies to all nodes) - # This ensures space is reserved even for nodes without circuits - minorByCPU[queue] = minorByCPU[queue] + CIRCUIT_PADDING - - # Recursive call this function for children nodes attached to this node - if 'children' in data[node]: - # Sort children to ensure consistent traversal order - sorted_children = dict(sorted(data[node]['children'].items())) - # We need to keep tabs on the minor counter, because we can't have repeating class IDs. Here, we bring back the minor counter from the recursive function - minorByCPU[queue] = minorByCPU[queue] + 1 - # Check for overflow - TC uses u16 for minor class ID (max 65535) - if minorByCPU[queue] > 0xFFFF: - msg = f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds TC's u16 limit (65535). Consider increasing queue count or restructuring network hierarchy." - logging.error(msg) - try: - ctx = json.dumps({"cpu": queue, "minor": minorByCPU[queue]}) - submit_urgent_issue("LibreQoS", "Error", "TC_U16_OVERFLOW", msg, ctx, f"TC_U16_OVERFLOW_CPU_{queue}") - except Exception: - pass - raise ValueError(f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds limit of 65535") - minorByCPU = traverseNetwork(sorted_children, depth+1, major, minorByCPU, queue, nodeClassID, upNodeClassID, data[node]['downloadBandwidthMbps'], data[node]['uploadBandwidthMbps'], data[node]['downloadBandwidthMbpsMin'], data[node]['uploadBandwidthMbpsMin']) - # If top level node, increment to next queue / cpu core - if depth == 0: - if queue >= queuesAvailable: - queue = 1 - major = queue - else: - queue += 1 - major += 1 - return minorByCPU + return keys # If we're in binpacking mode, we need to sort the network structure a bit if use_bin_packing_to_balance_cpu() and not is_network_flat(): @@ -1345,16 +1226,6 @@ def refreshShapers(): except Exception: pass - def round_robin_assign(items_list, bins): - if not bins: - return {}, [] - names = [str(it["id"]) for it in items_list] - names.sort() - assignment_local = {} - for idx, name in enumerate(names): - assignment_local[name] = bins[idx % len(bins)] - return assignment_local, list(assignment_local.keys()) - for node in network: w = weight_by_name.get(str(node), 1.0) try: @@ -1367,134 +1238,66 @@ def refreshShapers(): w = 1.0 items.append({"id": str(node), "weight": w}) - def greedy_assign(items_list, bins): - bin_loads = {key: 0.0 for key in bins} - pairs = [(str(it["id"]), float(it["weight"])) for it in items_list] - pairs.sort(key=lambda nw: (-nw[1], nw[0])) - assignment_local = {} - for name, wgt in pairs: - target = min(bin_loads.items(), key=lambda kv: (kv[1], kv[0]))[0] - assignment_local[name] = target - bin_loads[target] += wgt - return assignment_local, list(assignment_local.keys()) - - # Prepare bins and capacities cpu_keys = ["CpueQueue" + str(cpu) for cpu in range(queuesAvailable)] - bins_list = [{"id": key} for key in cpu_keys] - capacities = {key: 1.0 for key in cpu_keys} - valid_bins = set(capacities.keys()) + valid_bins = set(cpu_keys) planner_used = False - state_path = os.path.join(get_libreqos_directory(), "planner_state.json") + state_path = get_planner_state_path() state = {} now_ts = time.time() assignment = {} changed = [] - bin_planner = None - - # Load planner state and generate assignments when Insight is enabled/licensed - if insight_enabled: - try: - import bin_planner as bin_planner # type: ignore - except ImportError: - bin_planner = None + try: + state = load_planner_state(state_path, None) + except Exception: + state = {} - if bin_planner is not None: - try: - state = bin_planner.load_state(state_path) - except Exception: - state = {} - prev_assign = {} - last_change_ts = {} - if isinstance(state, dict): - prev_assign = state.get("assignments", {}) or {} - last_change_ts = state.get("last_change_ts", {}) or {} - item_ids = {str(it["id"]) for it in items} - prev_assign = { - iid: b for iid, b in prev_assign.items() if iid in item_ids and b in valid_bins - } - last_change_ts = {iid: last_change_ts.get(iid, 0.0) for iid in item_ids} - - params = { - "candidate_set_size": 4, - "headroom": 0.05, - "alpha": 0.1, - "hysteresis_threshold": 0.03, - "cooldown_seconds": 3600, - "move_budget_per_run": max(1, min(32, int(0.01 * max(1, len(items))))), - "salt": state.get("salt", "default_salt") if isinstance(state, dict) else "default_salt", - "last_change_ts_by_item": last_change_ts, - } - if monitor_mode_only() == True: - params["move_budget_per_run"] = 0 + prev_assign = {} + last_change_ts = {} + if isinstance(state, dict): + prev_assign = state.get("assignments", {}) or {} + last_change_ts = state.get("last_change_ts", {}) or {} + item_ids = {str(it["id"]) for it in items} + prev_assign = { + iid: b for iid, b in prev_assign.items() if iid in item_ids and b in valid_bins + } + last_change_ts = {iid: last_change_ts.get(iid, 0.0) for iid in item_ids} - try: - assignment, changed = bin_planner.plan_assignments( - items, bins_list, capacities, prev_assign, now_ts, params - ) - planner_used = True - except Exception as e: - warnings.warn( - f"Planner failed ({e}); falling back to greedy distribution.", - stacklevel=2, - ) - assignment, changed = greedy_assign(items, cpu_keys) - planner_used = False - else: - warnings.warn( - "Binpacking requested, but planner module is unavailable; using greedy distribution.", - stacklevel=2, - ) - assignment, changed = greedy_assign(items, cpu_keys) - planner_used = False - else: - # Insight is unavailable; use deterministic round-robin distribution. - assignment, changed = round_robin_assign(items, cpu_keys) - planner_used = False + move_budget = max(1, min(32, int(0.01 * max(1, len(items))))) + if monitor_mode_only() == True: + move_budget = 0 - # Validate assignment covers all items and uses known bins (planner may return partial results) + planner_mode = "stable_greedy" if insight_enabled else "round_robin" try: - if not isinstance(assignment, dict): - assignment, changed = greedy_assign(items, cpu_keys) - except Exception: - assignment, changed = greedy_assign(items, cpu_keys) - try: - item_ids = {str(it["id"]) for it in items} - rr_fallback, _ = round_robin_assign(items, cpu_keys) - for iid in item_ids: - tgt = assignment.get(iid) - if tgt not in valid_bins: - assignment[iid] = rr_fallback.get( - iid, cpu_keys[-1] if cpu_keys else "CpueQueue0" - ) - except Exception: - pass - - # Sanity check: if planner returns a degenerate assignment (everything in one bin), - # fall back to a simple greedy distribution so the physical tree can spread. - if planner_used: - try: - # Exclude Generated_PN_* placeholders from the degeneracy test: they may not - # appear in the UI tree and can mask a collapsed real topology. - interesting_ids = { - str(it["id"]) - for it in items - if not str(it["id"]).startswith("Generated_PN_") - } - used = { - tgt - for iid, tgt in assignment.items() - if iid in interesting_ids and tgt in valid_bins - } - if queuesAvailable > 1 and len(interesting_ids) > 1 and len(used) <= 1: - warnings.warn( - "Planner produced degenerate CPU binning (single-bin result); falling back to greedy distribution.", - stacklevel=2, - ) - assignment, changed = greedy_assign(items, cpu_keys) - planner_used = False - except Exception: - pass + plan_result = plan_top_level_cpu_bins( + items, + queuesAvailable, + prev_assign=prev_assign, + last_change_ts=last_change_ts, + now_ts=now_ts, + mode=planner_mode, + move_budget_per_run=move_budget, + cooldown_seconds=3600.0, + hysteresis_threshold=0.03, + ) + assignment = dict(plan_result.get("assignment", {}) or {}) + changed = list(plan_result.get("changed", []) or []) + planner_used = bool(plan_result.get("planner_used", False)) + except Exception as e: + warnings.warn( + f"Shared Rust planner failed ({e}); falling back to deterministic local assignment.", + stacklevel=2, + ) + assignment = {} + names = sorted(str(it["id"]) for it in items) + if cpu_keys: + for idx, name in enumerate(names): + if insight_enabled: + assignment[name] = cpu_keys[idx % len(cpu_keys)] + else: + assignment[name] = cpu_keys[idx % len(cpu_keys)] + changed = list(assignment.keys()) + planner_used = False for x in range(queuesAvailable): key = "CpueQueue" + str(x) @@ -1522,7 +1325,7 @@ def refreshShapers(): network = binnedNetwork # Update and save state - if planner_used and bin_planner is not None and isinstance(state, dict): + if planner_used and isinstance(state, dict): if state.get("salt") is None: state["salt"] = "default_salt" if "assignments" not in state or not isinstance(state["assignments"], dict): @@ -1535,54 +1338,306 @@ def refreshShapers(): state["assignments"][iid] = b try: print(f"Saving planner state to {state_path} (top-level CPU binning)") - bin_planner.save_state(state_path, state) + save_planner_state(state, state_path, None) except Exception as e: warnings.warn( f"Failed to save planner state at {state_path}: {e}", stacklevel=2 ) - # Seed persisted circuit minor assignments (TTL already enforced in bin_planner.load_state()). + # Seed persisted site/circuit minor assignments. When planner state is absent, + # fall back to the previous queuing structure so the first run after an upgrade + # can preserve existing class IDs. try: state # noqa: B018 except NameError: state = {} - try: - import bin_planner # noqa: F401 - except ImportError: - bin_planner = None - if bin_planner is not None and (not isinstance(state, dict) or len(state.keys()) == 0): - try: - state_path = os.path.join(get_libreqos_directory(), "planner_state.json") - state = bin_planner.load_state(state_path) - except Exception: - state = {} + state_path = get_planner_state_path() + if not isinstance(state, dict) or len(state.keys()) == 0: + state = load_planner_state(state_path, None) try: circuit_state_from_disk = state.get("circuits", {}) if isinstance(state, dict) else {} except Exception: circuit_state_from_disk = {} + try: + site_state_from_disk = state.get("sites", {}) if isinstance(state, dict) else {} + except Exception: + site_state_from_disk = {} + if not isinstance(circuit_state_from_disk, dict): + circuit_state_from_disk = {} + if not isinstance(site_state_from_disk, dict): + site_state_from_disk = {} + if not circuit_state_from_disk or not site_state_from_disk: + fallback_minor_state = load_minor_state_from_queuing_structure() + if not site_state_from_disk: + site_state_from_disk = fallback_minor_state.get("sites", {}) or {} + if not circuit_state_from_disk: + circuit_state_from_disk = fallback_minor_state.get("circuits", {}) or {} circuit_state_updated = {} - used_minors_by_queue = {cpu + 1: set() for cpu in range(queuesAvailable)} - - # Here is the actual call to the recursive traverseNetwork() function. finalMinor is not used. - minorByCPU = traverseNetwork(network, 0, major=1, minorByCPU=minorByCPUpreloaded, queue=1, parentClassID=None, upParentClassID=None, parentMaxDL=upstream_bandwidth_capacity_download_mbps(), parentMaxUL=upstream_bandwidth_capacity_upload_mbps(), parentMinDL=upstream_bandwidth_capacity_download_mbps(), parentMinUL=upstream_bandwidth_capacity_upload_mbps()) - - # Persist the updated circuit minor map for future stability - if 'bin_planner' not in locals(): - bin_planner = None - if bin_planner is not None and isinstance(state, dict): - if 'circuits' not in state or not isinstance(state.get('circuits'), dict): - state['circuits'] = {} - state['circuits'] = circuit_state_updated - try: - state_path = os.path.join(get_libreqos_directory(), "planner_state.json") - except Exception: - state_path = None - if state_path: - try: - print(f"Saving planner state to {state_path} (circuit minors)") - bin_planner.save_state(state_path, state) - except Exception as e: - warnings.warn(f"Failed to save planner circuit state at {state_path}: {e}", stacklevel=2) + site_state_updated = {} + planner_site_inputs = [] + planner_circuit_groups = [] + + def collect_identity_planner_inputs(data, depth, queue, path=()): + for node in sorted_node_keys(data, depth): + current_queue = queue + node_path = path + (node,) + parent_path = '/'.join(path) + has_children = bool(data[node].get('children')) + planner_site_inputs.append( + { + "site_key": '/'.join(node_path), + "parent_path": parent_path, + "queue": current_queue, + "has_children": has_children, + } + ) + if node in circuits_by_parent_node: + sorted_circuits = sorted( + circuits_by_parent_node[node], + key=lambda c: c.get('circuitName', c.get('circuitID', '')), + ) + planner_circuit_groups.append( + { + "parent_node": node, + "queue": current_queue, + "circuit_ids": [ + planner_circuit_identity_key(circuit) + for circuit in sorted_circuits + if node == circuit['ParentNode'] + ], + } + ) + + if has_children: + sorted_children = dict(sorted(data[node]['children'].items())) + collect_identity_planner_inputs( + sorted_children, + depth + 1, + current_queue, + node_path, + ) + + if depth == 0: + if queue >= queuesAvailable: + queue = 1 + else: + queue += 1 + + collect_identity_planner_inputs(network, 0, 1) + + identity_plan = plan_class_identities( + planner_site_inputs, + planner_circuit_groups, + site_state=site_state_from_disk, + circuit_state=circuit_state_from_disk, + stick_offset=stickOffset, + circuit_padding=CIRCUIT_PADDING, + ) + site_assignment_by_key = { + entry["site_key"]: entry for entry in identity_plan.get("sites", []) + } + circuit_assignment_by_key = { + entry["circuit_id"]: entry for entry in identity_plan.get("circuits", []) + } + site_state_updated = identity_plan.get("site_state", {}) or {} + circuit_state_updated = identity_plan.get("circuit_state", {}) or {} + + def apply_site_assignments(data, depth, queue, parentClassID, upParentClassID, parentMaxDL, parentMaxUL, parentMinDL, parentMinUL, path=()): + for node in sorted_node_keys(data, depth): + current_queue = queue + node_path = path + (node,) + site_key = '/'.join(node_path) + assignment = site_assignment_by_key.get(site_key) + if assignment is None: + raise ValueError(f"Missing planned site identity for {site_key}") + assigned_site_minor = int(assignment["class_minor"]) + major = int(assignment["class_major"]) + up_major = int(assignment["up_class_major"]) + ensure_minor_capacity(current_queue, assigned_site_minor) + nodeClassID = hex(major) + ':' + hex(assigned_site_minor) + upNodeClassID = hex(up_major) + ':' + hex(assigned_site_minor) + data[node]['classid'] = nodeClassID + data[node]['up_classid'] = upNodeClassID + current_parent_classid = parentClassID + current_up_parent_classid = upParentClassID + if depth == 0: + current_parent_classid = hex(major) + ':' + current_up_parent_classid = hex(up_major) + ':' + data[node]['parentClassID'] = current_parent_classid + data[node]['up_parentClassID'] = current_up_parent_classid + if monitor_mode_only() == True: + data[node]['downloadBandwidthMbps'] = 100000 + data[node]['uploadBandwidthMbps'] = 100000 + data[node]['downloadBandwidthMbpsMin'] = 100000 + data[node]['uploadBandwidthMbpsMin'] = 100000 + else: + data[node]['downloadBandwidthMbps'] = min(data[node]['downloadBandwidthMbps'], parentMaxDL) + data[node]['uploadBandwidthMbps'] = min(data[node]['uploadBandwidthMbps'], parentMaxUL) + data[node]['downloadBandwidthMbpsMin'] = min(data[node]['downloadBandwidthMbpsMin'], data[node]['downloadBandwidthMbps'], parentMinDL) + data[node]['uploadBandwidthMbpsMin'] = min(data[node]['uploadBandwidthMbpsMin'], data[node]['uploadBandwidthMbps'], parentMinUL) + data[node]['classMajor'] = hex(major) + data[node]['up_classMajor'] = hex(up_major) + data[node]['classMinor'] = hex(assigned_site_minor) + data[node]['cpuNum'] = hex(current_queue-1) + data[node]['up_cpuNum'] = hex(current_queue-1+stickOffset) + parentNodes.append( + { + "parentNodeName": node, + "classID": nodeClassID, + "maxDownload": data[node]['downloadBandwidthMbps'], + "maxUpload": data[node]['uploadBandwidthMbps'], + } + ) + + if 'children' in data[node]: + sorted_children = dict(sorted(data[node]['children'].items())) + apply_site_assignments( + sorted_children, + depth+1, + current_queue, + nodeClassID, + upNodeClassID, + data[node]['downloadBandwidthMbps'], + data[node]['uploadBandwidthMbps'], + data[node]['downloadBandwidthMbpsMin'], + data[node]['uploadBandwidthMbpsMin'], + node_path, + ) + + if depth == 0: + if queue >= queuesAvailable: + queue = 1 + else: + queue += 1 + + apply_site_assignments( + network, + 0, + queue=1, + parentClassID=None, + upParentClassID=None, + parentMaxDL=upstream_bandwidth_capacity_download_mbps(), + parentMaxUL=upstream_bandwidth_capacity_upload_mbps(), + parentMinDL=upstream_bandwidth_capacity_download_mbps(), + parentMinUL=upstream_bandwidth_capacity_upload_mbps(), + ) + + def attach_circuits(data, depth, path=()): + for node in sorted_node_keys(data, depth): + node_data = data[node] + queue_token = _parse_int_token(node_data.get('cpuNum')) + major = _parse_int_token(node_data.get('classMajor')) + if queue_token is None or major is None: + continue + queue = queue_token + 1 + circuitsForThisNetworkNode = [] + if node in circuits_by_parent_node: + override_min_down = None + override_min_up = None + if monitor_mode_only() == False: + if (circuit_min_down_combined_by_parent_node[node] > node_data['downloadBandwidthMbpsMin']) or (circuit_min_up_combined_by_parent_node[node] > node_data['uploadBandwidthMbpsMin']): + override_min_down = 1 + override_min_up = 1 + logging.info("The combined minimums of circuits in Parent Node [" + node + "] exceeded that of the parent node. Reducing these circuits' minimums to 1 now.", stacklevel=2) + if ((override_min_down * len(circuits_by_parent_node[node])) > node_data['downloadBandwidthMbpsMin']) or ((override_min_up * len(circuits_by_parent_node[node])) > node_data['uploadBandwidthMbpsMin']): + logging.info("Even with this change, minimums will exceed the min rate of the parent node. Using 10 kbps as the minimum for these circuits instead.", stacklevel=2) + nodes_requiring_min_squashing[node] = True + sorted_circuits = sorted(circuits_by_parent_node[node], key=lambda c: c.get('circuitName', c.get('circuitID', ''))) + for circuit in sorted_circuits: + if node != circuit['ParentNode']: + continue + if monitor_mode_only() == False: + if circuit['maxDownload'] > node_data['downloadBandwidthMbps']: + logging.info("downloadMax of Circuit ID [" + circuit['circuitID'] + "] exceeded that of its parent node. Reducing to that of its parent node now.", stacklevel=2) + if circuit['maxUpload'] > node_data['uploadBandwidthMbps']: + logging.info("uploadMax of Circuit ID [" + circuit['circuitID'] + "] exceeded that of its parent node. Reducing to that of its parent node now.", stacklevel=2) + planner_key = planner_circuit_identity_key(circuit) + planned_identity = circuit_assignment_by_key.get(planner_key) + if planned_identity is None: + raise ValueError(f"Missing planned circuit identity for {planner_key}") + candidate_minor = int(planned_identity["class_minor"]) + major = int(planned_identity["class_major"]) + up_major = int(planned_identity["up_class_major"]) + ensure_minor_capacity(queue, candidate_minor) + flowIDstring = hex(major) + ':' + hex(candidate_minor) + upFlowIDstring = hex(up_major) + ':' + hex(candidate_minor) + circuit['classid'] = flowIDstring + circuit['up_classid'] = upFlowIDstring + logging.info("Added up_classid to circuit: " + circuit['up_classid']) + maxDownload = min(circuit['maxDownload'], node_data['downloadBandwidthMbps']) + maxUpload = min(circuit['maxUpload'], node_data['uploadBandwidthMbps']) + if override_min_down: + circuit['minDownload'] = 1 + if override_min_up: + circuit['minUpload'] = 1 + minDownload = min(circuit['minDownload'], maxDownload) + minUpload = min(circuit['minUpload'], maxUpload) + thisNewCircuitItemForNetwork = { + 'maxDownload': maxDownload, + 'maxUpload': maxUpload, + 'minDownload': minDownload, + 'minUpload': minUpload, + "circuitID": circuit['circuitID'], + "circuitName": circuit['circuitName'], + "ParentNode": circuit['ParentNode'], + "logicalParentNode": circuit.get('logicalParentNode', circuit['ParentNode']), + "devices": circuit['devices'], + "classid": flowIDstring, + "up_classid": upFlowIDstring, + "classMajor": hex(major), + "up_classMajor": hex(up_major), + "classMinor": hex(candidate_minor), + "comment": circuit['comment'], + } + try: + cid = str(circuit.get('circuitID', '')) + w = None + if cid in weight_by_circuit_id: + w = float(weight_by_circuit_id[cid]) + if w is None: + w = float(maxDownload) + if abs(w - 1000.0) < 1e-6: + w = float(maxDownload) + try: + default_rate = float(generated_pn_download_mbps()) + if abs(float(maxDownload) - default_rate) < 1e-6: + w = 0.0 + except Exception: + pass + thisNewCircuitItemForNetwork['planner_weight'] = w + except Exception: + pass + if 'sqm' in circuit and circuit['sqm']: + thisNewCircuitItemForNetwork['sqm'] = circuit['sqm'] + thisNewCircuitItemForNetwork['devices'] = circuit['devices'] + circuitsForThisNetworkNode.append(thisNewCircuitItemForNetwork) + + if len(circuitsForThisNetworkNode) > 0: + node_data['circuits'] = circuitsForThisNetworkNode + else: + node_data.pop('circuits', None) + + if 'children' in node_data: + sorted_children = dict(sorted(node_data['children'].items())) + attach_circuits(sorted_children, depth+1, path + (node,)) + + attach_circuits(network, 0) + minorByCPU = { + int(queue): int(minor) + for queue, minor in (identity_plan.get("last_used_minor_by_queue", {}) or {}).items() + } + for cpu in range(queuesAvailable): + minorByCPU.setdefault(cpu + 1, 3) + + if not isinstance(state, dict): + state = {} + state['circuits'] = circuit_state_updated + state['sites'] = site_state_updated + try: + print(f"Saving planner state to {state_path} (circuit/site minors)") + save_planner_state(state, state_path, None) + except Exception as e: + warnings.warn(f"Failed to save planner circuit state at {state_path}: {e}", stacklevel=2) bakery = Bakery() bakery.start_batch() # Initializes the bakery transaction @@ -1885,23 +1940,20 @@ def refreshShapers(): if not qdiscBudgetEstimate["ok"]: interfaceCounts = qdiscBudgetEstimate["interfaces"] sortedInterfaces = sorted(interfaceCounts.items()) - interfaceSummary = ", ".join( - f"{interface} estimated {count} qdiscs" - for interface, count in sortedInterfaces - ) + preflightSummary = qdiscBudgetEstimate.get("summary") or "" report_refresh_failure( "TC_QDISC_CAPACITY", - "Planned queue model exceeds qdisc budget. " - + interfaceSummary - + "; safe budget " - + str(qdiscBudgetEstimate["safe_budget"]) - + ", kernel limit " - + str(qdiscBudgetEstimate["hard_limit"]) - + ". Aborting refresh before apply.", + (preflightSummary + " Aborting refresh before apply.").strip(), { "interfaces": dict(sortedInterfaces), + "interface_details": qdiscBudgetEstimate.get("interface_details", {}), "safe_budget": qdiscBudgetEstimate["safe_budget"], "hard_limit": qdiscBudgetEstimate["hard_limit"], + "estimated_total_memory_bytes": qdiscBudgetEstimate.get("estimated_total_memory_bytes"), + "memory_ok": qdiscBudgetEstimate.get("memory_ok"), + "memory_guard_min_available_bytes": qdiscBudgetEstimate.get("memory_guard_min_available_bytes"), + "memory_total_bytes": qdiscBudgetEstimate.get("memory_total_bytes"), + "memory_available_bytes": qdiscBudgetEstimate.get("memory_available_bytes"), "on_a_stick": on_a_stick(), "monitor_only": monitor_mode_only(), "shaped_devices_file": shapedDevicesFile, @@ -2184,7 +2236,7 @@ if __name__ == '__main__': if getattr(args, 'planner_reset', False): try: - state_path = os.path.join(get_libreqos_directory(), "planner_state.json") + state_path = get_planner_state_path() if os.path.exists(state_path): os.remove(state_path) print(f"Removed planner state: {state_path}") diff --git a/src/bakery_integration_test.py b/src/bakery_integration_test.py index db8a481d..5c668bbc 100644 --- a/src/bakery_integration_test.py +++ b/src/bakery_integration_test.py @@ -646,6 +646,23 @@ def _hex_to_int(s: str) -> Optional[int]: return None +def _tc_id_token_to_int(tok: str) -> Optional[int]: + """Parse tc class/qdisc ID tokens. + + The live `tc` text output commonly emits bare hex tokens like `10f` rather than + `0x10f`. Treat bare tokens as hex so lookups line up with queuingStructure.json. + """ + s = tok.strip() + if not s: + return None + try: + if s.lower().startswith("0x"): + return int(s, 16) + return int(s, 16) + except Exception: + return None + + def _parse_tc_rate_to_mbps(token: str, unit: Optional[str]) -> float: try: val = float(token) @@ -675,24 +692,11 @@ def _read_htb_rate_ceil_mbps(iface: str, major: int, minor: int) -> Optional[Tup # Match the class line for this major/minor, accepting decimal or hex forms. cls_pat = re.compile(r"^class\s+htb\s+([0-9A-Fa-fx]+):([0-9A-Fa-fx]+)\b.*$", re.MULTILINE) - def _to_int(tok: str) -> Optional[int]: - s = tok.strip() - # Accept decimal, 0x-prefixed hex, or bare hex (e.g. "f") - try: - if s.lower().startswith("0x"): - return int(s, 16) - try: - return int(s) # decimal - except Exception: - return int(s, 16) # bare hex - except Exception: - return None - line = None for m in cls_pat.finditer(out): mj_tok, mn_tok = m.group(1), m.group(2) - mj = _to_int(mj_tok) - mn = _to_int(mn_tok) + mj = _tc_id_token_to_int(mj_tok) + mn = _tc_id_token_to_int(mn_tok) if mj == major and mn == minor: line = m.group(0) break @@ -760,6 +764,65 @@ def check_no_site_circuit_minor_collisions() -> Tuple[bool, List[str]]: return ok, msgs +def snapshot_site_class_assignments() -> Tuple[bool, str, Dict[str, Tuple[str, str, str, str]]]: + """Capture current site class assignment state from queuingStructure.json.""" + qs = _load_queuing_structure() + if not isinstance(qs, dict): + return False, "site snapshot: queuingStructure.json not found", {} + net = qs.get("Network") + if not isinstance(net, dict): + return False, "site snapshot: queuingStructure has no 'Network'", {} + + snapshot: Dict[str, Tuple[str, str, str, str]] = {} + + def walk(node_map: Dict[str, dict], trail: Tuple[str, ...] = ()) -> None: + for name, node in node_map.items(): + if not isinstance(node, dict): + continue + path = "/".join(trail + (name,)) + snapshot[path] = ( + str(node.get("classMinor", "")), + str(node.get("classid", "")), + str(node.get("parentClassID", "")), + str(node.get("cpuNum", "")), + ) + ch = node.get("children") + if isinstance(ch, dict): + walk(ch, trail + (name,)) + + walk(net) + return True, "", snapshot + + +def check_site_class_assignments_unchanged( + before: Dict[str, Tuple[str, str, str, str]] +) -> Tuple[bool, List[str]]: + """Verify that site class assignments did not drift between two snapshots.""" + ok, err, after = snapshot_site_class_assignments() + if not ok: + return False, [err] + + msgs: List[str] = [] + changed = [] + for path in sorted(set(before.keys()) | set(after.keys())): + if before.get(path) != after.get(path): + changed.append((path, before.get(path), after.get(path))) + + if changed: + for path, old_value, new_value in changed[:20]: + msgs.append( + f"site assignment stability: {path} changed {old_value} -> {new_value}" + ) + if len(changed) > 20: + msgs.append( + f"site assignment stability: additional changed sites omitted ({len(changed) - 20})" + ) + return False, msgs + + msgs.append("site assignment stability: all site class assignments unchanged") + return True, msgs + + # ----------------------- # IP mapping checks # ----------------------- @@ -780,8 +843,13 @@ def _list_ip_mappings() -> Tuple[bool, str, List[Tuple[str, int, str]]]: if "Socket" in out or "Socket" in err: return False, "ipmap check: lqosd bus socket not found; skipping", [] entries: List[Tuple[str, int, str]] = [] - # Lines look like: " CPU: TC: " - pat = re.compile(r"^\s*([0-9A-Fa-f:.]+)/\d+\s+CPU:\s+(\d+)\s+TC:\s+([0-9A-Fa-f]+:[0-9A-Fa-f]+)\s*$") + # Lines look like: + # " CPU: TC: " + # or newer output with trailing identity fields: + # " CPU: TC: CIRCUIT: DEVICE: " + pat = re.compile( + r"^\s*([0-9A-Fa-f:.]+)/\d+\s+CPU:\s+(\d+)\s+TC:\s+([0-9A-Fa-f]+:[0-9A-Fa-f]+)(?:\s+.*)?$" + ) for line in out.splitlines(): m = pat.match(line) if m: @@ -1588,24 +1656,11 @@ def run_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bo else: pat = re.compile(r"^qdisc\s+\S+\s+\S+:\s+parent\s+([0-9A-Fa-fx]+):([0-9A-Fa-fx]+)\b.*$", re.MULTILINE) - def _to_int(tok: str) -> Optional[int]: - s = tok.strip() - # Accept decimal, 0x-prefixed hex, or bare hex (e.g. "f") - try: - if s.lower().startswith("0x"): - return int(s, 16) - try: - return int(s) # decimal - except Exception: - return int(s, 16) # bare hex - except Exception: - return None - line = None for m in pat.finditer(out): mj_tok, mn_tok = m.group(1), m.group(2) - mj = _to_int(mj_tok) - mn = _to_int(mn_tok) + mj = _tc_id_token_to_int(mj_tok) + mn = _tc_id_token_to_int(mn_tok) if mj == maj and mn == mnr: line = m.group(0) break @@ -1630,24 +1685,11 @@ def run_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bo else: pat2 = re.compile(r"^qdisc\s+\S+\s+\S+:\s+parent\s+([0-9A-Fa-fx]+):([0-9A-Fa-fx]+)\b.*$", re.MULTILINE) - def _to_int2(tok: str) -> Optional[int]: - s = tok.strip() - # Accept decimal, 0x-prefixed hex, or bare hex (e.g. "f") - try: - if s.lower().startswith("0x"): - return int(s, 16) - try: - return int(s) # decimal - except Exception: - return int(s, 16) # bare hex - except Exception: - return None - line2 = None for m2 in pat2.finditer(out2): mj_tok, mn_tok = m2.group(1), m2.group(2) - mj = _to_int2(mj_tok) - mn = _to_int2(mn_tok) + mj = _tc_id_token_to_int(mj_tok) + mn = _tc_id_token_to_int(mn_tok) if mj == upm and mn == mnr: line2 = m2.group(0) break @@ -1861,9 +1903,42 @@ def run_realistic_tiered_suite(log: LogReader, timeout_s: float, results: List[s results.extend(msgs_map) ok &= passed_map + passed_site_snapshot, site_snapshot_msg, site_snapshot = snapshot_site_class_assignments() + if not passed_site_snapshot: + results.append(site_snapshot_msg) + ok = False + + # Circuit parent-node move between existing nodes (should not trigger full reload) + _mark_step("realistic: circuit parent move") + rows_parent = json.loads(json.dumps(rows2)) + old_parent = str(rows_parent[target_idx]["Parent Node"]) + new_parent = "NET1-1-2" if old_parent != "NET1-1-2" else "NET1-2" + rows_parent[target_idx]["Parent Node"] = new_parent + write_circuits(rows_parent) + step_t0 = time.time() + res = run_refresh_and_wait(log, timeout_s) + passed, msg = assert_no_full_reload("realistic: circuit parent move", res, step_t0) + results.append(msg) + ok &= passed + + _mark_step("realistic: site class assignment stability after parent move") + passed_sites_stable, msgs_sites_stable = check_site_class_assignments_unchanged(site_snapshot) + results.extend(msgs_sites_stable) + ok &= passed_sites_stable + + _mark_step("realistic: parent-moved circuit direction mapping (ceil)") + passed_parent_dir, msgs_parent_dir = check_circuit_direction_ceil(target_id) + results.extend(msgs_parent_dir) + ok &= passed_parent_dir + + _mark_step("realistic: parent-moved circuit ip mappings") + passed_parent_map, msgs_parent_map = check_ip_mappings_for_circuit(target_id) + results.extend(msgs_parent_map) + ok &= passed_parent_map + # Add circuit under a different leaf (NET3-2) _mark_step("realistic: add circuit") - rows3 = json.loads(json.dumps(rows2)) + rows3 = json.loads(json.dumps(rows_parent)) new_circuit_id = "99901" new_circuit_ip = "100.64.200.1" rows3.append({ diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index 398bc331..7ed3500d 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -182,6 +182,18 @@ dependencies = [ "rustversion", ] +[[package]] +name = "argon2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures", + "password-hash", +] + [[package]] name = "async-trait" version = "0.1.89" @@ -207,9 +219,9 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "aws-lc-rs" -version = "1.15.4" +version = "1.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b7b6141e96a8c160799cc2d5adecd5cbbe5054cb8c7c4af53da0f83bb7ad256" +checksum = "a054912289d18629dc78375ba2c3726a3afe3ff71b4edba9dedfca0e3446d1fc" dependencies = [ "aws-lc-sys", "zeroize", @@ -217,9 +229,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.37.0" +version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c34dda4df7017c8db52132f0f8a2e0f8161649d15723ed63fc00c82d0f2081a" +checksum = "1fa7e52a4c5c547c741610a2c6f123f3881e409b714cd27e6798ef020c514f0a" dependencies = [ "cc", "cmake", @@ -315,6 +327,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bincode" version = "1.3.3" @@ -356,6 +374,15 @@ version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -1027,6 +1054,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", + "subtle", ] [[package]] @@ -1462,6 +1490,15 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + [[package]] name = "http" version = "1.4.0" @@ -2018,6 +2055,7 @@ dependencies = [ "allocative", "allocative_derive", "arc-swap", + "argon2", "csv", "encoding_rs", "ip_network", @@ -2025,6 +2063,7 @@ dependencies = [ "lqos_utils", "nix", "once_cell", + "rand_core 0.6.4", "serde", "serde_json", "sha2", @@ -2204,6 +2243,7 @@ dependencies = [ "arc-swap", "axum", "axum-extra", + "base64", "bincode", "crossbeam-channel", "crossbeam-queue", @@ -2213,6 +2253,7 @@ dependencies = [ "flate2", "futures-util", "fxhash", + "hmac", "ip_network", "ip_network_table", "itertools 0.13.0", @@ -2235,6 +2276,7 @@ dependencies = [ "serde", "serde_cbor", "serde_json", + "sha2", "sha256", "signal-hook", "smallvec", @@ -2275,7 +2317,9 @@ version = "0.1.0" dependencies = [ "anyhow", "clap", + "lqos_bus", "lqos_config", + "tokio", ] [[package]] @@ -2744,6 +2788,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "password-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" +dependencies = [ + "base64ct", + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "paste" version = "1.0.15" @@ -3238,9 +3293,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.36" +version = "0.23.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c665f33d38cea657d9614f766881e4d510e0eda4239891eea56b4cadcf01801b" +checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4" dependencies = [ "aws-lc-rs", "log", @@ -3302,9 +3357,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" [[package]] name = "rustls-webpki" -version = "0.103.9" +version = "0.103.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53" +checksum = "df33b2b81ac578cabaf06b89b0631153a3f416b0a886e8a7a1707fb51abbd1ef" dependencies = [ "aws-lc-rs", "ring", diff --git a/src/rust/Cargo.toml b/src/rust/Cargo.toml index 895e4bad..d0a1a253 100644 --- a/src/rust/Cargo.toml +++ b/src/rust/Cargo.toml @@ -54,6 +54,10 @@ csv = "1" ip_network_table = "0" ip_network = "0" sha2 = "0" +hmac = "0.12" +base64 = "0.22" +argon2 = "0.5" +rand_core = { version = "0.6", features = ["getrandom"] } uuid = { version = "1", features = ["v4", "fast-rng" ] } dashmap = "^5.5.3" toml = "0.8.8" diff --git a/src/rust/lqos_bakery/src/commands.rs b/src/rust/lqos_bakery/src/commands.rs index 3783aa5c..2700d7a7 100644 --- a/src/rust/lqos_bakery/src/commands.rs +++ b/src/rust/lqos_bakery/src/commands.rs @@ -8,6 +8,7 @@ use lqos_bus::TcHandle; use lqos_config::LazyQueueMode; use std::collections::HashSet; use std::sync::Arc; +use std::sync::mpsc::Sender as ReplySender; use tracing::{debug, info}; #[derive(Debug, Clone, Copy, Allocative)] @@ -172,6 +173,16 @@ pub enum BakeryCommands { /// New class ceiling rate in Mbps (the handler sets ceil and rate-1). new_rate: u64, }, + /// Runtime TreeGuard request to virtualize or restore a non-top-level site without a full reload. + TreeGuardSetNodeVirtual { + /// Stable Bakery site hash derived from the node name. + site_hash: i64, + /// Whether the site should be virtualized (`true`) or restored (`false`). + virtualized: bool, + /// Optional synchronous reply channel for immediate success/failure reporting. + #[allocative(skip)] + reply: Option>>, + }, } impl BakeryCommands { @@ -266,9 +277,8 @@ impl BakeryCommands { stick_offset: usize, ) -> Option>> { let mut result = Vec::new(); - info!("Clearing prior settings"); + info!("Clearing prior root qdiscs before MQ setup"); if config.on_a_stick_mode() { - // Clear just the MQ on the ISP-facing interface result.push(vec![ "qdisc".to_string(), "del".to_string(), @@ -962,3 +972,88 @@ impl BakeryCommands { Some(result) } } + +#[cfg(test)] +mod tests { + use super::{BakeryCommands, ExecutionMode}; + use lqos_config::{Config, SingleInterfaceConfig}; + use std::sync::Arc; + + fn is_root_delete(cmd: &[String], interface: &str) -> bool { + cmd.len() == 5 + && cmd[0] == "qdisc" + && cmd[1] == "del" + && cmd[2] == "dev" + && cmd[3] == interface + && cmd[4] == "root" + } + + fn is_root_replace_mq(cmd: &[String], interface: &str) -> bool { + cmd.len() == 8 + && cmd[0] == "qdisc" + && cmd[1] == "replace" + && cmd[2] == "dev" + && cmd[3] == interface + && cmd[4] == "root" + && cmd[5] == "handle" + && cmd[6] == "7FFF:" + && cmd[7] == "mq" + } + + #[test] + fn mq_setup_bridge_mode_emits_root_delete_before_replace() { + let config = Arc::new(Config::default()); + let commands = BakeryCommands::MqSetup { + queues_available: 1, + stick_offset: 0, + } + .to_commands(&config, ExecutionMode::Builder) + .expect("mq setup should emit commands"); + + assert!(is_root_delete(&commands[0], &config.isp_interface())); + assert!(is_root_delete(&commands[1], &config.internet_interface())); + assert!(is_root_replace_mq(&commands[2], &config.isp_interface())); + let internet_replace_idx = commands + .iter() + .position(|cmd| is_root_replace_mq(cmd, &config.internet_interface())) + .expect("expected internet-interface root replace"); + assert!( + internet_replace_idx > 1, + "internet-interface root replace should occur after both deletes" + ); + } + + #[test] + fn mq_setup_on_a_stick_emits_single_root_delete_before_replace() { + let mut cfg = Config::default(); + cfg.bridge = None; + cfg.single_interface = Some(SingleInterfaceConfig::default()); + let config = Arc::new(cfg); + + let commands = BakeryCommands::MqSetup { + queues_available: 1, + stick_offset: 3, + } + .to_commands(&config, ExecutionMode::Builder) + .expect("mq setup should emit commands"); + + assert!(is_root_delete(&commands[0], &config.isp_interface())); + assert!(is_root_replace_mq(&commands[1], &config.isp_interface())); + assert_eq!( + commands + .iter() + .filter(|cmd| is_root_delete(cmd, &config.isp_interface())) + .count(), + 1, + "expected a single root delete on the shared interface" + ); + assert_eq!( + commands + .iter() + .filter(|cmd| is_root_replace_mq(cmd, &config.isp_interface())) + .count(), + 1, + "expected a single root replace on the shared interface" + ); + } +} diff --git a/src/rust/lqos_bakery/src/diff/circuits.rs b/src/rust/lqos_bakery/src/diff/circuits.rs index 272152f5..c9fdfe1d 100644 --- a/src/rust/lqos_bakery/src/diff/circuits.rs +++ b/src/rust/lqos_bakery/src/diff/circuits.rs @@ -8,6 +8,7 @@ pub(crate) struct CircuitDiffCategories<'a> { pub removed_circuits: Vec, pub speed_changed: Vec<&'a Arc>, pub ip_changed: Vec<&'a Arc>, + pub migrated: Vec<&'a Arc>, pub structural_changed: Vec<&'a Arc>, } @@ -35,7 +36,8 @@ pub(crate) fn diff_circuits<'a>( let mut removed_circuits = Vec::new(); let mut speed_changed = Vec::new(); let mut ip_changed = Vec::new(); - let mut structural_changed = Vec::new(); + let mut migrated = Vec::new(); + let structural_changed = Vec::new(); for (circuit_hash, new_cmd) in &new_circuits { if !old_circuits.contains_key(circuit_hash) { @@ -53,7 +55,7 @@ pub(crate) fn diff_circuits<'a>( if let Some(new_cmd) = new_circuits.get(circuit_hash) { match classify_circuit_change(old_cmd.as_ref(), new_cmd.as_ref()) { CircuitChange::None => {} - CircuitChange::Structural => structural_changed.push(*new_cmd), + CircuitChange::Migration => migrated.push(*new_cmd), CircuitChange::Speed => speed_changed.push(*new_cmd), CircuitChange::Ip => ip_changed.push(*new_cmd), CircuitChange::SpeedAndIp => { @@ -68,6 +70,7 @@ pub(crate) fn diff_circuits<'a>( || !removed_circuits.is_empty() || !speed_changed.is_empty() || !ip_changed.is_empty() + || !migrated.is_empty() || !structural_changed.is_empty() { CircuitDiffResult::Categorized(CircuitDiffCategories { @@ -75,6 +78,7 @@ pub(crate) fn diff_circuits<'a>( removed_circuits, speed_changed, ip_changed, + migrated, structural_changed, }) } else { @@ -84,7 +88,7 @@ pub(crate) fn diff_circuits<'a>( enum CircuitChange { None, - Structural, + Migration, Speed, Ip, SpeedAndIp, @@ -141,7 +145,7 @@ fn classify_circuit_change(a: &BakeryCommands, b: &BakeryCommands) -> CircuitCha || up_class_major != other_up_class_major; if structural { - return CircuitChange::Structural; + return CircuitChange::Migration; } let speed = download_bandwidth_min != other_download_bandwidth_min @@ -159,3 +163,128 @@ fn classify_circuit_change(a: &BakeryCommands, b: &BakeryCommands) -> CircuitCha (true, true) => CircuitChange::SpeedAndIp, } } + +#[cfg(test)] +mod tests { + use super::{CircuitDiffResult, diff_circuits}; + use crate::BakeryCommands; + use lqos_bus::TcHandle; + use std::collections::HashMap; + use std::sync::Arc; + + fn add_circuit( + circuit_hash: i64, + parent_class_id: u32, + up_parent_class_id: u32, + class_minor: u16, + class_major: u16, + up_class_major: u16, + dl_min: f32, + ul_min: f32, + dl_max: f32, + ul_max: f32, + ) -> Arc { + Arc::new(BakeryCommands::AddCircuit { + circuit_hash, + parent_class_id: TcHandle::from_u32(parent_class_id), + up_parent_class_id: TcHandle::from_u32(up_parent_class_id), + class_minor, + download_bandwidth_min: dl_min, + upload_bandwidth_min: ul_min, + download_bandwidth_max: dl_max, + upload_bandwidth_max: ul_max, + class_major, + up_class_major, + down_qdisc_handle: Some(0x9000), + up_qdisc_handle: Some(0x9001), + ip_addresses: "192.0.2.1/32".to_string(), + sqm_override: None, + }) + } + + #[test] + fn parent_move_is_categorized_as_migration() { + let old = add_circuit(1, 0x10020, 0x20020, 0x21, 0x1, 0x2, 1.0, 1.0, 10.0, 10.0); + let new = add_circuit(1, 0x10034, 0x20034, 0x35, 0x1, 0x2, 1.0, 1.0, 10.0, 10.0); + let old_circuits = HashMap::from([(1, Arc::clone(&old))]); + let batch = vec![new]; + + let CircuitDiffResult::Categorized(categories) = diff_circuits(&batch, &old_circuits) + else { + panic!("expected categorized diff"); + }; + + assert_eq!(categories.migrated.len(), 1); + assert!(categories.structural_changed.is_empty()); + assert!(categories.speed_changed.is_empty()); + } + + #[test] + fn rate_change_stays_speed_only() { + let old = add_circuit(1, 0x10020, 0x20020, 0x21, 0x1, 0x2, 1.0, 1.0, 10.0, 10.0); + let new = add_circuit(1, 0x10020, 0x20020, 0x21, 0x1, 0x2, 2.0, 1.5, 20.0, 15.0); + let old_circuits = HashMap::from([(1, Arc::clone(&old))]); + let batch = vec![new]; + + let CircuitDiffResult::Categorized(categories) = diff_circuits(&batch, &old_circuits) + else { + panic!("expected categorized diff"); + }; + + assert_eq!(categories.speed_changed.len(), 1); + assert!(categories.migrated.is_empty()); + assert!(categories.structural_changed.is_empty()); + } + + #[test] + fn ip_change_stays_ip_only() { + let old = add_circuit(1, 0x10020, 0x20020, 0x21, 0x1, 0x2, 1.0, 1.0, 10.0, 10.0); + let BakeryCommands::AddCircuit { + circuit_hash, + parent_class_id, + up_parent_class_id, + class_minor, + download_bandwidth_min, + upload_bandwidth_min, + download_bandwidth_max, + upload_bandwidth_max, + class_major, + up_class_major, + down_qdisc_handle, + up_qdisc_handle, + sqm_override, + .. + } = old.as_ref() + else { + panic!("expected add circuit"); + }; + let new = Arc::new(BakeryCommands::AddCircuit { + circuit_hash: *circuit_hash, + parent_class_id: *parent_class_id, + up_parent_class_id: *up_parent_class_id, + class_minor: *class_minor, + download_bandwidth_min: *download_bandwidth_min, + upload_bandwidth_min: *upload_bandwidth_min, + download_bandwidth_max: *download_bandwidth_max, + upload_bandwidth_max: *upload_bandwidth_max, + class_major: *class_major, + up_class_major: *up_class_major, + down_qdisc_handle: *down_qdisc_handle, + up_qdisc_handle: *up_qdisc_handle, + ip_addresses: "198.51.100.10/32".to_string(), + sqm_override: sqm_override.clone(), + }); + let old_circuits = HashMap::from([(1, Arc::clone(&old))]); + let batch = vec![new]; + + let CircuitDiffResult::Categorized(categories) = diff_circuits(&batch, &old_circuits) + else { + panic!("expected categorized diff"); + }; + + assert_eq!(categories.ip_changed.len(), 1); + assert!(categories.speed_changed.is_empty()); + assert!(categories.migrated.is_empty()); + assert!(categories.structural_changed.is_empty()); + } +} diff --git a/src/rust/lqos_bakery/src/lib.rs b/src/rust/lqos_bakery/src/lib.rs index 198dc0bd..cebd7c0e 100644 --- a/src/rust/lqos_bakery/src/lib.rs +++ b/src/rust/lqos_bakery/src/lib.rs @@ -28,7 +28,7 @@ mod utils; use crossbeam_channel::{Receiver, Sender}; use parking_lot::RwLock; use std::collections::VecDeque; -use std::collections::{BTreeMap, HashMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::path::Path; use std::sync::atomic::Ordering::Relaxed; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; @@ -40,13 +40,20 @@ use crate::commands::ExecutionMode; use crate::diff::{CircuitDiffResult, SiteDiffResult, diff_circuits, diff_sites}; use crate::qdisc_handles::QdiscHandleState; use crate::queue_math::{SqmKind, effective_sqm_kind, format_rate_for_tc_f32}; -use crate::utils::{ExecuteResult, execute_in_memory, write_command_file}; +use crate::utils::{ + ExecuteResult, MemorySnapshot, execute_in_memory, execute_in_memory_chunked, + read_live_qdisc_handle_majors, read_memory_snapshot, write_command_file, +}; pub use commands::BakeryCommands; use lqos_bus::{ BusRequest, BusResponse, InsightLicenseSummary, LibreqosBusClient, TcHandle, UrgentSeverity, UrgentSource, }; -use lqos_config::{Config, LazyQueueMode}; +use lqos_config::{ + CircuitIdentityGroupInput, Config, LazyQueueMode, PlannerCircuitIdentityState, + PlannerSiteIdentityState, SiteIdentityInput, TopLevelPlannerItem, TopLevelPlannerMode, + TopLevelPlannerParams, plan_class_identities, plan_top_level_assignments, +}; use qdisc_handles::MqDeviceLayout; // ---------------------- Live-Move Types and Helpers (module scope) ---------------------- @@ -63,7 +70,12 @@ enum MigrationStage { #[derive(Clone, Debug)] struct Migration { circuit_hash: i64, - // Parent handles and majors + // Old parent handles and majors + old_parent_class_id: TcHandle, + old_up_parent_class_id: TcHandle, + old_class_major: u16, + old_up_class_major: u16, + // New parent handles and majors parent_class_id: TcHandle, up_parent_class_id: TcHandle, class_major: u16, @@ -96,6 +108,15 @@ struct StormguardOverrideKey { class: TcHandle, } +#[derive(Clone, Debug)] +struct VirtualizedSiteState { + site: Arc, + saved_sites: HashMap>, + saved_circuits: HashMap>, + active_sites: HashMap>, + active_circuits: HashMap>, +} + fn parse_ip_list(s: &str) -> Vec { s.split(',') .map(|x| x.trim().to_string()) @@ -206,6 +227,91 @@ fn build_temp_add_cmd( } } +fn queue_live_migration( + old_cmd: &BakeryCommands, + new_cmd: &Arc, + circuits: &mut HashMap>, + live_circuits: &HashMap, + migrations: &mut HashMap, +) -> bool { + let BakeryCommands::AddCircuit { + circuit_hash, + parent_class_id, + up_parent_class_id, + class_minor, + download_bandwidth_min, + upload_bandwidth_min, + download_bandwidth_max, + upload_bandwidth_max, + class_major, + up_class_major, + down_qdisc_handle, + up_qdisc_handle, + ip_addresses, + sqm_override, + .. + } = new_cmd.as_ref() + else { + return false; + }; + + let Some(_) = live_circuits.get(circuit_hash) else { + return false; + }; + + let BakeryCommands::AddCircuit { + parent_class_id: old_parent_class_id, + up_parent_class_id: old_up_parent_class_id, + class_minor: old_minor, + download_bandwidth_min: old_down_min, + upload_bandwidth_min: old_up_min, + download_bandwidth_max: old_down_max, + upload_bandwidth_max: old_up_max, + class_major: old_class_major, + up_class_major: old_up_class_major, + .. + } = old_cmd + else { + return false; + }; + + let Some(shadow_minor) = find_free_minor(circuits, parent_class_id, up_parent_class_id) else { + return false; + }; + + let mig = Migration { + circuit_hash: *circuit_hash, + old_parent_class_id: *old_parent_class_id, + old_up_parent_class_id: *old_up_parent_class_id, + old_class_major: *old_class_major, + old_up_class_major: *old_up_class_major, + parent_class_id: *parent_class_id, + up_parent_class_id: *up_parent_class_id, + class_major: *class_major, + up_class_major: *up_class_major, + down_qdisc_handle: *down_qdisc_handle, + up_qdisc_handle: *up_qdisc_handle, + old_down_min: *old_down_min, + old_down_max: *old_down_max, + old_up_min: *old_up_min, + old_up_max: *old_up_max, + new_down_min: *download_bandwidth_min, + new_down_max: *download_bandwidth_max, + new_up_min: *upload_bandwidth_min, + new_up_max: *upload_bandwidth_max, + old_minor: *old_minor, + shadow_minor, + final_minor: *class_minor, + ips: parse_ip_list(ip_addresses), + sqm_override: sqm_override.clone(), + stage: MigrationStage::PrepareShadow, + }; + + migrations.insert(*circuit_hash, mig); + circuits.insert(*circuit_hash, Arc::clone(new_cmd)); + true +} + /// Count of Bakery-Managed circuits that are currently active. pub static ACTIVE_CIRCUITS: AtomicUsize = AtomicUsize::new(0); /// True while Bakery is applying a full reload batch to `tc`. @@ -214,6 +320,24 @@ static FULL_RELOAD_IN_PROGRESS: AtomicBool = AtomicBool::new(false); pub const HARD_QDISC_HANDLE_LIMIT_PER_INTERFACE: usize = 65_534; /// Conservative operational limit used to fail a full reload before qdisc handle exhaustion. pub const SAFE_QDISC_BUDGET_PER_INTERFACE: usize = 65_000; +/// Conservative estimated kernel-memory cost of a non-leaf infrastructure qdisc. +/// +/// These weights are not kernel ABI sizes. They are deliberately conservative +/// safety estimates used to block or stop obviously risky full reloads before +/// the host reaches OOM pressure. +pub const INFRA_QDISC_ESTIMATED_MEMORY_BYTES: u64 = 16 * 1024; +/// Conservative estimated kernel-memory cost of an `fq_codel` leaf qdisc. +/// +/// This remains intentionally lower than CAKE, but is biased high enough to +/// prefer false-positive safety blocks over OOM risk on large reloads. +pub const FQ_CODEL_QDISC_ESTIMATED_MEMORY_BYTES: u64 = 64 * 1024; +/// Conservative estimated kernel-memory cost of a `cake` leaf qdisc. +/// +/// Tuned upward after live production capture showed summed CAKE runtime memory +/// substantially exceeding the earlier heuristic during busy periods. +pub const CAKE_QDISC_ESTIMATED_MEMORY_BYTES: u64 = 512 * 1024; +/// Minimum memory headroom Bakery tries to leave unused after a projected or in-flight apply. +pub const BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES: u64 = 768 * 1024 * 1024; /// Maximum number of mapped circuits allowed without Insight. const DEFAULT_MAPPED_CIRCUITS_LIMIT: usize = 1000; /// Minimum interval between repeated mapped-circuit-limit urgent issues. @@ -221,6 +345,7 @@ const CIRCUIT_LIMIT_URGENT_INTERVAL_SECONDS: u64 = 30 * 60; /// Last timestamp at which we emitted a mapped-circuit-limit urgent issue. static LAST_CIRCUIT_LIMIT_URGENT_TS: AtomicU64 = AtomicU64::new(0); const BAKERY_EVENT_LIMIT: usize = 50; +const FULL_RELOAD_TC_CHUNK_SIZE: usize = 2_500; /// High-level Bakery execution mode for operator-facing status. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -251,6 +376,14 @@ pub struct BakeryCapacityInterfaceSnapshot { pub name: String, /// Planned qdisc count for that interface. pub planned_qdiscs: usize, + /// Planned infrastructure qdiscs (`mq`, `htb`, etc.) for that interface. + pub infra_qdiscs: usize, + /// Planned `cake` leaf qdiscs for that interface. + pub cake_qdiscs: usize, + /// Planned `fq_codel` leaf qdiscs for that interface. + pub fq_codel_qdiscs: usize, + /// Estimated kernel memory cost for that interface's planned qdiscs. + pub estimated_memory_bytes: u64, } /// Last qdisc preflight result retained for Bakery UI/status. @@ -264,6 +397,14 @@ pub struct BakeryPreflightSnapshot { pub safe_budget: usize, /// Hard kernel limit used for reference. pub hard_limit: usize, + /// Estimated total kernel memory cost of the planned qdisc model. + pub estimated_total_memory_bytes: u64, + /// Current host memory available during the preflight, if known. + pub memory_available_bytes: Option, + /// Memory floor that must remain available before the apply proceeds. + pub memory_guard_min_available_bytes: u64, + /// Whether the memory preflight passed. + pub memory_ok: bool, /// Per-interface planned qdisc counts. pub interfaces: Vec, } @@ -275,6 +416,16 @@ pub struct BakeryStatusSnapshot { pub mode: BakeryMode, /// Unix timestamp when the current action started, if any. pub current_action_started_unix: Option, + /// Current apply phase for the in-flight action, if any. + pub current_apply_phase: Option, + /// Total `tc` commands planned for the in-flight action. + pub current_apply_total_tc_commands: usize, + /// `tc` commands already completed for the in-flight action. + pub current_apply_completed_tc_commands: usize, + /// Total apply chunks planned for the in-flight action. + pub current_apply_total_chunks: usize, + /// Apply chunks already completed for the in-flight action. + pub current_apply_completed_chunks: usize, /// Currently active circuit count. pub active_circuits: usize, /// Unix timestamp of the last successful apply, if any. @@ -316,6 +467,11 @@ pub struct BakeryActivityEntry { struct BakeryTelemetryState { mode: BakeryMode, current_action_started_unix: Option, + current_apply_phase: Option, + current_apply_total_tc_commands: usize, + current_apply_completed_tc_commands: usize, + current_apply_total_chunks: usize, + current_apply_completed_chunks: usize, last_success_unix: Option, last_failure_unix: Option, last_failure_summary: Option, @@ -346,6 +502,11 @@ impl Default for BakeryTelemetryState { Self { mode: BakeryMode::Idle, current_action_started_unix: None, + current_apply_phase: None, + current_apply_total_tc_commands: 0, + current_apply_completed_tc_commands: 0, + current_apply_total_chunks: 0, + current_apply_completed_chunks: 0, last_success_unix: None, last_failure_unix: None, last_failure_summary: None, @@ -376,6 +537,7 @@ impl Drop for FullReloadScope { fn drop(&mut self) { FULL_RELOAD_IN_PROGRESS.store(false, Ordering::Relaxed); let mut state = telemetry_state().write(); + clear_bakery_apply_progress(&mut state); if state.mode == BakeryMode::ApplyingFullReload { state.mode = BakeryMode::Idle; state.current_action_started_unix = None; @@ -417,16 +579,40 @@ fn push_bakery_event(event: &str, status: &str, summary: String) { } } +fn clear_bakery_apply_progress(state: &mut BakeryTelemetryState) { + state.current_apply_phase = None; + state.current_apply_total_tc_commands = 0; + state.current_apply_completed_tc_commands = 0; + state.current_apply_total_chunks = 0; + state.current_apply_completed_chunks = 0; +} + fn mark_bakery_action_started(mode: BakeryMode, event: &str, summary: String) { let ts = current_timestamp(); { let mut state = telemetry_state().write(); state.mode = mode; state.current_action_started_unix = Some(ts); + clear_bakery_apply_progress(&mut state); } push_bakery_event(event, "info", summary); } +fn update_bakery_apply_progress( + phase: Option<&str>, + total_tc_commands: usize, + completed_tc_commands: usize, + total_chunks: usize, + completed_chunks: usize, +) { + let mut state = telemetry_state().write(); + state.current_apply_phase = phase.map(str::to_string); + state.current_apply_total_tc_commands = total_tc_commands; + state.current_apply_completed_tc_commands = completed_tc_commands; + state.current_apply_total_chunks = total_chunks; + state.current_apply_completed_chunks = completed_chunks; +} + fn mark_bakery_action_finished(metrics: BakeryApplyMetrics<'_>) { let ts = current_timestamp(); { @@ -443,6 +629,7 @@ fn mark_bakery_action_finished(metrics: BakeryApplyMetrics<'_>) { state.last_failure_unix = Some(ts); state.last_failure_summary = Some(metrics.summary.to_string()); } + clear_bakery_apply_progress(&mut state); if state.mode != BakeryMode::ApplyingFullReload { state.mode = BakeryMode::Idle; state.current_action_started_unix = None; @@ -465,6 +652,11 @@ pub fn bakery_status_snapshot() -> BakeryStatusSnapshot { BakeryStatusSnapshot { mode: state.mode, current_action_started_unix: state.current_action_started_unix, + current_apply_phase: state.current_apply_phase, + current_apply_total_tc_commands: state.current_apply_total_tc_commands, + current_apply_completed_tc_commands: state.current_apply_completed_tc_commands, + current_apply_total_chunks: state.current_apply_total_chunks, + current_apply_completed_chunks: state.current_apply_completed_chunks, active_circuits: ACTIVE_CIRCUITS.load(Ordering::Relaxed), last_success_unix: state.last_success_unix, last_failure_unix: state.last_failure_unix, @@ -513,10 +705,7 @@ fn summarize_apply_result(purpose: &str, result: &ExecuteResult) -> String { } } -fn execute_and_record_live_change( - command_buffer: &Vec>, - purpose: &str, -) -> ExecuteResult { +fn execute_and_record_live_change(command_buffer: &[Vec], purpose: &str) -> ExecuteResult { let (total, class_commands, qdisc_commands) = count_tc_command_types(command_buffer); mark_bakery_action_started( BakeryMode::ApplyingLiveChange, @@ -540,13 +729,36 @@ fn execute_and_record_live_change( /// Estimated qdisc-handle usage for a planned full reload. #[derive(Debug, Clone, PartialEq, Eq)] +pub struct QdiscInterfaceEstimate { + /// Total planned qdiscs for the interface. + pub planned_qdiscs: usize, + /// Planned infrastructure qdiscs (`mq`, `htb`, etc.) for the interface. + pub infra_qdiscs: usize, + /// Planned CAKE leaf qdiscs for the interface. + pub cake_qdiscs: usize, + /// Planned fq_codel leaf qdiscs for the interface. + pub fq_codel_qdiscs: usize, + /// Estimated kernel memory cost for the interface's planned qdiscs. + pub estimated_memory_bytes: u64, +} + +/// Estimated qdisc budget and conservative memory-safety forecast for a planned full reload. +#[derive(Debug, Clone, PartialEq, Eq)] pub struct QdiscBudgetEstimate { /// Estimated total qdisc count grouped by network interface name. pub interfaces: BTreeMap, + /// Detailed per-interface qdisc breakdown. + pub interface_details: BTreeMap, /// Conservative operational limit enforced before a full reload is committed. pub safe_budget: usize, /// Kernel hard limit for the per-device qdisc-handle namespace. pub hard_limit: usize, + /// Estimated total kernel memory cost of the planned qdisc model. + pub estimated_total_memory_bytes: u64, + /// Current host memory snapshot used for preflight, if available. + pub memory_snapshot: Option, + /// Whether the memory preflight passed. + pub memory_ok: bool, } impl QdiscBudgetEstimate { @@ -555,6 +767,7 @@ impl QdiscBudgetEstimate { self.interfaces .values() .all(|count| *count <= self.safe_budget) + && self.memory_ok } } @@ -563,6 +776,57 @@ fn find_arg_value<'a>(argv: &'a [String], key: &str) -> Option<&'a str> { .find_map(|pair| (pair[0] == key).then_some(pair[1].as_str())) } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum PlannedQdiscKind { + Infra, + Cake, + FqCodel, +} + +fn planned_qdisc_kind(argv: &[String]) -> Option { + if argv.len() < 2 || argv[0] != "qdisc" { + return None; + } + if !matches!(argv[1].as_str(), "add" | "replace") { + return None; + } + + if argv.iter().any(|arg| arg == "cake") { + return Some(if planned_qdisc_is_leaf(argv) { + PlannedQdiscKind::Cake + } else { + PlannedQdiscKind::Infra + }); + } + if argv.iter().any(|arg| arg == "fq_codel") { + return Some(if planned_qdisc_is_leaf(argv) { + PlannedQdiscKind::FqCodel + } else { + PlannedQdiscKind::Infra + }); + } + Some(PlannedQdiscKind::Infra) +} + +fn planned_qdisc_is_leaf(argv: &[String]) -> bool { + let Some(parent) = find_arg_value(argv, "parent") else { + return false; + }; + let Ok(parent_handle) = TcHandle::from_string(parent) else { + return false; + }; + let (_, minor) = parent_handle.get_major_minor(); + minor != 1 && minor != 2 +} + +fn qdisc_kind_estimated_memory_bytes(kind: PlannedQdiscKind) -> u64 { + match kind { + PlannedQdiscKind::Infra => INFRA_QDISC_ESTIMATED_MEMORY_BYTES, + PlannedQdiscKind::Cake => CAKE_QDISC_ESTIMATED_MEMORY_BYTES, + PlannedQdiscKind::FqCodel => FQ_CODEL_QDISC_ESTIMATED_MEMORY_BYTES, + } +} + fn planned_qdisc_identity(argv: &[String]) -> Option<(String, String)> { if argv.len() < 2 || argv[0] != "qdisc" { return None; @@ -591,6 +855,7 @@ pub fn estimate_full_reload_auto_qdisc_budget( queue: &[BakeryCommands], ) -> QdiscBudgetEstimate { let mut interfaces = BTreeMap::new(); + let mut interface_details: BTreeMap = BTreeMap::new(); let mut seen_qdiscs = HashSet::new(); for command in queue { @@ -602,15 +867,50 @@ pub fn estimate_full_reload_auto_qdisc_budget( continue; }; if seen_qdiscs.insert((dev.clone(), identity)) { - *interfaces.entry(dev).or_insert(0) += 1; + let kind = planned_qdisc_kind(&argv).unwrap_or(PlannedQdiscKind::Infra); + *interfaces.entry(dev.clone()).or_insert(0) += 1; + let detail = + interface_details + .entry(dev) + .or_insert_with(|| QdiscInterfaceEstimate { + planned_qdiscs: 0, + infra_qdiscs: 0, + cake_qdiscs: 0, + fq_codel_qdiscs: 0, + estimated_memory_bytes: 0, + }); + detail.planned_qdiscs += 1; + match kind { + PlannedQdiscKind::Infra => detail.infra_qdiscs += 1, + PlannedQdiscKind::Cake => detail.cake_qdiscs += 1, + PlannedQdiscKind::FqCodel => detail.fq_codel_qdiscs += 1, + } + detail.estimated_memory_bytes = detail + .estimated_memory_bytes + .saturating_add(qdisc_kind_estimated_memory_bytes(kind)); } } } + let estimated_total_memory_bytes = interface_details.values().fold(0u64, |acc, detail| { + acc.saturating_add(detail.estimated_memory_bytes) + }); + let memory_snapshot = read_memory_snapshot().ok(); + let memory_ok = memory_snapshot.as_ref().is_none_or(|snapshot| { + snapshot + .available_bytes + .saturating_sub(BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES) + >= estimated_total_memory_bytes + }); + QdiscBudgetEstimate { interfaces, + interface_details, safe_budget: SAFE_QDISC_BUDGET_PER_INTERFACE, hard_limit: HARD_QDISC_HANDLE_LIMIT_PER_INTERFACE, + estimated_total_memory_bytes, + memory_snapshot, + memory_ok, } } @@ -641,6 +941,16 @@ fn with_assigned_qdisc_handles( config: &Arc, mq_layout: &MqDeviceLayout, qdisc_handles: &mut QdiscHandleState, +) -> Arc { + with_assigned_qdisc_handles_reserved(command, config, mq_layout, qdisc_handles, &HashMap::new()) +} + +fn with_assigned_qdisc_handles_reserved( + command: &Arc, + config: &Arc, + mq_layout: &MqDeviceLayout, + qdisc_handles: &mut QdiscHandleState, + extra_reserved_handles: &HashMap>, ) -> Arc { let BakeryCommands::AddCircuit { circuit_hash, .. } = command.as_ref() else { return Arc::clone(command); @@ -653,8 +963,14 @@ fn with_assigned_qdisc_handles( let mut enriched = command.as_ref().clone(); let isp_interface = config.isp_interface(); let internet_interface = config.internet_interface(); - let isp_reserved = mq_layout.reserved_handles(&isp_interface); - let up_reserved = mq_layout.reserved_handles(&internet_interface); + let mut isp_reserved = mq_layout.reserved_handles(&isp_interface); + if let Some(extra) = extra_reserved_handles.get(&isp_interface) { + isp_reserved.extend(extra.iter().copied()); + } + let mut up_reserved = mq_layout.reserved_handles(&internet_interface); + if let Some(extra) = extra_reserved_handles.get(&internet_interface) { + up_reserved.extend(extra.iter().copied()); + } if let BakeryCommands::AddCircuit { down_qdisc_handle, @@ -678,6 +994,29 @@ fn with_assigned_qdisc_handles( Arc::new(enriched) } +fn snapshot_live_qdisc_handle_majors( + config: &Arc, +) -> Result>, String> { + let mut reserved = HashMap::new(); + let isp_interface = config.isp_interface(); + reserved.insert( + isp_interface.clone(), + read_live_qdisc_handle_majors(&isp_interface)?, + ); + + if !config.on_a_stick_mode() { + let internet_interface = config.internet_interface(); + if internet_interface != isp_interface { + reserved.insert( + internet_interface.clone(), + read_live_qdisc_handle_majors(&internet_interface)?, + ); + } + } + + Ok(reserved) +} + fn parse_directional_sqm_override( sqm_override: &Option, ) -> (Option, Option) { @@ -1062,6 +1401,45 @@ fn maybe_emit_mapped_circuit_limit_urgent(stats: &MappedLimitStats) { }); } +fn maybe_emit_memory_guard_urgent(summary: &str) { + if !summary.contains("Bakery memory guard stopped") { + return; + } + + let message = summary.to_string(); + let context = read_memory_snapshot().ok().map(|snapshot| { + format!( + "{{\"available_bytes\":{},\"total_bytes\":{},\"memory_guard_floor_bytes\":{}}}", + snapshot.available_bytes, snapshot.total_bytes, BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES + ) + }); + + let rt = match tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + { + Ok(rt) => rt, + Err(e) => { + warn!("Bakery: failed to build runtime for urgent issue submission: {e:?}"); + return; + } + }; + rt.block_on(async { + if let Ok(mut bus) = LibreqosBusClient::new().await { + let _ = bus + .request(vec![BusRequest::SubmitUrgentIssue { + source: UrgentSource::System, + severity: UrgentSeverity::Error, + code: "BAKERY_MEMORY_GUARD".to_string(), + message, + context, + dedupe_key: Some("bakery_memory_guard".to_string()), + }]) + .await; + } + }); +} + fn log_mapped_limit_decision( context: &str, mapped_limit: ResolvedMappedLimit, @@ -1108,6 +1486,7 @@ fn bakery_main(rx: Receiver, tx: Sender) { .unwrap_or_default(); // Persist latest StormGuard ceilings keyed by interface + class so we can replay after rebuilds. let mut stormguard_overrides: HashMap = HashMap::new(); + let mut virtualized_sites: HashMap = HashMap::new(); // Mapping state #[derive(Clone, Hash, PartialEq, Eq, Debug)] @@ -1391,6 +1770,7 @@ fn bakery_main(rx: Receiver, tx: Sender) { &tx, &mut migrations, &stormguard_overrides, + &virtualized_sites, ); } BakeryCommands::MqSetup { .. } => { @@ -1529,19 +1909,19 @@ fn bakery_main(rx: Receiver, tx: Sender) { advanced += 1; } MigrationStage::BuildFinal => { - // Delete old classes/qdiscs and create final with NEW rates at original minor + // Delete old classes/qdiscs and create final with NEW rates at final minor. if let Some(old_cmd) = build_temp_add_cmd( &BakeryCommands::AddCircuit { circuit_hash: mig.circuit_hash, - parent_class_id: mig.parent_class_id, - up_parent_class_id: mig.up_parent_class_id, + parent_class_id: mig.old_parent_class_id, + up_parent_class_id: mig.old_up_parent_class_id, class_minor: mig.old_minor, download_bandwidth_min: mig.old_down_min, upload_bandwidth_min: mig.old_up_min, download_bandwidth_max: mig.old_down_max, upload_bandwidth_max: mig.old_up_max, - class_major: mig.class_major, - up_class_major: mig.up_class_major, + class_major: mig.old_class_major, + up_class_major: mig.old_up_class_major, down_qdisc_handle: None, up_qdisc_handle: None, ip_addresses: "".to_string(), @@ -1560,7 +1940,22 @@ fn bakery_main(rx: Receiver, tx: Sender) { } // Final add (new rates) at final_minor if let Some(final_cmd) = build_temp_add_cmd( - &old_cmd, + &BakeryCommands::AddCircuit { + circuit_hash: mig.circuit_hash, + parent_class_id: mig.parent_class_id, + up_parent_class_id: mig.up_parent_class_id, + class_minor: mig.final_minor, + download_bandwidth_min: mig.new_down_min, + upload_bandwidth_min: mig.new_up_min, + download_bandwidth_max: mig.new_down_max, + upload_bandwidth_max: mig.new_up_max, + class_major: mig.class_major, + up_class_major: mig.up_class_major, + down_qdisc_handle: mig.down_qdisc_handle, + up_qdisc_handle: mig.up_qdisc_handle, + ip_addresses: "".to_string(), + sqm_override: mig.sqm_override.clone(), + }, mig.final_minor, mig.new_down_min, mig.new_down_max, @@ -1757,6 +2152,26 @@ fn bakery_main(rx: Receiver, tx: Sender) { } } } + BakeryCommands::TreeGuardSetNodeVirtual { + site_hash, + virtualized, + reply, + } => { + let result = handle_treeguard_set_node_virtual_live( + site_hash, + virtualized, + &mut sites, + &mut circuits, + &live_circuits, + &mq_layout, + &mut qdisc_handles, + &mut migrations, + &mut virtualized_sites, + ); + if let Some(reply) = reply { + let _ = reply.send(result); + } + } } } error!("Bakery thread exited unexpectedly."); @@ -1773,6 +2188,7 @@ fn handle_commit_batch( tx: &Sender, migrations: &mut HashMap, stormguard_overrides: &HashMap, + virtualized_sites: &HashMap, ) { let Ok(config) = lqos_config::load_config() else { error!("Failed to load configuration, exiting Bakery thread."); @@ -1784,6 +2200,7 @@ fn handle_commit_batch( debug!("CommitBatch received without a batch to commit."); return; }; + let new_batch = apply_runtime_virtualization_overlay(new_batch, virtualized_sites); let resolved_mq_layout = current_mq_layout(&new_batch, &config, mq_layout); let mapped_limit = resolve_mapped_circuit_limit(); @@ -1965,11 +2382,12 @@ fn handle_commit_batch( if let CircuitDiffResult::Categorized(categories) = circuit_change_mode { // One-line summary of changes (info!) info!( - "Bakery changes: sites_speed={}, circuits_added={}, removed={}, speed={}, ip={}", + "Bakery changes: sites_speed={}, circuits_added={}, removed={}, speed={}, migrated={}, ip={}", site_speed_change_count, categories.newly_added.len(), categories.removed_circuits.len(), categories.speed_changed.len(), + categories.migrated.len(), categories.ip_changed.len() ); @@ -2022,9 +2440,14 @@ fn handle_commit_batch( for cmd in &categories.speed_changed { let mut enriched_cmd = with_assigned_qdisc_handles(cmd, &config, layout, qdisc_handles); - if let BakeryCommands::AddCircuit { circuit_hash, .. } = enriched_cmd.as_ref() - && let Some(old_cmd) = circuits.get(circuit_hash) + let old_cmd = if let BakeryCommands::AddCircuit { circuit_hash, .. } = + enriched_cmd.as_ref() { + circuits.get(circuit_hash).cloned() + } else { + None + }; + if let Some(old_cmd) = old_cmd.as_ref() { enriched_cmd = rotate_changed_qdisc_handles( old_cmd.as_ref(), &enriched_cmd, @@ -2033,70 +2456,19 @@ fn handle_commit_batch( qdisc_handles, ); } - if let BakeryCommands::AddCircuit { - circuit_hash, - parent_class_id, - up_parent_class_id, - class_minor, - download_bandwidth_min, - upload_bandwidth_min, - download_bandwidth_max, - upload_bandwidth_max, - class_major, - up_class_major, - ip_addresses, - sqm_override, - .. - } = enriched_cmd.as_ref() + if let Some(old_cmd) = old_cmd.as_ref() + && queue_live_migration( + old_cmd.as_ref(), + &enriched_cmd, + circuits, + live_circuits, + migrations, + ) { + continue; + } + if let BakeryCommands::AddCircuit { circuit_hash, .. } = enriched_cmd.as_ref() { let was_activated = live_circuits.contains_key(circuit_hash); - if was_activated { - // Attempt live-move - if let Some(shadow_minor) = - find_free_minor(circuits, parent_class_id, up_parent_class_id) - { - // Find old command for old rates - if let Some(old_cmd) = circuits.get(circuit_hash) - && let BakeryCommands::AddCircuit { - download_bandwidth_min: old_down_min, - upload_bandwidth_min: old_up_min, - download_bandwidth_max: old_down_max, - upload_bandwidth_max: old_up_max, - down_qdisc_handle, - up_qdisc_handle, - .. - } = old_cmd.as_ref() - { - let mig = Migration { - circuit_hash: *circuit_hash, - parent_class_id: *parent_class_id, - up_parent_class_id: *up_parent_class_id, - class_major: *class_major, - up_class_major: *up_class_major, - down_qdisc_handle: *down_qdisc_handle, - up_qdisc_handle: *up_qdisc_handle, - old_down_min: *old_down_min, - old_down_max: *old_down_max, - old_up_min: *old_up_min, - old_up_max: *old_up_max, - new_down_min: *download_bandwidth_min, - new_down_max: *download_bandwidth_max, - new_up_min: *upload_bandwidth_min, - new_up_max: *upload_bandwidth_max, - old_minor: *class_minor, - shadow_minor, - final_minor: *class_minor, - ips: parse_ip_list(ip_addresses), - sqm_override: sqm_override.clone(), - stage: MigrationStage::PrepareShadow, - }; - migrations.insert(*circuit_hash, mig); - // Update desired circuit definition now - circuits.insert(*circuit_hash, Arc::clone(&enriched_cmd)); - continue; // skip immediate path - } - } - } // Fallback: immediate safe update match config.queues.lazy_queues.as_ref() { None | Some(LazyQueueMode::No) => { @@ -2156,6 +2528,111 @@ fn handle_commit_batch( } } + // 2b) Parent/class migrations + if !categories.migrated.is_empty() { + let Some(layout) = resolved_mq_layout.as_ref() else { + warn!("Bakery: missing MQ layout during circuit migrations"); + return; + }; + let mut immediate_commands = Vec::new(); + for cmd in &categories.migrated { + let mut enriched_cmd = + with_assigned_qdisc_handles(cmd, &config, layout, qdisc_handles); + let Some(old_cmd) = (if let BakeryCommands::AddCircuit { circuit_hash, .. } = + enriched_cmd.as_ref() + { + circuits.get(circuit_hash).cloned() + } else { + None + }) else { + continue; + }; + + enriched_cmd = rotate_changed_qdisc_handles( + old_cmd.as_ref(), + &enriched_cmd, + &config, + layout, + qdisc_handles, + ); + + if queue_live_migration( + old_cmd.as_ref(), + &enriched_cmd, + circuits, + live_circuits, + migrations, + ) { + continue; + } + + let BakeryCommands::AddCircuit { circuit_hash, .. } = enriched_cmd.as_ref() else { + continue; + }; + let was_activated = live_circuits.contains_key(circuit_hash); + if was_activated { + warn!( + "Bakery: falling back to full reload for active migrated circuit {} because live migration setup failed", + circuit_hash + ); + let (new_batch, mapped_limit_stats) = filter_batch_by_mapped_circuit_limit( + new_batch.clone(), + circuits, + effective_limit, + ); + log_mapped_limit_decision( + "circuit-migration rebuild", + mapped_limit, + mapped_limit_stats, + ); + full_reload( + batch, + sites, + circuits, + live_circuits, + mq_layout, + qdisc_handles, + &config, + new_batch, + resolved_mq_layout.clone(), + stormguard_overrides, + ); + MQ_CREATED.store(true, std::sync::atomic::Ordering::Relaxed); + return; + } + + match config.queues.lazy_queues.as_ref() { + None | Some(LazyQueueMode::No) => { + if let Some(prune) = old_cmd.to_prune(&config, true) { + immediate_commands.extend(prune); + } + if let Some(add) = enriched_cmd.to_commands(&config, ExecutionMode::Builder) + { + immediate_commands.extend(add); + } + } + Some(LazyQueueMode::Htb) => { + if let Some(prune) = old_cmd.to_prune(&config, true) { + immediate_commands.extend(prune); + } + if let Some(add_htb) = + enriched_cmd.to_commands(&config, ExecutionMode::Builder) + { + immediate_commands.extend(add_htb); + } + } + Some(LazyQueueMode::Full) => {} + } + circuits.insert(*circuit_hash, enriched_cmd); + } + if !immediate_commands.is_empty() { + execute_and_record_live_change( + &immediate_commands, + "migrating circuits between parent nodes (fallback)", + ); + } + } + // 3) Additions if !categories.newly_added.is_empty() { let mut accepted_additions: Vec<&Arc> = Vec::new(); @@ -2516,61 +2993,1634 @@ fn handle_change_site_speed_live( } } -#[allow(clippy::too_many_arguments)] -fn full_reload( - batch: &mut Option>>, - sites: &mut HashMap>, - circuits: &mut HashMap>, - live_circuits: &mut HashMap, - mq_layout: &mut Option, - qdisc_handles: &mut QdiscHandleState, - config: &Arc, - new_batch: Vec>, - resolved_mq_layout: Option, - stormguard_overrides: &HashMap, -) { - warn!("Bakery: Full reload triggered due to site or circuit changes."); - FULL_RELOAD_IN_PROGRESS.store(true, Ordering::Relaxed); - mark_bakery_action_started( - BakeryMode::ApplyingFullReload, - "full_reload_started", - "Full reload triggered due to site or circuit changes.".to_string(), - ); - let _reload_scope = FullReloadScope; - sites.clear(); - let previous_circuits = std::mem::take(circuits); - live_circuits.clear(); - if let Some(layout) = resolved_mq_layout.as_ref() { - process_batch( - new_batch, - config, - sites, - circuits, - &previous_circuits, - layout, - qdisc_handles, - ); - let active_hashes = circuits.keys().copied().collect::>(); - qdisc_handles.retain_circuits(&config.isp_interface(), &active_hashes); - if !config.on_a_stick_mode() { - qdisc_handles.retain_circuits(&config.internet_interface(), &active_hashes); - } - qdisc_handles.save(config); - *mq_layout = resolved_mq_layout; - } else { - warn!("Bakery: full reload skipped qdisc-handle assignment because MQ layout is unknown"); - process_batch( - new_batch, - config, - sites, - circuits, - &previous_circuits, - &MqDeviceLayout::default(), - qdisc_handles, - ); - } +fn site_class_handles(site: &BakeryCommands) -> Option<(TcHandle, TcHandle)> { + let BakeryCommands::AddSite { + parent_class_id, + up_parent_class_id, + class_minor, + .. + } = site + else { + return None; + }; + Some(( + tc_handle_from_major_minor(parent_class_id.get_major_minor().0, *class_minor), + tc_handle_from_major_minor(up_parent_class_id.get_major_minor().0, *class_minor), + )) +} + +fn site_is_top_level(site: &BakeryCommands) -> bool { + let BakeryCommands::AddSite { + parent_class_id, + up_parent_class_id, + .. + } = site + else { + return false; + }; + parent_class_id.get_major_minor().1 == 0 && up_parent_class_id.get_major_minor().1 == 0 +} + +fn site_runtime_virtualization_eligibility_error(site: &BakeryCommands) -> Option { + let BakeryCommands::AddSite { + site_hash, + parent_class_id, + up_parent_class_id, + .. + } = site + else { + return Some("TreeGuard runtime virtualization requires an AddSite command".to_string()); + }; + + if site_is_top_level(site) { + return Some(format!( + "Site {} is top-level in HTB and cannot be runtime-virtualized in v1", + site_hash + )); + } + + let Some((site_down_class, site_up_class)) = site_class_handles(site) else { + return Some(format!("Site {} is not a valid AddSite command", site_hash)); + }; + + let (parent_down_major, _) = parent_class_id.get_major_minor(); + let (parent_up_major, _) = up_parent_class_id.get_major_minor(); + let (site_down_major, _) = site_down_class.get_major_minor(); + let (site_up_major, _) = site_up_class.get_major_minor(); + + if parent_down_major != site_down_major || parent_up_major != site_up_major { + return Some(format!( + "Site {} crosses queue/major domains (parent down/up majors {:x}/{:x}, site down/up majors {:x}/{:x}) and cannot be runtime-virtualized in v1", + site_hash, parent_down_major, parent_up_major, site_down_major, site_up_major + )); + } + + None +} + +fn site_prune_commands(config: &Arc, site: &BakeryCommands) -> Option>> { + let BakeryCommands::AddSite { + parent_class_id, + up_parent_class_id, + class_minor, + .. + } = site + else { + return None; + }; + + Some(vec![ + vec![ + "class".to_string(), + "del".to_string(), + "dev".to_string(), + config.isp_interface(), + "parent".to_string(), + parent_class_id.as_tc_string(), + "classid".to_string(), + format!( + "0x{:x}:0x{:x}", + parent_class_id.get_major_minor().0, + class_minor + ), + ], + vec![ + "class".to_string(), + "del".to_string(), + "dev".to_string(), + config.internet_interface(), + "parent".to_string(), + up_parent_class_id.as_tc_string(), + "classid".to_string(), + format!( + "0x{:x}:0x{:x}", + up_parent_class_id.get_major_minor().0, + class_minor + ), + ], + ]) +} + +fn reparent_site_command( + site: &Arc, + parent_class_id: TcHandle, + up_parent_class_id: TcHandle, +) -> Option> { + let BakeryCommands::AddSite { + site_hash, + class_minor, + download_bandwidth_min, + upload_bandwidth_min, + download_bandwidth_max, + upload_bandwidth_max, + .. + } = site.as_ref() + else { + return None; + }; + + Some(Arc::new(BakeryCommands::AddSite { + site_hash: *site_hash, + parent_class_id, + up_parent_class_id, + class_minor: *class_minor, + download_bandwidth_min: *download_bandwidth_min, + upload_bandwidth_min: *upload_bandwidth_min, + download_bandwidth_max: *download_bandwidth_max, + upload_bandwidth_max: *upload_bandwidth_max, + })) +} + +fn reparent_circuit_command( + circuit: &Arc, + parent_class_id: TcHandle, + up_parent_class_id: TcHandle, +) -> Option> { + let BakeryCommands::AddCircuit { + circuit_hash, + class_minor, + download_bandwidth_min, + upload_bandwidth_min, + download_bandwidth_max, + upload_bandwidth_max, + class_major, + up_class_major, + ip_addresses, + sqm_override, + .. + } = circuit.as_ref() + else { + return None; + }; + + Some(Arc::new(BakeryCommands::AddCircuit { + circuit_hash: *circuit_hash, + parent_class_id, + up_parent_class_id, + class_minor: *class_minor, + download_bandwidth_min: *download_bandwidth_min, + upload_bandwidth_min: *upload_bandwidth_min, + download_bandwidth_max: *download_bandwidth_max, + upload_bandwidth_max: *upload_bandwidth_max, + class_major: *class_major, + up_class_major: *up_class_major, + down_qdisc_handle: None, + up_qdisc_handle: None, + ip_addresses: ip_addresses.clone(), + sqm_override: sqm_override.clone(), + })) +} + +fn collect_direct_child_site_hashes( + sites: &HashMap>, + target_down: TcHandle, + target_up: TcHandle, + target_hash: i64, +) -> Vec { + let mut hashes: Vec = sites + .iter() + .filter_map(|(site_hash, site)| { + let BakeryCommands::AddSite { + parent_class_id, + up_parent_class_id, + .. + } = site.as_ref() + else { + return None; + }; + (*site_hash != target_hash + && *parent_class_id == target_down + && *up_parent_class_id == target_up) + .then_some(*site_hash) + }) + .collect(); + hashes.sort_unstable(); + hashes +} + +fn collect_direct_circuit_hashes( + circuits: &HashMap>, + target_down: TcHandle, + target_up: TcHandle, +) -> Vec { + let mut hashes: Vec = circuits + .iter() + .filter_map(|(circuit_hash, circuit)| { + let BakeryCommands::AddCircuit { + parent_class_id, + up_parent_class_id, + .. + } = circuit.as_ref() + else { + return None; + }; + (*parent_class_id == target_down && *up_parent_class_id == target_up) + .then_some(*circuit_hash) + }) + .collect(); + hashes.sort_unstable(); + hashes +} + +fn apply_direct_circuit_reparents( + config: &Arc, + circuit_hashes: &[i64], + new_parent_class_id: TcHandle, + new_up_parent_class_id: TcHandle, + circuits: &mut HashMap>, + live_circuits: &HashMap, + mq_layout: &Option, + qdisc_handles: &mut QdiscHandleState, + migrations: &mut HashMap, +) -> Result<(), String> { + if circuit_hashes.is_empty() { + return Ok(()); + } + let Some(layout) = mq_layout.as_ref() else { + return Err("Bakery runtime virtualization requires MQ layout to be available".to_string()); + }; + + for circuit_hash in circuit_hashes { + let Some(old_cmd) = circuits.get(circuit_hash).cloned() else { + continue; + }; + let Some(candidate_cmd) = + reparent_circuit_command(&old_cmd, new_parent_class_id, new_up_parent_class_id) + else { + continue; + }; + if live_circuits.contains_key(circuit_hash) + && let BakeryCommands::AddCircuit { + parent_class_id, + up_parent_class_id, + .. + } = candidate_cmd.as_ref() + && find_free_minor(circuits, parent_class_id, up_parent_class_id).is_none() + { + return Err(format!( + "Unable to queue live migration for active circuit {}: no shadow minor available", + circuit_hash + )); + } + } + + let mut immediate_commands = Vec::new(); + let mut updated_circuits: Vec<(i64, Arc)> = Vec::new(); + + for circuit_hash in circuit_hashes { + let Some(old_cmd) = circuits.get(circuit_hash).cloned() else { + continue; + }; + let Some(candidate_cmd) = + reparent_circuit_command(&old_cmd, new_parent_class_id, new_up_parent_class_id) + else { + continue; + }; + let enriched_cmd = rotate_changed_qdisc_handles( + old_cmd.as_ref(), + &candidate_cmd, + config, + layout, + qdisc_handles, + ); + + if queue_live_migration( + old_cmd.as_ref(), + &enriched_cmd, + circuits, + live_circuits, + migrations, + ) { + continue; + } + + let BakeryCommands::AddCircuit { circuit_hash, .. } = enriched_cmd.as_ref() else { + continue; + }; + let was_activated = live_circuits.contains_key(circuit_hash); + if was_activated { + return Err(format!( + "Bakery runtime virtualization could not live-migrate active circuit {}", + circuit_hash + )); + } + + match config.queues.lazy_queues.as_ref() { + None | Some(LazyQueueMode::No) => { + if let Some(prune) = old_cmd.to_prune(config, true) { + immediate_commands.extend(prune); + } + if let Some(add) = enriched_cmd.to_commands(config, ExecutionMode::Builder) { + immediate_commands.extend(add); + } + } + Some(LazyQueueMode::Htb) => { + if let Some(prune) = old_cmd.to_prune(config, true) { + immediate_commands.extend(prune); + } + if let Some(add_htb) = enriched_cmd.to_commands(config, ExecutionMode::Builder) { + immediate_commands.extend(add_htb); + } + } + Some(LazyQueueMode::Full) => {} + } + updated_circuits.push((*circuit_hash, enriched_cmd)); + } + + if !immediate_commands.is_empty() { + let result = execute_and_record_live_change( + &immediate_commands, + "TreeGuard runtime circuit reparent", + ); + if !result.ok { + return Err(summarize_apply_result( + "TreeGuard runtime circuit reparent", + &result, + )); + } + } + + for (circuit_hash, command) in updated_circuits { + circuits.insert(circuit_hash, command); + } + + Ok(()) +} + +#[derive(Clone, Debug)] +struct PlannedSiteUpdate { + queue: u32, + parent_site: Option, + command: Arc, +} + +#[derive(Clone, Debug)] +struct PlannedCircuitUpdate { + queue: u32, + parent_site: Option, + command: Arc, +} + +#[derive(Clone, Debug)] +struct TopLevelVirtualizationPlan { + saved_sites: HashMap>, + saved_circuits: HashMap>, + active_sites: HashMap, + active_circuits: HashMap, +} + +fn site_hash_from_command(site: &BakeryCommands) -> Option { + if let BakeryCommands::AddSite { site_hash, .. } = site { + Some(*site_hash) + } else { + None + } +} + +fn circuit_hash_from_command(circuit: &BakeryCommands) -> Option { + if let BakeryCommands::AddCircuit { circuit_hash, .. } = circuit { + Some(*circuit_hash) + } else { + None + } +} + +fn site_max_weight(site: &BakeryCommands) -> f64 { + if let BakeryCommands::AddSite { + download_bandwidth_max, + upload_bandwidth_max, + .. + } = site + { + f64::from(*download_bandwidth_max + *upload_bandwidth_max) + } else { + 1.0 + } +} + +fn circuit_max_weight(circuit: &BakeryCommands) -> f64 { + if let BakeryCommands::AddCircuit { + download_bandwidth_max, + upload_bandwidth_max, + .. + } = circuit + { + f64::from(*download_bandwidth_max + *upload_bandwidth_max) + } else { + 1.0 + } +} + +fn current_site_queue(site: &BakeryCommands) -> Option { + let BakeryCommands::AddSite { + parent_class_id, + class_minor, + .. + } = site + else { + return None; + }; + let (major, _) = parent_class_id.get_major_minor(); + let class_handle = tc_handle_from_major_minor(major, *class_minor); + Some(u32::from(class_handle.get_major_minor().0)) +} + +fn current_circuit_queue(circuit: &BakeryCommands) -> Option { + let BakeryCommands::AddCircuit { class_major, .. } = circuit else { + return None; + }; + Some(u32::from(*class_major)) +} + +fn site_parent_hash( + site_hash: i64, + sites: &HashMap>, + class_to_site: &HashMap<(TcHandle, TcHandle), i64>, +) -> Option { + let site = sites.get(&site_hash)?; + let BakeryCommands::AddSite { + parent_class_id, + up_parent_class_id, + .. + } = site.as_ref() + else { + return None; + }; + class_to_site + .get(&(*parent_class_id, *up_parent_class_id)) + .copied() +} + +fn direct_child_sites_by_parent( + sites: &HashMap>, +) -> HashMap> { + let mut class_to_site = HashMap::new(); + for (site_hash, site) in sites { + if let Some(handles) = site_class_handles(site.as_ref()) { + class_to_site.insert(handles, *site_hash); + } + } + + let mut result: HashMap> = HashMap::new(); + for site_hash in sites.keys().copied() { + if let Some(parent_hash) = site_parent_hash(site_hash, sites, &class_to_site) { + result.entry(parent_hash).or_default().push(site_hash); + } + } + for children in result.values_mut() { + children.sort_unstable(); + } + result +} + +fn collect_site_subtree_hashes( + root_hash: i64, + children_by_parent: &HashMap>, +) -> Vec { + let mut ordered = Vec::new(); + let mut stack = vec![root_hash]; + while let Some(site_hash) = stack.pop() { + ordered.push(site_hash); + if let Some(children) = children_by_parent.get(&site_hash) { + for child in children.iter().rev() { + stack.push(*child); + } + } + } + ordered +} + +fn collect_circuits_attached_to_sites( + circuits: &HashMap>, + sites: &HashMap>, + site_hashes: &[i64], +) -> Vec { + let mut site_handles = HashSet::new(); + for site_hash in site_hashes { + if let Some(site) = sites.get(site_hash) + && let Some(handles) = site_class_handles(site.as_ref()) + { + site_handles.insert(handles); + } + } + + let mut result: Vec = circuits + .iter() + .filter_map(|(circuit_hash, circuit)| { + let BakeryCommands::AddCircuit { + parent_class_id, + up_parent_class_id, + .. + } = circuit.as_ref() + else { + return None; + }; + site_handles + .contains(&(*parent_class_id, *up_parent_class_id)) + .then_some(*circuit_hash) + }) + .collect(); + result.sort_unstable(); + result +} + +fn root_handle_for_queue(queue: u32) -> TcHandle { + TcHandle::from_u32(queue << 16) +} + +fn site_stick_offset(site: &BakeryCommands) -> u16 { + let BakeryCommands::AddSite { + parent_class_id, + up_parent_class_id, + .. + } = site + else { + return 0; + }; + let (down_major, _) = parent_class_id.get_major_minor(); + let (up_major, _) = up_parent_class_id.get_major_minor(); + up_major.saturating_sub(down_major) +} + +fn top_level_bin_name(queue: u32) -> String { + format!("CpueQueue{}", queue.saturating_sub(1)) +} + +fn queue_from_bin_name(name: &str) -> Option { + name.strip_prefix("CpueQueue") + .and_then(|v| v.parse::().ok()) + .map(|cpu| cpu + 1) +} + +fn planner_site_key(site_hash: i64) -> String { + format!("site:{site_hash}") +} + +fn planner_circuit_key(circuit_hash: i64) -> String { + format!("circuit:{circuit_hash}") +} + +fn build_current_planner_state( + sites: &HashMap>, + circuits: &HashMap>, +) -> ( + BTreeMap, + BTreeMap, +) { + let mut class_to_site = HashMap::new(); + for (site_hash, site) in sites { + if let Some(handles) = site_class_handles(site.as_ref()) { + class_to_site.insert(handles, *site_hash); + } + } + + let mut previous_sites = BTreeMap::new(); + for (site_hash, site) in sites { + let Some(queue) = current_site_queue(site.as_ref()) else { + continue; + }; + let Some(class_minor) = (if let BakeryCommands::AddSite { class_minor, .. } = site.as_ref() { + Some(*class_minor) + } else { + None + }) else { + continue; + }; + let parent_path = site_parent_hash(*site_hash, sites, &class_to_site) + .map(planner_site_key) + .unwrap_or_default(); + previous_sites.insert( + planner_site_key(*site_hash), + PlannerSiteIdentityState { + class_minor, + queue, + parent_path, + class_major: queue as u16, + up_class_major: 0, + }, + ); + } + + let mut previous_circuits = BTreeMap::new(); + for (circuit_hash, circuit) in circuits { + let BakeryCommands::AddCircuit { + class_minor, + class_major, + up_class_major, + parent_class_id, + up_parent_class_id, + .. + } = circuit.as_ref() + else { + continue; + }; + let parent_node = class_to_site + .get(&(*parent_class_id, *up_parent_class_id)) + .map(|site_hash| planner_site_key(*site_hash)) + .unwrap_or_else(|| format!("root:{}", class_major)); + previous_circuits.insert( + planner_circuit_key(*circuit_hash), + PlannerCircuitIdentityState { + class_minor: *class_minor, + queue: u32::from(*class_major), + parent_node, + class_major: *class_major, + up_class_major: *up_class_major, + }, + ); + } + + (previous_sites, previous_circuits) +} + +fn top_level_site_hashes(sites: &HashMap>) -> Vec { + let mut hashes: Vec = sites + .iter() + .filter_map(|(site_hash, site)| site_is_top_level(site.as_ref()).then_some(*site_hash)) + .collect(); + hashes.sort_unstable(); + hashes +} + +fn site_descendant_depth( + site_hash: i64, + parents: &HashMap>, +) -> usize { + let mut depth = 0usize; + let mut current = parents.get(&site_hash).copied().flatten(); + while let Some(parent) = current { + depth += 1; + current = parents.get(&parent).copied().flatten(); + } + depth +} + +fn build_top_level_virtualization_plan( + target_site: Arc, + sites: &HashMap>, + circuits: &HashMap>, + stick_offset: u16, +) -> Result { + let Some(target_site_hash) = site_hash_from_command(target_site.as_ref()) else { + return Err("TreeGuard top-level virtualization target is not a site".to_string()); + }; + if !site_is_top_level(target_site.as_ref()) { + return Err(format!( + "Site {} is not top-level and should use the v1 same-queue runtime virtualization path", + target_site_hash + )); + } + + let children_by_parent = direct_child_sites_by_parent(sites); + let Some((target_down_class, target_up_class)) = site_class_handles(target_site.as_ref()) else { + return Err(format!("Site {} is not a valid AddSite command", target_site_hash)); + }; + + let promoted_site_roots = children_by_parent + .get(&target_site_hash) + .cloned() + .unwrap_or_default(); + let direct_circuits = collect_direct_circuit_hashes(circuits, target_down_class, target_up_class); + let top_level_sites = top_level_site_hashes(sites); + + let bins: Vec = top_level_sites + .iter() + .filter_map(|site_hash| { + sites.get(site_hash) + .and_then(|site| current_site_queue(site.as_ref())) + .map(top_level_bin_name) + }) + .collect::>() + .into_iter() + .collect(); + if bins.is_empty() { + return Err("No top-level queues available for runtime top-level virtualization".to_string()); + } + + let target_queue = current_site_queue(target_site.as_ref()).unwrap_or(1); + let mut planner_items = Vec::new(); + let mut prev_assign = BTreeMap::new(); + for site_hash in &top_level_sites { + if *site_hash == target_site_hash { + continue; + } + let Some(site) = sites.get(site_hash) else { + continue; + }; + let Some(queue) = current_site_queue(site.as_ref()) else { + continue; + }; + let id = planner_site_key(*site_hash); + planner_items.push(TopLevelPlannerItem { + id: id.clone(), + weight: site_max_weight(site.as_ref()), + }); + prev_assign.insert(id, top_level_bin_name(queue)); + } + for site_hash in &promoted_site_roots { + let Some(site) = sites.get(site_hash) else { + continue; + }; + let id = planner_site_key(*site_hash); + planner_items.push(TopLevelPlannerItem { + id: id.clone(), + weight: site_max_weight(site.as_ref()), + }); + prev_assign.insert(id, top_level_bin_name(target_queue)); + } + for circuit_hash in &direct_circuits { + let Some(circuit) = circuits.get(circuit_hash) else { + continue; + }; + let id = planner_circuit_key(*circuit_hash); + planner_items.push(TopLevelPlannerItem { + id: id.clone(), + weight: circuit_max_weight(circuit.as_ref()), + }); + prev_assign.insert(id, top_level_bin_name(target_queue)); + } + + let planner = plan_top_level_assignments( + &planner_items, + &bins, + &prev_assign, + &BTreeMap::new(), + current_timestamp() as f64, + &TopLevelPlannerParams { + mode: TopLevelPlannerMode::StableGreedy, + move_budget_per_run: std::cmp::max(1, std::cmp::min(32, planner_items.len())), + ..TopLevelPlannerParams::default() + }, + ); + + let mut future_top_level_roots = Vec::new(); + for site_hash in &top_level_sites { + if *site_hash != target_site_hash { + future_top_level_roots.push(*site_hash); + } + } + future_top_level_roots.extend(promoted_site_roots.iter().copied()); + future_top_level_roots.sort_unstable(); + + let mut future_top_level_queue = HashMap::new(); + for site_hash in &future_top_level_roots { + let key = planner_site_key(*site_hash); + let assigned = planner + .assignment + .get(&key) + .or_else(|| prev_assign.get(&key)) + .ok_or_else(|| format!("Planner did not assign top-level site {}", site_hash))?; + let queue = queue_from_bin_name(assigned) + .ok_or_else(|| format!("Invalid planner queue assignment {}", assigned))?; + future_top_level_queue.insert(*site_hash, queue); + } + + let mut moved_top_level_roots = Vec::new(); + for site_hash in &future_top_level_roots { + let Some(site) = sites.get(site_hash) else { + continue; + }; + let current_queue = current_site_queue(site.as_ref()).unwrap_or(1); + let new_queue = future_top_level_queue + .get(site_hash) + .copied() + .unwrap_or(current_queue); + if *site_hash == target_site_hash + || promoted_site_roots.contains(site_hash) + || new_queue != current_queue + { + moved_top_level_roots.push(*site_hash); + } + } + moved_top_level_roots.sort_unstable(); + moved_top_level_roots.dedup(); + + let mut saved_sites = HashMap::new(); + let mut saved_circuits = HashMap::new(); + let mut affected_site_hashes = HashSet::new(); + for site_hash in &moved_top_level_roots { + for hash in collect_site_subtree_hashes(*site_hash, &children_by_parent) { + affected_site_hashes.insert(hash); + } + } + for site_hash in &affected_site_hashes { + if let Some(site) = sites.get(site_hash) { + saved_sites.insert(*site_hash, Arc::clone(site)); + } + } + let affected_site_hashes_vec: Vec = affected_site_hashes.iter().copied().collect(); + for circuit_hash in collect_circuits_attached_to_sites(circuits, sites, &affected_site_hashes_vec) { + if let Some(circuit) = circuits.get(&circuit_hash) { + saved_circuits.insert(circuit_hash, Arc::clone(circuit)); + } + } + for circuit_hash in &direct_circuits { + if let Some(circuit) = circuits.get(circuit_hash) { + saved_circuits.insert(*circuit_hash, Arc::clone(circuit)); + } + } + + let (previous_sites, previous_circuits) = build_current_planner_state(sites, circuits); + + let mut future_parent_by_site: HashMap> = HashMap::new(); + for site_hash in &future_top_level_roots { + future_parent_by_site.insert(*site_hash, None); + } + for site_hash in &affected_site_hashes { + if future_parent_by_site.contains_key(site_hash) { + continue; + } + let parent_hash = site_parent_hash(*site_hash, sites, &{ + let mut class_to_site = HashMap::new(); + for (hash, site) in sites { + if let Some(handles) = site_class_handles(site.as_ref()) { + class_to_site.insert(handles, *hash); + } + } + class_to_site + }); + future_parent_by_site.insert(*site_hash, parent_hash); + } + + let mut planner_site_inputs = Vec::new(); + let mut planner_site_hashes: Vec = sites.keys().copied().filter(|hash| *hash != target_site_hash).collect(); + planner_site_hashes.sort_by_key(|hash| { + ( + site_descendant_depth(*hash, &future_parent_by_site), + *hash, + ) + }); + for site_hash in &planner_site_hashes { + let Some(site) = sites.get(site_hash) else { + continue; + }; + let queue = if let Some(root_queue) = future_top_level_queue.get(site_hash) { + *root_queue + } else { + let mut cursor = *site_hash; + loop { + let Some(parent) = future_parent_by_site.get(&cursor).copied().flatten() else { + break future_top_level_queue.get(&cursor).copied().unwrap_or(1); + }; + cursor = parent; + } + }; + let parent_path = future_parent_by_site + .get(site_hash) + .copied() + .flatten() + .map(planner_site_key) + .unwrap_or_default(); + let has_children = children_by_parent + .get(site_hash) + .map(|children| !children.is_empty()) + .unwrap_or(false); + planner_site_inputs.push(SiteIdentityInput { + site_key: planner_site_key(*site_hash), + parent_path, + queue, + has_children, + }); + let _ = site; + } + + let class_to_site = { + let mut m = HashMap::new(); + for (hash, site) in sites { + if let Some(handles) = site_class_handles(site.as_ref()) { + m.insert(handles, *hash); + } + } + m + }; + + let mut circuit_ids_by_parent: BTreeMap> = BTreeMap::new(); + for (circuit_hash, circuit) in circuits { + let BakeryCommands::AddCircuit { + parent_class_id, + up_parent_class_id, + .. + } = circuit.as_ref() + else { + continue; + }; + if *parent_class_id == target_down_class && *up_parent_class_id == target_up_class { + continue; + } + let parent = class_to_site + .get(&(*parent_class_id, *up_parent_class_id)) + .map(|site_hash| planner_site_key(*site_hash)) + .unwrap_or_else(|| format!("root:{}", current_circuit_queue(circuit.as_ref()).unwrap_or(1))); + circuit_ids_by_parent + .entry(parent) + .or_default() + .push(planner_circuit_key(*circuit_hash)); + } + for circuit_hash in &direct_circuits { + let id = planner_circuit_key(*circuit_hash); + let assigned = planner + .assignment + .get(&id) + .or_else(|| prev_assign.get(&id)) + .ok_or_else(|| format!("Planner did not assign direct circuit {}", circuit_hash))?; + let queue = queue_from_bin_name(assigned) + .ok_or_else(|| format!("Invalid planner queue assignment {}", assigned))?; + circuit_ids_by_parent + .entry(format!("root:{queue}")) + .or_default() + .push(id); + } + + let mut planner_circuit_groups = Vec::new(); + for (parent_node, mut circuit_ids) in circuit_ids_by_parent { + circuit_ids.sort(); + let queue = if let Some(root) = parent_node.strip_prefix("root:") { + root.parse::().unwrap_or(1) + } else if let Some(site_hash) = parent_node.strip_prefix("site:").and_then(|s| s.parse::().ok()) { + planner_site_inputs + .iter() + .find(|site| site.site_key == planner_site_key(site_hash)) + .map(|site| site.queue) + .unwrap_or(1) + } else { + 1 + }; + planner_circuit_groups.push(CircuitIdentityGroupInput { + parent_node, + queue, + circuit_ids, + }); + } + + let identity = plan_class_identities( + &planner_site_inputs, + &planner_circuit_groups, + &previous_sites, + &previous_circuits, + stick_offset, + 0, + ); + let site_identity_by_key: HashMap = identity + .sites + .iter() + .map(|entry| (entry.site_key.clone(), entry.clone())) + .collect(); + let circuit_identity_by_key: HashMap = identity + .circuits + .iter() + .map(|entry| (entry.circuit_id.clone(), entry.clone())) + .collect(); + + let mut active_sites = HashMap::new(); + for site_hash in &planner_site_hashes { + let Some(old_site) = sites.get(site_hash) else { + continue; + }; + let site_key = planner_site_key(*site_hash); + let Some(identity_entry) = site_identity_by_key.get(&site_key) else { + continue; + }; + let parent_handles = future_parent_by_site + .get(site_hash) + .copied() + .flatten() + .and_then(|parent_hash| { + site_identity_by_key.get(&planner_site_key(parent_hash)).map(|parent_identity| { + ( + tc_handle_from_major_minor(parent_identity.class_major, parent_identity.class_minor), + tc_handle_from_major_minor(parent_identity.up_class_major, parent_identity.class_minor), + ) + }) + }) + .unwrap_or_else(|| { + ( + root_handle_for_queue(identity_entry.queue), + root_handle_for_queue(u32::from(identity_entry.up_class_major)), + ) + }); + let BakeryCommands::AddSite { + site_hash, + download_bandwidth_min, + upload_bandwidth_min, + download_bandwidth_max, + upload_bandwidth_max, + .. + } = old_site.as_ref() + else { + continue; + }; + active_sites.insert( + *site_hash, + PlannedSiteUpdate { + queue: identity_entry.queue, + parent_site: future_parent_by_site.get(site_hash).copied().flatten(), + command: Arc::new(BakeryCommands::AddSite { + site_hash: *site_hash, + parent_class_id: parent_handles.0, + up_parent_class_id: parent_handles.1, + class_minor: identity_entry.class_minor, + download_bandwidth_min: *download_bandwidth_min, + upload_bandwidth_min: *upload_bandwidth_min, + download_bandwidth_max: *download_bandwidth_max, + upload_bandwidth_max: *upload_bandwidth_max, + }), + }, + ); + } + + let mut active_circuits = HashMap::new(); + for (circuit_hash, circuit) in circuits { + let circuit_key = planner_circuit_key(*circuit_hash); + let Some(identity_entry) = circuit_identity_by_key.get(&circuit_key) else { + continue; + }; + let parent_site = previous_circuits + .get(&circuit_key) + .and_then(|prev| prev.parent_node.strip_prefix("site:")) + .and_then(|s| s.parse::().ok()); + let future_parent_site = if direct_circuits.contains(circuit_hash) { + None + } else { + class_to_site + .get(&{ + let BakeryCommands::AddCircuit { + parent_class_id, + up_parent_class_id, + .. + } = circuit.as_ref() + else { + continue; + }; + (*parent_class_id, *up_parent_class_id) + }) + .copied() + }; + let parent_handles = if let Some(parent_site_hash) = future_parent_site { + if let Some(parent_identity) = site_identity_by_key.get(&planner_site_key(parent_site_hash)) { + ( + tc_handle_from_major_minor(parent_identity.class_major, parent_identity.class_minor), + tc_handle_from_major_minor(parent_identity.up_class_major, parent_identity.class_minor), + ) + } else { + ( + root_handle_for_queue(identity_entry.queue), + root_handle_for_queue(u32::from(identity_entry.up_class_major)), + ) + } + } else { + ( + root_handle_for_queue(identity_entry.queue), + root_handle_for_queue(u32::from(identity_entry.up_class_major)), + ) + }; + let BakeryCommands::AddCircuit { + circuit_hash, + download_bandwidth_min, + upload_bandwidth_min, + download_bandwidth_max, + upload_bandwidth_max, + ip_addresses, + sqm_override, + .. + } = circuit.as_ref() + else { + continue; + }; + active_circuits.insert( + *circuit_hash, + PlannedCircuitUpdate { + queue: identity_entry.queue, + parent_site: future_parent_site.or(parent_site), + command: Arc::new(BakeryCommands::AddCircuit { + circuit_hash: *circuit_hash, + parent_class_id: parent_handles.0, + up_parent_class_id: parent_handles.1, + class_minor: identity_entry.class_minor, + download_bandwidth_min: *download_bandwidth_min, + upload_bandwidth_min: *upload_bandwidth_min, + download_bandwidth_max: *download_bandwidth_max, + upload_bandwidth_max: *upload_bandwidth_max, + class_major: identity_entry.class_major, + up_class_major: identity_entry.up_class_major, + down_qdisc_handle: None, + up_qdisc_handle: None, + ip_addresses: ip_addresses.clone(), + sqm_override: sqm_override.clone(), + }), + }, + ); + } + active_circuits.retain(|hash, _| saved_circuits.contains_key(hash)); + + Ok(TopLevelVirtualizationPlan { + saved_sites, + saved_circuits, + active_sites, + active_circuits, + }) +} + +fn apply_site_command_updates( + config: &Arc, + sites: &mut HashMap>, + updates: &HashMap, + action_label: &str, +) -> Result<(), String> { + if updates.is_empty() { + return Ok(()); + } + let mut ordered: Vec<_> = updates.iter().collect(); + ordered.sort_by_key(|(_, update)| { + ( + update.parent_site.is_some(), + update.queue, + update.parent_site.unwrap_or_default(), + site_hash_from_command(update.command.as_ref()).unwrap_or_default(), + ) + }); + let mut commands = Vec::new(); + for (_, update) in &ordered { + if let Some(cmds) = update.command.to_commands(config, ExecutionMode::Builder) { + commands.extend(cmds); + } + } + if !commands.is_empty() { + let result = execute_and_record_live_change(&commands, action_label); + if !result.ok { + return Err(summarize_apply_result(action_label, &result)); + } + } + for (site_hash, update) in ordered { + sites.insert(*site_hash, Arc::clone(&update.command)); + } + Ok(()) +} + +fn apply_circuit_command_updates( + config: &Arc, + circuits: &mut HashMap>, + updates: &HashMap, + live_circuits: &HashMap, + mq_layout: &Option, + qdisc_handles: &mut QdiscHandleState, + migrations: &mut HashMap, + action_label: &str, +) -> Result<(), String> { + if updates.is_empty() { + return Ok(()); + } + let Some(layout) = mq_layout.as_ref() else { + return Err("Bakery runtime virtualization requires MQ layout to be available".to_string()); + }; + let mut immediate_commands = Vec::new(); + let mut updated_circuits = Vec::new(); + let mut ordered: Vec<_> = updates.iter().collect(); + ordered.sort_by_key(|(_, update)| { + ( + update.parent_site.is_none(), + update.queue, + update.parent_site.unwrap_or_default(), + circuit_hash_from_command(update.command.as_ref()).unwrap_or_default(), + ) + }); + + for (circuit_hash, update) in ordered { + let Some(old_cmd) = circuits.get(circuit_hash).cloned() else { + continue; + }; + let enriched_cmd = rotate_changed_qdisc_handles( + old_cmd.as_ref(), + &update.command, + config, + layout, + qdisc_handles, + ); + if live_circuits.contains_key(circuit_hash) + && let BakeryCommands::AddCircuit { + parent_class_id, + up_parent_class_id, + .. + } = enriched_cmd.as_ref() + && find_free_minor(circuits, parent_class_id, up_parent_class_id).is_none() + { + return Err(format!( + "Unable to queue live migration for active circuit {}: no shadow minor available", + circuit_hash + )); + } + if queue_live_migration( + old_cmd.as_ref(), + &enriched_cmd, + circuits, + live_circuits, + migrations, + ) { + continue; + } + if live_circuits.contains_key(circuit_hash) { + return Err(format!( + "Bakery runtime virtualization could not live-migrate active circuit {}", + circuit_hash + )); + } + match config.queues.lazy_queues.as_ref() { + None | Some(LazyQueueMode::No) | Some(LazyQueueMode::Htb) => { + if let Some(prune) = old_cmd.to_prune(config, true) { + immediate_commands.extend(prune); + } + if let Some(add) = enriched_cmd.to_commands(config, ExecutionMode::Builder) { + immediate_commands.extend(add); + } + } + Some(LazyQueueMode::Full) => {} + } + updated_circuits.push((*circuit_hash, enriched_cmd)); + } + + if !immediate_commands.is_empty() { + let result = execute_and_record_live_change(&immediate_commands, action_label); + if !result.ok { + return Err(summarize_apply_result(action_label, &result)); + } + } + for (circuit_hash, command) in updated_circuits { + circuits.insert(circuit_hash, command); + } + Ok(()) +} + +fn apply_runtime_virtualization_overlay( + batch: Vec>, + virtualized_sites: &HashMap, +) -> Vec> { + if virtualized_sites.is_empty() { + return batch; + } + + let mut hidden_site_hashes = HashSet::new(); + let mut active_site_overrides: HashMap> = HashMap::new(); + let mut active_circuit_overrides: HashMap> = HashMap::new(); + for (site_hash, state) in virtualized_sites { + hidden_site_hashes.insert(*site_hash); + for (hash, command) in &state.active_sites { + active_site_overrides.insert(*hash, Arc::clone(command)); + } + for (hash, command) in &state.active_circuits { + active_circuit_overrides.insert(*hash, Arc::clone(command)); + } + } + + batch + .into_iter() + .filter_map(|command| match command.as_ref() { + BakeryCommands::AddSite { site_hash, .. } => { + if hidden_site_hashes.contains(site_hash) { + return None; + } + if let Some(override_cmd) = active_site_overrides.get(site_hash) { + return Some(Arc::clone(override_cmd)); + } + Some(command) + } + BakeryCommands::AddCircuit { circuit_hash, .. } => { + if let Some(override_cmd) = active_circuit_overrides.get(circuit_hash) { + return Some(Arc::clone(override_cmd)); + } + Some(command) + } + _ => Some(command), + }) + .collect() +} + +#[allow(clippy::too_many_arguments)] +fn handle_treeguard_set_node_virtual_live( + site_hash: i64, + virtualized: bool, + sites: &mut HashMap>, + circuits: &mut HashMap>, + live_circuits: &HashMap, + mq_layout: &Option, + qdisc_handles: &mut QdiscHandleState, + migrations: &mut HashMap, + virtualized_sites: &mut HashMap, +) -> Result<(), String> { + let Ok(config) = lqos_config::load_config() else { + return Err("Failed to load configuration".to_string()); + }; + + if virtualized { + if virtualized_sites.contains_key(&site_hash) { + return Ok(()); + } + + let Some(target_site) = sites.get(&site_hash).cloned() else { + return Err(format!("Unknown site hash {}", site_hash)); + }; + if site_is_top_level(target_site.as_ref()) { + let plan = build_top_level_virtualization_plan( + Arc::clone(&target_site), + sites, + circuits, + site_stick_offset(target_site.as_ref()), + )?; + apply_site_command_updates( + &config, + sites, + &plan.active_sites, + "TreeGuard runtime top-level site reparent", + )?; + apply_circuit_command_updates( + &config, + circuits, + &plan.active_circuits, + live_circuits, + mq_layout, + qdisc_handles, + migrations, + "TreeGuard runtime top-level circuit reparent", + )?; + if let Some(prune) = site_prune_commands(&config, target_site.as_ref()) { + let result = + execute_and_record_live_change(&prune, "TreeGuard runtime top-level site prune"); + if !result.ok { + return Err(summarize_apply_result( + "TreeGuard runtime top-level site prune", + &result, + )); + } + } + sites.remove(&site_hash); + virtualized_sites.insert( + site_hash, + VirtualizedSiteState { + site: target_site, + saved_sites: plan.saved_sites, + saved_circuits: plan.saved_circuits, + active_sites: plan + .active_sites + .into_iter() + .map(|(hash, update)| (hash, update.command)) + .collect(), + active_circuits: plan + .active_circuits + .into_iter() + .map(|(hash, update)| (hash, update.command)) + .collect(), + }, + ); + return Ok(()); + } + + if let Some(reason) = site_runtime_virtualization_eligibility_error(target_site.as_ref()) { + return Err(reason); + } + let Some((target_down_class, target_up_class)) = site_class_handles(target_site.as_ref()) + else { + return Err(format!("Site {} is not a valid AddSite command", site_hash)); + }; + let BakeryCommands::AddSite { + parent_class_id, + up_parent_class_id, + .. + } = target_site.as_ref() + else { + return Err(format!("Site {} is not a valid AddSite command", site_hash)); + }; + + let child_sites = + collect_direct_child_site_hashes(sites, target_down_class, target_up_class, site_hash); + let direct_circuits = + collect_direct_circuit_hashes(circuits, target_down_class, target_up_class); + let saved_sites: HashMap> = child_sites + .iter() + .filter_map(|hash| sites.get(hash).cloned().map(|cmd| (*hash, cmd))) + .collect(); + let saved_circuits: HashMap> = direct_circuits + .iter() + .filter_map(|hash| circuits.get(hash).cloned().map(|cmd| (*hash, cmd))) + .collect(); + + let mut active_sites = HashMap::new(); + for child_hash in &child_sites { + let Some(child_site) = sites.get(child_hash).cloned() else { + continue; + }; + let Some(updated_site) = + reparent_site_command(&child_site, *parent_class_id, *up_parent_class_id) + else { + continue; + }; + active_sites.insert( + *child_hash, + PlannedSiteUpdate { + queue: current_site_queue(updated_site.as_ref()).unwrap_or(1), + parent_site: Some(site_hash), + command: updated_site, + }, + ); + } + apply_site_command_updates( + &config, + sites, + &active_sites, + "TreeGuard runtime site reparent", + )?; + + apply_direct_circuit_reparents( + &config, + &direct_circuits, + *parent_class_id, + *up_parent_class_id, + circuits, + live_circuits, + mq_layout, + qdisc_handles, + migrations, + )?; + + if let Some(prune) = site_prune_commands(&config, target_site.as_ref()) { + let result = execute_and_record_live_change(&prune, "TreeGuard runtime site prune"); + if !result.ok { + return Err(summarize_apply_result( + "TreeGuard runtime site prune", + &result, + )); + } + } + sites.remove(&site_hash); + virtualized_sites.insert( + site_hash, + VirtualizedSiteState { + site: target_site, + saved_sites, + saved_circuits, + active_sites: active_sites + .into_iter() + .map(|(hash, update)| (hash, update.command)) + .collect(), + active_circuits: direct_circuits + .iter() + .filter_map(|hash| circuits.get(hash).cloned().map(|cmd| (*hash, cmd))) + .collect(), + }, + ); + return Ok(()); + } + + let Some(saved_state) = virtualized_sites.get(&site_hash).cloned() else { + return Ok(()); + }; + if !site_is_top_level(saved_state.site.as_ref()) + && let Some(reason) = site_runtime_virtualization_eligibility_error(saved_state.site.as_ref()) + { + return Err(reason); + } + + if let Some(cmds) = saved_state.site.to_commands(&config, ExecutionMode::Builder) { + let result = execute_and_record_live_change(&cmds, "TreeGuard runtime hidden site restore"); + if !result.ok { + return Err(summarize_apply_result( + "TreeGuard runtime hidden site restore", + &result, + )); + } + } + sites.insert(site_hash, saved_state.site.clone()); + + let restore_sites: HashMap = saved_state + .saved_sites + .iter() + .map(|(hash, command)| { + ( + *hash, + PlannedSiteUpdate { + queue: current_site_queue(command.as_ref()).unwrap_or(1), + parent_site: None, + command: Arc::clone(command), + }, + ) + }) + .collect(); + apply_site_command_updates( + &config, + sites, + &restore_sites, + "TreeGuard runtime site restore", + )?; + + let restore_circuits: HashMap = saved_state + .saved_circuits + .iter() + .map(|(hash, command)| { + ( + *hash, + PlannedCircuitUpdate { + queue: current_circuit_queue(command.as_ref()).unwrap_or(1), + parent_site: None, + command: Arc::clone(command), + }, + ) + }) + .collect(); + apply_circuit_command_updates( + &config, + circuits, + &restore_circuits, + live_circuits, + mq_layout, + qdisc_handles, + migrations, + "TreeGuard runtime circuit restore", + )?; + + virtualized_sites.remove(&site_hash); + Ok(()) +} + +#[allow(clippy::too_many_arguments)] +fn full_reload( + batch: &mut Option>>, + sites: &mut HashMap>, + circuits: &mut HashMap>, + live_circuits: &mut HashMap, + mq_layout: &mut Option, + qdisc_handles: &mut QdiscHandleState, + config: &Arc, + new_batch: Vec>, + resolved_mq_layout: Option, + stormguard_overrides: &HashMap, +) { + warn!("Bakery: Full reload triggered due to site or circuit changes."); + FULL_RELOAD_IN_PROGRESS.store(true, Ordering::Relaxed); + mark_bakery_action_started( + BakeryMode::ApplyingFullReload, + "full_reload_started", + "Full reload triggered due to site or circuit changes.".to_string(), + ); + let _reload_scope = FullReloadScope; + let previous_sites = sites.clone(); + let previous_circuits = circuits.clone(); + let previous_live_circuits = live_circuits.clone(); + let previous_mq_layout = mq_layout.clone(); + + let live_reserved_handles = match snapshot_live_qdisc_handle_majors(config) { + Ok(handles) => handles, + Err(error) => { + let summary = + format!("Failed to snapshot live qdisc handles before full reload: {error}"); + error!("{summary}"); + mark_bakery_action_finished(BakeryApplyMetrics { + apply_type: BakeryApplyType::FullReload, + summary: &summary, + build_duration_ms: 0, + apply_duration_ms: 0, + total_tc_commands: 0, + class_commands: 0, + qdisc_commands: 0, + ok: false, + }); + *batch = None; + return; + } + }; + + let mut working_sites = HashMap::new(); + let mut working_circuits = HashMap::new(); + let mut working_qdisc_handles = QdiscHandleState::default(); + let layout = resolved_mq_layout.clone().unwrap_or_default(); + if resolved_mq_layout.is_none() { + warn!("Bakery: full reload skipped MQ layout restore because layout is unknown"); + } + + let result = process_batch( + new_batch, + config, + &mut working_sites, + &mut working_circuits, + &layout, + &mut working_qdisc_handles, + &live_reserved_handles, + ); + + if result.ok { + *sites = working_sites; + *circuits = working_circuits; + live_circuits.clear(); + *qdisc_handles = working_qdisc_handles; + qdisc_handles.save(config); + if resolved_mq_layout.is_some() { + *mq_layout = resolved_mq_layout; + } + FIRST_COMMIT_APPLIED.store(true, Ordering::Relaxed); + apply_stormguard_overrides(stormguard_overrides, config); + } else { + *sites = previous_sites; + *circuits = previous_circuits; + *live_circuits = previous_live_circuits; + *mq_layout = previous_mq_layout; + } *batch = None; - apply_stormguard_overrides(stormguard_overrides, config); } fn process_batch( @@ -2578,29 +4628,23 @@ fn process_batch( config: &Arc, sites: &mut HashMap>, circuits: &mut HashMap>, - previous_circuits: &HashMap>, mq_layout: &MqDeviceLayout, qdisc_handles: &mut QdiscHandleState, -) { + extra_reserved_handles: &HashMap>, +) -> ExecuteResult { info!("Bakery: Processing batch of {} commands", batch.len()); + update_bakery_apply_progress(Some("Building tc command batch"), 0, 0, 0, 0); let build_started = std::time::Instant::now(); let mut circuit_count = 0u64; let commands = batch .into_iter() .map(|b| { - let enriched = with_assigned_qdisc_handles(&b, config, mq_layout, qdisc_handles); - let BakeryCommands::AddCircuit { circuit_hash, .. } = enriched.as_ref() else { - return enriched; - }; - let Some(previous) = previous_circuits.get(circuit_hash) else { - return enriched; - }; - rotate_changed_qdisc_handles( - previous.as_ref(), - &enriched, + with_assigned_qdisc_handles_reserved( + &b, config, mq_layout, qdisc_handles, + extra_reserved_handles, ) }) .filter_map(|b| { @@ -2624,8 +4668,35 @@ fn process_batch( write_command_file(&path, &commands); let build_duration_ms = build_started.elapsed().as_millis() as u64; let (total_tc_commands, class_commands, qdisc_commands) = count_tc_command_types(&commands); - let result = execute_in_memory(&commands, "processing batch"); + let total_chunks = if total_tc_commands == 0 { + 0 + } else { + total_tc_commands.div_ceil(FULL_RELOAD_TC_CHUNK_SIZE) + }; + update_bakery_apply_progress( + Some("Applying tc command chunks"), + total_tc_commands, + 0, + total_chunks, + 0, + ); + let result = execute_in_memory_chunked( + &commands, + "processing batch", + FULL_RELOAD_TC_CHUNK_SIZE, + Some(BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES), + |completed_tc_commands, total_tc_commands, completed_chunks, total_chunks| { + update_bakery_apply_progress( + Some("Applying tc command chunks"), + total_tc_commands, + completed_tc_commands, + total_chunks, + completed_chunks, + ); + }, + ); let summary = summarize_apply_result("processing batch", &result); + maybe_emit_memory_guard_urgent(&summary); mark_bakery_action_finished(BakeryApplyMetrics { apply_type: BakeryApplyType::FullReload, summary: &summary, @@ -2637,8 +4708,7 @@ fn process_batch( ok: result.ok, }); - // Mark that at least one batch has been applied, unblocking live activation. - FIRST_COMMIT_APPLIED.store(true, Ordering::Relaxed); + result } fn apply_stormguard_overrides( @@ -2700,6 +4770,24 @@ mod tests { }) } + fn mk_add_site( + site_hash: i64, + parent_class_id: u32, + up_parent_class_id: u32, + class_minor: u16, + ) -> Arc { + Arc::new(BakeryCommands::AddSite { + site_hash, + parent_class_id: TcHandle::from_u32(parent_class_id), + up_parent_class_id: TcHandle::from_u32(up_parent_class_id), + class_minor, + download_bandwidth_min: 10.0, + upload_bandwidth_min: 10.0, + download_bandwidth_max: 100.0, + upload_bandwidth_max: 100.0, + }) + } + fn test_config_with_runtime_dir(name: &str) -> Arc { let mut cfg = Config::default(); let ts = SystemTime::now() @@ -2712,6 +4800,33 @@ mod tests { Arc::new(cfg) } + fn mk_test_circuit( + circuit_hash: i64, + parent_class_id: u32, + up_parent_class_id: u32, + class_minor: u16, + class_major: u16, + up_class_major: u16, + ip_addresses: &str, + ) -> Arc { + Arc::new(BakeryCommands::AddCircuit { + circuit_hash, + parent_class_id: TcHandle::from_u32(parent_class_id), + up_parent_class_id: TcHandle::from_u32(up_parent_class_id), + class_minor, + download_bandwidth_min: 10.0, + upload_bandwidth_min: 10.0, + download_bandwidth_max: 100.0, + upload_bandwidth_max: 100.0, + class_major, + up_class_major, + down_qdisc_handle: Some(0x9000), + up_qdisc_handle: Some(0x9001), + ip_addresses: ip_addresses.to_string(), + sqm_override: None, + }) + } + fn has_hash(batch: &[Arc], hash: i64) -> bool { batch.iter().any(|cmd| { matches!( @@ -2784,6 +4899,205 @@ mod tests { assert_eq!(filtered.len(), 1001); } + #[test] + fn runtime_virtualization_overlay_hides_virtualized_site_and_reparents_children() { + let parent_site = mk_add_site(10, 0x10001, 0x20001, 0x20); + let virtualized_site = mk_add_site(20, 0x10020, 0x20020, 0x21); + let child_site = mk_add_site(30, 0x10021, 0x20021, 0x22); + let child_circuit = Arc::new(BakeryCommands::AddCircuit { + circuit_hash: 40, + parent_class_id: TcHandle::from_u32(0x10021), + up_parent_class_id: TcHandle::from_u32(0x20021), + class_minor: 0x30, + download_bandwidth_min: 10.0, + upload_bandwidth_min: 10.0, + download_bandwidth_max: 100.0, + upload_bandwidth_max: 100.0, + class_major: 0x110, + up_class_major: 0x210, + down_qdisc_handle: None, + up_qdisc_handle: None, + ip_addresses: "192.0.2.40/32".to_string(), + sqm_override: None, + }); + + let mut virtualized_sites = HashMap::new(); + virtualized_sites.insert( + 20, + VirtualizedSiteState { + site: virtualized_site.clone(), + saved_sites: HashMap::new(), + saved_circuits: HashMap::new(), + active_sites: HashMap::from([( + 30, + Arc::new(BakeryCommands::AddSite { + site_hash: 30, + parent_class_id: TcHandle::from_u32(0x10020), + up_parent_class_id: TcHandle::from_u32(0x20020), + class_minor: 0x22, + download_bandwidth_min: 50.0, + upload_bandwidth_min: 50.0, + download_bandwidth_max: 500.0, + upload_bandwidth_max: 500.0, + }), + )]), + active_circuits: HashMap::from([( + 40, + Arc::new(BakeryCommands::AddCircuit { + circuit_hash: 40, + parent_class_id: TcHandle::from_u32(0x10020), + up_parent_class_id: TcHandle::from_u32(0x20020), + class_minor: 0x30, + download_bandwidth_min: 10.0, + upload_bandwidth_min: 10.0, + download_bandwidth_max: 100.0, + upload_bandwidth_max: 100.0, + class_major: 0x110, + up_class_major: 0x210, + down_qdisc_handle: None, + up_qdisc_handle: None, + ip_addresses: "192.0.2.40/32".to_string(), + sqm_override: None, + }), + )]), + }, + ); + + let overlaid = apply_runtime_virtualization_overlay( + vec![parent_site, virtualized_site, child_site, child_circuit], + &virtualized_sites, + ); + + assert_eq!(overlaid.len(), 3); + assert!(!overlaid.iter().any(|cmd| matches!( + cmd.as_ref(), + BakeryCommands::AddSite { site_hash, .. } if *site_hash == 20 + ))); + + let child_site = overlaid + .iter() + .find_map(|cmd| match cmd.as_ref() { + BakeryCommands::AddSite { + site_hash, + parent_class_id, + up_parent_class_id, + .. + } if *site_hash == 30 => Some((*parent_class_id, *up_parent_class_id)), + _ => None, + }) + .expect("child site should remain in batch"); + assert_eq!(child_site.0, TcHandle::from_u32(0x10020)); + assert_eq!(child_site.1, TcHandle::from_u32(0x20020)); + + let child_circuit = overlaid + .iter() + .find_map(|cmd| match cmd.as_ref() { + BakeryCommands::AddCircuit { + circuit_hash, + parent_class_id, + up_parent_class_id, + .. + } if *circuit_hash == 40 => Some((*parent_class_id, *up_parent_class_id)), + _ => None, + }) + .expect("child circuit should remain in batch"); + assert_eq!(child_circuit.0, TcHandle::from_u32(0x10020)); + assert_eq!(child_circuit.1, TcHandle::from_u32(0x20020)); + } + + #[test] + fn top_level_virtualization_plan_promotes_children_and_direct_circuits() { + let target_site = mk_add_site(20, 0x10000, 0x20000, 0x21); + let sibling_site = mk_add_site(10, 0x10000, 0x20000, 0x20); + let child_site = mk_add_site(30, 0x10021, 0x20021, 0x22); + let grandchild_site = mk_add_site(31, 0x10022, 0x20022, 0x23); + let direct_circuit = Arc::new(BakeryCommands::AddCircuit { + circuit_hash: 40, + parent_class_id: TcHandle::from_u32(0x10021), + up_parent_class_id: TcHandle::from_u32(0x20021), + class_minor: 0x30, + download_bandwidth_min: 10.0, + upload_bandwidth_min: 10.0, + download_bandwidth_max: 100.0, + upload_bandwidth_max: 100.0, + class_major: 0x1, + up_class_major: 0x2, + down_qdisc_handle: None, + up_qdisc_handle: None, + ip_addresses: "192.0.2.40/32".to_string(), + sqm_override: None, + }); + + let mut sites = HashMap::new(); + sites.insert(10, sibling_site); + sites.insert(20, Arc::clone(&target_site)); + sites.insert(30, child_site); + sites.insert(31, grandchild_site); + + let mut circuits = HashMap::new(); + circuits.insert(40, direct_circuit); + + let plan = + build_top_level_virtualization_plan(Arc::clone(&target_site), &sites, &circuits, 1) + .expect("top-level plan should build"); + + assert!(plan.saved_sites.contains_key(&30)); + assert!(plan.saved_sites.contains_key(&31)); + assert!(plan.saved_circuits.contains_key(&40)); + + let promoted_site = plan + .active_sites + .get(&30) + .expect("promoted child site should be rewritten"); + let BakeryCommands::AddSite { + parent_class_id, + up_parent_class_id, + .. + } = promoted_site.command.as_ref() + else { + panic!("expected AddSite"); + }; + assert_eq!(parent_class_id.get_major_minor().1, 0); + assert_eq!(up_parent_class_id.get_major_minor().1, 0); + + let promoted_circuit = plan + .active_circuits + .get(&40) + .expect("direct circuit should be rewritten"); + let BakeryCommands::AddCircuit { + parent_class_id, + up_parent_class_id, + .. + } = promoted_circuit.command.as_ref() + else { + panic!("expected AddCircuit"); + }; + assert_eq!(parent_class_id.get_major_minor().1, 0); + assert_eq!(up_parent_class_id.get_major_minor().1, 0); + } + + #[test] + fn site_runtime_virtualization_rejects_top_level_sites() { + let site = mk_add_site(99, 0x10000, 0x20000, 0x21); + let reason = site_runtime_virtualization_eligibility_error(site.as_ref()) + .expect("top-level site should be rejected"); + assert!(reason.contains("top-level")); + } + + #[test] + fn site_runtime_virtualization_accepts_normal_same_queue_site() { + let site = mk_add_site(77, 0x10020, 0x20020, 0x22); + assert!(site_runtime_virtualization_eligibility_error(site.as_ref()).is_none()); + } + + #[test] + fn site_runtime_virtualization_rejects_non_site_commands() { + let circuit = mk_add_circuit(77, "192.0.2.77/32"); + let reason = site_runtime_virtualization_eligibility_error(circuit.as_ref()) + .expect("non-site commands should be rejected"); + assert!(reason.contains("AddSite command")); + } + #[test] fn mapped_circuit_limit_uses_custom_limit() { let existing = HashMap::new(); @@ -2859,6 +5173,34 @@ mod tests { let estimate = estimate_full_reload_auto_qdisc_budget(&config, &queue); assert_eq!(estimate.interfaces.get("eth1"), Some(&8)); assert_eq!(estimate.interfaces.get("eth0"), Some(&8)); + assert_eq!( + estimate + .interface_details + .get("eth0") + .map(|d| d.cake_qdiscs), + Some(1) + ); + assert_eq!( + estimate + .interface_details + .get("eth1") + .map(|d| d.cake_qdiscs), + Some(1) + ); + assert_eq!( + estimate + .interface_details + .get("eth0") + .map(|d| d.infra_qdiscs), + Some(7) + ); + assert_eq!( + estimate + .interface_details + .get("eth1") + .map(|d| d.infra_qdiscs), + Some(7) + ); assert!(estimate.ok()); } @@ -2893,6 +5235,70 @@ mod tests { let estimate = estimate_full_reload_auto_qdisc_budget(&config, &queue); assert_eq!(estimate.interfaces.get("eth1"), Some(&4)); assert_eq!(estimate.interfaces.get("eth0"), Some(&4)); + assert_eq!( + estimate + .interface_details + .get("eth0") + .map(|d| d.cake_qdiscs), + Some(0) + ); + assert_eq!( + estimate + .interface_details + .get("eth1") + .map(|d| d.cake_qdiscs), + Some(0) + ); + } + + #[test] + fn qdisc_budget_estimate_counts_fq_codel_leaf_qdiscs_separately() { + let config = Arc::new(Config::default()); + let queue = vec![ + BakeryCommands::MqSetup { + queues_available: 1, + stick_offset: 0, + }, + BakeryCommands::AddCircuit { + circuit_hash: 2, + parent_class_id: TcHandle::from_u32(0x10001), + up_parent_class_id: TcHandle::from_u32(0x20001), + class_minor: 0x20, + download_bandwidth_min: 10.0, + upload_bandwidth_min: 10.0, + download_bandwidth_max: 2_000.0, + upload_bandwidth_max: 2_000.0, + class_major: 0x100, + up_class_major: 0x200, + down_qdisc_handle: Some(0x9000), + up_qdisc_handle: Some(0x9001), + ip_addresses: "192.0.2.1/32".to_string(), + sqm_override: Some("fq_codel".to_string()), + }, + ]; + + let estimate = estimate_full_reload_auto_qdisc_budget(&config, &queue); + assert_eq!( + estimate + .interface_details + .get("eth0") + .map(|d| d.fq_codel_qdiscs), + Some(1) + ); + assert_eq!( + estimate + .interface_details + .get("eth1") + .map(|d| d.fq_codel_qdiscs), + Some(1) + ); + assert_eq!( + estimate + .interface_details + .get("eth0") + .map(|d| d.cake_qdiscs), + Some(0) + ); } #[test] @@ -3105,4 +5511,151 @@ mod tests { }; assert_eq!(*new_down, *original_down); } + + #[test] + fn queue_live_migration_succeeds_for_active_parent_move() { + let old_cmd = mk_test_circuit(9001, 0x10020, 0x20020, 0x21, 0x1, 0x2, "192.0.2.90/32"); + let new_cmd = mk_test_circuit(9001, 0x10034, 0x20034, 0x35, 0x3, 0x4, "192.0.2.90/32"); + + let mut circuits = HashMap::from([(9001, Arc::clone(&old_cmd))]); + let live_circuits = HashMap::from([(9001, 1u64)]); + let mut migrations = HashMap::new(); + + let queued = queue_live_migration( + old_cmd.as_ref(), + &new_cmd, + &mut circuits, + &live_circuits, + &mut migrations, + ); + + assert!(queued); + let migration = migrations.get(&9001).expect("migration should be queued"); + assert_eq!(migration.stage, MigrationStage::PrepareShadow); + assert_eq!(migration.old_parent_class_id, TcHandle::from_u32(0x10020)); + assert_eq!(migration.parent_class_id, TcHandle::from_u32(0x10034)); + assert_eq!(migration.final_minor, 0x35); + assert_ne!(migration.shadow_minor, migration.old_minor); + assert!(matches!( + circuits.get(&9001), + Some(cmd) if Arc::ptr_eq(cmd, &new_cmd) + )); + } + + #[test] + fn queue_live_migration_fails_when_target_parent_has_no_shadow_minor() { + let old_cmd = mk_test_circuit(9100, 0x10020, 0x20020, 0x21, 0x1, 0x2, "192.0.2.91/32"); + let new_cmd = mk_test_circuit(9100, 0x10034, 0x20034, 0x35, 0x3, 0x4, "192.0.2.91/32"); + + let mut circuits = HashMap::from([(9100, Arc::clone(&old_cmd))]); + for minor in 1..=0xFFFEu16 { + circuits.insert( + 100_000 + i64::from(minor), + mk_test_circuit( + 100_000 + i64::from(minor), + 0x10034, + 0x20034, + minor, + 0x3, + 0x4, + &format!("198.51.100.{}/32", (minor % 250) + 1), + ), + ); + } + + let live_circuits = HashMap::from([(9100, 1u64)]); + let mut migrations = HashMap::new(); + + let queued = queue_live_migration( + old_cmd.as_ref(), + &new_cmd, + &mut circuits, + &live_circuits, + &mut migrations, + ); + + assert!(!queued); + assert!(!migrations.contains_key(&9100)); + assert!(matches!( + circuits.get(&9100), + Some(cmd) if Arc::ptr_eq(cmd, &old_cmd) + )); + } + + #[test] + fn full_reload_allocation_uses_fresh_handles_reserved_from_live_tree() { + let config = test_config_with_runtime_dir("fresh-full-reload"); + let layout = MqDeviceLayout::from_setup(&config, 2, 0); + let mut persisted = QdiscHandleState::default(); + + let original = Arc::new(BakeryCommands::AddCircuit { + circuit_hash: 505, + parent_class_id: TcHandle::from_u32(0x10001), + up_parent_class_id: TcHandle::from_u32(0x20001), + class_minor: 0x20, + download_bandwidth_min: 10.0, + upload_bandwidth_min: 10.0, + download_bandwidth_max: 100.0, + upload_bandwidth_max: 100.0, + class_major: 0x100, + up_class_major: 0x200, + down_qdisc_handle: None, + up_qdisc_handle: None, + ip_addresses: "192.0.2.5/32".to_string(), + sqm_override: None, + }); + + let original = with_assigned_qdisc_handles(&original, &config, &layout, &mut persisted); + let BakeryCommands::AddCircuit { + down_qdisc_handle: Some(original_down), + up_qdisc_handle: Some(original_up), + .. + } = original.as_ref() + else { + panic!("expected assigned handles"); + }; + + let mut full_reload_handles = QdiscHandleState::default(); + let live_reserved = HashMap::from([ + (config.isp_interface(), HashSet::from([*original_down])), + (config.internet_interface(), HashSet::from([*original_up])), + ]); + let rebuilt_cmd = Arc::new(BakeryCommands::AddCircuit { + circuit_hash: 505, + parent_class_id: TcHandle::from_u32(0x10001), + up_parent_class_id: TcHandle::from_u32(0x20001), + class_minor: 0x20, + download_bandwidth_min: 10.0, + upload_bandwidth_min: 10.0, + download_bandwidth_max: 100.0, + upload_bandwidth_max: 100.0, + class_major: 0x100, + up_class_major: 0x200, + down_qdisc_handle: None, + up_qdisc_handle: None, + ip_addresses: "192.0.2.5/32".to_string(), + sqm_override: None, + }); + let rebuilt = with_assigned_qdisc_handles_reserved( + &rebuilt_cmd, + &config, + &layout, + &mut full_reload_handles, + &live_reserved, + ); + + let BakeryCommands::AddCircuit { + down_qdisc_handle: Some(rebuilt_down), + up_qdisc_handle: Some(rebuilt_up), + .. + } = rebuilt.as_ref() + else { + panic!("expected rebuilt handles"); + }; + + assert_ne!(*rebuilt_down, *original_down); + assert_ne!(*rebuilt_up, *original_up); + assert_eq!(*rebuilt_down, *original_down + 1); + assert_eq!(*rebuilt_up, *original_up + 1); + } } diff --git a/src/rust/lqos_bakery/src/qdisc_handles.rs b/src/rust/lqos_bakery/src/qdisc_handles.rs index 42ebec07..7b7a93bc 100644 --- a/src/rust/lqos_bakery/src/qdisc_handles.rs +++ b/src/rust/lqos_bakery/src/qdisc_handles.rs @@ -261,13 +261,6 @@ impl QdiscHandleState { .and_then(|state| state.remove(circuit_hash)) .is_some() } - - /// Drops persisted handle assignments for circuits no longer present on an interface. - pub(crate) fn retain_circuits(&mut self, interface: &str, active: &HashSet) { - if let Some(state) = self.interfaces.get_mut(interface) { - state.retain_circuits(active); - } - } } #[derive(Debug, Clone, PartialEq, Eq)] @@ -322,20 +315,6 @@ impl InterfaceHandleState { Some(removed) } - fn retain_circuits(&mut self, active: &HashSet) { - let removed = self - .circuits - .iter() - .filter_map(|(hash, handle)| (!active.contains(hash)).then_some((*hash, *handle))) - .collect::>(); - - for (hash, handle) in removed { - self.circuits.remove(&hash); - self.owners.remove(&handle); - self.note_reusable_handle(handle); - } - } - fn note_reusable_handle(&mut self, handle: u16) { if handle >= PREFERRED_CIRCUIT_START || self.next_candidate < PREFERRED_CIRCUIT_START { self.next_candidate = self.next_candidate.min(handle); diff --git a/src/rust/lqos_bakery/src/utils.rs b/src/rust/lqos_bakery/src/utils.rs index 3fc09a7b..dae1c5a4 100644 --- a/src/rust/lqos_bakery/src/utils.rs +++ b/src/rust/lqos_bakery/src/utils.rs @@ -1,4 +1,6 @@ +use lqos_bus::TcHandle; use parking_lot::Mutex; +use std::collections::HashSet; use std::fs::File; use std::io::{BufWriter, Write}; use std::path::Path; @@ -21,18 +23,158 @@ pub(crate) struct ExecuteResult { pub(crate) failure_summary: Option, } -pub(crate) fn execute_in_memory(command_buffer: &Vec>, purpose: &str) -> ExecuteResult { +/// Lightweight host-memory snapshot used by Bakery safety checks. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MemorySnapshot { + /// Total installed RAM in bytes. + pub total_bytes: u64, + /// Currently available RAM in bytes. + pub available_bytes: u64, +} + +fn format_numbered_lines(lines: &str, starting_line_number: usize) -> String { + let mut numbered = String::new(); + for (i, line) in lines.lines().enumerate() { + numbered.push_str(&format!("{:>4}: {}\n", starting_line_number + i, line)); + } + numbered +} + +fn run_tc_batch(path: &Path, purpose: &str) -> Result { + std::process::Command::new("/sbin/tc") + .args(["-f", "-batch", path.to_str().unwrap_or_default()]) + .output() + .map_err(|_| format!("Failed to execute tc batch command for {purpose}.")) +} + +pub(crate) fn read_memory_snapshot() -> Result { + let raw = std::fs::read_to_string("/proc/meminfo") + .map_err(|e| format!("Failed to read /proc/meminfo: {e}"))?; + parse_memory_snapshot(&raw) +} + +fn parse_memory_snapshot(raw: &str) -> Result { + let mut total_kib = None; + let mut available_kib = None; + + for line in raw.lines() { + let Some((key, value)) = line.split_once(':') else { + continue; + }; + let kib = value + .split_whitespace() + .next() + .and_then(|n| n.parse::().ok()); + match key.trim() { + "MemTotal" => total_kib = kib, + "MemAvailable" => available_kib = kib, + _ => {} + } + } + + let total_kib = total_kib.ok_or_else(|| "MemTotal missing from /proc/meminfo".to_string())?; + let available_kib = + available_kib.ok_or_else(|| "MemAvailable missing from /proc/meminfo".to_string())?; + + Ok(MemorySnapshot { + total_bytes: total_kib.saturating_mul(1024), + available_bytes: available_kib.saturating_mul(1024), + }) +} + +fn memory_guard_failure_summary( + snapshot: MemorySnapshot, + min_available_bytes: u64, + purpose: &str, + chunk_number: usize, + total_chunks: usize, + phase: &str, +) -> String { + format!( + "Bakery memory guard stopped {purpose} {phase} chunk {}/{}: available memory {} bytes is below safety floor {} bytes (total RAM {} bytes).", + chunk_number, + total_chunks, + snapshot.available_bytes, + min_available_bytes, + snapshot.total_bytes + ) +} + +pub(crate) fn read_live_qdisc_handle_majors(interface: &str) -> Result, String> { + let output = std::process::Command::new("/sbin/tc") + .args(["-s", "-j", "qdisc", "show", "dev", interface]) + .output() + .map_err(|e| format!("Failed to snapshot live qdiscs on {interface}: {e}"))?; + + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + return Err(format!( + "Failed to snapshot live qdiscs on {interface}: {}", + stderr.trim() + )); + } + + let stdout = String::from_utf8(output.stdout) + .map_err(|e| format!("Live qdisc snapshot on {interface} was not UTF-8: {e}"))?; + + parse_live_qdisc_handle_majors(&stdout) + .map_err(|e| format!("Failed to parse live qdisc snapshot on {interface}: {e}")) +} + +fn parse_live_qdisc_handle_majors(raw_json: &str) -> Result, String> { + let parsed = serde_json::from_str::(raw_json) + .map_err(|e| format!("invalid JSON: {e}"))?; + let items = parsed + .as_array() + .ok_or_else(|| "expected JSON array from tc qdisc show -j".to_string())?; + + let mut handles = HashSet::new(); + for item in items { + let Some(handle) = item.get("handle").and_then(|value| value.as_str()) else { + continue; + }; + let Ok(tc_handle) = TcHandle::from_string(handle) else { + continue; + }; + let (major, _) = tc_handle.get_major_minor(); + if major != 0 { + handles.insert(major); + } + } + + Ok(handles) +} + +pub(crate) fn execute_in_memory(command_buffer: &[Vec], purpose: &str) -> ExecuteResult { + execute_in_memory_chunked( + command_buffer, + purpose, + command_buffer.len().max(1), + None, + |_, _, _, _| {}, + ) +} + +pub(crate) fn execute_in_memory_chunked( + command_buffer: &[Vec], + purpose: &str, + chunk_size: usize, + memory_guard_min_available_bytes: Option, + mut on_progress: F, +) -> ExecuteResult +where + F: FnMut(usize, usize, usize, usize), +{ let started = std::time::Instant::now(); - let lock = FILE_LOCK.lock(); + let _lock = FILE_LOCK.lock(); info!( "Bakery: Executing in-memory commands: {} lines, for {purpose}", command_buffer.len() ); - let path = Path::new("/tmp/lqos_bakery_commands.txt"); - let Some(lines) = write_command_file(path, command_buffer) else { + let full_path = Path::new("/tmp/lqos_bakery_commands.txt"); + let Some(_) = write_command_file(full_path, command_buffer) else { error!("Failed to write commands to file for {purpose}"); - drop(lock); return ExecuteResult { ok: false, duration_ms: started.elapsed().as_millis() as u64, @@ -40,73 +182,173 @@ pub(crate) fn execute_in_memory(command_buffer: &Vec>, purpose: &str }; }; - let Ok(output) = std::process::Command::new("/sbin/tc") - .args(["-f", "-batch", path.to_str().unwrap_or_default()]) - .output() - else { - let message = format!("Failed to execute tc batch command for {purpose}."); - error!(message); - drop(lock); + if command_buffer.is_empty() { return ExecuteResult { - ok: false, + ok: true, duration_ms: started.elapsed().as_millis() as u64, - failure_summary: Some(message), + failure_summary: None, }; - }; - - let output_str = String::from_utf8_lossy(&output.stdout) - .replace("Error: Exclusivity flag on, cannot modify.\n", ""); - if !output_str.is_empty() { - error!("Command output for ({purpose}): {:?}", output_str.trim()); } - let error_str = String::from_utf8_lossy(&output.stderr); - if !error_str.is_empty() { - // Add line numbers to aid debugging with tc -batch's reported line numbers - let mut numbered = String::new(); - for (i, line) in lines.lines().enumerate() { - // tc -batch reports 1-based line numbers - numbered.push_str(&format!("{:>4}: {}\n", i + 1, line)); + let chunk_size = chunk_size.max(1); + let total_chunks = command_buffer.len().div_ceil(chunk_size); + let chunk_path = Path::new("/tmp/lqos_bakery_commands_chunk.txt"); + let mut completed_commands = 0usize; + let mut completed_chunks = 0usize; + + for chunk in command_buffer.chunks(chunk_size) { + if let Some(min_available_bytes) = memory_guard_min_available_bytes { + match read_memory_snapshot() { + Ok(snapshot) if snapshot.available_bytes < min_available_bytes => { + let summary = memory_guard_failure_summary( + snapshot, + min_available_bytes, + purpose, + completed_chunks + 1, + total_chunks, + "before", + ); + error!("{summary}"); + return ExecuteResult { + ok: false, + duration_ms: started.elapsed().as_millis() as u64, + failure_summary: Some(summary), + }; + } + Ok(_) => {} + Err(err) => { + let summary = format!( + "Bakery memory guard could not read host memory state before chunk {}/{} for {purpose}: {err}", + completed_chunks + 1, + total_chunks + ); + error!("{summary}"); + return ExecuteResult { + ok: false, + duration_ms: started.elapsed().as_millis() as u64, + failure_summary: Some(summary), + }; + } + } } - let detailed = format!( - "Command error for ({purpose}): {}\nCommands with line numbers:\n{}", - error_str.trim(), - numbered - ); - // Log to console - error!(detailed); - - // Also persist to /tmp for easier debugging of large batches - let ts = current_timestamp(); - let path_ts = Path::new("/tmp").join(format!("lqos_bakery_failed_{}.txt", ts)); - if let Ok(mut f) = File::create(&path_ts) { - let _ = f.write_all(detailed.as_bytes()); - let _ = f.flush(); - error!( - "Bakery wrote numbered command failure to {}", - path_ts.display() - ); - } else { - error!( - "Bakery failed to write numbered command failure file: {}", - path_ts.display() + + let global_line_start = completed_commands + 1; + let Some(lines) = write_command_file(chunk_path, chunk) else { + error!("Failed to write chunked commands to file for {purpose}"); + return ExecuteResult { + ok: false, + duration_ms: started.elapsed().as_millis() as u64, + failure_summary: Some(format!("Failed to write commands to file for {purpose}")), + }; + }; + + let output = match run_tc_batch(chunk_path, purpose) { + Ok(output) => output, + Err(message) => { + error!(message); + return ExecuteResult { + ok: false, + duration_ms: started.elapsed().as_millis() as u64, + failure_summary: Some(message), + }; + } + }; + + let output_str = String::from_utf8_lossy(&output.stdout) + .replace("Error: Exclusivity flag on, cannot modify.\n", ""); + if !output_str.is_empty() { + error!("Command output for ({purpose}): {:?}", output_str.trim()); + } + + let error_str = String::from_utf8_lossy(&output.stderr); + if !error_str.is_empty() { + let numbered = format_numbered_lines(&lines, global_line_start); + let chunk_line_end = global_line_start + chunk.len().saturating_sub(1); + let detailed = format!( + "Command error for ({purpose}): {}\nFailed chunk {}/{} (global lines {}-{})\nFull batch: {}\nChunk batch: {}\nChunk commands with global line numbers:\n{}", + error_str.trim(), + completed_chunks + 1, + total_chunks, + global_line_start, + chunk_line_end, + full_path.display(), + chunk_path.display(), + numbered ); + error!(detailed); + + let ts = current_timestamp(); + let path_ts = Path::new("/tmp").join(format!("lqos_bakery_failed_{}.txt", ts)); + if let Ok(mut f) = File::create(&path_ts) { + let _ = f.write_all(detailed.as_bytes()); + let _ = f.flush(); + error!( + "Bakery wrote numbered command failure to {}", + path_ts.display() + ); + } else { + error!( + "Bakery failed to write numbered command failure file: {}", + path_ts.display() + ); + } + let path_last = Path::new("/tmp/lqos_bakery_last_error.txt"); + if let Ok(mut f) = File::create(path_last) { + let _ = f.write_all(detailed.as_bytes()); + let _ = f.flush(); + } + return ExecuteResult { + ok: false, + duration_ms: started.elapsed().as_millis() as u64, + failure_summary: Some(error_str.trim().to_string()), + }; } - // Convenience: keep a rolling 'last error' file - let path_last = Path::new("/tmp/lqos_bakery_last_error.txt"); - if let Ok(mut f) = File::create(path_last) { - let _ = f.write_all(detailed.as_bytes()); - let _ = f.flush(); + + completed_commands += chunk.len(); + completed_chunks += 1; + + if let Some(min_available_bytes) = memory_guard_min_available_bytes { + match read_memory_snapshot() { + Ok(snapshot) if snapshot.available_bytes < min_available_bytes => { + let summary = memory_guard_failure_summary( + snapshot, + min_available_bytes, + purpose, + completed_chunks, + total_chunks, + "after", + ); + error!("{summary}"); + return ExecuteResult { + ok: false, + duration_ms: started.elapsed().as_millis() as u64, + failure_summary: Some(summary), + }; + } + Ok(_) => {} + Err(err) => { + let summary = format!( + "Bakery memory guard could not read host memory state after chunk {}/{} for {purpose}: {err}", + completed_chunks, total_chunks + ); + error!("{summary}"); + return ExecuteResult { + ok: false, + duration_ms: started.elapsed().as_millis() as u64, + failure_summary: Some(summary), + }; + } + } } - drop(lock); - return ExecuteResult { - ok: false, - duration_ms: started.elapsed().as_millis() as u64, - failure_summary: Some(error_str.trim().to_string()), - }; + + on_progress( + completed_commands, + command_buffer.len(), + completed_chunks, + total_chunks, + ); } - drop(lock); // Explicitly drop the lock to release it. This happens automatically at the end of the scope, but it's good to be explicit. ExecuteResult { ok: true, duration_ms: started.elapsed().as_millis() as u64, @@ -114,7 +356,7 @@ pub(crate) fn execute_in_memory(command_buffer: &Vec>, purpose: &str } } -pub(crate) fn write_command_file(path: &Path, commands: &Vec>) -> Option { +pub(crate) fn write_command_file(path: &Path, commands: &[Vec]) -> Option { let mut lines = String::new(); let Ok(file) = File::create(path) else { error!("Failed to create output file: {}", path.display()); @@ -149,3 +391,56 @@ pub(crate) fn write_command_file(path: &Path, commands: &Vec>) -> Op } Some(lines) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_live_qdisc_handle_majors_collects_non_zero_handles() { + let raw = r#" +[ + { "kind": "mq", "handle": "7fff:", "parent": "root" }, + { "kind": "cake", "handle": "90f1:", "parent": "2:1039" }, + { "kind": "fq_codel", "handle": "50c0:", "parent": "8:24dd" }, + { "kind": "ingress", "handle": "ffff:", "parent": "ffff:fff1" }, + { "kind": "fq_codel", "handle": "0:", "parent": "3:20" } +] +"#; + let handles = parse_live_qdisc_handle_majors(raw).expect("handles parsed"); + assert!(handles.contains(&0x7fff)); + assert!(handles.contains(&0x90f1)); + assert!(handles.contains(&0x50c0)); + assert!(handles.contains(&0xffff)); + assert!(!handles.contains(&0)); + } + + #[test] + fn parse_live_qdisc_handle_majors_rejects_non_arrays() { + let err = parse_live_qdisc_handle_majors(r#"{"handle":"90f1:"}"#) + .expect_err("non-array should fail"); + assert!(err.contains("expected JSON array")); + } + + #[test] + fn parse_memory_snapshot_extracts_total_and_available() { + let raw = "\ +MemTotal: 32768000 kB +MemFree: 1024000 kB +MemAvailable: 8192000 kB +"; + let snapshot = parse_memory_snapshot(raw).expect("meminfo parsed"); + assert_eq!(snapshot.total_bytes, 32_768_000_u64 * 1024); + assert_eq!(snapshot.available_bytes, 8_192_000_u64 * 1024); + } + + #[test] + fn parse_memory_snapshot_requires_memavailable() { + let raw = "\ +MemTotal: 32768000 kB +MemFree: 1024000 kB +"; + let err = parse_memory_snapshot(raw).expect_err("memavailable should be required"); + assert!(err.contains("MemAvailable")); + } +} diff --git a/src/rust/lqos_bus/src/bus/request.rs b/src/rust/lqos_bus/src/bus/request.rs index 86071f0f..45349679 100644 --- a/src/rust/lqos_bus/src/bus/request.rs +++ b/src/rust/lqos_bus/src/bus/request.rs @@ -13,6 +13,14 @@ pub struct BakeryCapacityReportInterface { pub name: String, /// Planned qdisc count for the interface. pub planned_qdiscs: usize, + /// Planned infrastructure qdiscs (`mq`, `htb`, etc.) for the interface. + pub infra_qdiscs: usize, + /// Planned `cake` leaf qdiscs for the interface. + pub cake_qdiscs: usize, + /// Planned `fq_codel` leaf qdiscs for the interface. + pub fq_codel_qdiscs: usize, + /// Estimated kernel memory cost for the interface's planned qdiscs. + pub estimated_memory_bytes: u64, } /// Source system for an urgent issue @@ -191,6 +199,9 @@ pub enum BusRequest { /// Requests that the configuration be updated UpdateLqosdConfig(Box), + /// Invalidate cached Node Manager authentication state. + InvalidateAuthCache, + /// Request that we start watching a circuit's queue WatchQueue(String), @@ -379,6 +390,14 @@ pub enum BusRequest { safe_budget: usize, /// Hard kernel limit for reference. hard_limit: usize, + /// Estimated total kernel memory cost of the planned qdisc model. + estimated_total_memory_bytes: u64, + /// Current host memory available during preflight, if known. + memory_available_bytes: Option, + /// Memory floor that must remain available before the apply proceeds. + memory_guard_min_available_bytes: u64, + /// Whether the memory preflight passed. + memory_ok: bool, /// Per-interface planned qdisc counts. interfaces: Vec, }, diff --git a/src/rust/lqos_config/Cargo.toml b/src/rust/lqos_config/Cargo.toml index 170ac5ab..64de7383 100644 --- a/src/rust/lqos_config/Cargo.toml +++ b/src/rust/lqos_config/Cargo.toml @@ -13,6 +13,8 @@ csv = { workspace = true } ip_network_table = { workspace = true } ip_network = { workspace = true } sha2 = { workspace = true } +argon2 = { workspace = true } +rand_core = { workspace = true } uuid = { workspace = true } tracing = { workspace = true } toml = { workspace = true } diff --git a/src/rust/lqos_config/src/authentication.rs b/src/rust/lqos_config/src/authentication.rs index 154bc84d..3262030b 100644 --- a/src/rust/lqos_config/src/authentication.rs +++ b/src/rust/lqos_config/src/authentication.rs @@ -2,11 +2,13 @@ //! local web UI on LibreQoS boxes. It maps to `//lqusers.toml` use allocative::Allocative; +use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier, password_hash::SaltString}; +use rand_core::OsRng; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::{ fmt::Display, - fs::{OpenOptions, read_to_string, remove_file}, + fs::{OpenOptions, read_to_string, remove_file, rename}, io::Write, path::{Path, PathBuf}, }; @@ -14,6 +16,21 @@ use thiserror::Error; use tracing::{error, warn}; use uuid::Uuid; +const AUTH_FILE_VERSION: u32 = 2; +const LEGACY_AUTH_FILE_VERSION: u32 = 1; +const INITIAL_AUTH_EPOCH: u64 = 1; +const LEGACY_AUTH_FILE_NAME: &str = "webusers.toml"; +const CURRENT_AUTH_FILE_NAME: &str = "lqusers.toml"; +const LEGACY_PASSWORD_PEPPER: &str = "_LibreQosLikesPasswordsForDinner"; + +fn default_auth_file_version() -> u32 { + LEGACY_AUTH_FILE_VERSION +} + +fn default_auth_epoch() -> u64 { + INITIAL_AUTH_EPOCH +} + /// Access rights of a user #[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Allocative)] pub enum UserRole { @@ -59,29 +76,91 @@ impl Display for UserRole { pub struct WebUser { /// The user's username. pub username: String, - /// The user's password hash. + /// The user's password hash. This may be a legacy SHA-256 hash or an + /// Argon2id PHC string until the user next logs in. pub password_hash: String, /// The user's role. pub role: UserRole, - /// The user's token. - pub token: String, +} + +/// Result of authenticating a single user. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AuthenticatedUser { + /// The authenticated username. + pub username: String, + /// The user's role. + pub role: UserRole, + /// Current auth epoch after any migration-side rewrite. + pub auth_epoch: u64, + /// True when a legacy password hash was upgraded to Argon2id. + pub password_upgraded: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct PasswordVerification { + valid: bool, + needs_rehash: bool, } /// Container holding the authorized web users. -#[derive(Clone, Debug, Deserialize, Serialize, Default, Allocative)] +#[derive(Clone, Debug, Deserialize, Serialize, Allocative)] pub struct WebUsers { + #[serde(default = "default_auth_file_version")] + version: u32, + #[serde(default = "default_auth_epoch")] + auth_epoch: u64, + #[serde(default)] allow_unauthenticated_to_view: bool, + #[serde(default)] users: Vec, } +impl Default for WebUsers { + fn default() -> Self { + Self { + version: AUTH_FILE_VERSION, + auth_epoch: INITIAL_AUTH_EPOCH, + allow_unauthenticated_to_view: false, + users: Vec::new(), + } + } +} + impl WebUsers { - fn path() -> Result { + fn base_path() -> Result { let base_path = crate::load_config() .map_err(|_| AuthenticationError::UnableToLoadEtcLqos)? .lqos_directory .clone(); - let filename = Path::new(&base_path).join("lqusers.toml"); - Ok(filename) + Ok(PathBuf::from(base_path)) + } + + fn primary_path() -> Result { + Ok(Self::base_path()?.join(CURRENT_AUTH_FILE_NAME)) + } + + fn legacy_path() -> Result { + Ok(Self::base_path()?.join(LEGACY_AUTH_FILE_NAME)) + } + + /// Returns the current `lqusers.toml` path. + pub fn path() -> Result { + Self::primary_path() + } + + /// Returns the existing auth file path, checking the legacy filename as a fallback. + pub fn existing_path() -> Result, AuthenticationError> { + let current = Self::primary_path()?; + if current.exists() { + return Ok(Some(current)); + } + + let legacy = Self::legacy_path()?; + if legacy.exists() { + return Ok(Some(legacy)); + } + + Ok(None) } /// Is the list of users empty? @@ -89,66 +168,156 @@ impl WebUsers { self.users.is_empty() } + fn normalize_for_save(&self) -> Self { + let mut normalized = self.clone(); + normalized.version = AUTH_FILE_VERSION; + if normalized.auth_epoch == 0 { + normalized.auth_epoch = INITIAL_AUTH_EPOCH; + } + normalized + } + fn save_to_disk(&self) -> Result<(), AuthenticationError> { - let path = Self::path()?; - let new_contents = - toml_edit::ser::to_string(&self).map_err(AuthenticationError::SerializationError)?; - if path.exists() && remove_file(&path).is_err() { - error!("Unable to delete web users file"); - return Err(AuthenticationError::UnableToDelete); + let path = Self::primary_path()?; + let tmp_path = path.with_extension(format!("toml.tmp-{}", Uuid::new_v4())); + let normalized = self.normalize_for_save(); + let new_contents = toml_edit::ser::to_string(&normalized) + .map_err(AuthenticationError::SerializationError)?; + + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp_path) + .map_err(|e| { + error!( + "Unable to open temporary auth file {:?} for writing: {e}", + tmp_path + ); + AuthenticationError::UnableToWrite + })?; + file.write_all(new_contents.as_bytes()).map_err(|e| { + error!("Unable to write temporary auth file {:?}: {e}", tmp_path); + AuthenticationError::UnableToWrite + })?; + drop(file); + + rename(&tmp_path, &path).map_err(|e| { + error!( + "Unable to rename temporary auth file {:?} to {:?}: {e}", + tmp_path, path + ); + let _ = remove_file(&tmp_path); + AuthenticationError::UnableToWrite + })?; + + let legacy_path = Self::legacy_path()?; + if legacy_path != path + && legacy_path.exists() + && let Err(e) = remove_file(&legacy_path) + { + warn!("Unable to remove legacy auth file {:?}: {e}", legacy_path); } - if let Ok(mut file) = OpenOptions::new().write(true).create_new(true).open(path) { - if file.write_all(new_contents.as_bytes()).is_err() { - error!("Unable to write web users file to disk."); - return Err(AuthenticationError::UnableToWrite); - } - } else { - error!("Unable to open web users file for writing."); - return Err(AuthenticationError::UnableToWrite); + + Ok(()) + } + + fn migrate_if_needed(&mut self, loaded_from: &Path) -> Result<(), AuthenticationError> { + let current_path = Self::primary_path()?; + let loaded_from_legacy_path = loaded_from != current_path; + let mut needs_rewrite = false; + + if self.version != AUTH_FILE_VERSION { + self.version = AUTH_FILE_VERSION; + needs_rewrite = true; + } + + if self.auth_epoch == 0 { + self.auth_epoch = INITIAL_AUTH_EPOCH; + needs_rewrite = true; + } + + if loaded_from_legacy_path { + needs_rewrite = true; + } + + if needs_rewrite { + self.bump_auth_epoch(); + self.save_to_disk()?; } + Ok(()) } /// Does the user's file exist? True if it does, false otherwise. pub fn does_users_file_exist() -> Result { - Ok(Self::path()?.exists()) + Ok(Self::existing_path()?.is_some()) } - /// Try to load `lqusers.toml`. If it is unavailable, create a new--empty-- - /// file. + /// Try to load `lqusers.toml`, creating a new version 2 file if no auth file exists. pub fn load_or_create() -> Result { - let path = Self::path()?; - if !path.exists() { - // Create a new users file, save it and return the - // empty file + if let Some(path) = Self::existing_path()? { + let raw = read_to_string(&path).map_err(|e| { + error!("Unable to read auth file {:?}: {e}", path); + AuthenticationError::UnableToRead + })?; + let mut users: Self = toml_edit::de::from_str(&raw).map_err(|e| { + error!("Unable to deserialize auth file {:?}: {e}", path); + AuthenticationError::UnableToParse + })?; + users.migrate_if_needed(&path)?; + Ok(users) + } else { let new_users = Self::default(); new_users.save_to_disk()?; Ok(new_users) - } else { - // Load from disk - if let Ok(raw) = read_to_string(path) { - let parse_result = toml_edit::de::from_str(&raw); - if let Ok(users) = parse_result { - Ok(users) - } else { - error!("Unable to deserialize lqusers.toml. Error in next message."); - error!("{:?}", parse_result); - Err(AuthenticationError::UnableToParse) - } - } else { - error!("Unable to read lqusers.toml"); - Err(AuthenticationError::UnableToRead) - } } } - fn hash_password(password: &str) -> String { - let salted = format!("!x{password}_LibreQosLikesPasswordsForDinner"); + fn hash_password(password: &str) -> Result { + let salt = SaltString::generate(&mut OsRng); + Argon2::default() + .hash_password(password.as_bytes(), &salt) + .map(|hash| hash.to_string()) + .map_err(AuthenticationError::PasswordHashError) + } + + fn hash_password_legacy(password: &str) -> String { + let salted = format!("!x{password}{LEGACY_PASSWORD_PEPPER}"); let mut sha256 = Sha256::new(); sha256.update(salted); format!("{:X}", sha256.finalize()) } + fn verify_password( + password: &str, + password_hash: &str, + ) -> Result { + if password_hash.starts_with("$argon2") { + let parsed = + PasswordHash::new(password_hash).map_err(AuthenticationError::PasswordHashError)?; + Ok(PasswordVerification { + valid: Argon2::default() + .verify_password(password.as_bytes(), &parsed) + .is_ok(), + needs_rehash: false, + }) + } else { + Ok(PasswordVerification { + valid: Self::hash_password_legacy(password) == password_hash, + needs_rehash: true, + }) + } + } + + fn bump_auth_epoch(&mut self) { + self.auth_epoch = self.auth_epoch.saturating_add(1).max(INITIAL_AUTH_EPOCH); + } + + /// Returns the current auth epoch used to revoke signed sessions. + pub fn auth_epoch(&self) -> u64 { + self.auth_epoch + } + /// If a user exists with this username, update their details to the /// provided values. If the user does not exist, create them with the /// provided values. @@ -157,25 +326,23 @@ impl WebUsers { username: &str, password: &str, role: UserRole, - ) -> Result { - let token; // Assigned in a branch + ) -> Result<(), AuthenticationError> { + let password_hash = Self::hash_password(password)?; if let Some(user) = self.users.iter_mut().find(|u| u.username == username) { - user.password_hash = Self::hash_password(password); + user.password_hash = password_hash; user.role = role; - token = user.token.clone(); } else { - token = Uuid::new_v4().to_string(); let new_user = WebUser { username: username.to_string(), - password_hash: Self::hash_password(password), + password_hash, role, - token: token.clone(), }; self.users.push(new_user); } + self.bump_auth_epoch(); self.save_to_disk()?; - Ok(token) + Ok(()) } /// Update an existing user, optionally changing their password. @@ -189,20 +356,18 @@ impl WebUsers { username: &str, password: Option<&str>, role: UserRole, - ) -> Result { - let token; - if let Some(user) = self.users.iter_mut().find(|u| u.username == username) { - if let Some(password) = password { - user.password_hash = Self::hash_password(password); - } - user.role = role; - token = user.token.clone(); - } else { + ) -> Result<(), AuthenticationError> { + let Some(user) = self.users.iter_mut().find(|u| u.username == username) else { return Err(AuthenticationError::UserNotFound); - } + }; + if let Some(password) = password { + user.password_hash = Self::hash_password(password)?; + } + user.role = role; + self.bump_auth_epoch(); self.save_to_disk()?; - Ok(token) + Ok(()) } /// Delete a user from `lqusers.toml` @@ -213,48 +378,42 @@ impl WebUsers { error!("User {username} not found, hence not deleted."); return Err(AuthenticationError::UserNotFound); } + self.bump_auth_epoch(); self.save_to_disk()?; Ok(()) } - /// Attempt a login with the specified username and password. If - /// the login succeeds, returns the publically shareable token that - /// uniquely identifies the user a a string. If it fails, returns an - /// `Err`. - pub fn login(&self, username: &str, password: &str) -> Result { - let hash = Self::hash_password(password); - if let Some(user) = self - .users - .iter() - .find(|u| u.username == username && u.password_hash == hash) - { - Ok(user.token.clone()) - } else if self.allow_unauthenticated_to_view { - Ok("default".to_string()) - } else { - Err(AuthenticationError::InvalidLogin) - } - } + /// Attempt a login with the specified username and password. If the login + /// succeeds, returns the authenticated user details and transparently + /// upgrades legacy password hashes to Argon2id. + pub fn authenticate( + &mut self, + username: &str, + password: &str, + ) -> Result { + let Some(index) = self.users.iter().position(|u| u.username == username) else { + return Err(AuthenticationError::InvalidLogin); + }; - /// Given a token, lookup the matching user and return their role. - pub fn get_role_from_token(&self, token: &str) -> Result { - if let Some(user) = self.users.iter().find(|u| u.token == token) { - Ok(user.role) - } else if self.allow_unauthenticated_to_view { - Ok(UserRole::ReadOnly) - } else { - warn!("Token {token} not found, invalid data access attempt."); - Err(AuthenticationError::InvalidToken) + let verification = Self::verify_password(password, &self.users[index].password_hash)?; + if !verification.valid { + return Err(AuthenticationError::InvalidLogin); } - } - /// Given a token, lookup the matching user and return their username. - pub fn get_username(&self, token: &str) -> String { - if let Some(user) = self.users.iter().find(|u| u.token == token) { - user.username.clone() - } else { - "Anonymous".to_string() + let mut password_upgraded = false; + if verification.needs_rehash { + self.users[index].password_hash = Self::hash_password(password)?; + self.bump_auth_epoch(); + self.save_to_disk()?; + password_upgraded = true; } + + Ok(AuthenticatedUser { + username: self.users[index].username.clone(), + role: self.users[index].role, + auth_epoch: self.auth_epoch, + password_upgraded, + }) } /// Dump all users to the console. @@ -275,6 +434,7 @@ impl WebUsers { /// for demonstration purposes. pub fn allow_anonymous(&mut self, allow: bool) -> Result<(), AuthenticationError> { self.allow_unauthenticated_to_view = allow; + self.bump_auth_epoch(); self.save_to_disk()?; Ok(()) } @@ -286,16 +446,6 @@ impl WebUsers { } /// Errors that can occur while managing web-UI authentication. -/// -/// This enum groups failures encountered by helpers in this module while -/// interacting with `lqusers.toml` and related configuration, including: -/// - Resolving the LibreQoS config directory via `crate::load_config`. -/// - Serializing/deserializing user data with `toml_edit`. -/// - Reading, writing, or deleting the `lqusers.toml` file on disk. -/// - Looking up users, validating credentials, and resolving tokens. -/// -/// Each variant implements a concise display message via `thiserror::Error` -/// and is suitable for logging or bubbling up to higher layers. #[derive(Error, Debug)] pub enum AuthenticationError { /// Failed to load the main configuration (`/etc/lqos.conf`) to @@ -306,11 +456,8 @@ pub enum AuthenticationError { /// `lqusers.toml` to disk. #[error("Unable to serialize to TOML")] SerializationError(toml_edit::ser::Error), - /// Failed to remove an existing `lqusers.toml` prior to rewriting it. - #[error("Unable to remove existing web users file")] - UnableToDelete, - /// Failed to create or write `lqusers.toml` (e.g., permissions or IO). - #[error("Unable to open lqusers.toml for writing. Check permissions?")] + /// Failed to persist `lqusers.toml` (e.g., permissions or IO). + #[error("Unable to write lqusers.toml")] UnableToWrite, /// Failed to read `lqusers.toml` from disk. #[error("Unable to read lqusers.toml")] @@ -318,13 +465,13 @@ pub enum AuthenticationError { /// Failed to parse `lqusers.toml` contents as valid TOML. #[error("Unable to parse lqusers.toml")] UnableToParse, + /// Password hash creation or verification failed. + #[error("Unable to process password hash")] + PasswordHashError(argon2::password_hash::Error), /// Attempted to remove or reference a user that does not exist. #[error("User not found")] UserNotFound, - /// Username/password did not match (and anonymous read-only is disabled). + /// Username/password did not match. #[error("Invalid Login")] InvalidLogin, - /// Provided token did not match any user (and anonymous read-only is disabled). - #[error("Invalid User Token")] - InvalidToken, } diff --git a/src/rust/lqos_config/src/lib.rs b/src/rust/lqos_config/src/lib.rs index 3ec74504..b01cdb62 100644 --- a/src/rust/lqos_config/src/lib.rs +++ b/src/rust/lqos_config/src/lib.rs @@ -11,11 +11,12 @@ pub mod authentication; mod cpu_topology; mod etc; mod network_json; +mod planner; mod program_control; mod qoo_profiles; mod shaped_devices; -pub use authentication::{UserRole, WebUser, WebUsers}; +pub use authentication::{AuthenticatedUser, UserRole, WebUser, WebUsers}; pub use cpu_topology::{ CpuListParseError, ShapingCpuDetection, ShapingCpuSource, detect_shaping_cpus, }; @@ -26,6 +27,12 @@ pub use etc::{ disable_xdp_bridge, enable_long_term_stats, load_config, update_config, }; pub use network_json::{NetworkJson, NetworkJsonNode, NetworkJsonTransport}; +pub use planner::{ + CircuitIdentityAssignment, CircuitIdentityGroupInput, ClassIdentityPlannerOutput, + PlannerCircuitIdentityState, PlannerSiteIdentityState, SiteIdentityAssignment, + SiteIdentityInput, TopLevelPlannerItem, TopLevelPlannerMode, TopLevelPlannerOutput, + TopLevelPlannerParams, plan_class_identities, plan_top_level_assignments, +}; pub use program_control::load_libreqos; pub use qoo_profiles::{ DEFAULT_QOO_PROFILE_ID, QooProfileInfo, QooProfilesError, active_qoo_profile, diff --git a/src/rust/lqos_config/src/network_json.rs b/src/rust/lqos_config/src/network_json.rs index f395ad2d..ca327a62 100644 --- a/src/rust/lqos_config/src/network_json.rs +++ b/src/rust/lqos_config/src/network_json.rs @@ -570,8 +570,10 @@ mod test { assert!(tiny.max_throughput.1 > 0.0); let transport = tiny.clone_to_transit(); + assert!(!transport.runtime_virtualized); let encoded = serde_json::to_value(&transport).expect("transport must serialize"); assert_eq!(encoded["max_throughput"], serde_json::json!([1.5, 0.5])); + assert_eq!(encoded["runtime_virtualized"], serde_json::json!(false)); } #[test] diff --git a/src/rust/lqos_config/src/network_json/network_json_node.rs b/src/rust/lqos_config/src/network_json/network_json_node.rs index 1ac1762e..993b2cb9 100644 --- a/src/rust/lqos_config/src/network_json/network_json_node.rs +++ b/src/rust/lqos_config/src/network_json/network_json_node.rs @@ -107,6 +107,7 @@ impl NetworkJsonNode { name: self.name.clone(), id: self.id.clone(), is_virtual: self.virtual_node, + runtime_virtualized: false, max_throughput: self.max_throughput, configured_max_throughput: self.max_throughput, effective_max_throughput: None, diff --git a/src/rust/lqos_config/src/network_json/network_json_transport.rs b/src/rust/lqos_config/src/network_json/network_json_transport.rs index 1017f99a..eb48d1e4 100644 --- a/src/rust/lqos_config/src/network_json/network_json_transport.rs +++ b/src/rust/lqos_config/src/network_json/network_json_transport.rs @@ -14,6 +14,9 @@ pub struct NetworkJsonTransport { /// True if this node is a "virtual" (logical-only) node. #[serde(rename = "virtual", default)] pub is_virtual: bool, + /// True if TreeGuard has runtime-virtualized this node in the active Bakery tree. + #[serde(default)] + pub runtime_virtualized: bool, /// Max throughput for node (not clamped) pub max_throughput: (f64, f64), /// Configured max throughput from `network.json`. diff --git a/src/rust/lqos_config/src/planner.rs b/src/rust/lqos_config/src/planner.rs new file mode 100644 index 00000000..fe1c832b --- /dev/null +++ b/src/rust/lqos_config/src/planner.rs @@ -0,0 +1,698 @@ +//! Shared planning helpers for physical queue placement. +//! +//! This module provides a reusable top-level CPU/bin planner so both the Python shaper build path +//! and future Bakery/TreeGuard runtime replans can use the same assignment logic. + +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +/// A top-level item to be assigned to a shaping queue/bin. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct TopLevelPlannerItem { + /// Stable logical identifier for the item being planned. + pub id: String, + /// Relative weight used when balancing items across bins. + pub weight: f64, +} + +/// Supported planner strategies. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub enum TopLevelPlannerMode { + /// Deterministic round-robin assignment by item id. + RoundRobin, + /// Deterministic greedy balancing with no hysteresis or cooldown. + Greedy, + /// Greedy balancing that prefers to keep prior assignments unless a move is worthwhile. + StableGreedy, +} + +impl Default for TopLevelPlannerMode { + fn default() -> Self { + Self::StableGreedy + } +} + +/// Tunables for top-level queue planning. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct TopLevelPlannerParams { + /// Planning mode. + pub mode: TopLevelPlannerMode, + /// Fraction of total weight improvement required before a move is considered worthwhile. + pub hysteresis_threshold: f64, + /// Minimum seconds between moves for a previously assigned item. + pub cooldown_seconds: f64, + /// Maximum number of assignment changes allowed in a single planning run. + pub move_budget_per_run: usize, +} + +impl Default for TopLevelPlannerParams { + fn default() -> Self { + Self { + mode: TopLevelPlannerMode::StableGreedy, + hysteresis_threshold: 0.03, + cooldown_seconds: 3600.0, + move_budget_per_run: 1, + } + } +} + +/// Result of a top-level assignment pass. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct TopLevelPlannerOutput { + /// Final per-item bin assignment. + pub assignment: BTreeMap, + /// Item ids whose assigned bin changed relative to the previous assignment map. + pub changed: Vec, + /// Whether the stable planner path, rather than a simple fallback, was used. + pub planner_used: bool, +} + +/// Input describing a site that needs class identity assignment. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct SiteIdentityInput { + /// Stable path key for the site within the logical hierarchy. + pub site_key: String, + /// Stable path key for the parent site, or empty for top-level nodes. + pub parent_path: String, + /// Target shaping queue number, 1-based. + pub queue: u32, + /// Whether this site has child sites in the physical tree. + pub has_children: bool, +} + +/// Assigned class identity for a site. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct SiteIdentityAssignment { + /// Stable path key for the site. + pub site_key: String, + /// Assigned queue number, 1-based. + pub queue: u32, + /// Assigned class minor. + pub class_minor: u16, + /// Assigned downlink class major. + pub class_major: u16, + /// Assigned uplink class major. + pub up_class_major: u16, + /// Parent path used when deciding minor reuse. + pub parent_path: String, +} + +/// Input describing a circuit group under a single parent site. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct CircuitIdentityGroupInput { + /// Parent node name for this group of circuits. + pub parent_node: String, + /// Queue number, 1-based. + pub queue: u32, + /// Circuit ids in deterministic order for this parent. + pub circuit_ids: Vec, +} + +/// Assigned class identity for a circuit. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct CircuitIdentityAssignment { + /// Stable circuit id. + pub circuit_id: String, + /// Parent node used when deciding minor reuse. + pub parent_node: String, + /// Assigned queue number, 1-based. + pub queue: u32, + /// Assigned class minor. + pub class_minor: u16, + /// Assigned downlink class major. + pub class_major: u16, + /// Assigned uplink class major. + pub up_class_major: u16, +} + +/// Persisted planner identity for a site. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] +pub struct PlannerSiteIdentityState { + /// Assigned class minor. + pub class_minor: u16, + /// Assigned queue number, 1-based. + pub queue: u32, + /// Stable parent path for reuse checks. + pub parent_path: String, + /// Downlink class major. + pub class_major: u16, + /// Uplink class major. + pub up_class_major: u16, +} + +/// Persisted planner identity for a circuit. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] +pub struct PlannerCircuitIdentityState { + /// Assigned class minor. + pub class_minor: u16, + /// Assigned queue number, 1-based. + pub queue: u32, + /// Stable parent node for reuse checks. + pub parent_node: String, + /// Downlink class major. + pub class_major: u16, + /// Uplink class major. + pub up_class_major: u16, +} + +/// Output of site/circuit identity assignment. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct ClassIdentityPlannerOutput { + /// Assigned site identities keyed in traversal order. + pub sites: Vec, + /// Assigned circuit identities keyed in traversal order. + pub circuits: Vec, + /// Planner-state site map suitable for persistence. + pub site_state: BTreeMap, + /// Planner-state circuit map suitable for persistence. + pub circuit_state: BTreeMap, + /// Highest allocated minor counter per queue after assignment. + pub last_used_minor_by_queue: BTreeMap, +} + +fn sanitize_weight(weight: f64) -> f64 { + if !weight.is_finite() || weight <= 0.0 { + 1.0 + } else { + weight + } +} + +fn next_free_minor(start_minor: u32, reserved: &std::collections::BTreeSet) -> u32 { + let mut candidate = start_minor.max(3); + while reserved.contains(&candidate) { + candidate += 1; + } + candidate +} + +fn round_robin_assign(items: &[TopLevelPlannerItem], bins: &[String]) -> BTreeMap { + let mut ids: Vec<&str> = items.iter().map(|item| item.id.as_str()).collect(); + ids.sort_unstable(); + + let mut assignment = BTreeMap::new(); + for (idx, id) in ids.into_iter().enumerate() { + if let Some(bin) = bins.get(idx % bins.len()) { + assignment.insert(id.to_string(), bin.clone()); + } + } + assignment +} + +fn greedy_assign(items: &[TopLevelPlannerItem], bins: &[String]) -> BTreeMap { + let mut pairs: Vec<(&str, f64)> = items + .iter() + .map(|item| (item.id.as_str(), sanitize_weight(item.weight))) + .collect(); + pairs.sort_by(|a, b| { + b.1.partial_cmp(&a.1) + .unwrap_or(std::cmp::Ordering::Equal) + .then_with(|| a.0.cmp(b.0)) + }); + + let mut loads: BTreeMap = bins.iter().cloned().map(|bin| (bin, 0.0)).collect(); + let mut assignment = BTreeMap::new(); + for (id, weight) in pairs { + let target = loads + .iter() + .min_by(|a, b| { + a.1.partial_cmp(b.1) + .unwrap_or(std::cmp::Ordering::Equal) + .then_with(|| a.0.cmp(b.0)) + }) + .map(|(bin, _)| bin.clone()) + .unwrap_or_else(|| bins[0].clone()); + assignment.insert(id.to_string(), target.clone()); + if let Some(load) = loads.get_mut(&target) { + *load += weight; + } + } + assignment +} + +fn load_by_bin( + assignment: &BTreeMap, + item_weights: &BTreeMap, + bins: &[String], +) -> BTreeMap { + let mut loads: BTreeMap = bins.iter().cloned().map(|bin| (bin, 0.0)).collect(); + for (id, bin) in assignment { + if let Some(weight) = item_weights.get(id) + && let Some(load) = loads.get_mut(bin) + { + *load += *weight; + } + } + loads +} + +/// Plans top-level queue assignments for the given logical items and bins. +/// +/// This function is pure: it computes a deterministic assignment and does not perform any I/O. +pub fn plan_top_level_assignments( + items: &[TopLevelPlannerItem], + bins: &[String], + prev_assign: &BTreeMap, + last_change_ts: &BTreeMap, + now_ts: f64, + params: &TopLevelPlannerParams, +) -> TopLevelPlannerOutput { + if bins.is_empty() || items.is_empty() { + return TopLevelPlannerOutput { + assignment: BTreeMap::new(), + changed: Vec::new(), + planner_used: !matches!(params.mode, TopLevelPlannerMode::RoundRobin), + }; + } + + let item_ids: Vec = items.iter().map(|item| item.id.clone()).collect(); + let item_weights: BTreeMap = items + .iter() + .map(|item| (item.id.clone(), sanitize_weight(item.weight))) + .collect(); + let valid_bins: std::collections::BTreeSet<&String> = bins.iter().collect(); + let prev_valid: BTreeMap = prev_assign + .iter() + .filter(|(id, bin)| item_weights.contains_key(*id) && valid_bins.contains(*bin)) + .map(|(id, bin)| (id.clone(), bin.clone())) + .collect(); + + let rr_assignment = round_robin_assign(items, bins); + let greedy_assignment = greedy_assign(items, bins); + + let (mut assignment, planner_used) = match params.mode { + TopLevelPlannerMode::RoundRobin => (rr_assignment.clone(), false), + TopLevelPlannerMode::Greedy => (greedy_assignment.clone(), false), + TopLevelPlannerMode::StableGreedy => { + let mut assignment = rr_assignment.clone(); + for id in &item_ids { + let chosen = prev_valid + .get(id) + .cloned() + .or_else(|| greedy_assignment.get(id).cloned()) + .or_else(|| rr_assignment.get(id).cloned()) + .unwrap_or_else(|| bins[0].clone()); + assignment.insert(id.clone(), chosen); + } + + let mut loads = load_by_bin(&assignment, &item_weights, bins); + let total_weight: f64 = item_weights.values().sum(); + let min_improvement = total_weight * params.hysteresis_threshold.max(0.0); + let mut weighted_ids = item_ids.clone(); + weighted_ids.sort_by(|a, b| { + item_weights[b] + .partial_cmp(&item_weights[a]) + .unwrap_or(std::cmp::Ordering::Equal) + .then_with(|| a.cmp(b)) + }); + + let mut moves_used = 0usize; + for id in weighted_ids { + let Some(current_bin) = assignment.get(&id).cloned() else { + continue; + }; + let Some(target_bin) = greedy_assignment.get(&id).cloned() else { + continue; + }; + if current_bin == target_bin { + continue; + } + if moves_used >= params.move_budget_per_run { + continue; + } + let last_changed = last_change_ts.get(&id).copied().unwrap_or(0.0); + if now_ts - last_changed < params.cooldown_seconds { + continue; + } + let current_load = loads.get(¤t_bin).copied().unwrap_or(0.0); + let target_load = loads.get(&target_bin).copied().unwrap_or(0.0); + if current_load - target_load <= min_improvement { + continue; + } + + let weight = item_weights.get(&id).copied().unwrap_or(1.0); + if let Some(load) = loads.get_mut(¤t_bin) { + *load -= weight; + } + if let Some(load) = loads.get_mut(&target_bin) { + *load += weight; + } + assignment.insert(id, target_bin); + moves_used += 1; + } + + (assignment, true) + } + }; + + let used_bins: std::collections::BTreeSet<&String> = assignment.values().collect(); + if bins.len() > 1 && assignment.len() > 1 && used_bins.len() <= 1 { + assignment = greedy_assignment.clone(); + } + + let mut changed: Vec = assignment + .iter() + .filter_map(|(id, bin)| { + prev_valid + .get(id) + .and_then(|prev| (prev != bin).then_some(id.clone())) + }) + .collect(); + changed.sort_unstable(); + + TopLevelPlannerOutput { + assignment, + changed, + planner_used, + } +} + +/// Plans site and circuit class identities for a physical queue tree. +/// +/// This function is pure: it computes deterministic minor/class-major assignments from the +/// provided planner state and traversal order without performing any I/O. +pub fn plan_class_identities( + sites: &[SiteIdentityInput], + circuit_groups: &[CircuitIdentityGroupInput], + previous_sites: &BTreeMap, + previous_circuits: &BTreeMap, + stick_offset: u16, + circuit_padding: u32, +) -> ClassIdentityPlannerOutput { + let mut reserved_site_minors: BTreeMap> = BTreeMap::new(); + let mut next_site_minor_by_queue: BTreeMap = BTreeMap::new(); + let mut site_assignments = Vec::with_capacity(sites.len()); + let mut site_state = BTreeMap::new(); + + for site in sites { + let reserved = reserved_site_minors.entry(site.queue).or_default(); + let next_minor = next_site_minor_by_queue.entry(site.queue).or_insert(3); + let reuse_minor = previous_sites.get(&site.site_key).and_then(|stored| { + (stored.queue == site.queue + && stored.parent_path == site.parent_path + && !reserved.contains(&(stored.class_minor as u32))) + .then_some(stored.class_minor as u32) + }); + + let class_minor_u32 = reuse_minor.unwrap_or_else(|| next_free_minor(*next_minor, reserved)); + let class_minor = u16::try_from(class_minor_u32).unwrap_or(u16::MAX); + let class_major = u16::try_from(site.queue).unwrap_or(u16::MAX); + let up_class_major = class_major.saturating_add(stick_offset); + reserved.insert(class_minor_u32); + *next_minor = (*next_minor).max(class_minor_u32).saturating_add(1); + if site.has_children { + *next_minor = (*next_minor).saturating_add(1); + } + + let assigned = SiteIdentityAssignment { + site_key: site.site_key.clone(), + queue: site.queue, + class_minor, + class_major, + up_class_major, + parent_path: site.parent_path.clone(), + }; + site_state.insert( + site.site_key.clone(), + PlannerSiteIdentityState { + class_minor, + queue: site.queue, + parent_path: site.parent_path.clone(), + class_major, + up_class_major, + }, + ); + site_assignments.push(assigned); + } + + let mut reserved_circuit_minors: BTreeMap> = + reserved_site_minors.clone(); + let mut next_circuit_minor_by_queue = BTreeMap::new(); + for (queue, reserved) in &reserved_circuit_minors { + let start = next_site_minor_by_queue + .get(queue) + .copied() + .unwrap_or_else(|| next_free_minor(3, reserved)); + next_circuit_minor_by_queue.insert(*queue, next_free_minor(start, reserved)); + } + + let mut circuit_assignments = Vec::new(); + let mut circuit_state = BTreeMap::new(); + for group in circuit_groups { + let reserved = reserved_circuit_minors.entry(group.queue).or_default(); + let next_minor = next_circuit_minor_by_queue + .entry(group.queue) + .or_insert_with(|| next_free_minor(3, reserved)); + for circuit_id in &group.circuit_ids { + let reuse_minor = previous_circuits.get(circuit_id).and_then(|stored| { + (stored.queue == group.queue + && stored.parent_node == group.parent_node + && !reserved.contains(&(stored.class_minor as u32))) + .then_some(stored.class_minor as u32) + }); + let class_minor_u32 = + reuse_minor.unwrap_or_else(|| next_free_minor(*next_minor, reserved)); + let class_minor = u16::try_from(class_minor_u32).unwrap_or(u16::MAX); + let class_major = u16::try_from(group.queue).unwrap_or(u16::MAX); + let up_class_major = class_major.saturating_add(stick_offset); + reserved.insert(class_minor_u32); + *next_minor = (*next_minor).max(class_minor_u32).saturating_add(1); + + circuit_assignments.push(CircuitIdentityAssignment { + circuit_id: circuit_id.clone(), + parent_node: group.parent_node.clone(), + queue: group.queue, + class_minor, + class_major, + up_class_major, + }); + circuit_state.insert( + circuit_id.clone(), + PlannerCircuitIdentityState { + class_minor, + queue: group.queue, + parent_node: group.parent_node.clone(), + class_major, + up_class_major, + }, + ); + } + *next_minor = (*next_minor).saturating_add(circuit_padding); + } + + let mut last_used_minor_by_queue = BTreeMap::new(); + for queue in reserved_circuit_minors + .keys() + .chain(next_site_minor_by_queue.keys()) + .cloned() + .collect::>() + { + let site_next = next_site_minor_by_queue.get(&queue).copied().unwrap_or(3); + let circuit_next = next_circuit_minor_by_queue + .get(&queue) + .copied() + .unwrap_or(3); + last_used_minor_by_queue.insert(queue, site_next.max(circuit_next)); + } + + ClassIdentityPlannerOutput { + sites: site_assignments, + circuits: circuit_assignments, + site_state, + circuit_state, + last_used_minor_by_queue, + } +} + +#[cfg(test)] +mod tests { + use super::{ + CircuitIdentityGroupInput, PlannerCircuitIdentityState, PlannerSiteIdentityState, + SiteIdentityInput, TopLevelPlannerItem, TopLevelPlannerMode, TopLevelPlannerParams, + plan_class_identities, plan_top_level_assignments, + }; + use std::collections::BTreeMap; + + fn bins() -> Vec { + vec!["CpueQueue0".to_string(), "CpueQueue1".to_string()] + } + + #[test] + fn round_robin_is_deterministic() { + let items = vec![ + TopLevelPlannerItem { + id: "b".to_string(), + weight: 1.0, + }, + TopLevelPlannerItem { + id: "a".to_string(), + weight: 1.0, + }, + ]; + let result = plan_top_level_assignments( + &items, + &bins(), + &BTreeMap::new(), + &BTreeMap::new(), + 0.0, + &TopLevelPlannerParams { + mode: TopLevelPlannerMode::RoundRobin, + ..Default::default() + }, + ); + assert_eq!( + result.assignment.get("a").map(String::as_str), + Some("CpueQueue0") + ); + assert_eq!( + result.assignment.get("b").map(String::as_str), + Some("CpueQueue1") + ); + assert!(!result.planner_used); + } + + #[test] + fn stable_greedy_breaks_degenerate_single_bin_assignments() { + let items = vec![ + TopLevelPlannerItem { + id: "heavy".to_string(), + weight: 100.0, + }, + TopLevelPlannerItem { + id: "light".to_string(), + weight: 1.0, + }, + ]; + let prev_assign = BTreeMap::from([ + ("heavy".to_string(), "CpueQueue0".to_string()), + ("light".to_string(), "CpueQueue0".to_string()), + ]); + let last_change_ts = + BTreeMap::from([("heavy".to_string(), 990.0), ("light".to_string(), 990.0)]); + let result = plan_top_level_assignments( + &items, + &bins(), + &prev_assign, + &last_change_ts, + 1000.0, + &TopLevelPlannerParams { + mode: TopLevelPlannerMode::StableGreedy, + cooldown_seconds: 3600.0, + move_budget_per_run: 1, + hysteresis_threshold: 0.0, + }, + ); + assert_eq!( + result.assignment.get("light").map(String::as_str), + Some("CpueQueue1") + ); + assert_eq!(result.changed, vec!["light".to_string()]); + } + + #[test] + fn stable_greedy_can_move_when_cooldown_expired() { + let items = vec![ + TopLevelPlannerItem { + id: "heavy".to_string(), + weight: 100.0, + }, + TopLevelPlannerItem { + id: "light".to_string(), + weight: 1.0, + }, + ]; + let prev_assign = BTreeMap::from([ + ("heavy".to_string(), "CpueQueue0".to_string()), + ("light".to_string(), "CpueQueue0".to_string()), + ]); + let result = plan_top_level_assignments( + &items, + &bins(), + &prev_assign, + &BTreeMap::new(), + 10_000.0, + &TopLevelPlannerParams { + mode: TopLevelPlannerMode::StableGreedy, + cooldown_seconds: 0.0, + move_budget_per_run: 1, + hysteresis_threshold: 0.0, + }, + ); + assert_eq!( + result.assignment.get("light").map(String::as_str), + Some("CpueQueue1") + ); + assert_eq!(result.changed, vec!["light".to_string()]); + assert!(result.planner_used); + } + + #[test] + fn class_identity_planner_reuses_site_and_circuit_minors() { + let site_inputs = vec![ + SiteIdentityInput { + site_key: "CpueQueue0/site-a".to_string(), + parent_path: "CpueQueue0".to_string(), + queue: 1, + has_children: true, + }, + SiteIdentityInput { + site_key: "CpueQueue0/site-a/child".to_string(), + parent_path: "CpueQueue0/site-a".to_string(), + queue: 1, + has_children: false, + }, + ]; + let circuit_groups = vec![CircuitIdentityGroupInput { + parent_node: "child".to_string(), + queue: 1, + circuit_ids: vec!["c1".to_string(), "c2".to_string()], + }]; + let prev_sites = BTreeMap::from([ + ( + "CpueQueue0/site-a".to_string(), + PlannerSiteIdentityState { + class_minor: 0x20, + queue: 1, + parent_path: "CpueQueue0".to_string(), + class_major: 1, + up_class_major: 0x41, + }, + ), + ( + "CpueQueue0/site-a/child".to_string(), + PlannerSiteIdentityState { + class_minor: 0x22, + queue: 1, + parent_path: "CpueQueue0/site-a".to_string(), + class_major: 1, + up_class_major: 0x41, + }, + ), + ]); + let prev_circuits = BTreeMap::from([( + "c1".to_string(), + PlannerCircuitIdentityState { + class_minor: 0x30, + queue: 1, + parent_node: "child".to_string(), + class_major: 1, + up_class_major: 0x41, + }, + )]); + + let result = plan_class_identities( + &site_inputs, + &circuit_groups, + &prev_sites, + &prev_circuits, + 0x40, + 8, + ); + + assert_eq!(result.sites[0].class_minor, 0x20); + assert_eq!(result.sites[1].class_minor, 0x22); + assert_eq!(result.circuits[0].class_minor, 0x30); + assert_eq!(result.circuits[1].queue, 1); + assert_eq!(result.circuits[1].class_major, 1); + } +} diff --git a/src/rust/lqos_overrides/src/overrides_file.rs b/src/rust/lqos_overrides/src/overrides_file.rs index 4459ce5e..7a5c1abd 100644 --- a/src/rust/lqos_overrides/src/overrides_file.rs +++ b/src/rust/lqos_overrides/src/overrides_file.rs @@ -371,7 +371,7 @@ fn merge_circuit_adjustments_owned( fn merge_network_adjustments_owned( operator_adjustments: &[NetworkAdjustment], stormguard_adjustments: &[NetworkAdjustment], - treeguard_adjustments: &[NetworkAdjustment], + _treeguard_adjustments: &[NetworkAdjustment], ) -> Vec { use std::collections::{HashMap, HashSet}; @@ -403,27 +403,7 @@ fn merge_network_adjustments_owned( } } - let mut treeguard_virtual: HashMap<&str, bool> = HashMap::new(); - let mut treeguard_virtual_order: Vec<&str> = Vec::new(); - let mut treeguard_virtual_seen: HashSet<&str> = HashSet::new(); - - for adj in treeguard_adjustments { - if let NetworkAdjustment::SetNodeVirtual { - node_name, - virtual_node, - } = adj - { - let name = node_name.as_str(); - treeguard_virtual.insert(name, *virtual_node); - if !treeguard_virtual_seen.contains(name) { - treeguard_virtual_order.push(name); - treeguard_virtual_seen.insert(name); - } - } - } - let mut out = Vec::new(); - let mut used_treeguard_virtual: HashSet<&str> = HashSet::new(); let mut operator_virtual_seen: HashSet<&str> = HashSet::new(); let mut operator_site_speed_seen: HashSet = HashSet::new(); let mut operator_site_name_seen: HashSet = HashSet::new(); @@ -439,19 +419,10 @@ fn merge_network_adjustments_owned( continue; } operator_virtual_seen.insert(name); - - if let Some(v) = treeguard_virtual.get(name) { - out.push(NetworkAdjustment::SetNodeVirtual { - node_name: node_name.clone(), - virtual_node: *v, - }); - used_treeguard_virtual.insert(name); - } else { - out.push(NetworkAdjustment::SetNodeVirtual { - node_name: node_name.clone(), - virtual_node: *virtual_node, - }); - } + out.push(NetworkAdjustment::SetNodeVirtual { + node_name: node_name.clone(), + virtual_node: *virtual_node, + }); } NetworkAdjustment::AdjustSiteSpeed { node_id, @@ -499,20 +470,6 @@ fn merge_network_adjustments_owned( }); } - // Append TreeGuard-only virtual-node entries (ignore other network adjustments). - for name in treeguard_virtual_order { - if used_treeguard_virtual.contains(name) { - continue; - } - let Some(v) = treeguard_virtual.get(name) else { - continue; - }; - out.push(NetworkAdjustment::SetNodeVirtual { - node_name: name.to_string(), - virtual_node: *v, - }); - } - out } @@ -1130,7 +1087,7 @@ mod tests { } #[test] - fn effective_merge_treeguard_wins_for_node_virtual_only() { + fn effective_merge_keeps_operator_node_virtual_and_ignores_treeguard_runtime_virtualization() { let mut operator = OverrideFile::default(); operator.set_network_node_virtual("NodeA".to_string(), false); operator.add_network_adjustment(NetworkAdjustment::AdjustSiteSpeed { @@ -1165,7 +1122,19 @@ mod tests { } if node_name == "NodeA" => Some(*virtual_node), _ => None, }); - assert_eq!(node_a_virtual, Some(true)); + assert_eq!(node_a_virtual, Some(false)); + + let node_three_virtual = merged + .network_adjustments() + .iter() + .find_map(|adj| match adj { + NetworkAdjustment::SetNodeVirtual { + node_name, + virtual_node, + } if node_name == "Node3" => Some(*virtual_node), + _ => None, + }); + assert_eq!(node_three_virtual, None); // Operator site speed should beat StormGuard; TreeGuard site speed should be ignored. let site_speed_names: Vec<&str> = merged diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index a9f2ce58..fb9ef326 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -12,7 +12,7 @@ use lqos_utils::rustls::ensure_rustls_crypto_provider; use nix::libc::getpid; use pyo3::exceptions::PyOSError; use pyo3::prelude::*; -use pyo3::types::PyDict; +use pyo3::types::{PyDict, PyList}; use std::{ fs::{File, read_to_string, remove_file}, io::Write, @@ -114,6 +114,273 @@ fn get_bool(d: &pyo3::Bound<'_, pyo3::types::PyDict>, key: &str, default: bool) } } +#[pyfunction( + signature = ( + items, + queues_available, + prev_assign=None, + last_change_ts=None, + now_ts=None, + mode=None, + move_budget_per_run=None, + cooldown_seconds=None, + hysteresis_threshold=None + ) +)] +fn plan_top_level_cpu_bins( + py: Python, + items: PyObject, + queues_available: usize, + prev_assign: Option, + last_change_ts: Option, + now_ts: Option, + mode: Option, + move_budget_per_run: Option, + cooldown_seconds: Option, + hysteresis_threshold: Option, +) -> PyResult { + let items_any = items.bind(py); + let items_list = items_any.downcast::()?; + let planner_items: Vec = items_list + .iter() + .map(|item| -> PyResult { + let dict = item.downcast::()?; + let id = get_string(dict, "id", String::new()); + let weight = get_f64(dict, "weight", 1.0); + Ok(lqos_config::TopLevelPlannerItem { id, weight }) + }) + .collect::>>()?; + + let prev_assign_map = match prev_assign { + Some(obj) => { + let any = obj.bind(py); + let dict = any.downcast::()?; + dict.iter() + .filter_map(|(k, v)| { + Some((k.extract::().ok()?, v.extract::().ok()?)) + }) + .collect::>() + } + None => BTreeMap::new(), + }; + let last_change_map = match last_change_ts { + Some(obj) => { + let any = obj.bind(py); + let dict = any.downcast::()?; + dict.iter() + .filter_map(|(k, v)| Some((k.extract::().ok()?, v.extract::().ok()?))) + .collect::>() + } + None => BTreeMap::new(), + }; + + let bins: Vec = (0..queues_available) + .map(|idx| format!("CpueQueue{idx}")) + .collect(); + let planner_mode = match mode.as_deref() { + Some("round_robin") => lqos_config::TopLevelPlannerMode::RoundRobin, + Some("greedy") => lqos_config::TopLevelPlannerMode::Greedy, + _ => lqos_config::TopLevelPlannerMode::StableGreedy, + }; + let params = lqos_config::TopLevelPlannerParams { + mode: planner_mode, + hysteresis_threshold: hysteresis_threshold.unwrap_or(0.03), + cooldown_seconds: cooldown_seconds.unwrap_or(3600.0), + move_budget_per_run: move_budget_per_run.unwrap_or(1), + }; + let result = lqos_config::plan_top_level_assignments( + &planner_items, + &bins, + &prev_assign_map, + &last_change_map, + now_ts.unwrap_or_else(|| { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs_f64()) + .unwrap_or(0.0) + }), + ¶ms, + ); + + let out = PyDict::new(py); + let assignment = PyDict::new(py); + for (item, bin) in result.assignment { + assignment.set_item(item, bin)?; + } + out.set_item("assignment", assignment)?; + out.set_item("changed", result.changed)?; + out.set_item("planner_used", result.planner_used)?; + Ok(out.into()) +} + +#[pyfunction( + signature = ( + sites, + circuit_groups, + site_state=None, + circuit_state=None, + stick_offset=0, + circuit_padding=8 + ) +)] +fn plan_class_identities( + py: Python, + sites: PyObject, + circuit_groups: PyObject, + site_state: Option, + circuit_state: Option, + stick_offset: u16, + circuit_padding: u32, +) -> PyResult { + let sites_list = sites.bind(py).downcast::()?; + let site_inputs: Vec = sites_list + .iter() + .map(|item| -> PyResult { + let dict = item.downcast::()?; + Ok(lqos_config::SiteIdentityInput { + site_key: get_string(dict, "site_key", String::new()), + parent_path: get_string(dict, "parent_path", String::new()), + queue: get_i64(dict, "queue", 0).max(0) as u32, + has_children: get_bool(dict, "has_children", false), + }) + }) + .collect::>>()?; + + let groups_list = circuit_groups.bind(py).downcast::()?; + let circuit_group_inputs: Vec = groups_list + .iter() + .map(|item| -> PyResult { + let dict = item.downcast::()?; + let ids = match dict.get_item("circuit_ids")? { + Some(value) => value + .downcast::()? + .iter() + .filter_map(|entry| entry.extract::().ok()) + .collect::>(), + None => Vec::new(), + }; + Ok(lqos_config::CircuitIdentityGroupInput { + parent_node: get_string(dict, "parent_node", String::new()), + queue: get_i64(dict, "queue", 0).max(0) as u32, + circuit_ids: ids, + }) + }) + .collect::>>()?; + + let previous_sites = match site_state { + Some(obj) => { + let dict = obj.bind(py).downcast::()?; + dict.iter() + .filter_map(|(k, v)| { + let key = k.extract::().ok()?; + let entry = v.downcast::().ok()?; + Some(( + key, + lqos_config::PlannerSiteIdentityState { + class_minor: get_i64(entry, "class_minor", 0).max(0) as u16, + queue: get_i64(entry, "queue", 0).max(0) as u32, + parent_path: get_string(entry, "parent_path", String::new()), + class_major: get_i64(entry, "class_major", 0).max(0) as u16, + up_class_major: get_i64(entry, "up_class_major", 0).max(0) as u16, + }, + )) + }) + .collect::>() + } + None => BTreeMap::new(), + }; + + let previous_circuits = match circuit_state { + Some(obj) => { + let dict = obj.bind(py).downcast::()?; + dict.iter() + .filter_map(|(k, v)| { + let key = k.extract::().ok()?; + let entry = v.downcast::().ok()?; + Some(( + key, + lqos_config::PlannerCircuitIdentityState { + class_minor: get_i64(entry, "class_minor", 0).max(0) as u16, + queue: get_i64(entry, "queue", 0).max(0) as u32, + parent_node: get_string(entry, "parent_node", String::new()), + class_major: get_i64(entry, "class_major", 0).max(0) as u16, + up_class_major: get_i64(entry, "up_class_major", 0).max(0) as u16, + }, + )) + }) + .collect::>() + } + None => BTreeMap::new(), + }; + + let result = lqos_config::plan_class_identities( + &site_inputs, + &circuit_group_inputs, + &previous_sites, + &previous_circuits, + stick_offset, + circuit_padding, + ); + + let out = PyDict::new(py); + let sites_out = PyList::empty(py); + for site in result.sites { + let d = PyDict::new(py); + d.set_item("site_key", site.site_key)?; + d.set_item("queue", site.queue)?; + d.set_item("class_minor", site.class_minor)?; + d.set_item("class_major", site.class_major)?; + d.set_item("up_class_major", site.up_class_major)?; + d.set_item("parent_path", site.parent_path)?; + sites_out.append(d)?; + } + out.set_item("sites", sites_out)?; + + let circuits_out = PyList::empty(py); + for circuit in result.circuits { + let d = PyDict::new(py); + d.set_item("circuit_id", circuit.circuit_id)?; + d.set_item("parent_node", circuit.parent_node)?; + d.set_item("queue", circuit.queue)?; + d.set_item("class_minor", circuit.class_minor)?; + d.set_item("class_major", circuit.class_major)?; + d.set_item("up_class_major", circuit.up_class_major)?; + circuits_out.append(d)?; + } + out.set_item("circuits", circuits_out)?; + + let site_state_out = PyDict::new(py); + for (key, state) in result.site_state { + let d = PyDict::new(py); + d.set_item("class_minor", state.class_minor)?; + d.set_item("queue", state.queue)?; + d.set_item("parent_path", state.parent_path)?; + d.set_item("class_major", state.class_major)?; + d.set_item("up_class_major", state.up_class_major)?; + site_state_out.set_item(key, d)?; + } + out.set_item("site_state", site_state_out)?; + + let circuit_state_out = PyDict::new(py); + for (key, state) in result.circuit_state { + let d = PyDict::new(py); + d.set_item("class_minor", state.class_minor)?; + d.set_item("queue", state.queue)?; + d.set_item("parent_node", state.parent_node)?; + d.set_item("class_major", state.class_major)?; + d.set_item("up_class_major", state.up_class_major)?; + circuit_state_out.set_item(key, d)?; + } + out.set_item("circuit_state", circuit_state_out)?; + + let last_used = PyDict::new(py); + for (queue, minor) in result.last_used_minor_by_queue { + last_used.set_item(queue, minor)?; + } + out.set_item("last_used_minor_by_queue", last_used)?; + Ok(out.into()) +} + #[pyfunction] fn write_planner_cbor(py: Python, path: String, state: PyObject) -> PyResult { use std::fs; @@ -672,11 +939,19 @@ fn liblqos_python(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(get_libreqos_directory, m)?)?; m.add_function(wrap_pyfunction!(overrides_persistent_devices, m)?)?; m.add_function(wrap_pyfunction!(overrides_persistent_devices_effective, m)?)?; + m.add_function(wrap_pyfunction!( + overrides_persistent_devices_materialized, + m + )?)?; m.add_function(wrap_pyfunction!(overrides_circuit_adjustments, m)?)?; m.add_function(wrap_pyfunction!( overrides_circuit_adjustments_effective, m )?)?; + m.add_function(wrap_pyfunction!( + overrides_circuit_adjustments_materialized, + m + )?)?; m.add_function(wrap_pyfunction!(overrides_network_adjustments, m)?)?; m.add_function(wrap_pyfunction!( overrides_network_adjustments_effective, @@ -710,6 +985,8 @@ fn liblqos_python(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(store_planner_remote, m)?)?; m.add_function(wrap_pyfunction!(write_planner_cbor, m)?)?; m.add_function(wrap_pyfunction!(read_planner_cbor, m)?)?; + m.add_function(wrap_pyfunction!(plan_top_level_cpu_bins, m)?)?; + m.add_function(wrap_pyfunction!(plan_class_identities, m)?)?; m.add_class::()?; Ok(()) @@ -1114,6 +1391,59 @@ fn overrides_persistent_devices_effective(py: Python<'_>) -> PyResult) -> PyResult> { + let overrides = match lqos_overrides::OverrideStore::load_effective(false, false) { + Ok(o) => o, + Err(e) => return Err(PyOSError::new_err(e.to_string())), + }; + + let mut out: Vec = Vec::new(); + for dev in overrides.persistent_devices().iter() { + let ipv4s: Vec = dev + .ipv4 + .iter() + .map(|(ip, prefix)| format!("{}/{}", ip, prefix)) + .collect(); + let ipv6s: Vec = dev + .ipv6 + .iter() + .map(|(ip, prefix)| format!("{}/{}", ip, prefix)) + .collect(); + + let d = PyDict::new(py); + d.set_item("circuitID", dev.circuit_id.clone())?; + d.set_item("circuitName", dev.circuit_name.clone())?; + d.set_item("deviceID", dev.device_id.clone())?; + d.set_item("deviceName", dev.device_name.clone())?; + d.set_item("ParentNode", dev.parent_node.clone())?; + d.set_item("mac", dev.mac.clone())?; + d.set_item("ipv4s", ipv4s)?; + d.set_item("ipv6s", ipv6s)?; + d.set_item("minDownload", dev.download_min_mbps)?; + d.set_item("minUpload", dev.upload_min_mbps)?; + d.set_item("maxDownload", dev.download_max_mbps)?; + d.set_item("maxUpload", dev.upload_max_mbps)?; + d.set_item("comment", dev.comment.clone())?; + d.set_item( + "sqm", + dev.sqm_override + .as_ref() + .map(|s| s.to_string()) + .unwrap_or_default(), + )?; + let obj: PyObject = d.unbind().into(); + out.push(obj); + } + + Ok(out) +} + /// Returns the list of circuit adjustments as Python dicts. #[pyfunction] fn overrides_circuit_adjustments(py: Python<'_>) -> PyResult> { @@ -1303,6 +1633,99 @@ fn overrides_circuit_adjustments_effective(py: Python<'_>) -> PyResult) -> PyResult> { + let overrides = match lqos_overrides::OverrideStore::load_effective(false, false) { + Ok(o) => o, + Err(e) => return Err(PyOSError::new_err(e.to_string())), + }; + + let mut out: Vec = Vec::new(); + for adj in overrides.circuit_adjustments().iter() { + let d = PyDict::new(py); + match adj { + lqos_overrides::CircuitAdjustment::CircuitAdjustSpeed { + circuit_id, + min_download_bandwidth, + max_download_bandwidth, + min_upload_bandwidth, + max_upload_bandwidth, + } => { + d.set_item("type", "circuit_adjust_speed")?; + d.set_item("circuit_id", circuit_id.clone())?; + if let Some(v) = min_download_bandwidth { + d.set_item("min_download_bandwidth", *v)?; + } + if let Some(v) = max_download_bandwidth { + d.set_item("max_download_bandwidth", *v)?; + } + if let Some(v) = min_upload_bandwidth { + d.set_item("min_upload_bandwidth", *v)?; + } + if let Some(v) = max_upload_bandwidth { + d.set_item("max_upload_bandwidth", *v)?; + } + } + lqos_overrides::CircuitAdjustment::DeviceAdjustSpeed { + device_id, + min_download_bandwidth, + max_download_bandwidth, + min_upload_bandwidth, + max_upload_bandwidth, + } => { + d.set_item("type", "device_adjust_speed")?; + d.set_item("device_id", device_id.clone())?; + if let Some(v) = min_download_bandwidth { + d.set_item("min_download_bandwidth", *v)?; + } + if let Some(v) = max_download_bandwidth { + d.set_item("max_download_bandwidth", *v)?; + } + if let Some(v) = min_upload_bandwidth { + d.set_item("min_upload_bandwidth", *v)?; + } + if let Some(v) = max_upload_bandwidth { + d.set_item("max_upload_bandwidth", *v)?; + } + } + lqos_overrides::CircuitAdjustment::DeviceAdjustSqm { + device_id, + sqm_override, + } => { + d.set_item("type", "device_adjust_sqm")?; + d.set_item("device_id", device_id.clone())?; + if let Some(value) = sqm_override { + d.set_item("sqm_override", value.clone())?; + } + } + lqos_overrides::CircuitAdjustment::RemoveCircuit { circuit_id } => { + d.set_item("type", "remove_circuit")?; + d.set_item("circuit_id", circuit_id.clone())?; + } + lqos_overrides::CircuitAdjustment::RemoveDevice { device_id } => { + d.set_item("type", "remove_device")?; + d.set_item("device_id", device_id.clone())?; + } + lqos_overrides::CircuitAdjustment::ReparentCircuit { + circuit_id, + parent_node, + } => { + d.set_item("type", "reparent_circuit")?; + d.set_item("circuit_id", circuit_id.clone())?; + d.set_item("parent_node", parent_node.clone())?; + } + } + let obj: PyObject = d.unbind().into(); + out.push(obj); + } + + Ok(out) +} + /// Returns the list of network adjustments as Python dicts. #[pyfunction] fn overrides_network_adjustments(py: Python<'_>) -> PyResult> { @@ -2346,26 +2769,56 @@ impl Bakery { let estimate = estimate_full_reload_auto_qdisc_budget(&config, &queue); let is_ok = estimate.ok(); let interface_reports = estimate - .interfaces + .interface_details .iter() - .map(|(name, planned_qdiscs)| BakeryCapacityReportInterface { + .map(|(name, detail)| BakeryCapacityReportInterface { name: name.clone(), - planned_qdiscs: *planned_qdiscs, + planned_qdiscs: detail.planned_qdiscs, + infra_qdiscs: detail.infra_qdiscs, + cake_qdiscs: detail.cake_qdiscs, + fq_codel_qdiscs: detail.fq_codel_qdiscs, + estimated_memory_bytes: detail.estimated_memory_bytes, }) .collect::>(); + let memory_summary = if let Some(snapshot) = estimate.memory_snapshot.as_ref() { + format!( + "estimated qdisc memory {} bytes with {} bytes currently available and safety floor {} bytes", + estimate.estimated_total_memory_bytes, + snapshot.available_bytes, + lqos_bakery::BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES + ) + } else { + format!( + "estimated qdisc memory {} bytes; host memory snapshot unavailable", + estimate.estimated_total_memory_bytes + ) + }; let summary = if interface_reports.is_empty() { format!( - "Planned queue model {} qdisc budget. No shaping interfaces were queued.", - if is_ok { "fits" } else { "exceeds" } + "Planned queue model {} preflight. No shaping interfaces were queued; {memory_summary}.", + if is_ok { "fits" } else { "exceeds" }, ) } else { let interface_summary = interface_reports .iter() - .map(|entry| format!("{} estimated {} qdiscs", entry.name, entry.planned_qdiscs)) + .map(|entry| { + let detail = estimate + .interface_details + .get(&entry.name) + .expect("detail should exist for interface"); + format!( + "{} estimated {} qdiscs (infra {}, cake {}, fq_codel {})", + entry.name, + entry.planned_qdiscs, + detail.infra_qdiscs, + detail.cake_qdiscs, + detail.fq_codel_qdiscs + ) + }) .collect::>() .join(", "); format!( - "Planned queue model {} qdisc budget. {interface_summary}; safe budget {}, kernel limit {}.", + "Planned queue model {} preflight. {interface_summary}; safe budget {}, kernel limit {}; {memory_summary}.", if is_ok { "fits" } else { "exceeds" }, estimate.safe_budget, estimate.hard_limit, @@ -2373,23 +2826,58 @@ impl Bakery { }; let _ = run_query(vec![BusRequest::BakeryReportPreflight { ok: is_ok, - message: summary, + message: summary.clone(), safe_budget: estimate.safe_budget, hard_limit: estimate.hard_limit, + estimated_total_memory_bytes: estimate.estimated_total_memory_bytes, + memory_available_bytes: estimate + .memory_snapshot + .as_ref() + .map(|snapshot| snapshot.available_bytes), + memory_guard_min_available_bytes: lqos_bakery::BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES, + memory_ok: estimate.memory_ok, interfaces: interface_reports, }]); let result = PyDict::new(py); let interfaces = PyDict::new(py); + let interface_details = PyDict::new(py); for (interface, count) in estimate.interfaces { interfaces.set_item(interface, count)?; } + for (interface, detail) in estimate.interface_details { + let detail_dict = PyDict::new(py); + detail_dict.set_item("planned_qdiscs", detail.planned_qdiscs)?; + detail_dict.set_item("infra_qdiscs", detail.infra_qdiscs)?; + detail_dict.set_item("cake_qdiscs", detail.cake_qdiscs)?; + detail_dict.set_item("fq_codel_qdiscs", detail.fq_codel_qdiscs)?; + detail_dict.set_item("estimated_memory_bytes", detail.estimated_memory_bytes)?; + interface_details.set_item(interface, detail_dict)?; + } result.set_item("interfaces", interfaces)?; + result.set_item("interface_details", interface_details)?; result.set_item("safe_budget", estimate.safe_budget)?; result.set_item("hard_limit", estimate.hard_limit)?; + result.set_item( + "estimated_total_memory_bytes", + estimate.estimated_total_memory_bytes, + )?; + result.set_item("memory_ok", estimate.memory_ok)?; + result.set_item( + "memory_guard_min_available_bytes", + lqos_bakery::BAKERY_MEMORY_GUARD_MIN_AVAILABLE_BYTES, + )?; + if let Some(snapshot) = estimate.memory_snapshot { + result.set_item("memory_total_bytes", snapshot.total_bytes)?; + result.set_item("memory_available_bytes", snapshot.available_bytes)?; + } else { + result.set_item("memory_total_bytes", py.None())?; + result.set_item("memory_available_bytes", py.None())?; + } result.set_item("ok", is_ok)?; + result.set_item("summary", summary)?; Ok(result.into()) } diff --git a/src/rust/lqos_queue_tracker/src/tracking/mod.rs b/src/rust/lqos_queue_tracker/src/tracking/mod.rs index 9c38ae79..8904bb31 100644 --- a/src/rust/lqos_queue_tracker/src/tracking/mod.rs +++ b/src/rust/lqos_queue_tracker/src/tracking/mod.rs @@ -21,6 +21,8 @@ use watched_queues::WATCHED_QUEUES; pub use watched_queues::{add_watched_queue, still_watching}; static QUEUE_STATS_STALE: AtomicBool = AtomicBool::new(false); +const ALL_QUEUE_MONITOR_INTERVAL_SECONDS: u64 = 2; +const RELOAD_QUEUE_MONITOR_INTERVAL_SECONDS: u64 = 10; /// Returns `true` when queue counts are intentionally held at their last-known values. /// @@ -31,6 +33,12 @@ pub fn queue_stats_stale() -> bool { } fn track_queues() { + if full_reload_in_progress() { + QUEUE_STATS_STALE.store(true, Ordering::Relaxed); + debug!("(TC monitor) Skipping watched queue reads during Bakery full reload"); + expire_watched_queues(); + return; + } if WATCHED_QUEUES.is_empty() { //info!("No queues marked for read."); return; // There's nothing to do - bail out fast @@ -261,7 +269,7 @@ pub fn spawn_queue_monitor() -> anyhow::Result<()> { std::thread::Builder::new() .name("All Queue Monitor".to_string()) .spawn(|| { - let mut interval_seconds = 2; + let mut interval_seconds = ALL_QUEUE_MONITOR_INTERVAL_SECONDS; let Ok(mut tfd) = TimerFd::new() else { error!("Unable to start timer file descriptor. All queue monitor cannot run."); return; @@ -269,7 +277,7 @@ pub fn spawn_queue_monitor() -> anyhow::Result<()> { assert_eq!(tfd.get_state(), TimerState::Disarmed); tfd.set_state( TimerState::Periodic { - current: Duration::new(2, 0), + current: Duration::new(interval_seconds, 0), interval: Duration::new(interval_seconds, 0), }, SetTimeFlags::Default, @@ -277,13 +285,34 @@ pub fn spawn_queue_monitor() -> anyhow::Result<()> { let _ = tfd.read(); // Initial pause loop { - all_queue_reader(); + let desired_interval_seconds = if full_reload_in_progress() { + RELOAD_QUEUE_MONITOR_INTERVAL_SECONDS + } else { + ALL_QUEUE_MONITOR_INTERVAL_SECONDS + }; + if interval_seconds != desired_interval_seconds { + interval_seconds = desired_interval_seconds; + tfd.set_state( + TimerState::Periodic { + current: Duration::new(interval_seconds, 0), + interval: Duration::new(interval_seconds, 0), + }, + SetTimeFlags::Default, + ); + } + + if full_reload_in_progress() { + QUEUE_STATS_STALE.store(true, Ordering::Relaxed); + debug!("(TC monitor) Backing off full queue reads during Bakery full reload"); + } else { + all_queue_reader(); + } // Sleep until the next second let missed_ticks = tfd.read(); if missed_ticks > 1 { warn!("All Queue Reader: Missed {} ticks", missed_ticks - 1); - interval_seconds = 2 + (missed_ticks - 1); + interval_seconds = desired_interval_seconds + (missed_ticks - 1); tfd.set_state( TimerState::Periodic { current: Duration::new(interval_seconds, 0), diff --git a/src/rust/lqosd/Cargo.toml b/src/rust/lqosd/Cargo.toml index 5ee808a6..7f710d2a 100644 --- a/src/rust/lqosd/Cargo.toml +++ b/src/rust/lqosd/Cargo.toml @@ -31,6 +31,9 @@ nix = { workspace = true } sysinfo = { workspace = true } itertools = "0.13.0" reqwest = { workspace = true } +hmac = { workspace = true } +base64 = { workspace = true } +sha2 = { workspace = true } flate2 = "1" bincode = { workspace = true } ip_network_table = { workspace = true } diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index 280b515a..d6c91c45 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -12,7 +12,6 @@ pub mod lts2_sys; mod node_manager; mod preflight_checks; mod program_control; -mod reload_lock; mod remote_commands; mod rtt_exclusions; mod scheduler_control; @@ -515,6 +514,10 @@ fn handle_bus_requests(requests: &[BusRequest], responses: &mut Vec } BusResponse::Ack } + BusRequest::InvalidateAuthCache => { + crate::node_manager::invalidate_auth_cache(); + BusResponse::Ack + } #[cfg(feature = "equinix_tests")] BusRequest::RequestLqosEquinixTest => lqos_daht_test::lqos_daht_test(), BusRequest::ValidateShapedDevicesCsv => validation::validate_shaped_devices_csv(), @@ -743,6 +746,10 @@ fn handle_bus_requests(requests: &[BusRequest], responses: &mut Vec message, safe_budget, hard_limit, + estimated_total_memory_bytes, + memory_available_bytes, + memory_guard_min_available_bytes, + memory_ok, interfaces, } => { lqos_bakery::record_qdisc_preflight_snapshot( @@ -751,11 +758,19 @@ fn handle_bus_requests(requests: &[BusRequest], responses: &mut Vec message: message.clone(), safe_budget: *safe_budget, hard_limit: *hard_limit, + estimated_total_memory_bytes: *estimated_total_memory_bytes, + memory_available_bytes: *memory_available_bytes, + memory_guard_min_available_bytes: *memory_guard_min_available_bytes, + memory_ok: *memory_ok, interfaces: interfaces .iter() .map(|entry| lqos_bakery::BakeryCapacityInterfaceSnapshot { name: entry.name.clone(), planned_qdiscs: entry.planned_qdiscs, + infra_qdiscs: entry.infra_qdiscs, + cake_qdiscs: entry.cake_qdiscs, + fq_codel_qdiscs: entry.fq_codel_qdiscs, + estimated_memory_bytes: entry.estimated_memory_bytes, }) .collect(), }, diff --git a/src/rust/lqosd/src/node_manager.rs b/src/rust/lqosd/src/node_manager.rs index 4e59893d..daf80a84 100644 --- a/src/rust/lqosd/src/node_manager.rs +++ b/src/rust/lqosd/src/node_manager.rs @@ -7,6 +7,7 @@ mod template; mod warnings; pub(crate) mod ws; +pub(crate) use auth::invalidate_auth_cache; pub use local_api::circuit_count::circuit_count_data; pub use local_api::device_counts::device_count; pub(crate) use local_api::executive_cache::invalidate_executive_cache_snapshot; diff --git a/src/rust/lqosd/src/node_manager/auth.rs b/src/rust/lqosd/src/node_manager/auth.rs index d4edbb1e..d0faac37 100644 --- a/src/rust/lqosd/src/node_manager/auth.rs +++ b/src/rust/lqosd/src/node_manager/auth.rs @@ -1,26 +1,89 @@ //! Provides authentication for the Node Manager. -//! This is designed to be broadly compatible with the original -//! cookie-based system but now uses an Axum layer to be largely -//! invisible. use axum::Json; use axum::http::StatusCode; -use axum::response::{Html, Response}; +use axum::response::{Html, IntoResponse, Redirect, Response}; use axum_extra::extract::CookieJar; -use axum_extra::extract::cookie::Cookie; -use lqos_config::{UserRole, WebUsers, load_config}; +use axum_extra::extract::cookie::{Cookie, SameSite}; +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use hmac::{Hmac, Mac}; +use lqos_config::{AuthenticatedUser, UserRole, WebUsers, load_config}; use once_cell::sync::Lazy; +use parking_lot::Mutex; +use rand::RngCore; use serde::{Deserialize, Serialize}; -use std::path::Path; +use sha2::Sha256; +use std::fs::OpenOptions; +use std::io::Write; +use std::path::{Path, PathBuf}; use std::sync::atomic::AtomicU64; use std::sync::atomic::Ordering::Relaxed; use std::time::{SystemTime, UNIX_EPOCH}; -use tokio::sync::Mutex; -use tracing::warn; +use tracing::{error, warn}; -const COOKIE_PATH: &str = "User-Token"; +const COOKIE_NAME: &str = "User-Token"; +const SESSION_TOKEN_VERSION: &str = "v1"; +const SESSION_DURATION_SECS: u64 = 60 * 60 * 24 * 30; +const SESSION_KEY_FILE_NAME: &str = "lqusers.session.key"; -static WEB_USERS: Lazy>> = Lazy::new(|| Mutex::new(None)); +type HmacSha256 = Hmac; + +#[derive(Clone, Debug, PartialEq, Eq)] +struct AuthFileFingerprint { + path: PathBuf, + modified_unix_secs: Option, + modified_subsec_nanos: Option, + len: u64, +} + +#[derive(Clone, Debug)] +struct CachedAuthSnapshot { + fingerprint: Option, + snapshot: AuthSnapshot, +} + +#[derive(Clone, Debug)] +struct AuthSnapshot { + bootstrap_state: AuthBootstrapState, + auth_epoch: u64, + allow_anonymous: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum AuthBootstrapState { + MissingUsersFile, + NoUsersConfigured, + Ready, + CorruptUsersFile, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct SessionClaims { + sub: String, + role: UserRole, + auth_epoch: u64, + iat: u64, + exp: u64, +} + +#[derive(Clone, Debug, Serialize)] +pub struct LoginResponse { + ok: bool, + #[serde(skip_serializing_if = "Option::is_none")] + reason: Option<&'static str>, + #[serde(skip_serializing_if = "Option::is_none")] + message: Option, +} + +#[derive(Clone, Debug)] +struct SessionUser { + username: String, + role: UserRole, +} + +static AUTH_SNAPSHOT: Lazy>> = Lazy::new(|| Mutex::new(None)); +static SESSION_KEY: Lazy>>> = Lazy::new(|| Mutex::new(None)); pub static FIRST_LOAD: AtomicU64 = AtomicU64::new(0); fn record_first_login_timestamp_if_needed() { @@ -60,15 +123,291 @@ fn record_first_login_timestamp_if_needed() { } } -pub async fn get_username(jar: &CookieJar) -> String { - let lock = WEB_USERS.lock().await; - if let Some(users) = &*lock - && let Some(token) = jar.get(COOKIE_PATH) +fn now_unix_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +fn auth_file_fingerprint(path: &Path) -> Result { + let metadata = std::fs::metadata(path)?; + let modified = metadata + .modified() + .ok() + .and_then(|t| t.duration_since(UNIX_EPOCH).ok()); + + Ok(AuthFileFingerprint { + path: path.to_path_buf(), + modified_unix_secs: modified.map(|d| d.as_secs()), + modified_subsec_nanos: modified.map(|d| d.subsec_nanos()), + len: metadata.len(), + }) +} + +fn auth_snapshot() -> AuthSnapshot { + let current_fingerprint = match WebUsers::existing_path() { + Ok(Some(path)) => match auth_file_fingerprint(&path) { + Ok(fingerprint) => Some(fingerprint), + Err(e) => { + warn!("Unable to stat auth file {:?}: {e}", path); + None + } + }, + Ok(None) => None, + Err(e) => { + warn!("Unable to resolve auth file path: {e}"); + return AuthSnapshot { + bootstrap_state: AuthBootstrapState::CorruptUsersFile, + auth_epoch: 0, + allow_anonymous: false, + }; + } + }; + + let mut cache = AUTH_SNAPSHOT.lock(); + if let Some(cached) = &*cache + && cached.fingerprint == current_fingerprint { - return users.get_username(token.value()); + return cached.snapshot.clone(); + } + + let snapshot = match current_fingerprint { + None => AuthSnapshot { + bootstrap_state: AuthBootstrapState::MissingUsersFile, + auth_epoch: 0, + allow_anonymous: false, + }, + Some(_) => match WebUsers::load_or_create() { + Ok(users) => AuthSnapshot { + bootstrap_state: if users.is_empty() { + AuthBootstrapState::NoUsersConfigured + } else { + AuthBootstrapState::Ready + }, + auth_epoch: users.auth_epoch(), + allow_anonymous: users.do_we_allow_anonymous(), + }, + Err(e) => { + warn!("Unable to load auth state: {e}"); + AuthSnapshot { + bootstrap_state: AuthBootstrapState::CorruptUsersFile, + auth_epoch: 0, + allow_anonymous: false, + } + } + }, + }; + + let refreshed_fingerprint = match WebUsers::existing_path() { + Ok(Some(path)) => auth_file_fingerprint(&path).ok(), + Ok(None) => None, + Err(e) => { + warn!("Unable to refresh auth file path after load: {e}"); + None + } + }; + + *cache = Some(CachedAuthSnapshot { + fingerprint: refreshed_fingerprint, + snapshot: snapshot.clone(), + }); + snapshot +} + +fn session_key_path() -> Result { + let config = load_config().map_err(|_| { + std::io::Error::other("Unable to load /etc/lqos.conf while locating session key") + })?; + Ok(Path::new(&config.lqos_directory).join(SESSION_KEY_FILE_NAME)) +} + +fn session_key() -> Result, std::io::Error> { + let mut cache = SESSION_KEY.lock(); + if let Some(key) = &*cache { + return Ok(key.clone()); + } + + let path = session_key_path()?; + let key = if path.exists() { + let bytes = std::fs::read(&path)?; + if bytes.is_empty() { + return Err(std::io::Error::other(format!( + "Session key file {:?} is empty", + path + ))); + } + bytes + } else { + let mut new_key = vec![0u8; 32]; + rand::thread_rng().fill_bytes(&mut new_key); + + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&path)?; + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + file.set_permissions(std::fs::Permissions::from_mode(0o600))?; + } + + file.write_all(&new_key)?; + drop(file); + new_key + }; + + *cache = Some(key.clone()); + Ok(key) +} + +fn build_session_cookie(token: String) -> Cookie<'static> { + let mut cookie = Cookie::new(COOKIE_NAME, token); + cookie.set_path("/"); + cookie.set_same_site(SameSite::Lax); + cookie +} + +fn build_signed_session(key: &[u8], user: &AuthenticatedUser) -> Result { + let now = now_unix_secs(); + let claims = SessionClaims { + sub: user.username.clone(), + role: user.role, + auth_epoch: user.auth_epoch, + iat: now, + exp: now.saturating_add(SESSION_DURATION_SECS), + }; + let payload = serde_json::to_vec(&claims).map_err(|e| { + error!("Unable to serialize session claims: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + let payload_b64 = URL_SAFE_NO_PAD.encode(payload); + + let mut mac = HmacSha256::new_from_slice(key).map_err(|e| { + error!("Unable to initialize session signer: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + mac.update(payload_b64.as_bytes()); + let signature = URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes()); + + Ok(format!("{SESSION_TOKEN_VERSION}.{payload_b64}.{signature}")) +} + +fn verify_signed_session( + key: &[u8], + token: &str, + snapshot: &AuthSnapshot, +) -> Result, StatusCode> { + let Some((version, remainder)) = token.split_once('.') else { + return Ok(None); + }; + if version != SESSION_TOKEN_VERSION { + return Ok(None); + } + let Some((payload_b64, signature_b64)) = remainder.rsplit_once('.') else { + return Ok(None); + }; + + let mut mac = HmacSha256::new_from_slice(key).map_err(|e| { + error!("Unable to initialize session verifier: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + mac.update(payload_b64.as_bytes()); + let signature = URL_SAFE_NO_PAD + .decode(signature_b64) + .map_err(|_| StatusCode::UNAUTHORIZED)?; + if mac.verify_slice(&signature).is_err() { + return Ok(None); + } + + let payload = URL_SAFE_NO_PAD + .decode(payload_b64) + .map_err(|_| StatusCode::UNAUTHORIZED)?; + let claims: SessionClaims = + serde_json::from_slice(&payload).map_err(|_| StatusCode::UNAUTHORIZED)?; + + let now = now_unix_secs(); + if claims.exp <= now || claims.auth_epoch != snapshot.auth_epoch { + return Ok(None); } - "Anonymous".to_string() + Ok(Some(SessionUser { + username: claims.sub, + role: claims.role, + })) +} + +fn session_from_cookie( + jar: &CookieJar, + snapshot: &AuthSnapshot, +) -> Result, StatusCode> { + let Some(token) = jar.get(COOKIE_NAME) else { + return Ok(None); + }; + let key = session_key().map_err(|e| { + error!("Unable to load session key: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + verify_signed_session(&key, token.value(), snapshot) +} + +fn standalone_page_path(page: &str) -> Result { + let config = load_config().map_err(|e| { + error!("Unable to load config for standalone page {page}: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + Ok(Path::new(&config.lqos_directory) + .join("bin") + .join("static2") + .join(page)) +} + +fn serve_standalone_page(page: &str) -> Result { + let path = standalone_page_path(page)?; + let body = std::fs::read_to_string(&path).map_err(|e| { + error!("Unable to read standalone page {:?}: {e}", path); + StatusCode::INTERNAL_SERVER_ERROR + })?; + Ok(Html(body).into_response()) +} + +pub async fn login_page(jar: CookieJar) -> Response { + let snapshot = auth_snapshot(); + match snapshot.bootstrap_state { + AuthBootstrapState::MissingUsersFile | AuthBootstrapState::NoUsersConfigured => { + Redirect::temporary("/first-run.html").into_response() + } + AuthBootstrapState::Ready => match session_from_cookie(&jar, &snapshot) { + Ok(Some(_)) => Redirect::temporary("/index.html").into_response(), + Ok(None) => serve_standalone_page("login.html") + .unwrap_or_else(|status| (status, "Unable to serve login page").into_response()), + Err(status) => (status, "Unable to validate login session").into_response(), + }, + AuthBootstrapState::CorruptUsersFile => serve_standalone_page("login.html") + .unwrap_or_else(|status| (status, "Unable to serve login page").into_response()), + } +} + +pub async fn first_run_page() -> Response { + let snapshot = auth_snapshot(); + match snapshot.bootstrap_state { + AuthBootstrapState::MissingUsersFile | AuthBootstrapState::NoUsersConfigured => { + serve_standalone_page("first-run.html") + .unwrap_or_else(|status| (status, "Unable to serve first-run page").into_response()) + } + AuthBootstrapState::Ready | AuthBootstrapState::CorruptUsersFile => { + Redirect::temporary("/index.html").into_response() + } + } +} + +pub async fn get_username(jar: &CookieJar) -> String { + let snapshot = auth_snapshot(); + match session_from_cookie(jar, &snapshot) { + Ok(Some(user)) => user.username, + Ok(None) | Err(_) => "Anonymous".to_string(), + } } #[derive(Copy, Clone, Eq, PartialEq)] @@ -78,100 +417,76 @@ pub enum LoginResult { Denied, } -async fn check_login(jar: &CookieJar, users: &WebUsers) -> LoginResult { - if let Some(token) = jar.get(COOKIE_PATH) { - // Validate the token - return match users.get_role_from_token(token.value()) { - Ok(UserRole::ReadOnly) => LoginResult::ReadOnly, - Ok(UserRole::Admin) => LoginResult::Admin, - Err(_e) => LoginResult::Denied, - }; +fn login_result_for_session(user: Option, allow_anonymous: bool) -> LoginResult { + match user { + Some(SessionUser { + role: UserRole::Admin, + .. + }) => LoginResult::Admin, + Some(SessionUser { + role: UserRole::ReadOnly, + .. + }) => LoginResult::ReadOnly, + None if allow_anonymous => LoginResult::ReadOnly, + None => LoginResult::Denied, } - LoginResult::Denied } -/// Checks an incoming request for a User-Token cookie. If found, -/// it validates the request against the web users file. If the -/// web users file isn't found, it redirects to 'first run'. If -/// it is found, the token is checked (and redirected to login if -/// it isn't good). Finally, the user's role is injected into -/// the middleware. +/// Checks an incoming request for a `User-Token` cookie. If found, +/// it validates the request against the signed session and current auth epoch. +/// Missing or empty auth state redirects to first-run; invalid sessions redirect +/// to login unless anonymous read-only is enabled. pub async fn auth_layer( jar: CookieJar, mut req: axum::extract::Request, next: axum::middleware::Next, -) -> Result> { - const BOUNCE: &str = - ""; - const FIRST_RUN: &str = - ""; - - let mut lock = WEB_USERS.lock().await; - if lock.is_none() { - // No lock - let's see if there's a file to use? - if WebUsers::does_users_file_exist().expect("Error checking if the users file exists") { - // It exists - we load it - let users = WebUsers::load_or_create().expect("Unable to load users file"); - *lock = Some(users); - } else { - // No users file - redirect to first run - return Err(Html(FIRST_RUN)); +) -> Response { + let snapshot = auth_snapshot(); + match snapshot.bootstrap_state { + AuthBootstrapState::MissingUsersFile | AuthBootstrapState::NoUsersConfigured => { + return Redirect::temporary("/first-run.html").into_response(); } + AuthBootstrapState::CorruptUsersFile => { + return Redirect::temporary("/login.html").into_response(); + } + AuthBootstrapState::Ready => {} } - if let Some(users) = &*lock { - let login_result = check_login(&jar, users).await; - return match login_result { - LoginResult::Admin | LoginResult::ReadOnly => { - record_first_login_timestamp_if_needed(); - req.extensions_mut().insert(login_result); - Ok(next.run(req).await) - } - LoginResult::Denied => { - let users = WebUsers::load_or_create().expect("Could not load users file"); - if users.do_we_allow_anonymous() { - req.extensions_mut().insert(LoginResult::ReadOnly); - Ok(next.run(req).await) - } else { - Err(Html(BOUNCE)) - } - } - }; + let login_result = match session_from_cookie(&jar, &snapshot) { + Ok(user) => login_result_for_session(user, snapshot.allow_anonymous), + Err(status) => return (status, "Unable to validate session").into_response(), + }; + + match login_result { + LoginResult::Admin | LoginResult::ReadOnly => { + record_first_login_timestamp_if_needed(); + req.extensions_mut().insert(login_result); + next.run(req).await + } + LoginResult::Denied => Redirect::temporary("/login.html").into_response(), } - Err(Html(BOUNCE)) } pub async fn login_from_token(token: &str) -> LoginResult { - let mut lock = WEB_USERS.lock().await; - if lock.is_none() { - match WebUsers::does_users_file_exist() { - Ok(true) => match WebUsers::load_or_create() { - Ok(users) => { - *lock = Some(users); - } - Err(e) => { - warn!("Unable to load users file for websocket auth: {e}"); - return LoginResult::Denied; - } - }, - Ok(false) => { - return LoginResult::Denied; - } - Err(e) => { - warn!("Unable to check users file for websocket auth: {e}"); - return LoginResult::Denied; - } - } + let snapshot = auth_snapshot(); + if snapshot.bootstrap_state != AuthBootstrapState::Ready { + return LoginResult::Denied; } - let Some(users) = &*lock else { - return LoginResult::Denied; + let key = match session_key() { + Ok(key) => key, + Err(e) => { + warn!("Unable to load session key for websocket auth: {e}"); + return LoginResult::Denied; + } }; - let login_result = match users.get_role_from_token(token) { - Ok(UserRole::ReadOnly) => LoginResult::ReadOnly, - Ok(UserRole::Admin) => LoginResult::Admin, - Err(_) => LoginResult::Denied, + let login_result = match verify_signed_session(&key, token, &snapshot) { + Ok(user) => login_result_for_session(user, snapshot.allow_anonymous), + Err(e) => { + warn!("Unable to verify websocket session token: {e}"); + LoginResult::Denied + } }; if login_result != LoginResult::Denied { @@ -181,25 +496,15 @@ pub async fn login_from_token(token: &str) -> LoginResult { login_result } -/// Reload the cached users from disk after user-management changes. +/// Invalidate the cached auth snapshot after user-management changes. +pub fn invalidate_auth_cache() { + let mut lock = AUTH_SNAPSHOT.lock(); + *lock = None; +} + +/// Reload the cached auth snapshot after user-management changes. pub async fn refresh_cached_users() { - let mut lock = WEB_USERS.lock().await; - match WebUsers::does_users_file_exist() { - Ok(true) => match WebUsers::load_or_create() { - Ok(users) => { - *lock = Some(users); - } - Err(e) => { - warn!("Unable to refresh users cache: {e}"); - } - }, - Ok(false) => { - *lock = None; - } - Err(e) => { - warn!("Unable to check users file while refreshing cache: {e}"); - } - } + invalidate_auth_cache(); } #[derive(Serialize, Deserialize)] @@ -211,25 +516,88 @@ pub struct LoginAttempt { pub async fn try_login( jar: CookieJar, Json(login): Json, -) -> Result<(CookieJar, StatusCode), StatusCode> { - let users = WEB_USERS.lock().await; - if let Some(users) = &*users { - return match users.login(&login.username, &login.password) { - Ok(token) => { - record_first_login_timestamp_if_needed(); - Ok((jar.add(Cookie::new(COOKIE_PATH, token)), StatusCode::OK)) - } - Err(..) => { - if users.do_we_allow_anonymous() { - record_first_login_timestamp_if_needed(); - Ok((jar, StatusCode::OK)) - } else { - Err(StatusCode::UNAUTHORIZED) - } - } - }; +) -> Result<(CookieJar, Json), (StatusCode, Json)> { + let snapshot = auth_snapshot(); + match snapshot.bootstrap_state { + AuthBootstrapState::MissingUsersFile | AuthBootstrapState::NoUsersConfigured => { + return Err(( + StatusCode::CONFLICT, + Json(LoginResponse { + ok: false, + reason: Some("first_run_required"), + message: Some("No users are configured yet.".to_string()), + }), + )); + } + AuthBootstrapState::CorruptUsersFile => { + return Err(( + StatusCode::CONFLICT, + Json(LoginResponse { + ok: false, + reason: Some("auth_corrupt"), + message: Some("The auth file is corrupt and must be repaired.".to_string()), + }), + )); + } + AuthBootstrapState::Ready => {} } - Err(StatusCode::UNAUTHORIZED) + + let mut users = WebUsers::load_or_create().map_err(|e| { + warn!("Unable to load users during login: {e}"); + ( + StatusCode::CONFLICT, + Json(LoginResponse { + ok: false, + reason: Some("auth_corrupt"), + message: Some("The auth file is corrupt and must be repaired.".to_string()), + }), + ) + })?; + let authenticated = users + .authenticate(&login.username, &login.password) + .map_err(|_| { + ( + StatusCode::UNAUTHORIZED, + Json(LoginResponse { + ok: false, + reason: Some("invalid_credentials"), + message: Some("Invalid username or password.".to_string()), + }), + ) + })?; + + invalidate_auth_cache(); + let key = session_key().map_err(|e| { + error!("Unable to load session key during login: {e}"); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(LoginResponse { + ok: false, + reason: Some("session_error"), + message: Some("Unable to create session token.".to_string()), + }), + ) + })?; + let token = build_signed_session(&key, &authenticated).map_err(|status| { + ( + status, + Json(LoginResponse { + ok: false, + reason: Some("session_error"), + message: Some("Unable to create session token.".to_string()), + }), + ) + })?; + + record_first_login_timestamp_if_needed(); + Ok(( + jar.add(build_session_cookie(token)), + Json(LoginResponse { + ok: true, + reason: None, + message: None, + }), + )) } #[derive(Serialize, Deserialize)] @@ -242,16 +610,106 @@ pub struct FirstUser { pub async fn first_user( jar: CookieJar, Json(new_user): Json, -) -> (CookieJar, StatusCode) { - let mut users = WebUsers::load_or_create().expect("Could not load users file"); +) -> Result<(CookieJar, Json), (StatusCode, Json)> { + let snapshot = auth_snapshot(); + match snapshot.bootstrap_state { + AuthBootstrapState::Ready => { + return Err(( + StatusCode::CONFLICT, + Json(LoginResponse { + ok: false, + reason: Some("already_configured"), + message: Some("Web authentication is already configured.".to_string()), + }), + )); + } + AuthBootstrapState::CorruptUsersFile => { + return Err(( + StatusCode::CONFLICT, + Json(LoginResponse { + ok: false, + reason: Some("auth_corrupt"), + message: Some("The auth file is corrupt and must be repaired.".to_string()), + }), + )); + } + AuthBootstrapState::MissingUsersFile | AuthBootstrapState::NoUsersConfigured => {} + } + + let mut users = WebUsers::load_or_create().map_err(|e| { + warn!("Unable to load users during first-run setup: {e}"); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(LoginResponse { + ok: false, + reason: Some("auth_corrupt"), + message: Some("Unable to initialize auth storage.".to_string()), + }), + ) + })?; users .allow_anonymous(new_user.allow_anonymous) - .expect("Unable to set property"); - let token = users + .map_err(|e| { + warn!("Unable to set anonymous auth policy: {e}"); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(LoginResponse { + ok: false, + reason: Some("auth_corrupt"), + message: Some("Unable to update auth settings.".to_string()), + }), + ) + })?; + users .add_or_update_user(&new_user.username, &new_user.password, UserRole::Admin) - .expect("Unable to add or update user"); - let mut lock = WEB_USERS.lock().await; - *lock = Some(users); + .map_err(|e| { + warn!("Unable to create first user: {e}"); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(LoginResponse { + ok: false, + reason: Some("auth_corrupt"), + message: Some("Unable to create the first user.".to_string()), + }), + ) + })?; + + invalidate_auth_cache(); + let authenticated = AuthenticatedUser { + username: new_user.username, + role: UserRole::Admin, + auth_epoch: users.auth_epoch(), + password_upgraded: false, + }; + let key = session_key().map_err(|e| { + error!("Unable to load session key during first-run setup: {e}"); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(LoginResponse { + ok: false, + reason: Some("session_error"), + message: Some("Unable to create session token.".to_string()), + }), + ) + })?; + let token = build_signed_session(&key, &authenticated).map_err(|status| { + ( + status, + Json(LoginResponse { + ok: false, + reason: Some("session_error"), + message: Some("Unable to create session token.".to_string()), + }), + ) + })?; + record_first_login_timestamp_if_needed(); - (jar.add(Cookie::new(COOKIE_PATH, token)), StatusCode::OK) + Ok(( + jar.add(build_session_cookie(token)), + Json(LoginResponse { + ok: true, + reason: None, + message: None, + }), + )) } diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_apply_summary.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_apply_summary.js index e52ea14d..a008b5d6 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_apply_summary.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_apply_summary.js @@ -24,7 +24,7 @@ export class BakeryApplySummaryDashlet extends BaseDashlet { } tooltip() { - return "
Apply Summary

Shows the most recent Bakery apply type, command counts, and recorded build/apply durations.

"; + return "
Apply Summary

Shows live full-reload progress and the most recent Bakery apply type, command counts, and recorded build/apply durations.

During large Bakery reloads, queue polling is intentionally backed off so progress reporting stays lightweight.

"; } subscribeTo() { @@ -39,6 +39,31 @@ export class BakeryApplySummaryDashlet extends BaseDashlet { const tableWrap = document.createElement("div"); tableWrap.classList.add("lqos-table-wrap"); + const progressWrap = document.createElement("div"); + progressWrap.classList.add("mb-3"); + + const progressHeader = document.createElement("div"); + progressHeader.classList.add("d-flex", "justify-content-between", "align-items-center", "small", "mb-1"); + this.progressSummaryEl = document.createElement("span"); + this.progressSummaryEl.classList.add("text-body-secondary"); + this.progressPercentEl = document.createElement("span"); + this.progressPercentEl.classList.add("fw-semibold"); + progressHeader.appendChild(this.progressSummaryEl); + progressHeader.appendChild(this.progressPercentEl); + + this.progressBarWrapEl = document.createElement("div"); + this.progressBarWrapEl.classList.add("progress"); + this.progressBarWrapEl.style.height = "0.85rem"; + this.progressBarEl = document.createElement("div"); + this.progressBarEl.classList.add("progress-bar"); + this.progressBarEl.setAttribute("role", "progressbar"); + this.progressBarEl.style.width = "0%"; + this.progressBarEl.textContent = "0%"; + this.progressBarWrapEl.appendChild(this.progressBarEl); + + progressWrap.appendChild(progressHeader); + progressWrap.appendChild(this.progressBarWrapEl); + const table = document.createElement("table"); table.classList.add("lqos-table", "lqos-table-compact", "mb-0", "small"); const tbody = document.createElement("tbody"); @@ -73,6 +98,7 @@ export class BakeryApplySummaryDashlet extends BaseDashlet { table.appendChild(tbody); tableWrap.appendChild(table); + wrap.appendChild(progressWrap); wrap.appendChild(tableWrap); base.appendChild(wrap); return base; @@ -83,6 +109,34 @@ export class BakeryApplySummaryDashlet extends BaseDashlet { return; } const status = msg?.data?.currentState || {}; + const totalCommands = Number.isFinite(status.currentApplyTotalTcCommands) + ? status.currentApplyTotalTcCommands + : 0; + const completedCommands = Number.isFinite(status.currentApplyCompletedTcCommands) + ? status.currentApplyCompletedTcCommands + : 0; + const totalChunks = Number.isFinite(status.currentApplyTotalChunks) + ? status.currentApplyTotalChunks + : 0; + const completedChunks = Number.isFinite(status.currentApplyCompletedChunks) + ? status.currentApplyCompletedChunks + : 0; + const percent = totalCommands > 0 + ? Math.max(0, Math.min(100, (completedCommands / totalCommands) * 100)) + : 0; + const activeFullReload = status.mode === "ApplyingFullReload" && totalCommands > 0; + this.progressSummaryEl.textContent = activeFullReload + ? `${status.currentApplyPhase || "Applying tc command chunks"} • ${completedCommands.toLocaleString()} / ${totalCommands.toLocaleString()} commands • chunk ${Math.min(completedChunks + 1, totalChunks).toLocaleString()} / ${totalChunks.toLocaleString()} • queue polling paused` + : "No full reload currently applying"; + this.progressPercentEl.textContent = activeFullReload ? `${percent.toFixed(1)}%` : "Idle"; + this.progressBarEl.style.width = `${percent}%`; + this.progressBarEl.textContent = activeFullReload ? `${percent.toFixed(1)}%` : "0%"; + this.progressBarEl.setAttribute("aria-valuenow", percent.toFixed(1)); + this.progressBarEl.setAttribute("aria-valuemin", "0"); + this.progressBarEl.setAttribute("aria-valuemax", "100"); + this.progressBarEl.className = activeFullReload + ? "progress-bar progress-bar-striped progress-bar-animated bg-warning" + : "progress-bar bg-secondary"; this.applyTypeEl.innerHTML = ""; this.applyTypeEl.appendChild(formatApplyType(status.lastApplyType)); this.totalCommandsEl.textContent = Number.isFinite(status.lastTotalTcCommands) diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_capacity.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_capacity.js index 87f70281..5a8f023d 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_capacity.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_capacity.js @@ -1,5 +1,64 @@ import {BaseDashlet} from "../lq_js_common/dashboard/base_dashlet"; -import {bakeryPreflightBadge} from "./bakery_shared"; +import {bakeryPreflightBadge, mkBadge} from "./bakery_shared"; + +function clamp(n, min, max) { + return Math.min(Math.max(n, min), max); +} + +function formatBinaryBytes(bytes) { + const value = typeof bytes === "number" ? bytes : parseInt(bytes, 10); + if (!Number.isFinite(value) || value < 0) { + return "—"; + } + if (value === 0) { + return "0 B"; + } + + const units = ["B", "KiB", "MiB", "GiB", "TiB"]; + let scaled = value; + let unitIndex = 0; + while (scaled >= 1024 && unitIndex < units.length - 1) { + scaled /= 1024; + unitIndex += 1; + } + const decimals = scaled >= 100 || unitIndex === 0 ? 0 : 1; + return `${scaled.toFixed(decimals)} ${units[unitIndex]}`; +} + +function formatPercent(value, max) { + if (!Number.isFinite(value) || !Number.isFinite(max) || max <= 0) { + return "—"; + } + const pct = (value / max) * 100.0; + return `${pct >= 10 ? pct.toFixed(0) : pct.toFixed(1)}%`; +} + +function usageBarClass(plannedQdiscs, safeBudget, hardLimit) { + if (!Number.isFinite(plannedQdiscs) || !Number.isFinite(safeBudget) || safeBudget <= 0) { + return "bg-secondary"; + } + if ((Number.isFinite(hardLimit) && plannedQdiscs > hardLimit) || plannedQdiscs > safeBudget) { + return "bg-danger"; + } + const pct = (plannedQdiscs / safeBudget) * 100.0; + if (pct >= 85) { + return "bg-warning"; + } + if (pct >= 60) { + return "bg-info"; + } + return "bg-success"; +} + +function bakeryMemoryBadge(preflight) { + if (!preflight) { + return mkBadge("Memory Unknown", "bg-light text-secondary border"); + } + if (preflight.memoryOk) { + return mkBadge("Memory OK", "bg-success-subtle text-success border border-success-subtle", preflight.message || ""); + } + return mkBadge("Memory Guard", "bg-danger-subtle text-danger border border-danger-subtle", preflight.message || ""); +} export class BakeryCapacityDashlet extends BaseDashlet { constructor(slot) { @@ -26,36 +85,65 @@ export class BakeryCapacityDashlet extends BaseDashlet { wrap.classList.add("p-2"); this.badgeWrap = document.createElement("div"); - this.badgeWrap.classList.add("mb-2"); + this.badgeWrap.classList.add("d-flex", "flex-wrap", "gap-2", "mb-3"); wrap.appendChild(this.badgeWrap); - this.summaryEl = document.createElement("div"); - this.summaryEl.classList.add("small", "text-muted", "mb-2"); - this.summaryEl.style.whiteSpace = "normal"; - this.summaryEl.style.wordBreak = "break-word"; - wrap.appendChild(this.summaryEl); - const tableWrap = document.createElement("div"); - tableWrap.classList.add("lqos-table-wrap"); + tableWrap.classList.add("lqos-table-wrap", "mb-3"); const table = document.createElement("table"); table.classList.add("lqos-table", "lqos-table-compact", "mb-0", "small"); const thead = document.createElement("thead"); const hr = document.createElement("tr"); - ["Interface", "Planned", "Budget"].forEach((label) => { + ["Interface", "Planned", "Usage", "Mix"].forEach((label) => { const th = document.createElement("th"); th.textContent = label; hr.appendChild(th); }); thead.appendChild(hr); - this.tbody = document.createElement("tbody"); + this.interfacesTbody = document.createElement("tbody"); table.appendChild(thead); - table.appendChild(this.tbody); + table.appendChild(this.interfacesTbody); tableWrap.appendChild(table); wrap.appendChild(tableWrap); + + const safetyWrap = document.createElement("div"); + safetyWrap.classList.add("lqos-table-wrap"); + + const safetyTable = document.createElement("table"); + safetyTable.classList.add("lqos-table", "lqos-table-compact", "mb-0", "small"); + const safetyBody = document.createElement("tbody"); + + const mkRow = (label) => { + const tr = document.createElement("tr"); + const tdL = document.createElement("td"); + tdL.classList.add("table-label-cell"); + tdL.style.width = "44%"; + tdL.textContent = label; + const tdV = document.createElement("td"); + tdV.classList.add("table-value-cell"); + const valueEl = document.createElement("span"); + valueEl.textContent = "—"; + tdV.appendChild(valueEl); + tr.appendChild(tdL); + tr.appendChild(tdV); + safetyBody.appendChild(tr); + return {tr, valueEl}; + }; + + this.safeBudgetRow = mkRow("Safe Budget"); + this.hardLimitRow = mkRow("Kernel Limit"); + this.estimatedMemoryRow = mkRow("Est. Memory"); + this.availableMemoryRow = mkRow("Avail. Memory"); + this.memoryFloorRow = mkRow("Safety Floor"); + this.memoryHeadroomRow = mkRow("Headroom"); + + safetyTable.appendChild(safetyBody); + safetyWrap.appendChild(safetyTable); + wrap.appendChild(safetyWrap); base.appendChild(wrap); return base; } @@ -71,18 +159,39 @@ export class BakeryCapacityDashlet extends BaseDashlet { renderPreflight() { this.badgeWrap.innerHTML = ""; this.badgeWrap.appendChild(bakeryPreflightBadge(this.lastPreflight)); + this.badgeWrap.appendChild(bakeryMemoryBadge(this.lastPreflight)); - this.summaryEl.textContent = this.lastPreflight?.message || "No preflight has been recorded yet."; - this.tbody.innerHTML = ""; + this.interfacesTbody.innerHTML = ""; + + if (!this.lastPreflight) { + this.setSafetySummary({}); + const tr = document.createElement("tr"); + const td = document.createElement("td"); + td.colSpan = 4; + td.textContent = "No interface budget data"; + tr.appendChild(td); + this.interfacesTbody.appendChild(tr); + return; + } + + const interfaces = Array.isArray(this.lastPreflight.interfaces) + ? [...this.lastPreflight.interfaces].sort((left, right) => { + const plannedDiff = (right?.plannedQdiscs || 0) - (left?.plannedQdiscs || 0); + if (plannedDiff !== 0) { + return plannedDiff; + } + return (left?.name || "").localeCompare(right?.name || ""); + }) + : []; + this.setSafetySummary(this.lastPreflight); - const interfaces = Array.isArray(this.lastPreflight?.interfaces) ? this.lastPreflight.interfaces : []; if (interfaces.length === 0) { const tr = document.createElement("tr"); const td = document.createElement("td"); - td.colSpan = 3; + td.colSpan = 4; td.textContent = "No interface budget data"; tr.appendChild(td); - this.tbody.appendChild(tr); + this.interfacesTbody.appendChild(tr); return; } @@ -90,26 +199,122 @@ export class BakeryCapacityDashlet extends BaseDashlet { const tr = document.createElement("tr"); const tdName = document.createElement("td"); const tdPlanned = document.createElement("td"); - const tdBudget = document.createElement("td"); + const tdUsage = document.createElement("td"); + const tdMix = document.createElement("td"); tdName.textContent = entry?.name || "—"; - tdPlanned.textContent = Number.isFinite(entry?.plannedQdiscs) + + const plannedValue = document.createElement("div"); + plannedValue.classList.add("fw-semibold"); + plannedValue.textContent = Number.isFinite(entry?.plannedQdiscs) ? entry.plannedQdiscs.toLocaleString() : "—"; + const plannedMeta = document.createElement("div"); + plannedMeta.classList.add("small", "text-body-secondary"); + plannedMeta.textContent = formatBinaryBytes(entry?.estimatedMemoryBytes); + tdPlanned.appendChild(plannedValue); + tdPlanned.appendChild(plannedMeta); - const hardLimit = Number.isFinite(this.lastPreflight?.hardLimit) ? this.lastPreflight.hardLimit : null; const safeBudget = Number.isFinite(this.lastPreflight?.safeBudget) ? this.lastPreflight.safeBudget : null; - tdBudget.textContent = safeBudget !== null && hardLimit !== null + const hardLimit = Number.isFinite(this.lastPreflight?.hardLimit) ? this.lastPreflight.hardLimit : null; + const usageText = document.createElement("div"); + usageText.classList.add("d-flex", "justify-content-between", "small", "mb-1"); + const usageLabel = document.createElement("span"); + usageLabel.textContent = Number.isFinite(entry?.plannedQdiscs) && safeBudget !== null + ? `${formatPercent(entry.plannedQdiscs, safeBudget)} of safe` + : "—"; + const usageCount = document.createElement("span"); + usageCount.classList.add("text-body-secondary"); + usageCount.textContent = safeBudget !== null && hardLimit !== null ? `${safeBudget.toLocaleString()} / ${hardLimit.toLocaleString()}` : "—"; - if (Number.isFinite(entry?.plannedQdiscs) && safeBudget !== null && entry.plannedQdiscs > safeBudget) { - tdPlanned.classList.add("text-danger"); + usageText.appendChild(usageLabel); + usageText.appendChild(usageCount); + + const progress = document.createElement("div"); + progress.classList.add("progress"); + progress.style.height = "0.55rem"; + const bar = document.createElement("div"); + bar.classList.add("progress-bar", usageBarClass(entry?.plannedQdiscs, safeBudget, hardLimit)); + bar.setAttribute("role", "progressbar"); + const pct = Number.isFinite(entry?.plannedQdiscs) && safeBudget !== null && safeBudget > 0 + ? clamp((entry.plannedQdiscs / safeBudget) * 100.0, 0, 100) + : 0; + bar.style.width = `${pct.toFixed(1)}%`; + bar.setAttribute("aria-valuemin", "0"); + bar.setAttribute("aria-valuemax", safeBudget !== null ? safeBudget.toString() : "0"); + bar.setAttribute("aria-valuenow", Number.isFinite(entry?.plannedQdiscs) ? entry.plannedQdiscs.toString() : "0"); + progress.appendChild(bar); + + tdUsage.appendChild(usageText); + tdUsage.appendChild(progress); + + const mixWrap = document.createElement("div"); + mixWrap.classList.add("d-flex", "flex-wrap", "gap-1", "mb-1"); + mixWrap.appendChild(mkBadge( + `infra ${Number.isFinite(entry?.infraQdiscs) ? entry.infraQdiscs.toLocaleString() : "—"}`, + "bg-light text-secondary border", + )); + if (Number.isFinite(entry?.cakeQdiscs) && entry.cakeQdiscs > 0) { + mixWrap.appendChild(mkBadge( + `cake ${entry.cakeQdiscs.toLocaleString()}`, + "bg-warning-subtle text-warning border border-warning-subtle", + )); + } + if (Number.isFinite(entry?.fqCodelQdiscs) && entry.fqCodelQdiscs > 0) { + mixWrap.appendChild(mkBadge( + `fq_codel ${entry.fqCodelQdiscs.toLocaleString()}`, + "bg-info-subtle text-info border border-info-subtle", + )); } + tdMix.appendChild(mixWrap); tr.appendChild(tdName); tr.appendChild(tdPlanned); - tr.appendChild(tdBudget); - this.tbody.appendChild(tr); + tr.appendChild(tdUsage); + tr.appendChild(tdMix); + this.interfacesTbody.appendChild(tr); }); } + + setSafetySummary(preflight) { + const setText = (row, value, className = "") => { + row.valueEl.textContent = value; + row.valueEl.className = className; + }; + const setVisible = (row, visible) => { + row.tr.hidden = !visible; + }; + + setText(this.safeBudgetRow, Number.isFinite(preflight?.safeBudget) ? preflight.safeBudget.toLocaleString() : "—"); + setText(this.hardLimitRow, Number.isFinite(preflight?.hardLimit) ? preflight.hardLimit.toLocaleString() : "—"); + setText( + this.estimatedMemoryRow, + Number.isFinite(preflight?.estimatedTotalMemoryBytes) ? formatBinaryBytes(preflight.estimatedTotalMemoryBytes) : "—", + ); + setVisible(this.availableMemoryRow, Number.isFinite(preflight?.memoryAvailableBytes)); + setVisible( + this.memoryFloorRow, + Number.isFinite(preflight?.memoryAvailableBytes) && Number.isFinite(preflight?.memoryGuardMinAvailableBytes), + ); + const headroom = Number.isFinite(preflight?.memoryAvailableBytes) + && Number.isFinite(preflight?.memoryGuardMinAvailableBytes) + ? preflight.memoryAvailableBytes - preflight.memoryGuardMinAvailableBytes + : null; + setVisible(this.memoryHeadroomRow, headroom !== null); + + if (Number.isFinite(preflight?.memoryAvailableBytes)) { + setText(this.availableMemoryRow, formatBinaryBytes(preflight.memoryAvailableBytes)); + } + if (Number.isFinite(preflight?.memoryGuardMinAvailableBytes)) { + setText(this.memoryFloorRow, formatBinaryBytes(preflight.memoryGuardMinAvailableBytes)); + } + if (headroom !== null) { + setText( + this.memoryHeadroomRow, + `${headroom >= 0 ? "+" : "-"}${formatBinaryBytes(Math.abs(headroom))}`, + headroom < 0 ? "text-danger" : "", + ); + } + } } diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_shared.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_shared.js index 5425d49b..524f6d76 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_shared.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/bakery_shared.js @@ -74,5 +74,12 @@ export function bakeryPreflightBadge(preflight) { if (preflight.ok) { return mkBadge("Within Budget", "bg-success-subtle text-success border border-success-subtle", preflight.message || ""); } + const interfaces = Array.isArray(preflight.interfaces) ? preflight.interfaces : []; + const safeBudget = Number.isFinite(preflight.safeBudget) ? preflight.safeBudget : null; + const overBudget = safeBudget !== null + && interfaces.some((entry) => Number.isFinite(entry?.plannedQdiscs) && entry.plannedQdiscs > safeBudget); + if (!overBudget && preflight.memoryOk === false) { + return mkBadge("Memory Blocked", "bg-danger-subtle text-danger border border-danger-subtle", preflight.message || ""); + } return mkBadge("Over Budget", "bg-danger-subtle text-danger border border-danger-subtle", preflight.message || ""); } diff --git a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/treeguard_controls.js b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/treeguard_controls.js index 437eeb15..e774e58d 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/dashlets/treeguard_controls.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/dashlets/treeguard_controls.js @@ -123,12 +123,17 @@ export class TreeguardControlsDashlet extends BaseDashlet { syncControls() { const enabled = document.getElementById(this.enabledId()); const dryRun = document.getElementById(this.dryRunId()); + const controls = document.getElementById(this.controlsId()); const statusEnabled = this.liveStatus?.enabled; const statusDryRun = this.liveStatus?.dry_run; + const paused = !!this.liveStatus?.paused_for_bakery_reload; enabled.checked = this.configLoaded ? !!this.treeguard.enabled : !!(statusEnabled ?? this.treeguard.enabled); dryRun.checked = this.configLoaded ? !!this.treeguard.dry_run : !!(statusDryRun ?? this.treeguard.dry_run); - enabled.disabled = this.isSaving; - dryRun.disabled = this.isSaving; + enabled.disabled = this.isSaving || paused; + dryRun.disabled = this.isSaving || paused; + if (controls) { + controls.classList.toggle("opacity-50", paused); + } } renderStatusLine() { @@ -136,6 +141,8 @@ export class TreeguardControlsDashlet extends BaseDashlet { const liveStatus = this.liveStatus || {}; const enabled = (liveStatus.enabled ?? this.treeguard.enabled) ? "Enabled" : "Disabled"; const dryRun = !!(liveStatus.dry_run ?? this.treeguard.dry_run); + const paused = !!liveStatus.paused_for_bakery_reload; + const pauseReason = (liveStatus.pause_reason || "Bakery full reload in progress").trim(); const liveState = dryRun ? "dry run" : "live"; const mode = this.treeguard.cpu?.mode === "cpu_aware" ? "CPU-aware" : "Traffic/RTT only"; const linkScope = this.treeguard.links?.all_nodes ? "all links" : "allowlisted links"; @@ -154,6 +161,9 @@ export class TreeguardControlsDashlet extends BaseDashlet { linkScope, circuitScope, ]; + if (paused) { + summaryBits.push(`paused: ${pauseReason}`); + } if (managedNodes !== null || managedCircuits !== null) { const counts = []; if (managedNodes !== null) counts.push(`${managedNodes} node${managedNodes === 1 ? "" : "s"}`); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/first-run.js b/src/rust/lqosd/src/node_manager/js_build/src/first-run.js index c4a024cb..a605adb1 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/first-run.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/first-run.js @@ -1,5 +1,5 @@ $("#btnCreateUser").on('click', () => { - let username = $("#username").val(); + let username = ($("#username").val() || "").trim(); let password = $("#password").val(); let anon = document.getElementById("allowAnonymous").checked; if (username === "") { @@ -21,11 +21,22 @@ $("#btnCreateUser").on('click', () => { url: "/firstLogin", data: JSON.stringify(login), contentType: 'application/json', + beforeSend: () => { + $("#firstRunError").removeClass("show").addClass("d-none"); + }, success: () => { window.location.href = "/index.html"; }, - error: () => { - alert("Something went wrong"); + error: (xhr) => { + const response = xhr && xhr.responseJSON ? xhr.responseJSON : {}; + const reason = response.reason || ""; + if (reason === "already_configured") { + window.location.href = "/login.html"; + return; + } + + $("#firstRunErrorText").text(response.message || "Something went wrong"); + $("#firstRunError").removeClass("d-none").addClass("show"); } }) -}); \ No newline at end of file +}); diff --git a/src/rust/lqosd/src/node_manager/js_build/src/index.js b/src/rust/lqosd/src/node_manager/js_build/src/index.js index 92bd093b..769840a5 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/index.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/index.js @@ -9,6 +9,7 @@ const defaultLayout = { activeTab: 0, tabs: [ { + id: "executive-summary", name: "Executive Summary", dashlets: [ { tag: "executiveSnapshot", size: 12 }, @@ -21,6 +22,7 @@ const defaultLayout = { ] }, { + id: "overview", name: "Overview", dashlets: [ { tag: "throughputRing", size: 12 }, @@ -33,6 +35,7 @@ const defaultLayout = { ] }, { + id: "system-overview", name: "System Overview", dashlets: [ { tag: "throughputBps", size: 2 }, @@ -45,6 +48,7 @@ const defaultLayout = { ] }, { + id: "network", name: "Network", dashlets: [ { tag: "networkTreeSankey", size: 6 }, @@ -52,6 +56,7 @@ const defaultLayout = { ] }, { + id: "top-10", name: "Top 10", dashlets: [ { tag: "top10downloaders", size: 6 }, @@ -64,6 +69,7 @@ const defaultLayout = { ] }, { + id: "protocols-cake", name: "Protocols & Cake", dashlets: [ { tag: "etherProtocols", size: 6 }, @@ -72,6 +78,7 @@ const defaultLayout = { ] }, { + id: "treeguard", name: "TreeGuard", dashlets: [ { tag: "treeguardControls", size: 6 }, @@ -80,6 +87,7 @@ const defaultLayout = { ] }, { + id: "bakery", name: "Bakery", dashlets: [ { tag: "bakeryStatusSummary", size: 4 }, diff --git a/src/rust/lqosd/src/node_manager/js_build/src/login.js b/src/rust/lqosd/src/node_manager/js_build/src/login.js index 3a523734..f1f35873 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/login.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/login.js @@ -1,5 +1,5 @@ $("#btnLogin").on('click', () => { - let username = $("#username").val(); + let username = ($("#username").val() || "").trim(); let password = $("#password").val(); if (username === "") { alert("You must enter a username"); @@ -21,12 +21,27 @@ $("#btnLogin").on('click', () => { data: JSON.stringify(login), contentType: 'application/json', beforeSend: () => { + $("#loginErrorText").html("Login failed. You can manage users via the lqusers CLI tool on the LibreQoS server."); $("#loginError").removeClass("show").addClass("d-none"); }, success: () => { window.location.href = "/index.html"; }, - error: () => { + error: (xhr) => { + const response = xhr && xhr.responseJSON ? xhr.responseJSON : {}; + const reason = response.reason || ""; + if (reason === "first_run_required") { + window.location.href = "/first-run.html"; + return; + } + + if (reason === "auth_corrupt") { + $("#loginErrorText").text(response.message || "The auth file is corrupt and must be repaired before anyone can log in."); + } else if (reason === "invalid_credentials") { + $("#loginErrorText").text(response.message || "Invalid username or password."); + } else { + $("#loginErrorText").html("Login failed. You can manage users via the lqusers CLI tool on the LibreQoS server."); + } $("#loginError").removeClass("d-none").addClass("show"); } }) diff --git a/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard_editor.js b/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard_editor.js index 242548b4..6a83209f 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard_editor.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/dashboard_editor.js @@ -1,3 +1,5 @@ +import {DashboardLayout} from "./layout"; + /** * Opens a full screen modal that lets the user edit dashboard items with tab support. * @param {Object} layout - The current dashboard layout object with tabs @@ -8,7 +10,13 @@ export function openDashboardEditor(layout, availableElements, callback, cookieName) { // Keep track of current tab and layout state let currentLayout = JSON.parse(JSON.stringify(layout)); // Deep copy - let activeTabIndex = currentLayout.activeTab || 0; + currentLayout.tabs = DashboardLayout.normalizeTabs(currentLayout.tabs || []); + let activeTabIndex = DashboardLayout.resolveActiveTabIndex( + currentLayout.tabs, + currentLayout.activeTab, + currentLayout.tabs[currentLayout.activeTab || 0]?.id || null + ); + currentLayout.activeTab = activeTabIndex; const sortableInstances = []; let committedLayout = null; @@ -301,10 +309,12 @@ export function openDashboardEditor(layout, availableElements, callback, cookieN $('#addTabButton').on('click', function() { let newTabName = `Tab ${currentLayout.tabs.length + 1}`; currentLayout.tabs.push({ + id: DashboardLayout.makeTabId(newTabName), name: newTabName, dashlets: [] }); activeTabIndex = currentLayout.tabs.length - 1; + currentLayout.activeTab = activeTabIndex; renderTabs(); renderDashboard(); }); @@ -516,8 +526,12 @@ export function openDashboardEditor(layout, availableElements, callback, cookieN // Apply the layout currentLayout = { version: imported.version || 2, - tabs: imported.tabs, - activeTab: imported.activeTab || 0 + tabs: DashboardLayout.normalizeTabs(imported.tabs), + activeTab: DashboardLayout.resolveActiveTabIndex( + DashboardLayout.normalizeTabs(imported.tabs), + imported.activeTab, + imported.tabs?.[imported.activeTab || 0]?.id || null + ) }; // Re-render diff --git a/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/layout.js b/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/layout.js index 97efc038..8f071b78 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/layout.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/lq_js_common/dashboard/layout.js @@ -3,8 +3,10 @@ const CURRENT_VERSION = 3; export class DashboardLayout { constructor(cookieName, defaultLayout) { this.cookieName = cookieName; + this.activeTabStorageKey = `${cookieName}.activeTabId`; // Keep a normalized copy of the default (tabs + dashlets only) this._defaultTabs = DashboardLayout.normalizeToTabs(defaultLayout); + const persistedActiveTabId = this.loadPersistedActiveTabId(); let template = localStorage.getItem(cookieName); if (template !== null) { let parsed = JSON.parse(template); @@ -15,21 +17,30 @@ export class DashboardLayout { Array.isArray(parsed.tabs) ? parsed.tabs : [], this._defaultTabs ); - this.activeTab = parsed.activeTab || 0; + this.activeTab = DashboardLayout.resolveActiveTabIndex( + this.tabs, + parsed.activeTab, + persistedActiveTabId + ); } else { // Old format saved in localStorage (pre-tabs) // Treat as a signal to reset to the new default layout, // so users see the new Overview tab instead of a single-tab conversion. this.version = CURRENT_VERSION; if (defaultLayout && defaultLayout.version >= 2) { - this.tabs = defaultLayout.tabs || []; - this.activeTab = defaultLayout.activeTab || 0; + this.tabs = DashboardLayout.normalizeToTabs(defaultLayout); + this.activeTab = DashboardLayout.resolveActiveTabIndex( + this.tabs, + defaultLayout.activeTab, + persistedActiveTabId + ); } else { - this.tabs = [{ - name: "Dashboard", - dashlets: defaultLayout || [] - }]; - this.activeTab = 0; + this.tabs = DashboardLayout.normalizeToTabs(defaultLayout); + this.activeTab = DashboardLayout.resolveActiveTabIndex( + this.tabs, + 0, + persistedActiveTabId + ); } try { localStorage.removeItem(this.cookieName); } catch (e) {} } @@ -38,18 +49,24 @@ export class DashboardLayout { if (defaultLayout && defaultLayout.version >= 2) { // New format default this.version = defaultLayout.version; - this.tabs = defaultLayout.tabs || []; - this.activeTab = defaultLayout.activeTab || 0; + this.tabs = DashboardLayout.normalizeToTabs(defaultLayout); + this.activeTab = DashboardLayout.resolveActiveTabIndex( + this.tabs, + defaultLayout.activeTab, + persistedActiveTabId + ); } else { // Old format default - convert to new format this.version = CURRENT_VERSION; - this.tabs = [{ - name: "Dashboard", - dashlets: defaultLayout || [] - }]; - this.activeTab = 0; + this.tabs = DashboardLayout.normalizeToTabs(defaultLayout); + this.activeTab = DashboardLayout.resolveActiveTabIndex( + this.tabs, + 0, + persistedActiveTabId + ); } } + this.persistActiveTabId(); } save(layoutData) { @@ -60,9 +77,14 @@ export class DashboardLayout { } else { // New style - full layout object this.version = layoutData.version || CURRENT_VERSION; - this.tabs = layoutData.tabs || []; - this.activeTab = layoutData.activeTab || 0; + this.tabs = DashboardLayout.normalizeTabs(layoutData.tabs || []); + this.activeTab = DashboardLayout.resolveActiveTabIndex( + this.tabs, + layoutData.activeTab, + this.getActiveTabId() + ); } + this.persistActiveTabId(); // Only persist if layout differs from default tabs/dashlets const isDefault = DashboardLayout.tabsEqual(this.tabs, this._defaultTabs); if (isDefault) { @@ -92,24 +114,97 @@ export class DashboardLayout { getCurrentTabDashlets() { return this.tabs[this.activeTab]?.dashlets || []; } + + getActiveTabId() { + return this.tabs[this.activeTab]?.id || null; + } + + loadPersistedActiveTabId() { + try { + return localStorage.getItem(this.activeTabStorageKey); + } catch (e) { + return null; + } + } + + persistActiveTabId() { + try { + const activeTabId = this.getActiveTabId(); + if (activeTabId) { + localStorage.setItem(this.activeTabStorageKey, activeTabId); + } else { + localStorage.removeItem(this.activeTabStorageKey); + } + } catch (e) {} + } } // Static helpers DashboardLayout.normalizeToTabs = function(defaultLayout) { if (!defaultLayout) return []; if (defaultLayout.version >= 2 && Array.isArray(defaultLayout.tabs)) { - return defaultLayout.tabs.map(t => ({ - name: t.name || "Dashboard", - dashlets: Array.isArray(t.dashlets) ? t.dashlets.map(d => ({ tag: d.tag, size: d.size })) : [] - })); + return DashboardLayout.normalizeTabs(defaultLayout.tabs); } // Old format: list of dashlets if (Array.isArray(defaultLayout)) { - return [{ name: "Dashboard", dashlets: defaultLayout.map(d => ({ tag: d.tag, size: d.size })) }]; + return [DashboardLayout.normalizeTab({ + id: "dashboard", + name: "Dashboard", + dashlets: defaultLayout + })]; } return []; }; +DashboardLayout.makeTabId = function(name = "tab") { + const base = String(name || "tab") + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") || "tab"; + return `${base}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`; +}; + +DashboardLayout.normalizeTab = function(tab, fallbackName = "Dashboard", fallbackId = null) { + const name = tab?.name || fallbackName; + return { + id: tab?.id || fallbackId || DashboardLayout.makeTabId(name), + name, + dashlets: Array.isArray(tab?.dashlets) + ? tab.dashlets.map((dashlet) => ({ tag: dashlet.tag, size: dashlet.size })) + : [] + }; +}; + +DashboardLayout.normalizeTabs = function(tabs) { + if (!Array.isArray(tabs) || tabs.length === 0) { + return []; + } + return tabs.map((tab, index) => + DashboardLayout.normalizeTab(tab, `Tab ${index + 1}`) + ); +}; + +DashboardLayout.resolveActiveTabIndex = function(tabs, requestedIndex, requestedTabId) { + if (!Array.isArray(tabs) || tabs.length === 0) { + return 0; + } + + if (requestedTabId) { + const indexById = tabs.findIndex((tab) => tab?.id === requestedTabId); + if (indexById >= 0) { + return indexById; + } + } + + const numericIndex = Number.parseInt(requestedIndex, 10); + if (Number.isFinite(numericIndex) && numericIndex >= 0 && numericIndex < tabs.length) { + return numericIndex; + } + + return 0; +}; + DashboardLayout.tabsEqual = function(tabsA, tabsB) { if (!Array.isArray(tabsA) || !Array.isArray(tabsB)) return false; if (tabsA.length !== tabsB.length) return false; @@ -131,23 +226,30 @@ DashboardLayout.tabsEqual = function(tabsA, tabsB) { }; DashboardLayout.mergeMissingDefaultTabs = function(existingTabs, defaultTabs) { - if (!Array.isArray(existingTabs) || !Array.isArray(defaultTabs) || defaultTabs.length === 0) { - return Array.isArray(existingTabs) ? existingTabs : []; - } - const knownNames = new Set(existingTabs.map((tab) => tab?.name || "")); - const merged = existingTabs.slice(); - defaultTabs.forEach((tab) => { - const name = tab?.name || ""; - if (!name || knownNames.has(name)) { + if (!Array.isArray(existingTabs) || existingTabs.length === 0) { + return Array.isArray(defaultTabs) ? DashboardLayout.normalizeTabs(defaultTabs) : []; + } + + const normalizedExisting = DashboardLayout.normalizeTabs(existingTabs); + if (!Array.isArray(defaultTabs) || defaultTabs.length === 0) { + return normalizedExisting; + } + + const merged = normalizedExisting.slice(); + const knownIds = new Set(normalizedExisting.map((tab) => tab?.id || "")); + const knownNames = new Set(normalizedExisting.map((tab) => tab?.name || "")); + defaultTabs.forEach((tab, index) => { + const normalizedTab = DashboardLayout.normalizeTab(tab, `Tab ${index + 1}`); + if ( + !normalizedTab.name + || knownIds.has(normalizedTab.id) + || knownNames.has(normalizedTab.name) + ) { return; } - knownNames.add(name); - merged.push({ - name, - dashlets: Array.isArray(tab?.dashlets) - ? tab.dashlets.map((dashlet) => ({ tag: dashlet.tag, size: dashlet.size })) - : [] - }); + knownIds.add(normalizedTab.id); + knownNames.add(normalizedTab.name); + merged.push(normalizedTab); }); return merged; }; diff --git a/src/rust/lqosd/src/node_manager/js_build/src/template.js b/src/rust/lqosd/src/node_manager/js_build/src/template.js index 7b921da1..5898d2ca 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/template.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/template.js @@ -55,23 +55,20 @@ function renderSchedulerStatus(container, state) { let color = "text-secondary"; let icon = "fa-spinner fa-spin"; let label = "Scheduler status is loading"; - let buttonText = "Scheduler starting..."; + const buttonText = "Scheduler"; if (state === "healthy") { color = "text-success"; icon = "fa-check-circle"; label = "Scheduler is available"; - buttonText = "Scheduler"; } else if (state === "unavailable") { color = "text-warning"; icon = "fa-clock"; label = "Scheduler is still unavailable"; - buttonText = "Scheduler unavailable"; } else if (state === "error") { color = "text-danger"; icon = "fa-triangle-exclamation"; label = "Scheduler has an internal error"; - buttonText = "Scheduler error"; } container.innerHTML = ` diff --git a/src/rust/lqosd/src/node_manager/js_build/src/tree.js b/src/rust/lqosd/src/node_manager/js_build/src/tree.js index be727e31..c4e2c1d1 100644 --- a/src/rust/lqosd/src/node_manager/js_build/src/tree.js +++ b/src/rust/lqosd/src/node_manager/js_build/src/tree.js @@ -302,6 +302,13 @@ function renderHeaderStatusIcons(node) { "Virtual node (logical only; not shaped in HTB)." )); } + if (node.runtime_virtualized === true) { + target.appendChild(buildStatusIcon( + "fa-layer-group", + "text-warning", + "TreeGuard runtime-virtualized node (physically bypassed in Bakery while preserved in the logical hierarchy)." + )); + } if (isStormguardNode(node)) { target.appendChild(buildStatusIcon( "fa-cloud-bolt", @@ -1247,6 +1254,12 @@ function buildRow(i, depth=0) { "Virtual node: Active", "Virtual node: Inactive", )); + statusWrap.appendChild(buildTreeRowStatusIcon( + "fa-layer-group", + node.runtime_virtualized === true, + "TreeGuard runtime virtualization: Active", + "TreeGuard runtime virtualization: Inactive", + )); statusWrap.appendChild(buildTreeRowStatusIcon( "fa-cloud-bolt", isStormguardNode(node), @@ -1400,6 +1413,7 @@ function treeUpdate(msg) { || tree[nodeId][1].subtree_circuit_count !== node.subtree_circuit_count || tree[nodeId][1].type !== node.type || tree[nodeId][1].virtual !== node.virtual + || tree[nodeId][1].runtime_virtualized !== node.runtime_virtualized || tree[nodeId][1].name !== node.name) { needsRebuild = true; } diff --git a/src/rust/lqosd/src/node_manager/local_api/directories.rs b/src/rust/lqosd/src/node_manager/local_api/directories.rs index e3b77469..63a5e525 100644 --- a/src/rust/lqosd/src/node_manager/local_api/directories.rs +++ b/src/rust/lqosd/src/node_manager/local_api/directories.rs @@ -206,7 +206,7 @@ pub fn treeguard_metadata_summary() -> TreeGuardMetadataSummary { .iter() .filter(|(_, node)| { let name = node.name.trim(); - !name.is_empty() && name != "Root" && node.is_virtual + !name.is_empty() && name != "Root" && node.runtime_virtualized }) .count(); diff --git a/src/rust/lqosd/src/node_manager/local_api/network_tree_lite.rs b/src/rust/lqosd/src/node_manager/local_api/network_tree_lite.rs index ecaa9b50..6862d9cd 100644 --- a/src/rust/lqosd/src/node_manager/local_api/network_tree_lite.rs +++ b/src/rust/lqosd/src/node_manager/local_api/network_tree_lite.rs @@ -12,6 +12,9 @@ pub struct NetworkTreeLiteNode { /// True if the node is virtual/logical-only. #[serde(rename = "virtual", default)] pub is_virtual: bool, + /// True if TreeGuard has runtime-virtualized this node in Bakery. + #[serde(default)] + pub runtime_virtualized: bool, /// Configured maximum throughput in Mbps. pub max_throughput: (f64, f64), /// Current throughput in bytes per second. diff --git a/src/rust/lqosd/src/node_manager/run.rs b/src/rust/lqosd/src/node_manager/run.rs index 9b398351..13075237 100644 --- a/src/rust/lqosd/src/node_manager/run.rs +++ b/src/rust/lqosd/src/node_manager/run.rs @@ -52,6 +52,8 @@ pub async fn spawn_webserver( // Construct the router from parts let router = Router::new() .route("/", get(redirect_to_index)) + .route("/login.html", get(auth::login_page)) + .route("/first-run.html", get(auth::first_run_page)) .route("/doLogin", post(auth::try_login)) .route("/firstLogin", post(auth::first_user)) .route("/health", get(health_check)) diff --git a/src/rust/lqosd/src/node_manager/static2/first-run.html b/src/rust/lqosd/src/node_manager/static2/first-run.html index 95683af3..7f4c89f2 100644 --- a/src/rust/lqosd/src/node_manager/static2/first-run.html +++ b/src/rust/lqosd/src/node_manager/static2/first-run.html @@ -72,6 +72,11 @@ +
+ + Unable to initialize web authentication. +
+