From 6b59434ffa526b67152e81b9d1f05e79a0f1caa6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Gruszczy=C5=84ski?= Date: Sat, 14 Nov 2026 09:57:21 +0100 Subject: [PATCH] 0.37.0 --- AGENTS.md | 2 +- CHANGELOG.md | 26 + Cargo.lock | 2 +- Cargo.toml | 2 +- SHA256SUMS | 112 +- docker-agent/README.md | 40 +- docker-agent/containers.go | 187 ++ docker-agent/disk_linux.go | 14 + docker-agent/disk_other.go | 5 + docker-agent/docker-agent.env.example | 3 + docker-agent/docker.go | 17 +- docker-agent/enroll.go | 193 ++ docker-agent/enroll_test.go | 155 ++ docker-agent/install.sh | 12 +- docker-agent/main.go | 40 +- docker-agent/model.go | 44 +- docker-agent/provision.go | 96 + docker-agent/runtime.go | 94 + docker-agent/rustproxy-docker-agent.service | 3 +- docker-agent/server.go | 21 +- docker-agent/system.go | 301 +++ docker-agent/system_test.go | 190 ++ docs/DASHBOARD.md | 4 + docs/DOCKER_DISCOVERY.md | 74 +- docs/FEATURES.md | 2 +- grafana/README.md | 23 + grafana/rustproxy-overview.json | 2300 ++++++++++++++---- integrations/routeros-oci-build/README.md | 4 +- langs/en_US.json | 143 +- langs/pl_pl.json | 143 +- src/admin/openapi.json | 684 +++++- src/admin/preferences.rs | 18 + src/admin/preferences_tests.rs | 25 +- src/admin/router.rs | 3 + src/admin/status.rs | 92 +- src/admin/status_live.rs | 1 + src/admin/web/acl-picker.js | 88 + src/admin/web/app/core.js | 9 +- src/admin/web/app/dashboard-inline-layout.js | 4 +- src/admin/web/app/dashboard-layout-editor.js | 6 +- src/admin/web/app/docker-dashboard.js | 179 ++ src/admin/web/app/preferences.js | 6 +- src/admin/web/css/10-base.css | 5 +- src/admin/web/css/30-overview.css | 22 + src/admin/web/css/50-settings.css | 69 + src/admin/web/dashboard-defaults.json | 50 +- src/admin/web/dashboard-widgets.json | 284 ++- src/admin/web/docker.js | 360 ++- src/admin/web/index.html | 14 +- src/admin/web/partials/overview-metrics.html | 140 ++ src/admin/web/vhosts/render.js | 1 + src/config/compile.rs | 4 +- src/docker/client.rs | 232 +- src/docker/model.rs | 269 +- src/docker/reconcile.rs | 623 ++++- src/docker/tests.rs | 421 +++- src/prometheus/docker_misc.rs | 7 +- src/prometheus/vhosts_backends.rs | 278 ++- src/tls/types.rs | 2 +- tests/panel_refresh_contract.js | 2 +- 60 files changed, 7418 insertions(+), 732 deletions(-) create mode 100644 docker-agent/containers.go create mode 100644 docker-agent/disk_linux.go create mode 100644 docker-agent/disk_other.go create mode 100644 docker-agent/enroll.go create mode 100644 docker-agent/enroll_test.go create mode 100644 docker-agent/provision.go create mode 100644 docker-agent/runtime.go create mode 100644 docker-agent/system.go create mode 100644 docker-agent/system_test.go create mode 100644 src/admin/web/app/docker-dashboard.js diff --git a/AGENTS.md b/AGENTS.md index 9237f96..c399e93 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # RustProxy source and documentation maintenance -Current source version: **0.36.13**. The Cargo package and binary are named `rust-proxy`. +Current source version: **0.37.0**. The Cargo package and binary are named `rust-proxy`. Before editing, read [README.md](README.md), the relevant [documentation guide](docs/README.md) and the actual code and tests. Historical release experiments are not current specifications. Use the bundled `src/admin/openapi.json` for API routes and payloads; the source implementation is authoritative for runtime behavior. diff --git a/CHANGELOG.md b/CHANGELOG.md index ef53d55..9dc6797 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,32 @@ Release history focused on **features, settings, default behavior, compatibility ## Unreleased +## 0.37.0 — Docker domains, certificate lists, agent provisioning and host diagnostics + +- **Backends table, ultra-compact density:** the backend name line is hidden in *Ultra compact* table density, so hovering the vhost name (dotted underline) or the identity cell now shows a tooltip with both the vhost and backend names. +- **Docker agent domains:** *Base domain* is replaced by **Domains** — a list of up to 16 DNS suffixes per agent (for example `app.example.com`, `example.com`, `random.example.net`), chosen in the same searchable multi-select as ACL profiles; type a domain and press Enter to add it. The first domain (★) is the master domain for new Docker vhosts; click ★ on another domain to make it the master. +- **Master domain per Docker vhost:** every published service picks its master domain from the agent domains (default: the first), so it works under `.` right after publishing. Aliases can be short labels (under the master domain or another agent domain chosen next to the alias input) or full names, which the panel accepts only inside the agent domains. +- **Docker certificates:** the single certificate selector is replaced by **Automatic** (global SNI / default certificate, the default) or **Selected certificates** (up to 32, same picker style as ACL profiles). Each generated vhost uses the selected certificate that covers all its names (exact names win, then the narrowest); otherwise it falls back to the generic SNI/default certificate. The service editor shows which certificate will be used. *Accept certificate/domain mismatch* forces the first selected certificate when none matches. +- **Provisioning code:** Docker agent 1.1.0 adds `rustproxy-docker-agent provision-code`, which prints one `RPDA1-…` code (base64url JSON with the HTTPS endpoint, Bearer token and certificate SHA-256). **Settings → Docker agents → Paste provisioning code** (or *Provisioning code* inside an existing agent, for rotated tokens) fills in the name, endpoint, token and pin at once. `info --show-token` and the manual installer also print the code. The code contains the secret token. +- **Docker agent ID:** generated automatically from the agent name using the same rule and widget as Vhost IDs (editable until saved). +- **Default backend IP:** now a list of the addresses detected by the agent (with interface/scope/source), *Automatic* or **Custom address…**. +- **Host diagnostics:** agents 1.1.0+ report OS, kernel, architecture, Docker/Podman runtime and version, uptime, load average, CPU usage, memory, swap, disk usage of the container data directory, host network totals/rates and running/total containers and images. They appear in **Docker vhosts → Agent details → Host system** and in a compact diagnostics strip (status, last check, error, host metrics) in **Settings → Docker agents**. Nothing is shown when an agent does not send them. +- **Docker Overview cards (optional, hidden by default):** **Docker agents**, **Docker apps**, **Docker app requests** (rate chart), **Docker hosts network** (RX/TX chart), **Docker hosts load** (CPU/memory bars and load per host) and **Containers**. With two or more agents every card has an agent selector (*All agents* or one agent), also shown next to the card when adding it in the layout editors; the choice is saved per administrator in the new `docker_widget_agents` preference. +- **Docker alerts:** RustProxy raises alerts from the latest agent poll only (no stored history): the agent could not be reached at the last check (error), a host's disk or memory use is at or above a threshold (default 90% / 95%), the load per CPU reported by the host (5-minute load average) is at or above a threshold (default 2.0), a **published service disappeared from the inventory**, a published container is unhealthy, restarting, exited or dead (containers without a health check are judged by their state only), or container labels cannot be published. They are shown as ordinary alerts: a **Docker** entry in the application status (amber/red), a notification when a new alert appears, a list at the top of **Docker vhosts**, a `Docker alert raised/cleared` log line and Prometheus `rust_proxy_docker_alert` / `rust_proxy_docker_alerts_active`. Thresholds and switches: **Settings → Docker agents → Alerts** (`docker_agents.alerts`). +- **Prometheus host metrics:** `rust_proxy_docker_agent_up`, `..._agent_last_success_timestamp_seconds`, `rust_proxy_docker_host_*` (info, uptime, CPU count and usage, memory, swap, disk, load 1/5/15 m, network totals and rates, containers, images) and `rust_proxy_docker_container_*` (state/health info, CPU, memory, memory limit, restarts), all labelled with `agent`; `rust_proxy_docker_vhost_label_published` marks label publications. +- **Grafana:** the bundled dashboard gets **Job** and **RustProxy server** variables applied to every query, a **RustProxy servers** row (per-server table with version, uptime, request/error rate, active exchanges, RSS and CPU, servers down, per-server time series) for monitoring several RustProxy servers, and a **Docker hosts and alerts** row. +- **Diagnostics charts:** small CPU, memory, load and network charts in **Agent details** are sampled in the browser from the agent polls while the page is open, like the other panel charts (length follows the Overview history sample setting); RustProxy itself stores no history. +- **Publishing from container labels:** with **Publish from container labels** on an agent, containers labelled `rustproxy.enable=true` are published automatically. Optional labels: `rustproxy.host`, `rustproxy.domain`, `rustproxy.aliases`, `rustproxy.scheme`, `rustproxy.port`, `rustproxy.force_ssl`, `rustproxy.websockets`, `rustproxy.cache`, `rustproxy.compression`, `rustproxy.preserve_host`. Names must be inside the agent domains and must not collide with existing hosts; such services get a **LABELS** badge, invalid ones a **LABEL ERROR** badge and an alert. A manual setting always wins: *Apply changes* takes a label publication over, switching *Publish* off stores a disabled manual override. Off by default. +- **Container state:** each service row shows the container state and health check (healthy, unhealthy, starting, or *no health check* for images without `HEALTHCHECK`), CPU, memory with its limit and restart count (agent 1.1.0, Docker and Podman). +- **Test connection:** a button in each agent checks endpoint, token and certificate pin before saving (`POST /api/docker/test`). +- **One-time provisioning codes:** `provision-code` now prints a one-time `RPDA1` code (format v2) that contains the endpoint, the certificate pin and a single-use enrollment secret valid for 15 minutes (`--ttl`), but not the token. Pasting it makes RustProxy redeem it at the agent over the pinned HTTPS connection (`POST /api/docker/enroll` → agent `POST /v1/enroll`) and fill in the permanent token; a used or expired code is rejected. `--static` prints the previous reusable code with the token. One-time codes require HTTPS. +- **More Docker cards:** every Docker Overview card exists four times (`docker_host_load`, `docker_host_load_2` … `_4`, likewise for the others), shown as *#2–#4*, so the same card can be placed per agent next to each other. +- **Podman support in the agent:** `RUSTPROXY_DOCKER_SOCKET=auto` (new default) uses `/var/run/docker.sock`, then `/run/podman/podman.sock`, then the rootless `$XDG_RUNTIME_DIR/podman/podman.sock`; `unix://` URLs are accepted. `podman-compose` labels (`io.podman.compose.*`) group services like Docker Compose. The systemd unit no longer *requires* `docker.service`, and the manual installer accepts Podman hosts. +- **Status API:** `GET /api/status` (full and `view=live`) adds a `docker` object (`null` without agents) with per-agent `ok`, `observed`, `services`, `published_pool_ids`, `missing_services` and `system`, plus `alerts`. `GET /api/docker` adds `alerts`, `label_issues`, label publications in `pool_routes` and `last_ok_unix_ms` in observations. `GET /api/docker` inventories may include `system`. +- **Configuration/API:** Docker agents add `domains` and `certificate_ids`; assignments add `domain` (master domain). Legacy `base_domain` and `certificate_id` are still accepted and migrated on save (`domains: [base_domain]`, `certificate_ids: [certificate_id]`) and are no longer written. The Docker inventory accepts unknown fields from newer agents. +- **Compatibility:** RustProxy 0.37.0 requests `GET /v1/inventory?system=1`; older agents ignore the parameter and keep working without diagnostics. Agent 1.1.0 sends `system` only on that request, so older RustProxy servers keep working with the new agent. +- **Upgrade notes:** no database migration. Existing Docker agents keep their behavior: the old base domain becomes the only domain and a selected certificate becomes the only selected certificate (a certificate that does not cover a service's names now falls back to the generic SNI/default certificate instead of being rejected, unless the mismatch override is enabled). Saving the configuration writes the new fields, so downgrading to 0.36.x afterwards requires restoring a previous configuration. Update agents to 1.1.0 for provisioning codes, host diagnostics and Podman. + ## 0.36.13 — panel-style origin rejection page - **Administration access error:** the generic inline "Could not open the panel" response is now a dedicated HTML template that uses the same RustProxy brand, login-card layout, typography, buttons and status styling as the administration panel. diff --git a/Cargo.lock b/Cargo.lock index 6c7b1ea..e9cb84f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1943,7 +1943,7 @@ dependencies = [ [[package]] name = "rust-proxy" -version = "0.36.13" +version = "0.37.0" dependencies = [ "anyhow", "arc-swap", diff --git a/Cargo.toml b/Cargo.toml index f1e271a..adb7a79 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rust-proxy" -version = "0.36.13" +version = "0.37.0" edition = "2021" rust-version = "1.99.1" description = "RustProxy - independent reverse proxy with local administration" diff --git a/SHA256SUMS b/SHA256SUMS index b380bd9..e05a7c5 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -1,10 +1,10 @@ 61bf40a0572889dc8b0dda9eae4e93e44b0de9364b3c798106c85700ffb37c23 .dockerignore 4140a2956264b44f259e6a37fc00ba02097bbe68b09296e04d3d243c1287129b .env.example e76e688874828e3743d03693b1d2872b9633b4db09909673786caf30f7cfe489 .gitignore -4429f22007079fd0e7281f2e9597c08c96ede00c1d64a398f733db111c26e175 AGENTS.md -4459e87c6776ea711c774338d3b44fdc4642a969ffc517b60366bbafdcaea546 CHANGELOG.md -c9be49deaf4a2e7b1408375b44dcd4058dfc221d08233e38104cddc0e788eadd Cargo.lock -f06306e77e64a757a318f2dae8627bbdec7eeb833fec8f219780b980d32cf7e4 Cargo.toml +c7a44d067d8190054e40f1aa78f6c3f532faec4b103295c1acab89b006fa26ea AGENTS.md +358c32848c57ad2cf6ec74ee50eee5579d30ecb46ec4a91763ee144ca6b31c32 CHANGELOG.md +3ff0c3825b95bbdfcaca324b1611132ff2fade7bcbfd20a490e8595cd9732094 Cargo.lock +4b91597db4f479b381b50eb39ac58ae3e72e2cc563f7eb994a765b3ac8550977 Cargo.toml 788745d4f70a0382c6280020afbd48844bb2af65e835a826852143f8132cdeca Dockerfile 0d96a4ff68ad6d4b6f1f30f713b18d5184912ba8dd389f86aa7710db079abcb0 LICENSE 82d1dee2fc68158f0ea73259151461e64c8b18d807cd1fecfb1ed99dc30cf5f4 README.md @@ -13,20 +13,29 @@ c0df6b46bf795d49d00fcd9e2a9247aed0d3a99b6cae1dc5ab6614e8b3d30009 build.rs 95ececaba550a4bcfd6754073877ba0633373b1e1451521b9ac905a51e8ca6eb deploy/README.md 13d514de5042a230cacf8c10abe1ef183c94ac799a89b8e2c111152ac7c69b48 deploy/rustproxy.service c111f5b20484707b80efb7dd9176acbaa27b63ac78db497261ac234821e1fade dev.sh -d213e774a9cd07bff0c79324722bd05c0aca18cc033d50b2c0558cdb72972bca docker-agent/README.md +f3aeefbf2ec7b65f63b868477e79ce4800857e2b1b260998265acd53b9c70ba1 docker-agent/README.md e9f18b358a740f1fe16e369ed16ee37581b8ce4c94ddeb34a1a37b89a49b5a06 docker-agent/certificate.go 600d5aebc8557d6987158969d494bade1ba46ccf9d1cd573d357d0106db26b2b docker-agent/cli_test.go +7a8ca48aca82178a301b41dfb4f1997b27f09352394d844bb2b627fa1c8aab0f docker-agent/containers.go 067793eee01fd284da66f79c6f8b6f19f8773e64f84af03168c8f751ff044685 docker-agent/credentials.go -5e4f565c3c9de4dba897af2e801ea646a83395e72eae4717a6d502dff2fcec10 docker-agent/docker-agent.env.example -ae660c2a90f193167b166977277abfc86a25e043ab4def4c273b2a13d5a51b8b docker-agent/docker.go +5140f45740a95817f711cffbbc096a378a137c506d3ded89c65a15e1e078e221 docker-agent/disk_linux.go +6ad4958e72e96e1623b396ba47e6c5f7dc2effe6244833030fbe769ca3ae4e02 docker-agent/disk_other.go +86f1259a7619f5d19500d833e515d67376464851878a84dd2a677350fd2344d6 docker-agent/docker-agent.env.example +95a6cd2d80702019d0bb249dad02c81d2bfd4b440bdd43995575a0fcb3f6c2d0 docker-agent/docker.go +4fe3d9313b11209fd649d52bcd651801e613a74fe2b027b1ab98abe7875ad488 docker-agent/enroll.go +10a2b07617f0fb68e63adc1a03db035d24e564a23244310407056bb76715762f docker-agent/enroll_test.go 9e9f3f17f38f9b0730f598f65988ce8ef562d2182ef6778fc7292b990e9cf22f docker-agent/go.mod -7b70bd43a7f39bae8968decf4cd76af80fe0d08bf1bc53b894d89ead80581d56 docker-agent/install.sh -b7d0466f70b541a705d234fc8a88b99b6197fdd5e682d3a288a78c76764358cf docker-agent/main.go +b849d39e94878c5a754c3d109d8e4b5e37609cfd2a0e05601a35271f4d95271e docker-agent/install.sh +56d6acd675c44c3a39538b321d2057cf251a6a27b0ad634d827eb7d6a20de8c0 docker-agent/main.go d660f46f7ef8c539dd3f5486a31d5a1254b9737be8a278c7f9352c254558f8ac docker-agent/main_test.go -351bcd0321c823694e12d578f96dc68ceb929979a70146d12af5394f639a486f docker-agent/model.go +37d4bcd4b1cb53c8359db3304418d3ac4820a6a0c55fd80672671f24c7cdd61c docker-agent/model.go e52b31d0abf65ae3034f6cb367cca113633014ce8d1d799ad4dd5624d2c7b8bb docker-agent/network.go -634790f35ff4627df2a78cec2ed371f6e9ec9df00afb386075595fc7f3ed72eb docker-agent/rustproxy-docker-agent.service -5220d669171ec3ad65f50e0bc8de5178dadaa4904def8e1a4f61002aa9e9a55b docker-agent/server.go +021e0799a95a7c76bc245ff464d94b4495ce0d22555ca202579bd5f45e4be794 docker-agent/provision.go +4a737e5922c2255492c85d5afc053cd15d9e5b83cada648369cfdeeecdbfaa92 docker-agent/runtime.go +24494010bb215c5ff7eda0a571272309eebb5c35fa4ed24430da87790e89e941 docker-agent/rustproxy-docker-agent.service +b0b19b5fa15fe589f10305a19b75894f5d5cee816348e831702c4e06186e73b0 docker-agent/server.go +afd5b425936acc4972e9054b31daffead5f39ea706b0c3e5ead54270e3d43979 docker-agent/system.go +18e275e5fbe2d45cd4da0778bffdcec18eda475bb27e225a4b09bff9fc8a0a20 docker-agent/system_test.go 60d108fd168064e4d6980ed7499f3219017f9878c743697e77f2efc592e4d629 docs/ACCESS.md e708fc937dba80ac311fb19e785deae4eed586923180bc2a6b1c1a21922b5c2f docs/API.md 728b15b9825f547f34c4121219784798dd046fbbdd72ece8906d0cd77e8efc64 docs/BACKUP.md @@ -34,9 +43,9 @@ e708fc937dba80ac311fb19e785deae4eed586923180bc2a6b1c1a21922b5c2f docs/API.md 5e7b6668be6bfec77755ae45b9d369aa14135fce7632de392c6b29a7b584245a docs/CERTIFICATES.md bfd185b3b16f8b9a95351c4be570c6491dd941f39799344110eea40d2ee1d185 docs/CONFIGURATION.md fec29ce846d6705eb45819d85d382f28e28a146b265feab2e4c7cce2a35e5883 docs/CUSTOM_LOCATIONS.md -99f928fda4f0011d647fbbc00d9064a7e50e138269609c88fbab39afdf9fb83b docs/DASHBOARD.md -11a08bf2110bbeabc924eb049a30177a216af5607ccdaf8be9178e751f78a2c4 docs/DOCKER_DISCOVERY.md -b93950503da032b2d24d5514c80014aefbacd55b7dec64f9d0c6499464412461 docs/FEATURES.md +bf7d7a3071c6198fb52b6b971a752bec80c39973a62824c6a5d0fc5974628b82 docs/DASHBOARD.md +d15f79249539d7c92f4041a0bb898597bd033cfd2b1f3f740fe0c84bc7dc26c5 docs/DOCKER_DISCOVERY.md +763ad7bdabc61f027f08fc9dcab30d1930ae09862688e1be28a9310bd56d5ebf docs/FEATURES.md 2c5f97b12be53db32c7e2888d23c0ef1d82d1742df44f7e60ea818dc801a719a docs/INSTALL.md 6e37859bf0dced99d4a7db93790cb38fcd90191932827946d5223eaa4c784fce docs/LOGS.md 0e9ae9509a78d00951d2c7c3f13eaf518d1f3448a29b048f5933e1f5f8440275 docs/MIGRATION.md @@ -77,8 +86,8 @@ a6b835dc07defc12b8f0e48491d5f413843c8be2ba4501d7c28140a2822b034f examples/oidc- 5a8f3a8a054abc89c6e78896b9fe2f903212199a24dc3d2d2bcbd0696a31bcde examples/transport.json d242de9614fbb52933b4accd32f4715ca94107abe4a3b1d7e088362b07a6ba60 examples/vhosts-balanced.json af2bdb1343a8141069e94ccd2c7f92574ad848437e2f9fdb5c7576a9a18ef4a5 examples/vhosts-private.json -35e4f3acc652ac23a9442600c4c76173ae34966592031b3e942b62c249fc869e grafana/README.md -0d389faa4f64f095e9ec62cbae329658682b96f5e4d02ead79c7d2892ab89fa8 grafana/rustproxy-overview.json +91ce19f8ec3b60ccc5780d756b533f4709f3132fddd7e17866e74e4ff1c46136 grafana/README.md +c720a4426d7b4dc52048077157dd05aefa427ae78ca811afc3b7b9cbbe875cae grafana/rustproxy-overview.json 1a041c505669625a7f0f8011484cf5b6d2ec69a7de859801312e4fcf4c8d3555 install-debian13.sh 909e9ab94617ace74a425f15084bf85f3086cc52ba5b28f2b441ff800abc6ef9 install.sh 42f9f1d18c021fc7734b5bd020844bf678725a0e539e2fcbe05ec676f6239eae integrations/README.md @@ -90,12 +99,12 @@ de6550ab8f48d556d752c252212c38ba65491fd224f972c10fbe552f91ed7520 integrations/o e9cbb0224c4a3d23a6019ba557e0cd568c1ad5e1582ff1e335fb7d99b7a1055d integrations/routeros-oci-build/.gitignore 14025f0cad10e1b89f366977123e4cebb68ae59df892d4eed29b6171e63ae908 integrations/routeros-oci-build/Dockerfile.routeros 7c7a3e51f43b43e1c962a4b0bb591f99c1f06977bf77f23719f7f867dfe7eb8e integrations/routeros-oci-build/Dockerfile.routeros.dockerignore -1f92e9cb9c8a5ff7eee33ea5b61755de19b0ec10a80e9ae47721293528a97f95 integrations/routeros-oci-build/README.md +040f975d3f415fa3c0d88a9a3482f7ee5c928a340a370450eb73f309283a5dd9 integrations/routeros-oci-build/README.md 3f092a9ab80221eddd67be4d1a776acbc6e04c1eb6011b588280c28e83b2582f integrations/routeros-oci-build/build-routeros-oci.sh 3f267cafa16006e5456ade78ee2d5fae02cc7ce747839523068ffd8d7c98798a integrations/routeros-oci-build/docker-entrypoint.sh 13189fa546c3488dddd8efc80c47f6da5241e5fc28b79cbfe795414ea05c7a4f langs/README.md -7abfc275ee8c3b27235b42d9623b58399db9c1dfcc7edde48f7043053b9e6b8b langs/en_US.json -e825a280d606eb17cd76de62e6d010632b3fc7b6f9c534818033ac1538069112 langs/pl_pl.json +85bc9068e6ec2dbca2c668f8fb598fe963a57598157ae0e9dd3b0ceb084376fd langs/en_US.json +c8a659de54951aa627997f47b2275f5ddae4726504694c9413ac3ad3b7b35ad8 langs/pl_pl.json 8ed80f14633970899d56f4ea72684a8d4b1f2843c1c78bfacc4cbb5f7ce9ef4b make_zip.py e830d37dd1f81a4b0aa7d535f5bba69e34e433b0fd99cc8ee0b296786c32379a migrations/0002_admin.sql 20112cc82192098b8d602f1c4f7ca08712e9e1366c845fabb92753187c370d35 migrations/0003_certificate_renewals.sql @@ -167,35 +176,36 @@ d58a2ed83319176de4e66790ed292447c9497ae031464ec55cfe27174acb639a src/admin/file 77b8c05645969834cc8a58e249a7b60a57d6c47ad1c5cd92ffa5e4a9b5a8e73c src/admin/file_logs_query.rs 743bb7436f77e04015328a0e7e7d425e43ef8aa8d61467bde157e462c1dcdc2e src/admin/logging_api.rs 243f4a9c3fa99781e19c3952354d2632c0ce65e1dafac729567cbe3c177f94cb src/admin/mod.rs -bab113f763d31d7247c8766f59b720d4120c8062f64475fa89bad8415be7f1e3 src/admin/openapi.json +e8accaabd974da53b3dac4b51323135052c8de68fed147d45ba3b456da109d79 src/admin/openapi.json f7a356109786635dd58cba590c71c796dbf36b47f25845190c75ee5c6a9fcb86 src/admin/operations.rs 257d93a29d0bda96462bcf695aba8d0ec0f9412c379e066ec46ae8ee034e3a53 src/admin/panel_assets.rs f5127855c2994d052678865df36d703b74f4a0afc633daf7718b10da18d26e37 src/admin/panel_content.rs -ff581de7dff43aa90b53be9efb5fa4d8ce89ab6526c37bbc6c2c4d34eac3d764 src/admin/preferences.rs +0ba8dfd4381f25356613218eb2be705509ec037fcc81f0bb341f5bc23772da8a src/admin/preferences.rs f3635b624cf48598d68274a470d84d15ef9f6070d56e437a0031afa724471d5e src/admin/preferences_columns.rs -7fabc2b9764d9f199fe4a3c171a8d9aed9666778855f2b016b5c39420b642e15 src/admin/preferences_tests.rs +8b7d6385465dafaaa1e110c798c57d556ece5562d2940af874d335fff6c2e56b src/admin/preferences_tests.rs 62ecbae5dee00aeeca3eb806e2605372471dfab971cde8f66f11e711df8fcea1 src/admin/public/mod.rs 7a00e4ab943f74d2b1bdcbfab7f9cd3f584e9f59536b4aca6c4c31f5f5508d12 src/admin/public/tests.rs 6930b4f4b45257772b321b20a9becdf9bc4610274852948ba38c2d0cdf02dfaf src/admin/refresh_preferences.rs -66eea4e8fd1c60a64090bd9e97b36903b10b1e2f7089c1a333e057d1d421bd6f src/admin/router.rs +f7cba11895741fcd54a85d483595fcd4487fa4d5ca9c6b9cc8a81f61af8c381a src/admin/router.rs fba52102e77ca8871a42f97c91be8f10a9aa4f997868652d550fff3fbd41b66e src/admin/session.rs -ee6e3a89a478e1092d2ed55686e216512b40d26963bc47fc6e30d4a75ac01b2f src/admin/status.rs -f7a696ae9924235790f4fdcb9bb77505fde364fbaf8d7fd94fc9fddf13d7a04b src/admin/status_live.rs +a3f834afb6fac6719fabb702eb574dc2634a3de0c2e54cb56e98fe5b87a91855 src/admin/status.rs +abb5cd89aac02745666b67da07de718ff70612aac370fbd49ca4d3340acad991 src/admin/status_live.rs 8315c856cd50f1072593ecb30c274d42d82f078b5fb93e7c68a8857cd81b0841 src/admin/status_system.rs cadd7dca29b9aad8c77c7bc23dd249ea37a15adfa4d636a8ef00273a91ce35dc src/admin/tail.rs 176173da61950866c61ab46b272a1ad95de3407dc6ef68a41c23a033b7d82b04 src/admin/tests.rs -c18c369124368f58524652565102817ed69fd25b222b0c5e737ef7632b45dcfb src/admin/web/acl-picker.js +cbe43a37d9239a6724d2d2a03daec1cf023e9e82c8a594043568eefc7a81deda src/admin/web/acl-picker.js 48fcd818c522fe80f2c7b2e218f87de6a7772ffd0a24e93502780b03ec78e335 src/admin/web/acme.js -b61a7d8fa850e191806a696c49a2e22786650e7a0d6408c1a7edd9144f5829b5 src/admin/web/admin_origin_rejected.html +30a71c399e9a2cd9a4c1830568e4767f219ce09bca35f6d5fd22424f1a6617ac src/admin/web/admin_origin_rejected.html 86abf50f39862d821cd2e43ca425671aa85289272915132c5a9a5dd1fc4182e2 src/admin/web/api-tokens.js faa9735c2a02746b2954bc4955eb609f94afebb685cd5521d2629640cea2777a src/admin/web/app/backend-dashboard.js aed3aea4eef0011c6b51d39736782e7d1ec52662e422f40e0c7b9ddfc19d0378 src/admin/web/app/certificate-inspection.js f6b0533ffd6d0e6471519120c440619a7fb4b255854ba3dd23d81cb35cd21afb src/admin/web/app/chart-scales.js dedda129e173a347ebca9445c8a313849d1d678c256deabeb18f9977559e021a src/admin/web/app/config-history.js -d20a1cfc53c160e809c34dc83f19be9cb19f075011c4c3f9a9d755230ac2ba18 src/admin/web/app/core.js -073c52c7c7d246703087aa9a8df3c3d8742e651da55c0edd6f2baef26bd241b0 src/admin/web/app/dashboard-inline-layout.js -b269cd90710d2e86b4c9b685d4d141271ef21fe6256d3b03b8f4018d00c48c7e src/admin/web/app/dashboard-layout-editor.js +bf295721a38761f88363eda856064f854e408cb9d7888a2e0d0f2eaf3d72d7ed src/admin/web/app/core.js +c782cdf0e6a23a1fc4bb5804e2d63e17bdc1faf75dda9d5ccc09b7752b6a245f src/admin/web/app/dashboard-inline-layout.js +92bd0567a2631b2b9441901dbaabf7a02ff71de1ddfee02930f6fe97128ec7c1 src/admin/web/app/dashboard-layout-editor.js 716d33249a52548f10153d8e2f5bea962a5f0427525272ddd3a1db636647672c src/admin/web/app/dashboard-presets.js +12880f470ddc8cae97ac79e8da68bcfe8aa15cd5c9d701044f88a670250a2eee src/admin/web/app/docker-dashboard.js 99c3e775b3a57d9a783ca9350f48132eecbb0471f10daa6961cb2bcc9de630db src/admin/web/app/icons.js 9fc3165febd83a6661b2827aacd612fbc0f834e99ef1585ec54e03e97fe54a72 src/admin/web/app/logo-animation.js 92ed982c3ac4bc4218a24a200d2a33f30fc6705b77b260db2be31b0ce91a7df9 src/admin/web/app/memory-breakdown.js @@ -205,7 +215,7 @@ bbbbe153ff37aa4cac0a83319e5b56a6442cabd1ef819380ae76e95bf79c7628 src/admin/web/ 6f10f3239aea505aa01796620981eed873930c129ed5a2fd7eb439e0e0d24558 src/admin/web/app/overview-samples.js db9012546cae8c58fc2bcbee71c9a95956a13a6db9e6d126c6a3770d45a4e4d2 src/admin/web/app/overview-wide-metrics.js e799e0406c7ff54cbf71faf704a20265bdf5180a8ed2f26388d0775231365410 src/admin/web/app/path-permissions.js -aa33c7782dc9a9a6cd765a9a41379a0a38a78494d3819800926789e6fde8602a src/admin/web/app/preferences.js +eb2295ffa197c5700cf6913979443a4588f220bcc184013b243f534099bb2163 src/admin/web/app/preferences.js 30ec0a7027215eae63946689af2c042de0cf468a6b1054535694da4dd4214cdb src/admin/web/app/rate-sampling.js 3b8e566d81a5b94ef21c73e7805ae128454f085554de9358040de266bcbdb0e0 src/admin/web/app/refresh.js 399a52a076872fa031113d475794e029cb7eb3813a3471eb54cbbac5e765ce03 src/admin/web/app/runtime.js @@ -217,20 +227,20 @@ b7ead49224a4ec67181d3f24f9d9634bd6d76756f826a4d5d993300637d1d8f3 src/admin/web/ 3563508f45f740f0cc0e84c72eb79045c0cb54d6fa06a50326a3a219221e0010 src/admin/web/cache-panel.js 99ed8c37e4fee646b9b26c96edbba4d823175dc3354c17c6574a7fc9a3dcbb0e src/admin/web/certificate-api.js 43d702b676cd4f9dbe42e2ca65d938afe19086e67ab6e24af0b81d6947bee215 src/admin/web/css/00-tokens.css -f37c80964a0854c016d67224d34e6423b3130489fef633c100ea94bda3a32454 src/admin/web/css/10-base.css +fcaed873e1ab68b73b75e18edfb9b8efceaec7f336c1910599065dbb08930f10 src/admin/web/css/10-base.css e711163fb144e38c3c961c20c38be55ebbb2e75898ab0ac1e58762e9ab8ff005 src/admin/web/css/20-shell.css -746117cda2a047d90b13c112e307deccd1dc51131bd8e85bfa2d7e465e6704b0 src/admin/web/css/30-overview.css +078473429e253e63b83778cc223daeb7f84445a98763621733413a306778cbf8 src/admin/web/css/30-overview.css 1d61f2eb90e39c79c7055845df4a9497bc89c35fa67aafaf10e4bc245f0f69c7 src/admin/web/css/40-editors.css -51acc56f65ea2680929fe2b4de859ec5aac308c7431a775c9c27d6cf48b7484b src/admin/web/css/50-settings.css +1b52de62fc2fd08f4c86acd3b9e16354370d27a7f4e5c72e50854e466fdc0cbb src/admin/web/css/50-settings.css 31c927777bb844c40305b96b6771b4f3956590fc8346a6b9f08724bad676bce2 src/admin/web/css/60-monitoring.css e4f276e7ab5ada8342b0c34a95a0e55f3cd5e446c4620ad1a8e1f07e287793a2 src/admin/web/css/70-responsive.css 8009afdb04d5170687816730cc930a22fead1fe0248835ca7e8de81d6907395d src/admin/web/css/README.md 8241bd9489dfed082863948829a44a49bf0a8e9cd63c55809655109e393e0918 src/admin/web/css/manifest.json -b369bd8927ee84d05f546c267dd48f849a0857ca4355847302d6ac2381100440 src/admin/web/dashboard-defaults.json -6f2631ffbd130db1f69f153749c018ed488116061a3462e0eeb38e5496fb1457 src/admin/web/dashboard-widgets.json +78bf6179f769b68d518028464697e50dea5d75e33ecb1b89d88e2c2b01e86bf2 src/admin/web/dashboard-defaults.json +355046ecb80ce6adb73ceabd29825b0cf79ca364771070cedd5eb44760fae890 src/admin/web/dashboard-widgets.json 50d1ebcbaf4d0b2968da23bb943fc3f67131c5d32df3f61d23ff37aad9da5b81 src/admin/web/demo.html -bd170341634d7fe98172e0714b3cb8ee299a31abdbc9ab1309f5e61816dbcf0d src/admin/web/docker.js -9d17b9bb74185144472345bd2b034f1ffdbe0f4ef3055e4fe4ef69e32f780e7a src/admin/web/docs.css +a32ee25ac7b117cd29d3ee51441eaf09edfd410ae99077065150cf4a1ce592d4 src/admin/web/docker.js +0ed78a8731beca8d5e67163b26804cdcc925b0ecfbbc4bf946f8ec68daa62357 src/admin/web/docs.css aeffd403fa1823df7d9fa4c48280b4033b2d15e4cb9f66608caff89290de0a52 src/admin/web/docs.html fd8506a91f769b57b62d9d8e389fb67764599354bf702958a913be79f779707b src/admin/web/docs.js 8fbc2a837d6f20a7f96c856a91fcba967b40a33494fe27ec876ee1b3b685178f src/admin/web/drafts.js @@ -250,14 +260,14 @@ e6c4d91d1542d0a5b47bb8736f9539d43a6713df5a473b635519d5b7eac2eb9c src/admin/web/ 0a5fff35555153f59d4346933030a67b6e1a8768cee7a47cfa2fcf1a2c564f63 src/admin/web/favicon.svg dad1498b1dca57b4f0ad4e13e047332b66b59a8ce2f398b090bc952279b808cb src/admin/web/file-logs.js 882e99059bb2ff110c452eadc0b5779a16af1e34cb1b2536c80cf2056f8c3e8a src/admin/web/host404.js -a8f3a0f1d5a973fa3ca0fa0c2df6400324abb8e11a0edb6f5356043fcfc2a302 src/admin/web/index.html +790e4068a8889ad1e4a784aed7383ce8513e30da73de3e39af94ab8b12c8f399 src/admin/web/index.html 5746049029caa135646ebcefb3d419b07eda17b560a9c015c59d27f815df64d8 src/admin/web/integrations.js 7a12f020fc587205694978ab41b660e9a80487d413fbf6e34fc525eabc58308f src/admin/web/login-keys.json ac9f667273918e18406df06cb2613c923f50a88897693a03a18f500e22dc6ec2 src/admin/web/login.html c2e5f554810b8e34fb47361fb90a01073a2e332ee26d82e030956fad3ec1f83e src/admin/web/login.js 44b44790341067304e15974afcbbc7cc99686e88c2e43f62979d285eca6f726e src/admin/web/management.js 1f3d10e389c9c20e6eb019509fa6e82b50c6b43bbf988c1210a4d42bb73985d0 src/admin/web/partials/overview-charts.html -f619250d8da61517eb2151f17b640b06057e091640280091e08afd483d67e5ff src/admin/web/partials/overview-metrics.html +1fcbe9017bd6f32cdbdcf65fcc6f4342daf9632a5e1a97c7a3a56d76cbe87095 src/admin/web/partials/overview-metrics.html 3928afce2ed6d5f2d3e29475dd29e4c3bd3c6df180ad5119beaff0c7a58e3b3b src/admin/web/prometheus-token.js 6f33915d33d3a8bbfaeec424651a63eda3d23b0f296ae028a59ea46463ba9fdf src/admin/web/redirects.js 76a01f590d49649dcb1f554c221290919b2a8438e6001737f3c096fa6daec74d src/admin/web/settings.js @@ -270,7 +280,7 @@ dc0fc85c64eef983d575f1b220c53c28cf5d4944b77860a57f9f28c6fde2a386 src/admin/web/ 3776f72d7051af86ac5fbdd4581040dd88a424c0c6cde789301b032b159094d8 src/admin/web/vhosts/health.js b3239e67901f1796d7a974ade0796f2e3590ff8064628a5629b78c7f6ce2f32e src/admin/web/vhosts/protocol.js 8c3da49973c62333559b0e3588c02beb0b425c025eac5cfa82a1bb968f70d9dd src/admin/web/vhosts/rates.js -dd9e7c73f725f3e74235c1e9405d8ec509a78f11f6d90af7d22bf09a4f8789dc src/admin/web/vhosts/render.js +9ae02166d190fd3ea0f2946912df6edd036f3c2727950277ae1a31768e2133f2 src/admin/web/vhosts/render.js 4dfdeb7c73c2775eacaca65fd8ef1dc80b275421b15522d319d338f5b96288cc src/admin/web/web-server-profiles.js f9854526ff1567de47ecb02af872bca6e13c0adb984ad5ef0c256e5fdbb3902e src/admin/web/web-server.js 2d40c2cb32d7365df0c9cd6c8cb6f0483c7a799786c648f4836a0d9740c6c5ef src/auth/files/mod.rs @@ -346,7 +356,7 @@ a1132b980833b1b4ce2bba9aa681ff255a0e2d61faaa65a316860da503ea1e27 src/cache/v022 8de82d9188c9c337690c6ec4afdad9fff20651c358e34602a93d8bb8c3d2489a src/compression/tests.rs e695079333ebdc2a6e7b3337cfabef171b3a0a01da0597b77feff70d417f833e src/config.rs 9f138f86a8d73dfc2d28a2c66d131751c8c85af9c9ccdf22938736973c963678 src/config/backend.rs -6ad644fc4ae821d2c30329ace36652a7ac12d674e71e7dbdcdda3554c983f6f9 src/config/compile.rs +38581b289d4d6b134bca9d8b907d3e430488f783face5c19406935ab9e14b891 src/config/compile.rs fbea01fea1213d98aea812c1b78d5db289e09200b98ae514d742235cd3fa70e1 src/config/internal_routing.rs cc75698be2828000e88f2c482bd26f2fa4050e3432bec1b5a581dca17fef4a37 src/config/model.rs 75839458ddbc7480ec4492a95eeb67b617ba7d62f7b67e7a767a3453b74dbcbc src/config/route_policy_tests.rs @@ -363,10 +373,10 @@ c05a02618d476e4670b4f9930555f199cac776cdf09edb8fcc1a675695b8f99f src/db/tests.r dada314e1709e960eb2e225b4d10c3cd12606c62c4bc2c0220aec1ba133e4ade src/demo.rs d2ef07d1565569f520a6a8eb01f4ea9bb673499d038018d52e65fe95e800bb27 src/diagnostics.rs 045593a42a6e4f632e5052c655788f0843faa313fc929265b89509f6dfff91ed src/docker.rs -9a68e0d5bd98541314f1ab5a4c2e344e9837f315bd39ea3988ffab6a0f0425ab src/docker/client.rs -8feba6d9eb7fde798cbe8a9e339d6a5346cfef039980fce46727386717635eec src/docker/model.rs -f095e5e3c564df409874019c647f7cec2156bf5a845b5b84864879fd07cf80ce src/docker/reconcile.rs -2e8d4841665cc1d29e6262a1789bb64ced1cecd0036681cc1ef7b5d5bfe22065 src/docker/tests.rs +3e3383b344e33a4a0b818f39309076c973db0a670eb4c4dc5acab63ad801c59e src/docker/client.rs +05cce4d9b8be354b86b10bde411edbf8b3421fca0ab8d53fe62a4fa4ad2ab6bd src/docker/model.rs +97a5ecb3bb90f3641b9691e8f86ba694f62ca7db1a817a8463d90fc5fc5978d3 src/docker/reconcile.rs +7e91ee27cd729b0484dbb380ead33d54d2922c08c9df623b1fffbb82a26f520d src/docker/tests.rs 34eb55a240928e98bd34e790ac63096b9ca8bf7a3008676dbbd11e1a392b8541 src/forward_auth/mod.rs 6c25951cf69e972c47cdf815f22a5062916b2b768e39d55a26a5fc9e625a2344 src/forward_auth/tests.rs 5d32cf9177a33d6fb50452541805b10ae1b0833e709d833f5bd1fc6907193ffb src/forwarding.rs @@ -415,12 +425,12 @@ eb95c68c8639ce3ae658eea3334795cdb5e129fb2ba10955f7dffe06d8909b57 src/pages/mod. d09dc18863b0508a5e8d54a5305904170f3e8f12857b7a0d5393a11849541e50 src/pages/tests.rs 5650a3f70162abd97021e0a51a92cac2c4dd39004426ef99dff36cbb0741aeac src/prometheus.rs b9d71633703469d1d14e89c4d8a7698f4d354e5111cfe6ed3b2587566d0e2333 src/prometheus/core.rs -2321ee667569803dfe6c92c0e98adba0ac8fcdc6a3eacd5857233f1acae93daf src/prometheus/docker_misc.rs +1fffe1540387632cd93f549025d69a13f39abccf86de376c3fe91b90c2f224c6 src/prometheus/docker_misc.rs cc909edf740a091f9057912f555dd888b644fa1cb49647fe0e2e1f5dba8ff5af src/prometheus/json.rs f9aab3297fcf647295849f77cbf99197f4dd27efd6817e54c03451e04972430c src/prometheus/model.rs f8a9541b568ade946dfc0b3353548a773a0126f705b537815ce0523439b07ef4 src/prometheus/tests.rs 028e1dd9f2ec2afaf699a6b21c2d4b0d96e76f11f5e4ed009c233dadf0f3be51 src/prometheus/traffic.rs -cdbfa0e7f49200dc70ea6df8f0594399ee3e0c5fc3d279cc336e2d83d0f8a535 src/prometheus/vhosts_backends.rs +12cf2b67072b10bcb163eeef76efc298dae1d9598ea6bb8a441f735339c1c467 src/prometheus/vhosts_backends.rs f1b0254f53b1a4336bd8170ad441ba072b49a114e497b985cb20699b4e375044 src/prometheus/web_php.rs 315cdf2ec1479433aabee00f616e8c0a9ebe4697bd4928885433b80e52a706cd src/proxy/body/mod.rs 5beeac12ca7f041bdb9b74b2dbc9781f5d5524fcf51294b8b6ad88284754ef20 src/proxy/body/tests.rs @@ -506,7 +516,7 @@ df98becda799b6bf4ff5e2fec7d0e0a486e6b7eca6f9f5ad49ffdafd49a4f498 src/tls.rs 937b95bb8621ab98d7cad3d223e4dee305350fbd0149b7527396d3bdcc28a68b src/tls/external_paths_tests.rs 1ff95e95d38eedeefcf8a931569d628763d5a328aa5573c73c928f06795037ba src/tls/server_config.rs 688b929615ebc1d873461237c3de6dfa169984230266a59aad78d93f0eaa2cd6 src/tls/tests.rs -ce51a3280331d67c8406d2c5bc156ac0b492afa58e1f328bcda76db0720a6a9d src/tls/types.rs +f0981c883e7969362c69d71d03c55e2a57fc833a750609f08ae14a651529e5f9 src/tls/types.rs 58f01b9a6dd1095877cc71445b3ccd651d8b2a1a9c0ad543547840834ec1d91b src/traffic/mod.rs bd62b4ecdcf831d183c7720766a11703c8612d614e3abf38d2bff28df34710fd src/traffic/tests.rs bfbbaa3b949ae946fa929bfbae3fd9a25f2ce792abbd0ed370ccf5683250bc4d src/transform/apply.rs @@ -567,7 +577,7 @@ f00743af2cf4a5952caef7a1dcf68e7817b5599a252a9973e1c22045517c0b0e tests/fixtures 102b83171a6429b6375d8001d6c5294702385cd58ee55727cb657b1f3566e877 tests/panel_icons_browser.py c4030b7d224553312012b1f25153dd3545e83de7bccff2894c0e8f7e0e84b721 tests/panel_icons_contract.js 886c89e8517f34af5e2aef9672a8de559f94c536b028f1b9cadf2a2a7220d826 tests/panel_interface_contract.py -b360e8dd2634976eb0e4fadd5d2afd9dc9b86c707e9c44e62978beb2f9f5bdb6 tests/panel_refresh_contract.js +7402118f81f5ee55a8a38876359d20c8b001f94951618288970d4fe037da1352 tests/panel_refresh_contract.js e24a0f84f1bfc46964df865ac387d651f7b384d781cbc8f3a9a5b0b60f3d69ca tests/vhost_auth_selection.js cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 third_party/swagger-ui-5.33.1/LICENSE 0d20d1adef18aee3f40dd258172155521ce702ac445cb5f7b7d60ed32dad2fb2 third_party/swagger-ui-5.33.1/NOTICE diff --git a/docker-agent/README.md b/docker-agent/README.md index 3ec4e9d..be6cfdd 100644 --- a/docker-agent/README.md +++ b/docker-agent/README.md @@ -4,7 +4,7 @@ The optional `rustproxy-docker-agent` runs **on a Docker host**, not on the Rust ## Requirements and security -- Linux amd64/x86_64 with **systemd and Docker Engine** (including a usable `/var/run/docker.sock`). No FreeBSD `pkg` is built for this agent. +- Linux amd64/x86_64 with **systemd and Docker Engine or Podman** (a usable `/var/run/docker.sock` or Podman API socket, see [Podman](#podman)). No FreeBSD `pkg` is built for this agent. - Restrict inbound port `9876` to the RustProxy server through a firewall. The example binds `0.0.0.0:9876`; this is reachable from other machines when the firewall permits it. - Access to `docker.sock` grants substantial **host-level privilege**, regardless of the agent's read-only HTTP API. The service uses a dedicated unprivileged identity granted access to the `docker` group. - Self-signed ECDSA P-256 HTTPS is enabled by default; the certificate and private key persist under `/var/lib/rustproxy-docker-agent/` and are **not** regenerated on upgrades/restarts. The key is `0600`. @@ -44,7 +44,16 @@ sudo systemctl status rustproxy-docker-agent sudo journalctl -u rustproxy-docker-agent -n 100 --no-pager ``` -Configure **RustProxy → Settings → Docker agents** with the host's `https://host:9876` URL, the full Bearer token, and the printed certificate SHA-256 fingerprint. The RustProxy server pins the certificate when a fingerprint is configured; a replaced certificate requires updating the fingerprint in the panel. +The quickest way to connect RustProxy is the **provisioning code**: + +```bash +sudo rustproxy-docker-agent provision-code +# RPDA1-eyJ2IjoxLCJuYW1lIjoiZG9ja2VyMSIsImVuZHBvaW50Ijoi... +``` + +Paste it into **RustProxy → Settings → Docker agents → Paste provisioning code**. The panel fills in the agent name and ID, the `https://IP:port` endpoint, the Bearer token and the pinned certificate SHA-256 fingerprint. By default the code is **one-time**: `RPDA1-` + base64url JSON with the endpoint, the certificate fingerprint and an enrollment secret valid for 15 minutes (`--ttl`). RustProxy redeems it at `POST /v1/enroll` over the pinned HTTPS connection and receives the permanent token; the secret is stored hashed in `enrollment.json` next to the TLS key and removed on use. `--static` prints the older reusable code, which **contains the secret token**. The endpoint host is `RUSTPROXY_DOCKER_ADVERTISE_IP`, a concrete listen address or the routed IP; override it with `--endpoint-host docker1.example.net` (or `RUSTPROXY_DOCKER_ENDPOINT_HOST`). `info --show-token` also prints the code. + +Alternatively configure **RustProxy → Settings → Docker agents** manually with the host's `https://host:9876` URL, the full Bearer token, and the printed certificate SHA-256 fingerprint. The RustProxy server pins the certificate when a fingerprint is configured; a replaced certificate requires updating the fingerprint in the panel. ## CLI commands @@ -55,6 +64,8 @@ Configure **RustProxy → Settings → Docker agents** with the host's `https:// | `sudo rustproxy-docker-agent info` | Show listening endpoint, hostname, Docker socket, token status/length, TLS certificate paths, SHA-256, issuer, subject, SAN, serial, algorithms and validity | | `sudo rustproxy-docker-agent info --show-token` | Explicitly reveal the full Bearer token in addition to metadata | | `sudo rustproxy-docker-agent show-token` | Print **only** the full secret token (protect stdout) | +| `sudo rustproxy-docker-agent provision-code [--ttl 15m] [--endpoint-host HOST]` | Print a one-time `RPDA1-…` code (endpoint, certificate fingerprint, single-use enrollment secret) for the RustProxy panel; HTTPS only | +| `sudo rustproxy-docker-agent provision-code --static` | Print a reusable code that contains the Bearer token (**sensitive**) | | `sudo rustproxy-docker-agent rotate-token` | Create a new token without replacing the certificate; **restart the service and update RustProxy** before continuing | | `sudo rustproxy-docker-agent cert-init` | Create a missing certificate/key and print SHA-256; never overwrites existing valid certificate/key | | `sudo rustproxy-docker-agent print-fingerprint` | Print current SHA-256 certificate fingerprint | @@ -93,12 +104,35 @@ Both installation types use the **same** config and certificate paths, but diffe Upgrades do not reset credentials or private state. The environment file is installed with `config|noreplace`; local edits remain in place according to package-manager conffile behavior. Removal does not delete `/etc/rustproxy/docker-agent.env` or `/var/lib/rustproxy-docker-agent` (back these up separately). +## Container labels and state + +With **Publish from container labels** enabled in RustProxy, containers with `rustproxy.enable=true` are published automatically (see `docs/DOCKER_DISCOVERY.md`). The agent forwards only `rustproxy.*` labels. For every published container it also reports state, health check, restart count, CPU and memory (`GET /containers/{id}/json` and `/stats?stream=false&one-shot=true`, at most 64 containers per poll). Labels and container state are sent only to RustProxy 0.37.0+ (`?system=1`); `RUSTPROXY_DOCKER_SYSTEM_INFO=false` also disables container statistics. + +## Podman + +The agent speaks the Docker Engine API, which Podman also serves on its API socket. With `RUSTPROXY_DOCKER_SOCKET=auto` (the default) the agent uses `/var/run/docker.sock` when present, then `/run/podman/podman.sock`, then `$XDG_RUNTIME_DIR/podman/podman.sock` (rootless). Set an explicit path or `unix://` URL to choose one. + +Rootful Podman: + +```bash +sudo systemctl enable --now podman.socket +# Give the service group access to the socket (the installer creates a 'docker' group when Podman is found): +sudo systemctl edit podman.socket # [Socket] SocketGroup=docker SocketMode=0660 +sudo systemctl restart podman.socket rustproxy-docker-agent +``` + +Containers started by `podman-compose` are grouped by their `com.docker.compose.*` or `io.podman.compose.*` labels exactly like Docker Compose services. Ports published by a Podman **pod** belong to the pod's infra container and are reported under that container name. The agent details in RustProxy show `podman` as the runtime. + +## Host diagnostics + +RustProxy 0.37.0 and newer request `GET /v1/inventory?system=1`; the agent then adds a `system` object with the OS name, kernel, architecture, uptime, load average, CPU count and usage, memory/swap, disk usage of the container data directory, host network totals and rates (container and virtual interfaces excluded), the runtime (`docker`/`podman`) with its version and running/total container and image counts. Older RustProxy versions never receive the block. Values the agent cannot read are omitted. Set `RUSTPROXY_DOCKER_SYSTEM_INFO=false` (or `--no-system-info`) to stop reporting it. + ## API and troubleshooting The API is `GET /v1/inventory` with `Authorization: Bearer `; `GET /healthz` has no inventory and requires no token. Both use HTTPS by default. Plain HTTP is possible with `RUSTPROXY_DOCKER_AGENT_TLS=false` but exposes credentials in transit; use it only in a secured network and never across the public Internet. - `no valid token`: execute `sudo rustproxy-docker-agent init`; check env file permissions and `EnvironmentFile`. -- `Docker socket unavailable`: install/start Docker Engine, check `/var/run/docker.sock`, the `docker` group and membership of `rustproxy-docker-agent`. +- `container socket unavailable`: install/start Docker Engine (or `podman.socket`), check `/var/run/docker.sock` / `/run/podman/podman.sock`, the `docker` group and membership of `rustproxy-docker-agent`. - `TLS certificate/key`: inspect ownership of `/var/lib/rustproxy-docker-agent/`, mode `0600` on the private key, and both certificate/key paths. Refuse partially missing pairs rather than overwriting them. - `x509` or fingerprint mismatch in RustProxy: compare `sudo rustproxy-docker-agent print-fingerprint` with the pin configured in Settings. - Cannot reach port `9876`: check `RUSTPROXY_DOCKER_AGENT_LISTEN`, listening socket, firewall, and that HTTPS is used. diff --git a/docker-agent/containers.go b/docker-agent/containers.go new file mode 100644 index 0000000..874942e --- /dev/null +++ b/docker-agent/containers.go @@ -0,0 +1,187 @@ +package main + +import ( + "context" + "net/url" + "strings" + "sync" + "time" +) + +const maxStatContainers = 64 + +type containerState struct { + State string `json:"state,omitempty"` + Health string `json:"health,omitempty"` + RestartCount *uint64 `json:"restart_count,omitempty"` + CPUPercent *float64 `json:"cpu_percent,omitempty"` + MemoryBytes *uint64 `json:"memory_bytes,omitempty"` + MemoryLimitBytes *uint64 `json:"memory_limit_bytes,omitempty"` + StartedAt string `json:"started_at,omitempty"` +} + +type containerInspect struct { + RestartCount uint64 `json:"RestartCount"` + State struct { + Status string `json:"Status"` + StartedAt string `json:"StartedAt"` + Health *struct { + Status string `json:"Status"` + } `json:"Health"` + } `json:"State"` +} + +type cpuUsage struct { + CPUUsage struct { + TotalUsage uint64 `json:"total_usage"` + } `json:"cpu_usage"` + SystemCPUUsage uint64 `json:"system_cpu_usage"` + OnlineCPUs uint32 `json:"online_cpus"` +} + +type containerStats struct { + CPUStats cpuUsage `json:"cpu_stats"` + PreCPUStats cpuUsage `json:"precpu_stats"` + MemoryStats struct { + Usage uint64 `json:"usage"` + Limit uint64 `json:"limit"` + Stats map[string]uint64 `json:"stats"` + } `json:"memory_stats"` +} + +func healthFromStatus(status string) string { + status = strings.ToLower(status) + switch { + case strings.Contains(status, "(unhealthy)"): + return "unhealthy" + case strings.Contains(status, "(healthy)"): + return "healthy" + case strings.Contains(status, "health: starting"): + return "starting" + } + return "" +} + +func rustproxyLabels(labels map[string]string) map[string]string { + out := map[string]string{} + for key, value := range labels { + if strings.HasPrefix(key, "rustproxy.") && len(key) <= 64 && len(value) <= 512 && len(out) < 32 { + out[key] = value + } + } + if len(out) == 0 { + return nil + } + return out +} + +type cpuSampleKey struct{ total, system uint64 } + +type containerCollector struct { + mu sync.Mutex + prev map[string]cpuSampleKey +} + +func newContainerCollector() *containerCollector { + return &containerCollector{prev: map[string]cpuSampleKey{}} +} + +func memoryWithoutCache(stats containerStats) uint64 { + usage := stats.MemoryStats.Usage + for _, key := range []string{"inactive_file", "total_inactive_file", "cache"} { + if value, ok := stats.MemoryStats.Stats[key]; ok && value < usage { + return usage - value + } + } + return usage +} + +func (c *containerCollector) cpuPercent(id string, stats containerStats) *float64 { + c.mu.Lock() + defer c.mu.Unlock() + current := cpuSampleKey{stats.CPUStats.CPUUsage.TotalUsage, stats.CPUStats.SystemCPUUsage} + previous, ok := c.prev[id] + c.prev[id] = current + if !ok && stats.PreCPUStats.SystemCPUUsage > 0 { + previous, ok = cpuSampleKey{stats.PreCPUStats.CPUUsage.TotalUsage, stats.PreCPUStats.SystemCPUUsage}, true + } + if !ok || current.system <= previous.system || current.total < previous.total { + return nil + } + cpus := float64(stats.CPUStats.OnlineCPUs) + if cpus == 0 { + cpus = 1 + } + value := round(float64(current.total-previous.total)/float64(current.system-previous.system)*cpus*100, 1) + return &value +} + +func (c *containerCollector) enrich(ctx context.Context, sock string, services []service) { + ids := map[string]*containerState{} + order := []string{} + for i := range services { + id := services[i].ContainerID + if id == "" { + continue + } + if _, ok := ids[id]; !ok { + if len(order) >= maxStatContainers { + continue + } + ids[id] = services[i].Container + order = append(order, id) + } + } + ctx, cancel := context.WithTimeout(ctx, 4*time.Second) + defer cancel() + var wg sync.WaitGroup + limit := make(chan struct{}, 8) + for _, id := range order { + state := ids[id] + if state == nil { + continue + } + wg.Add(1) + go func(id string, state *containerState) { + defer wg.Done() + limit <- struct{}{} + defer func() { <-limit }() + escaped := url.PathEscape(id) + var inspect containerInspect + if err := engineGet(ctx, sock, "/containers/"+escaped+"/json", &inspect); err == nil { + restarts := inspect.RestartCount + state.RestartCount = &restarts + if inspect.State.Status != "" { + state.State = inspect.State.Status + } + state.StartedAt = inspect.State.StartedAt + switch { + case inspect.State.Health != nil && inspect.State.Health.Status != "": + state.Health = strings.ToLower(inspect.State.Health.Status) + case inspect.State.Health == nil: + state.Health = "none" + } + } + var stats containerStats + if err := engineGet(ctx, sock, "/containers/"+escaped+"/stats?stream=false&one-shot=true", &stats); err == nil { + state.CPUPercent = c.cpuPercent(id, stats) + if stats.MemoryStats.Usage > 0 { + memory := memoryWithoutCache(stats) + state.MemoryBytes = &memory + } + if stats.MemoryStats.Limit > 0 && stats.MemoryStats.Limit < 1<<60 { + limitBytes := stats.MemoryStats.Limit + state.MemoryLimitBytes = &limitBytes + } + } + }(id, state) + } + wg.Wait() + c.mu.Lock() + for id := range c.prev { + if _, ok := ids[id]; !ok { + delete(c.prev, id) + } + } + c.mu.Unlock() +} diff --git a/docker-agent/disk_linux.go b/docker-agent/disk_linux.go new file mode 100644 index 0000000..8b9d39b --- /dev/null +++ b/docker-agent/disk_linux.go @@ -0,0 +1,14 @@ +//go:build linux + +package main + +import "syscall" + +func diskUsage(path string) (uint64, uint64, bool) { + var stat syscall.Statfs_t + if err := syscall.Statfs(path, &stat); err != nil || stat.Blocks == 0 { + return 0, 0, false + } + size := uint64(stat.Bsize) + return stat.Blocks * size, stat.Bavail * size, true +} diff --git a/docker-agent/disk_other.go b/docker-agent/disk_other.go new file mode 100644 index 0000000..23c2564 --- /dev/null +++ b/docker-agent/disk_other.go @@ -0,0 +1,5 @@ +//go:build !linux + +package main + +func diskUsage(string) (uint64, uint64, bool) { return 0, 0, false } diff --git a/docker-agent/docker-agent.env.example b/docker-agent/docker-agent.env.example index e66f470..c0b2c9a 100644 --- a/docker-agent/docker-agent.env.example +++ b/docker-agent/docker-agent.env.example @@ -4,6 +4,9 @@ RUSTPROXY_DOCKER_AGENT_TOKEN=replace-with-at-least-24-random-characters RUSTPROXY_DOCKER_AGENT_TLS=true RUSTPROXY_DOCKER_AGENT_CERT_FILE=/var/lib/rustproxy-docker-agent/agent.crt RUSTPROXY_DOCKER_AGENT_KEY_FILE=/var/lib/rustproxy-docker-agent/agent.key +RUSTPROXY_DOCKER_SOCKET=auto +RUSTPROXY_DOCKER_SYSTEM_INFO=true +RUSTPROXY_DOCKER_ENDPOINT_HOST= # Optional preferred address. Other usable host addresses are still auto-detected and reported. RUSTPROXY_DOCKER_ADVERTISE_IP= # Optional external/public address lookup. Set empty to disable. diff --git a/docker-agent/docker.go b/docker-agent/docker.go index a428973..b447cdc 100644 --- a/docker-agent/docker.go +++ b/docker-agent/docker.go @@ -80,11 +80,20 @@ func dnsLabel(value string) string { return out } +func firstLabel(labels map[string]string, names ...string) string { + for _, name := range names { + if value := strings.TrimSpace(labels[name]); value != "" { + return value + } + } + return "" +} + func serviceIdentity(c dockerContainer, p dockerPort) (key, technical string) { name := cleanName(c.Names) - project := c.Labels["com.docker.compose.project"] - composeService := c.Labels["com.docker.compose.service"] - replica := c.Labels["com.docker.compose.container-number"] + project := firstLabel(c.Labels, "com.docker.compose.project", "io.podman.compose.project") + composeService := firstLabel(c.Labels, "com.docker.compose.service", "io.podman.compose.service") + replica := firstLabel(c.Labels, "com.docker.compose.container-number", "io.podman.compose.container-number") if project != "" && composeService != "" { if replica == "" { replica = name @@ -121,6 +130,8 @@ func servicesFrom(containers []dockerContainer) []service { item = &service{ Key: key, TechnicalName: technical, ContainerID: id, ContainerName: name, Image: c.Image, PrivatePort: p.PrivatePort, Protocol: p.Type, + Labels: rustproxyLabels(c.Labels), + Container: &containerState{State: strings.ToLower(c.State), Health: healthFromStatus(c.Status)}, } byKey[key] = item bindingSeen[key] = make(map[string]struct{}) diff --git a/docker-agent/enroll.go b/docker-agent/enroll.go new file mode 100644 index 0000000..40fee28 --- /dev/null +++ b/docker-agent/enroll.go @@ -0,0 +1,193 @@ +package main + +import ( + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/http" + "os" + "os/user" + "path/filepath" + "strconv" + "strings" + "sync" + "time" +) + +const maxEnrollments = 8 + +type enrollment struct { + TokenSHA256 string `json:"token_sha256"` + Expires int64 `json:"expires"` +} + +func enrollmentPath(cfg config) string { + return filepath.Join(filepath.Dir(cfg.KeyFile), "enrollment.json") +} + +func readEnrollments(path string) ([]enrollment, error) { + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + var items []enrollment + if err := json.Unmarshal(data, &items); err != nil { + return nil, err + } + return items, nil +} + +func writeEnrollments(path string, items []enrollment) error { + data, err := json.Marshal(items) + if err != nil { + return err + } + if err := atomicWrite(path, data, 0o600); err != nil { + return err + } + if os.Geteuid() == 0 { + if serviceUser, err := user.Lookup("rustproxy-docker-agent"); err == nil { + uid, _ := strconv.Atoi(serviceUser.Uid) + gid, _ := strconv.Atoi(serviceUser.Gid) + _ = os.Chown(path, uid, gid) + } + } + return nil +} + +func hashToken(token string) string { + sum := sha256.Sum256([]byte(token)) + return hex.EncodeToString(sum[:]) +} + +func createEnrollment(cfg config, ttl time.Duration, now time.Time) (string, time.Time, error) { + if ttl < time.Minute || ttl > 7*24*time.Hour { + return "", time.Time{}, errors.New("enrollment code lifetime must be between 1m and 168h") + } + token, err := makeToken() + if err != nil { + return "", time.Time{}, err + } + path := enrollmentPath(cfg) + items, err := readEnrollments(path) + if err != nil { + return "", time.Time{}, err + } + fresh := items[:0] + for _, item := range items { + if item.Expires > now.Unix() { + fresh = append(fresh, item) + } + } + if len(fresh) >= maxEnrollments { + fresh = fresh[len(fresh)-maxEnrollments+1:] + } + expires := now.Add(ttl) + fresh = append(fresh, enrollment{TokenSHA256: hashToken(token), Expires: expires.Unix()}) + if err := writeEnrollments(path, fresh); err != nil { + return "", time.Time{}, err + } + return token, expires, nil +} + +type enroller struct { + mu sync.Mutex +} + +func (e *enroller) redeem(cfg config, presented string, now time.Time) bool { + e.mu.Lock() + defer e.mu.Unlock() + path := enrollmentPath(cfg) + items, err := readEnrollments(path) + if err != nil || presented == "" { + return false + } + want := hashToken(presented) + matched := -1 + kept := make([]enrollment, 0, len(items)) + for index, item := range items { + if item.Expires <= now.Unix() { + continue + } + if matched < 0 && subtle.ConstantTimeCompare([]byte(item.TokenSHA256), []byte(want)) == 1 { + matched = index + continue + } + kept = append(kept, item) + } + if matched < 0 { + return false + } + if err := writeEnrollments(path, kept); err != nil { + return false + } + return true +} + +func enrollHandler(cfg config) http.HandlerFunc { + state := &enroller{} + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + if !cfg.TLS || cfg.Fingerprint == "" { + http.Error(w, "enrollment requires HTTPS", http.StatusForbidden) + return + } + auth := strings.TrimSpace(r.Header.Get("Authorization")) + presented, ok := strings.CutPrefix(auth, "Bearer ") + if !ok || !state.redeem(cfg, strings.TrimSpace(presented), time.Now()) { + time.Sleep(300 * time.Millisecond) + http.Error(w, "unknown, expired or used enrollment code", http.StatusUnauthorized) + return + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(map[string]string{"token": cfg.Token, "certificate_sha256": cfg.Fingerprint}) + } +} + +type enrollmentPayload struct { + Version int `json:"v"` + Name string `json:"name"` + Endpoint string `json:"endpoint"` + Enroll string `json:"enroll"` + Fingerprint string `json:"fingerprint"` + Expires int64 `json:"expires"` + Agent string `json:"agent"` +} + +func enrollmentCode(cfg config, hostOverride string, ttl time.Duration, now time.Time) (string, time.Time, error) { + if !cfg.TLS { + return "", time.Time{}, errors.New("one-time codes require HTTPS; use --static with plain HTTP") + } + if !validToken(cfg.Token) { + return "", time.Time{}, errors.New("no valid token configured; run 'sudo rustproxy-docker-agent init'") + } + endpoint, err := provisionEndpoint(cfg, hostOverride) + if err != nil { + return "", time.Time{}, err + } + fingerprint, err := certificateFingerprint(cfg.CertFile) + if err != nil { + return "", time.Time{}, fmt.Errorf("TLS certificate: %w (run 'sudo rustproxy-docker-agent init')", err) + } + token, expires, err := createEnrollment(cfg, ttl, now) + if err != nil { + return "", time.Time{}, err + } + raw, err := json.Marshal(enrollmentPayload{Version: 2, Name: cfg.Hostname, Endpoint: endpoint, Enroll: token, + Fingerprint: strings.ToLower(strings.ReplaceAll(fingerprint, ":", "")), Expires: expires.Unix(), Agent: version}) + if err != nil { + return "", time.Time{}, err + } + return provisionPrefix + base64.RawURLEncoding.EncodeToString(raw), expires, nil +} diff --git a/docker-agent/enroll_test.go b/docker-agent/enroll_test.go new file mode 100644 index 0000000..eb8201f --- /dev/null +++ b/docker-agent/enroll_test.go @@ -0,0 +1,155 @@ +package main + +import ( + "context" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestEnrollmentCodeIsOneTimeAndExpires(t *testing.T) { + dir := t.TempDir() + cfg := config{Listen: "0.0.0.0:9876", Token: strings.Repeat("p", 32), TLS: true, AdvertiseIP: "192.0.2.10", Hostname: "dock1", + CertFile: filepath.Join(dir, "agent.crt"), KeyFile: filepath.Join(dir, "agent.key")} + fingerprint, _, err := ensureSelfSignedCertificate(cfg.CertFile, cfg.KeyFile, cfg.Hostname) + if err != nil { + t.Fatal(err) + } + cfg.Fingerprint = fingerprint + now := time.Unix(1_800_000_000, 0) + code, expires, err := enrollmentCode(cfg, "", 10*time.Minute, now) + if err != nil { + t.Fatal(err) + } + raw, err := base64.RawURLEncoding.DecodeString(strings.TrimPrefix(code, provisionPrefix)) + if err != nil { + t.Fatal(err) + } + var payload enrollmentPayload + if err := json.Unmarshal(raw, &payload); err != nil { + t.Fatal(err) + } + if payload.Version != 2 || payload.Enroll == "" || strings.Contains(string(raw), cfg.Token) || payload.Expires != expires.Unix() || payload.Fingerprint != fingerprint { + t.Fatalf("payload %s", raw) + } + state := &enroller{} + if state.redeem(cfg, "wrong-token-value-0123456789", now) { + t.Fatal("wrong token redeemed") + } + if !state.redeem(cfg, payload.Enroll, now.Add(time.Minute)) { + t.Fatal("valid code rejected") + } + if state.redeem(cfg, payload.Enroll, now.Add(time.Minute)) { + t.Fatal("code redeemed twice") + } + code2, _, err := enrollmentCode(cfg, "", time.Minute, now) + if err != nil { + t.Fatal(err) + } + raw, _ = base64.RawURLEncoding.DecodeString(strings.TrimPrefix(code2, provisionPrefix)) + _ = json.Unmarshal(raw, &payload) + if state.redeem(cfg, payload.Enroll, now.Add(2*time.Minute)) { + t.Fatal("expired code redeemed") + } + if _, _, err := enrollmentCode(config{TLS: false, Token: cfg.Token}, "", time.Minute, now); err == nil { + t.Fatal("plain HTTP one-time code allowed") + } +} + +func TestEnrollHandlerReturnsTokenOnlyOnce(t *testing.T) { + dir := t.TempDir() + cfg := config{Listen: "127.0.0.1:9876", Token: strings.Repeat("q", 32), TLS: true, Hostname: "dock1", Fingerprint: strings.Repeat("a", 64), + CertFile: filepath.Join(dir, "agent.crt"), KeyFile: filepath.Join(dir, "agent.key")} + secret, _, err := createEnrollment(cfg, time.Minute, time.Now()) + if err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(enrollHandler(cfg)) + defer srv.Close() + post := func() (int, map[string]string) { + req, _ := http.NewRequest(http.MethodPost, srv.URL, nil) + req.Header.Set("Authorization", "Bearer "+secret) + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + out := map[string]string{} + _ = json.NewDecoder(res.Body).Decode(&out) + return res.StatusCode, out + } + if status, body := post(); status != 200 || body["token"] != cfg.Token { + t.Fatalf("first %d %v", status, body) + } + if status, _ := post(); status != http.StatusUnauthorized { + t.Fatalf("second %d", status) + } +} + +func TestContainerLabelsHealthAndStats(t *testing.T) { + got := servicesFrom([]dockerContainer{{ID: "abcdef1234567890", Names: []string{"/web"}, Image: "nginx", State: "Running", Status: "Up 3 minutes (unhealthy)", + Labels: map[string]string{"rustproxy.enable": "true", "rustproxy.host": "shop", "com.example": "x"}, + Ports: []dockerPort{{IP: "0.0.0.0", PrivatePort: 80, PublicPort: 8080, Type: "tcp"}}}}) + if len(got) != 1 || got[0].Labels["rustproxy.host"] != "shop" || got[0].Labels["com.example"] != "" || got[0].Container.Health != "unhealthy" || got[0].Container.State != "running" { + t.Fatalf("service %#v %#v", got, got[0].Container) + } + sock := fakeEngine(t, "docker.sock", map[string]string{ + "/containers/abcdef123456/json": `{"RestartCount":3,"State":{"Status":"running","StartedAt":"2026-11-13T10:00:00Z","Health":{"Status":"unhealthy"}}}`, + "/containers/abcdef123456/stats": `{"cpu_stats":{"cpu_usage":{"total_usage":2000},"system_cpu_usage":20000,"online_cpus":2},"precpu_stats":{"cpu_usage":{"total_usage":1000},"system_cpu_usage":10000},"memory_stats":{"usage":5000,"limit":100000,"stats":{"inactive_file":1000}}}`, + }) + collector := newContainerCollector() + collector.enrich(context.Background(), sock, got) + if got[0].Container.Health != "unhealthy" { + t.Fatalf("health %q", got[0].Container.Health) + } + c := got[0].Container + if c.RestartCount == nil || *c.RestartCount != 3 || c.CPUPercent == nil || *c.CPUPercent != 20 || *c.MemoryBytes != 4000 || *c.MemoryLimitBytes != 100000 { + t.Fatalf("container %#v", c) + } +} + +func TestLegacyInventoryOmitsLabelsAndContainerState(t *testing.T) { + sock := fakeEngine(t, "docker.sock", map[string]string{ + "/containers/json": `[{"Id":"abcdef1234567890","Names":["/web"],"Image":"nginx","State":"running","Status":"Up","Labels":{"rustproxy.enable":"true"},"Ports":[{"IP":"0.0.0.0","PrivatePort":80,"PublicPort":8080,"Type":"tcp"}]}]`, + }) + cfg := config{Token: strings.Repeat("x", 24), DockerSock: sock, Hostname: "docker-a"} + srv := httptest.NewServer(handler(cfg)) + defer srv.Close() + req, _ := http.NewRequest(http.MethodGet, srv.URL+"/v1/inventory", nil) + req.Header.Set("Authorization", "Bearer "+cfg.Token) + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + var raw map[string]any + _ = json.NewDecoder(res.Body).Decode(&raw) + service := raw["services"].([]any)[0].(map[string]any) + if _, ok := service["labels"]; ok { + t.Fatal("labels sent to legacy server") + } + if _, ok := service["container"]; ok { + t.Fatal("container state sent to legacy server") + } +} + +func TestContainerWithoutHealthcheckIsReportedAsNone(t *testing.T) { + got := servicesFrom([]dockerContainer{{ID: "fedcba9876543210", Names: []string{"/plain"}, Image: "nginx", State: "running", Status: "Up 3 minutes", + Ports: []dockerPort{{IP: "0.0.0.0", PrivatePort: 80, PublicPort: 8081, Type: "tcp"}}}}) + if got[0].Container.Health != "" { + t.Fatalf("health before inspect %q", got[0].Container.Health) + } + sock := fakeEngine(t, "docker.sock", map[string]string{ + "/containers/fedcba987654/json": `{"RestartCount":0,"State":{"Status":"running","StartedAt":"2026-11-13T10:00:00Z"}}`, + }) + newContainerCollector().enrich(context.Background(), sock, got) + c := got[0].Container + if c.Health != "none" || c.State != "running" || c.CPUPercent != nil || c.MemoryBytes != nil { + t.Fatalf("container %#v", c) + } +} diff --git a/docker-agent/install.sh b/docker-agent/install.sh index 763c77e..78db089 100755 --- a/docker-agent/install.sh +++ b/docker-agent/install.sh @@ -7,7 +7,15 @@ if [[ ${EUID:-$(id -u)} -ne 0 ]]; then fi command -v go >/dev/null 2>&1 || { echo "Go is required to build the agent." >&2; exit 2; } command -v systemctl >/dev/null 2>&1 || { echo "systemd is required." >&2; exit 2; } -getent group docker >/dev/null 2>&1 || { echo "Docker group not found; install Docker first." >&2; exit 2; } +if ! getent group docker >/dev/null 2>&1; then + if command -v podman >/dev/null 2>&1; then + groupadd --system docker + echo "Created the 'docker' group for Podman socket access; see README.md (Podman) to grant it access to podman.sock." >&2 + else + echo "Neither Docker (docker group) nor Podman found; install a container runtime first." >&2 + exit 2 + fi +fi ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) TMP=$(mktemp -d) @@ -37,4 +45,4 @@ systemctl --no-pager --full status rustproxy-docker-agent.service || true printf '\nAgent endpoint, TLS certificate details and Bearer token (sensitive):\n' /usr/local/bin/rustproxy-docker-agent info --show-token -printf '\nInstalled. Configure RustProxy -> Settings -> Docker agents with the HTTPS endpoint, token and SHA-256 fingerprint above.\n' +printf '\nInstalled. In RustProxy -> Settings -> Docker agents choose "Paste provisioning code" and paste the RPDA1-... code above\n(or enter the HTTPS endpoint, token and SHA-256 fingerprint manually).\n' diff --git a/docker-agent/main.go b/docker-agent/main.go index 6237dd2..7b7fdf9 100644 --- a/docker-agent/main.go +++ b/docker-agent/main.go @@ -82,7 +82,11 @@ func run(args []string, stdout, stderr io.Writer) error { fs.StringVar(&cfg.Listen, "listen", env("RUSTPROXY_DOCKER_AGENT_LISTEN", "127.0.0.1:9876"), "listen address") // NEVER supply a token as a flag default: `--help` would leak it into output. tokenOverride := fs.String("token", "", "Bearer token override (prefer the protected environment file)") - fs.StringVar(&cfg.DockerSock, "docker-socket", env("RUSTPROXY_DOCKER_SOCKET", "/var/run/docker.sock"), "Docker Engine unix socket") + fs.StringVar(&cfg.DockerSock, "docker-socket", env("RUSTPROXY_DOCKER_SOCKET", env("RUSTPROXY_CONTAINER_SOCKET", "auto")), "Docker Engine or Podman API unix socket ('auto' detects Docker, then Podman)") + fs.BoolVar(&cfg.DisableSystemInfo, "no-system-info", !envBoolValue(env("RUSTPROXY_DOCKER_SYSTEM_INFO", "true"), true), "do not report host diagnostics (load, memory, network, uptime)") + staticCode := fs.Bool("static", false, "provision-code: print a reusable code with the permanent token instead of a one-time code") + codeTTL := fs.Duration("ttl", 15*time.Minute, "provision-code: lifetime of a one-time code") + endpointOverride := fs.String("endpoint-host", env("RUSTPROXY_DOCKER_ENDPOINT_HOST", ""), "host or IP placed in the provisioning code (default: advertised/route IP)") fs.StringVar(&cfg.AdvertiseIP, "advertise-ip", env("RUSTPROXY_DOCKER_ADVERTISE_IP", ""), "preferred host IP") fs.StringVar(&cfg.PublicIPURL, "public-ip-url", env("RUSTPROXY_DOCKER_PUBLIC_IP_URL", "https://api.ipify.org"), "public IP lookup URL") fs.StringVar(&cfg.Hostname, "hostname", env("RUSTPROXY_DOCKER_HOSTNAME", hostname), "reported host name") @@ -114,6 +118,7 @@ func run(args []string, stdout, stderr io.Writer) error { if *printFingerprint { command = "print-fingerprint" } + cfg.DockerSock = resolveSocket(cfg.DockerSock) cfg.Token = env("RUSTPROXY_DOCKER_AGENT_TOKEN", "") if *tokenOverride != "" { cfg.Token = *tokenOverride @@ -146,7 +151,23 @@ func run(args []string, stdout, stderr io.Writer) error { } fmt.Fprintf(stdout, "Certificate SHA-256: %s\n", fingerprint) } - fmt.Fprintf(stdout, "Provisioning complete. Run 'sudo rustproxy-docker-agent info --show-token' to configure RustProxy.\n") + fmt.Fprintf(stdout, "Provisioning complete. Run 'sudo rustproxy-docker-agent provision-code' and paste the code into RustProxy -> Settings -> Docker agents.\n") + return nil + case "provision-code": + if *staticCode { + code, err := provisionCode(cfg, *endpointOverride) + if err != nil { + return err + } + fmt.Fprintln(stdout, code) + return nil + } + code, expires, err := enrollmentCode(cfg, *endpointOverride, *codeTTL, time.Now()) + if err != nil { + return err + } + fmt.Fprintln(stdout, code) + fmt.Fprintf(stderr, "One-time code, valid until %s. The agent service must be running to redeem it.\n", expires.Local().Format(time.RFC3339)) return nil case "rotate-token": if _, _, err := provisionToken(envFile, true); err != nil { @@ -161,7 +182,15 @@ func run(args []string, stdout, stderr io.Writer) error { fmt.Fprintln(stdout, cfg.Token) // Deliberate: an explicit administrative command. return nil case "info": - return printAgentInfo(stdout, cfg, envFile, *showToken, *asJSON) + if err := printAgentInfo(stdout, cfg, envFile, *showToken, *asJSON); err != nil { + return err + } + if *showToken && !*asJSON { + if code, err := provisionCode(cfg, *endpointOverride); err == nil { + fmt.Fprintf(stdout, "Provisioning code (sensitive, paste into RustProxy -> Settings -> Docker agents):\n%s\n", code) + } + } + return nil case "cert-init": fingerprint, created, err := ensureSelfSignedCertificate(cfg.CertFile, cfg.KeyFile, cfg.Hostname) if err != nil { @@ -194,6 +223,8 @@ func printUsage(w io.Writer) { fmt.Fprintln(w, " init Generate missing token and certificate, preserve existing secrets") fmt.Fprintln(w, " info [--show-token] Show endpoint, TLS certificate details and token status") fmt.Fprintln(w, " show-token Print the full Bearer token (sensitive)") + fmt.Fprintln(w, " provision-code Print a one-time code (endpoint, fingerprint, enrollment secret) for the RustProxy panel") + fmt.Fprintln(w, " --ttl 15m sets its lifetime, --static prints a reusable code with the token") fmt.Fprintln(w, " rotate-token Replace the Bearer token (service restart required)") fmt.Fprintln(w, " cert-init Create a missing TLS certificate and key") fmt.Fprintln(w, " print-fingerprint Print current TLS certificate SHA-256 fingerprint") @@ -207,7 +238,7 @@ func serve(cfg config) error { return errors.New("RUSTPROXY_DOCKER_AGENT_TOKEN must be a non-placeholder value with at least 24 characters; run 'sudo rustproxy-docker-agent init'") } if _, err := os.Stat(cfg.DockerSock); err != nil { - return fmt.Errorf("Docker socket unavailable: %w", err) + return fmt.Errorf("container socket unavailable (Docker or Podman): %w", err) } if _, _, err := net.SplitHostPort(cfg.Listen); err != nil { return fmt.Errorf("invalid listen address: %w", err) @@ -239,6 +270,7 @@ func serve(cfg config) error { scheme = "https" } log.Printf("RustProxy Docker Agent %s listening on %s://%s; Bearer token configured (%d chars, redacted)", version, scheme, cfg.Listen, len(cfg.Token)) + log.Printf("container API socket: %s", cfg.DockerSock) var err error if cfg.TLS { err = server.ListenAndServeTLS(cfg.CertFile, cfg.KeyFile) diff --git a/docker-agent/model.go b/docker-agent/model.go index 1aea248..5e43503 100644 --- a/docker-agent/model.go +++ b/docker-agent/model.go @@ -1,18 +1,19 @@ package main -var version = "1.0.1" // overridden by the package builder using -ldflags -X main.version +var version = "1.1.0" // overridden by the package builder using -ldflags -X main.version type config struct { - Listen string - Token string - DockerSock string - AdvertiseIP string - PublicIPURL string - Hostname string - TLS bool - CertFile string - KeyFile string - Fingerprint string + Listen string + Token string + DockerSock string + AdvertiseIP string + PublicIPURL string + Hostname string + TLS bool + CertFile string + KeyFile string + Fingerprint string + DisableSystemInfo bool } type dockerPort struct { @@ -28,6 +29,8 @@ type dockerContainer struct { Image string `json:"Image"` Labels map[string]string `json:"Labels"` Ports []dockerPort `json:"Ports"` + State string `json:"State"` + Status string `json:"Status"` } type binding struct { @@ -36,14 +39,16 @@ type binding struct { } type service struct { - Key string `json:"key"` - TechnicalName string `json:"technical_name"` - ContainerID string `json:"container_id"` - ContainerName string `json:"container_name"` - Image string `json:"image"` - PrivatePort uint16 `json:"private_port"` - Protocol string `json:"protocol"` - Bindings []binding `json:"bindings"` + Key string `json:"key"` + TechnicalName string `json:"technical_name"` + ContainerID string `json:"container_id"` + ContainerName string `json:"container_name"` + Image string `json:"image"` + PrivatePort uint16 `json:"private_port"` + Protocol string `json:"protocol"` + Bindings []binding `json:"bindings"` + Labels map[string]string `json:"labels,omitempty"` + Container *containerState `json:"container,omitempty"` } type hostAddress struct { @@ -62,4 +67,5 @@ type inventory struct { Addresses []hostAddress `json:"addresses"` ObservedAt string `json:"observed_at"` Services []service `json:"services"` + System *systemInfo `json:"system,omitempty"` } diff --git a/docker-agent/provision.go b/docker-agent/provision.go new file mode 100644 index 0000000..1e19b14 --- /dev/null +++ b/docker-agent/provision.go @@ -0,0 +1,96 @@ +package main + +import ( + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net" + "strings" +) + +const provisionPrefix = "RPDA1-" + +type provisionPayload struct { + Version int `json:"v"` + Name string `json:"name"` + Endpoint string `json:"endpoint"` + Token string `json:"token"` + Fingerprint string `json:"fingerprint,omitempty"` + Agent string `json:"agent"` +} + +func endpointHost(cfg config, override string) string { + if host := strings.TrimSpace(override); host != "" { + return host + } + if ip := validIP(cfg.AdvertiseIP); ip != "" { + return ip + } + if host, _, err := net.SplitHostPort(cfg.Listen); err == nil { + if ip := net.ParseIP(host); ip != nil && !ip.IsUnspecified() && !ip.IsLoopback() { + return ip.String() + } + if ip := net.ParseIP(host); ip == nil && host != "" && host != "localhost" { + return host + } + } + if ip := routeIP(); ip != "" { + return ip + } + return "127.0.0.1" +} + +func provisionEndpoint(cfg config, hostOverride string) (string, error) { + _, port, err := net.SplitHostPort(cfg.Listen) + if err != nil { + return "", fmt.Errorf("invalid listen address: %w", err) + } + scheme := "http" + if cfg.TLS { + scheme = "https" + } + return fmt.Sprintf("%s://%s", scheme, net.JoinHostPort(endpointHost(cfg, hostOverride), port)), nil +} + +func provisionCode(cfg config, hostOverride string) (string, error) { + if !validToken(cfg.Token) { + return "", errors.New("no valid token configured; run 'sudo rustproxy-docker-agent init'") + } + endpoint, err := provisionEndpoint(cfg, hostOverride) + if err != nil { + return "", err + } + payload := provisionPayload{Version: 1, Name: cfg.Hostname, Endpoint: endpoint, Token: cfg.Token, Agent: version} + if cfg.TLS { + fingerprint, err := certificateFingerprint(cfg.CertFile) + if err != nil { + return "", fmt.Errorf("TLS certificate: %w (run 'sudo rustproxy-docker-agent init')", err) + } + payload.Fingerprint = strings.ToLower(strings.ReplaceAll(fingerprint, ":", "")) + } + raw, err := json.Marshal(payload) + if err != nil { + return "", err + } + return provisionPrefix + base64.RawURLEncoding.EncodeToString(raw), nil +} + +func decodeProvisionCode(code string) (provisionPayload, error) { + var payload provisionPayload + body, ok := strings.CutPrefix(strings.TrimSpace(code), provisionPrefix) + if !ok { + return payload, errors.New("not a RustProxy agent provisioning code") + } + raw, err := base64.RawURLEncoding.DecodeString(body) + if err != nil { + return payload, err + } + if err := json.Unmarshal(raw, &payload); err != nil { + return payload, err + } + if payload.Version != 1 || payload.Endpoint == "" || !validToken(payload.Token) { + return payload, errors.New("incomplete provisioning code") + } + return payload, nil +} diff --git a/docker-agent/runtime.go b/docker-agent/runtime.go new file mode 100644 index 0000000..9564774 --- /dev/null +++ b/docker-agent/runtime.go @@ -0,0 +1,94 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "time" +) + +const defaultDockerSocket = "/var/run/docker.sock" + +func socketCandidates() []string { + out := []string{defaultDockerSocket, "/run/docker.sock", "/run/podman/podman.sock", "/var/run/podman/podman.sock"} + if runtimeDir := strings.TrimSpace(os.Getenv("XDG_RUNTIME_DIR")); runtimeDir != "" { + out = append(out, filepath.Join(runtimeDir, "podman", "podman.sock"), filepath.Join(runtimeDir, "docker.sock")) + } + return out +} + +func normalizeSocket(raw string) string { + raw = strings.TrimSpace(raw) + if strings.HasPrefix(raw, "unix://") { + raw = strings.TrimPrefix(raw, "unix://") + } + return raw +} + +func resolveSocket(configured string) string { + configured = normalizeSocket(configured) + if configured != "" && !strings.EqualFold(configured, "auto") { + return configured + } + for _, candidate := range socketCandidates() { + if info, err := os.Stat(candidate); err == nil && info.Mode()&os.ModeSocket != 0 { + return candidate + } + } + return defaultDockerSocket +} + +type engineInfo struct { + Containers uint64 `json:"Containers"` + ContainersRunning uint64 `json:"ContainersRunning"` + Images uint64 `json:"Images"` + ServerVersion string `json:"ServerVersion"` + OperatingSystem string `json:"OperatingSystem"` + KernelVersion string `json:"KernelVersion"` + Architecture string `json:"Architecture"` + NCPU uint32 `json:"NCPU"` + MemTotal uint64 `json:"MemTotal"` + DockerRootDir string `json:"DockerRootDir"` +} + +type engineVersion struct { + Version string `json:"Version"` + Components []struct { + Name string `json:"Name"` + Version string `json:"Version"` + } `json:"Components"` +} + +func engineGet(ctx context.Context, sock, path string, target any) error { + client := &http.Client{Transport: unixRoundTripper{sock: sock}, Timeout: 3 * time.Second} + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://docker"+path, nil) + if err != nil { + return err + } + resp, err := client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("container API %s returned %s", path, resp.Status) + } + return json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(target) +} + +func runtimeName(version engineVersion, sock string) string { + for _, component := range version.Components { + if strings.Contains(strings.ToLower(component.Name), "podman") { + return "podman" + } + } + if strings.Contains(strings.ToLower(sock), "podman") { + return "podman" + } + return "docker" +} diff --git a/docker-agent/rustproxy-docker-agent.service b/docker-agent/rustproxy-docker-agent.service index ca1c54a..cd84fb2 100644 --- a/docker-agent/rustproxy-docker-agent.service +++ b/docker-agent/rustproxy-docker-agent.service @@ -1,8 +1,7 @@ [Unit] Description=RustProxy Docker discovery agent -After=docker.service network-online.target +After=docker.service podman.socket podman.service network-online.target Wants=network-online.target -Requires=docker.service [Service] Type=simple diff --git a/docker-agent/server.go b/docker-agent/server.go index c8ebcd1..dadd763 100644 --- a/docker-agent/server.go +++ b/docker-agent/server.go @@ -19,6 +19,9 @@ func tokenOK(got, expected string) bool { func handler(cfg config) http.Handler { mux := http.NewServeMux() detector := &ipDetector{} + collector := newSystemCollector() + stats := newContainerCollector() + mux.HandleFunc("/v1/enroll", enrollHandler(cfg)) mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) @@ -54,10 +57,24 @@ func handler(cfg config) http.Handler { if cfg.Fingerprint != "" { w.Header().Set("X-RustProxy-Agent-Certificate-SHA256", cfg.Fingerprint) } - _ = json.NewEncoder(w).Encode(inventory{ + result := inventory{ AgentVersion: version, Hostname: cfg.Hostname, PublicIP: primaryIP, PublicIPSource: primarySource, CertificateSHA256: cfg.Fingerprint, Addresses: addresses, ObservedAt: time.Now().UTC().Format(time.RFC3339), Services: servicesFrom(containers), - }) + } + extended := r.URL.Query().Get("system") == "1" + if extended && !cfg.DisableSystemInfo { + result.System = collector.collect(r.Context(), cfg.DockerSock) + stats.enrich(r.Context(), cfg.DockerSock, result.Services) + } + if !extended || cfg.DisableSystemInfo { + for i := range result.Services { + if !extended { + result.Services[i].Labels = nil + } + result.Services[i].Container = nil + } + } + _ = json.NewEncoder(w).Encode(result) }) return mux } diff --git a/docker-agent/system.go b/docker-agent/system.go new file mode 100644 index 0000000..ad8930f --- /dev/null +++ b/docker-agent/system.go @@ -0,0 +1,301 @@ +package main + +import ( + "bufio" + "context" + "math" + "os" + "runtime" + "strconv" + "strings" + "sync" + "time" +) + +type systemInfo struct { + OS string `json:"os,omitempty"` + Kernel string `json:"kernel,omitempty"` + Arch string `json:"arch,omitempty"` + Runtime string `json:"runtime,omitempty"` + RuntimeVersion string `json:"runtime_version,omitempty"` + UptimeSeconds *uint64 `json:"uptime_seconds,omitempty"` + Load1 *float64 `json:"load1,omitempty"` + Load5 *float64 `json:"load5,omitempty"` + Load15 *float64 `json:"load15,omitempty"` + CPUCount *uint32 `json:"cpu_count,omitempty"` + CPUPercent *float64 `json:"cpu_percent,omitempty"` + MemoryTotalBytes *uint64 `json:"memory_total_bytes,omitempty"` + MemoryAvailableBytes *uint64 `json:"memory_available_bytes,omitempty"` + SwapTotalBytes *uint64 `json:"swap_total_bytes,omitempty"` + SwapFreeBytes *uint64 `json:"swap_free_bytes,omitempty"` + DiskTotalBytes *uint64 `json:"disk_total_bytes,omitempty"` + DiskFreeBytes *uint64 `json:"disk_free_bytes,omitempty"` + NetworkRxBytes *uint64 `json:"network_rx_bytes,omitempty"` + NetworkTxBytes *uint64 `json:"network_tx_bytes,omitempty"` + NetworkRxBytesPerSecond *float64 `json:"network_rx_bytes_per_second,omitempty"` + NetworkTxBytesPerSecond *float64 `json:"network_tx_bytes_per_second,omitempty"` + ContainersRunning *uint64 `json:"containers_running,omitempty"` + ContainersTotal *uint64 `json:"containers_total,omitempty"` + Images *uint64 `json:"images,omitempty"` +} + +type cpuSample struct{ idle, total uint64 } +type netSample struct { + rx, tx uint64 + at time.Time +} + +type systemCollector struct { + mu sync.Mutex + procDir string + etcDir string + cpu *cpuSample + net *netSample +} + +func newSystemCollector() *systemCollector { + return &systemCollector{procDir: "/proc", etcDir: "/etc"} +} + +func ptr[T any](value T) *T { return &value } + +func round(value float64, places int) float64 { + scale := math.Pow(10, float64(places)) + return math.Round(value*scale) / scale +} + +func readTrimmed(path string) string { + data, err := os.ReadFile(path) + if err != nil { + return "" + } + return strings.TrimSpace(string(data)) +} + +func osPrettyName(etcDir string) string { + for _, path := range []string{etcDir + "/os-release", "/usr/lib/os-release"} { + file, err := os.Open(path) + if err != nil { + continue + } + scanner := bufio.NewScanner(file) + name := "" + for scanner.Scan() { + line := scanner.Text() + if value, ok := strings.CutPrefix(line, "PRETTY_NAME="); ok { + name = strings.Trim(value, `"'`) + break + } + if value, ok := strings.CutPrefix(line, "NAME="); ok && name == "" { + name = strings.Trim(value, `"'`) + } + } + file.Close() + if name != "" { + return name + } + } + return "" +} + +func parseLoadavg(raw string) (float64, float64, float64, bool) { + fields := strings.Fields(raw) + if len(fields) < 3 { + return 0, 0, 0, false + } + var values [3]float64 + for i := range values { + value, err := strconv.ParseFloat(fields[i], 64) + if err != nil || value < 0 { + return 0, 0, 0, false + } + values[i] = value + } + return values[0], values[1], values[2], true +} + +func parseMeminfo(raw string) map[string]uint64 { + out := map[string]uint64{} + for _, line := range strings.Split(raw, "\n") { + key, rest, ok := strings.Cut(line, ":") + if !ok { + continue + } + fields := strings.Fields(rest) + if len(fields) == 0 { + continue + } + value, err := strconv.ParseUint(fields[0], 10, 64) + if err != nil { + continue + } + if len(fields) > 1 && strings.EqualFold(fields[1], "kB") { + value *= 1024 + } + out[strings.TrimSpace(key)] = value + } + return out +} + +func parseCPUStat(raw string) (cpuSample, bool) { + for _, line := range strings.Split(raw, "\n") { + fields := strings.Fields(line) + if len(fields) < 5 || fields[0] != "cpu" { + continue + } + var total, idle uint64 + for index, field := range fields[1:] { + value, err := strconv.ParseUint(field, 10, 64) + if err != nil { + return cpuSample{}, false + } + if index >= 8 { + break + } + total += value + if index == 3 || index == 4 { + idle += value + } + } + return cpuSample{idle: idle, total: total}, total > 0 + } + return cpuSample{}, false +} + +func skipTrafficInterface(name string) bool { + name = strings.ToLower(name) + if name == "lo" || skipInterface(name) { + return true + } + for _, prefix := range []string{"cni", "flannel", "cali", "podman", "vxlan", "kube-", "weave", "tunl0"} { + if strings.HasPrefix(name, prefix) { + return true + } + } + return false +} + +func parseNetDev(raw string) (uint64, uint64, bool) { + var rx, tx uint64 + found := false + for _, line := range strings.Split(raw, "\n") { + name, rest, ok := strings.Cut(line, ":") + if !ok { + continue + } + name = strings.TrimSpace(name) + fields := strings.Fields(rest) + if len(fields) < 9 || skipTrafficInterface(name) { + continue + } + in, err1 := strconv.ParseUint(fields[0], 10, 64) + out, err2 := strconv.ParseUint(fields[8], 10, 64) + if err1 != nil || err2 != nil { + continue + } + rx += in + tx += out + found = true + } + return rx, tx, found +} + +func (c *systemCollector) cpuPercent() *float64 { + sample, ok := parseCPUStat(readTrimmed(c.procDir + "/stat")) + if !ok { + return nil + } + previous := c.cpu + if previous == nil { + time.Sleep(200 * time.Millisecond) + next, ok := parseCPUStat(readTrimmed(c.procDir + "/stat")) + if !ok { + return nil + } + previous, sample = &sample, next + } + c.cpu = &cpuSample{idle: sample.idle, total: sample.total} + if sample.total <= previous.total || sample.idle < previous.idle { + return nil + } + totalDelta := float64(sample.total - previous.total) + idleDelta := float64(sample.idle - previous.idle) + value := round(math.Max(0, math.Min(100, (1-idleDelta/totalDelta)*100)), 1) + return &value +} + +func (c *systemCollector) collect(ctx context.Context, sock string) *systemInfo { + c.mu.Lock() + defer c.mu.Unlock() + info := &systemInfo{OS: osPrettyName(c.etcDir), Kernel: readTrimmed(c.procDir + "/sys/kernel/osrelease"), Arch: runtime.GOARCH} + if fields := strings.Fields(readTrimmed(c.procDir + "/uptime")); len(fields) > 0 { + if value, err := strconv.ParseFloat(fields[0], 64); err == nil && value >= 0 { + info.UptimeSeconds = ptr(uint64(value)) + } + } + if l1, l5, l15, ok := parseLoadavg(readTrimmed(c.procDir + "/loadavg")); ok { + info.Load1, info.Load5, info.Load15 = ptr(l1), ptr(l5), ptr(l15) + } + info.CPUCount = ptr(uint32(runtime.NumCPU())) + info.CPUPercent = c.cpuPercent() + memory := parseMeminfo(readTrimmed(c.procDir + "/meminfo")) + if value, ok := memory["MemTotal"]; ok { + info.MemoryTotalBytes = ptr(value) + } + if value, ok := memory["MemAvailable"]; ok { + info.MemoryAvailableBytes = ptr(value) + } + if value, ok := memory["SwapTotal"]; ok { + info.SwapTotalBytes = ptr(value) + } + if value, ok := memory["SwapFree"]; ok { + info.SwapFreeBytes = ptr(value) + } + if rx, tx, ok := parseNetDev(readTrimmed(c.procDir + "/net/dev")); ok { + now := time.Now() + info.NetworkRxBytes, info.NetworkTxBytes = ptr(rx), ptr(tx) + if previous := c.net; previous != nil && rx >= previous.rx && tx >= previous.tx { + if seconds := now.Sub(previous.at).Seconds(); seconds >= 0.5 { + info.NetworkRxBytesPerSecond = ptr(round(float64(rx-previous.rx)/seconds, 1)) + info.NetworkTxBytesPerSecond = ptr(round(float64(tx-previous.tx)/seconds, 1)) + } + } + c.net = &netSample{rx: rx, tx: tx, at: now} + } + diskPath := "/" + if sock != "" { + var engine engineInfo + if err := engineGet(ctx, sock, "/info", &engine); err == nil { + info.ContainersRunning = ptr(engine.ContainersRunning) + info.ContainersTotal = ptr(engine.Containers) + info.Images = ptr(engine.Images) + if info.OS == "" { + info.OS = engine.OperatingSystem + } + if info.Kernel == "" { + info.Kernel = engine.KernelVersion + } + if engine.DockerRootDir != "" { + diskPath = engine.DockerRootDir + } + info.RuntimeVersion = engine.ServerVersion + } + var version engineVersion + if err := engineGet(ctx, sock, "/version", &version); err == nil { + info.Runtime = runtimeName(version, sock) + if version.Version != "" { + info.RuntimeVersion = version.Version + } + } else if info.RuntimeVersion != "" { + info.Runtime = runtimeName(engineVersion{}, sock) + } + } + if total, free, ok := diskUsage(diskPath); ok { + info.DiskTotalBytes, info.DiskFreeBytes = ptr(total), ptr(free) + } else if diskPath != "/" { + if total, free, ok := diskUsage("/"); ok { + info.DiskTotalBytes, info.DiskFreeBytes = ptr(total), ptr(free) + } + } + return info +} diff --git a/docker-agent/system_test.go b/docker-agent/system_test.go new file mode 100644 index 0000000..9fc87ea --- /dev/null +++ b/docker-agent/system_test.go @@ -0,0 +1,190 @@ +package main + +import ( + "context" + "encoding/json" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func fakeEngine(t *testing.T, name string, routes map[string]string) string { + t.Helper() + sock := filepath.Join(t.TempDir(), name) + ln, err := net.Listen("unix", sock) + if err != nil { + t.Fatal(err) + } + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, ok := routes[r.URL.Path] + if !ok { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(body)) + })} + go srv.Serve(ln) + t.Cleanup(func() { _ = srv.Close(); _ = os.Remove(sock) }) + return sock +} + +func writeFile(t *testing.T, path, data string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(data), 0o644); err != nil { + t.Fatal(err) + } +} + +func TestSystemParsers(t *testing.T) { + l1, l5, l15, ok := parseLoadavg("0.52 0.40 0.31 2/345 6789") + if !ok || l1 != 0.52 || l5 != 0.40 || l15 != 0.31 { + t.Fatalf("loadavg %v %v %v %v", l1, l5, l15, ok) + } + memory := parseMeminfo("MemTotal: 16384 kB\nMemAvailable: 8192 kB\nSwapTotal: 0 kB\n") + if memory["MemTotal"] != 16384*1024 || memory["MemAvailable"] != 8192*1024 { + t.Fatalf("meminfo %#v", memory) + } + sample, ok := parseCPUStat("cpu 100 0 100 700 100 0 0 0 50 0\ncpu0 1 2 3 4\n") + if !ok || sample.total != 1000 || sample.idle != 800 { + t.Fatalf("cpu %#v", sample) + } + rx, tx, ok := parseNetDev("Inter-| Receive\n face |bytes\n lo: 100 1 0 0 0 0 0 0 100 1 0 0 0 0 0 0\n eth0: 2000 10 0 0 0 0 0 0 3000 10 0 0 0 0 0 0\ndocker0: 50 1 0 0 0 0 0 0 60 1 0 0 0 0 0 0\nvethab12: 5 1 0 0 0 0 0 0 6 1 0 0 0 0 0 0\n wlan0: 1 1 0 0 0 0 0 0 2 1 0 0 0 0 0 0\n") + if !ok || rx != 2001 || tx != 3002 { + t.Fatalf("netdev %d %d %v", rx, tx, ok) + } +} + +func TestSystemCollectorReadsProcAndPodmanEngine(t *testing.T) { + root := t.TempDir() + writeFile(t, root+"/proc/loadavg", "1.00 0.50 0.25 1/100 42\n") + writeFile(t, root+"/proc/uptime", "3600.55 100.00\n") + writeFile(t, root+"/proc/meminfo", "MemTotal: 2048 kB\nMemAvailable: 1024 kB\nSwapTotal: 512 kB\nSwapFree: 256 kB\n") + writeFile(t, root+"/proc/stat", "cpu 10 0 10 80 0 0 0 0 0 0\n") + writeFile(t, root+"/proc/net/dev", "eth0: 1000 1 0 0 0 0 0 0 2000 1 0 0 0 0 0 0\n") + writeFile(t, root+"/proc/sys/kernel/osrelease", "6.12.0-test\n") + writeFile(t, root+"/etc/os-release", "NAME=Test\nPRETTY_NAME=\"Test Linux 1\"\n") + sock := fakeEngine(t, "podman.sock", map[string]string{ + "/info": `{"Containers":5,"ContainersRunning":3,"Images":7,"ServerVersion":"5.4.0"}`, + "/version": `{"Version":"5.4.0","Components":[{"Name":"Podman Engine","Version":"5.4.0"}]}`, + }) + collector := &systemCollector{procDir: root + "/proc", etcDir: root + "/etc"} + info := collector.collect(context.Background(), sock) + if info.OS != "Test Linux 1" || info.Kernel != "6.12.0-test" || info.Runtime != "podman" || info.RuntimeVersion != "5.4.0" { + t.Fatalf("identity %#v", info) + } + if *info.UptimeSeconds != 3600 || *info.Load1 != 1 || *info.MemoryTotalBytes != 2048*1024 || *info.ContainersRunning != 3 || *info.ContainersTotal != 5 || *info.Images != 7 { + t.Fatalf("values %#v", info) + } + if info.NetworkRxBytesPerSecond != nil { + t.Fatal("first sample must not report a rate") + } + collector.net.at = time.Now().Add(-2 * time.Second) + writeFile(t, root+"/proc/net/dev", "eth0: 3000 1 0 0 0 0 0 0 2000 1 0 0 0 0 0 0\n") + info = collector.collect(context.Background(), "") + if info.NetworkRxBytesPerSecond == nil || *info.NetworkRxBytesPerSecond < 900 || *info.NetworkRxBytesPerSecond > 1100 || *info.NetworkTxBytesPerSecond != 0 { + t.Fatalf("rates %#v", info) + } +} + +func TestInventorySystemInfoIsOptIn(t *testing.T) { + sock := fakeEngine(t, "docker.sock", map[string]string{ + "/containers/json": `[]`, + "/info": `{"Containers":1,"ContainersRunning":1,"Images":1,"ServerVersion":"27.0.1"}`, + "/version": `{"Version":"27.0.1","Components":[{"Name":"Engine","Version":"27.0.1"}]}`, + }) + cfg := config{Token: strings.Repeat("x", 24), DockerSock: sock, Hostname: "docker-a"} + srv := httptest.NewServer(handler(cfg)) + defer srv.Close() + get := func(path string) map[string]any { + req, _ := http.NewRequest(http.MethodGet, srv.URL+path, nil) + req.Header.Set("Authorization", "Bearer "+cfg.Token) + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + var out map[string]any + if err := json.NewDecoder(res.Body).Decode(&out); err != nil { + t.Fatal(err) + } + return out + } + if _, ok := get("/v1/inventory")["system"]; ok { + t.Fatal("legacy request must not receive system info") + } + system, ok := get("/v1/inventory?system=1")["system"].(map[string]any) + if !ok || system["runtime"] != "docker" || system["containers_running"] != float64(1) { + t.Fatalf("system %#v", system) + } +} + +func TestResolveSocketAndPodmanComposeLabels(t *testing.T) { + if got := resolveSocket("unix:///run/custom.sock"); got != "/run/custom.sock" { + t.Fatal(got) + } + runtimeDir := t.TempDir() + t.Setenv("XDG_RUNTIME_DIR", runtimeDir) + if err := os.MkdirAll(filepath.Join(runtimeDir, "podman"), 0o755); err != nil { + t.Fatal(err) + } + ln, err := net.Listen("unix", filepath.Join(runtimeDir, "podman", "podman.sock")) + if err != nil { + t.Fatal(err) + } + defer ln.Close() + if _, err := os.Stat(defaultDockerSocket); err != nil { + if got := resolveSocket("auto"); !strings.HasSuffix(got, "podman/podman.sock") { + t.Fatalf("auto socket %s", got) + } + } + c := dockerContainer{Names: []string{"/web_1"}, Labels: map[string]string{"io.podman.compose.project": "shop", "io.podman.compose.service": "web"}} + key, _ := serviceIdentity(c, dockerPort{PrivatePort: 80, Type: "tcp"}) + if key != "compose:shop/web/web_1:80/tcp" { + t.Fatal(key) + } +} + +func TestProvisionCodeRoundTrip(t *testing.T) { + dir := t.TempDir() + cfg := config{Listen: "0.0.0.0:9876", Token: strings.Repeat("a", 32), TLS: true, AdvertiseIP: "192.0.2.10", Hostname: "dock1", + CertFile: filepath.Join(dir, "agent.crt"), KeyFile: filepath.Join(dir, "agent.key")} + fingerprint, _, err := ensureSelfSignedCertificate(cfg.CertFile, cfg.KeyFile, cfg.Hostname) + if err != nil { + t.Fatal(err) + } + code, err := provisionCode(cfg, "") + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(code, provisionPrefix) || strings.ContainsAny(code, "+/= \n") { + t.Fatalf("code %q", code) + } + payload, err := decodeProvisionCode(code) + if err != nil { + t.Fatal(err) + } + if payload.Endpoint != "https://192.0.2.10:9876" || payload.Token != cfg.Token || payload.Fingerprint != fingerprint || payload.Name != "dock1" { + t.Fatalf("payload %#v", payload) + } + if code, _ := provisionCode(cfg, "2001:db8::5"); !strings.HasPrefix(code, provisionPrefix) { + t.Fatal("ipv6 override") + } else if payload, _ := decodeProvisionCode(code); payload.Endpoint != "https://[2001:db8::5]:9876" { + t.Fatalf("ipv6 endpoint %s", payload.Endpoint) + } + cfg.Token = "short" + if _, err := provisionCode(cfg, ""); err == nil { + t.Fatal("short token accepted") + } + if _, err := decodeProvisionCode("garbage"); err == nil { + t.Fatal("garbage accepted") + } +} diff --git a/docs/DASHBOARD.md b/docs/DASHBOARD.md index c0e534f..ce88c69 100644 --- a/docs/DASHBOARD.md +++ b/docs/DASHBOARD.md @@ -25,6 +25,10 @@ Optional quick-health tiles (since 0.35.2, hidden by default; enable them in the Enabled tiles are added at the end of the Overview, so the standard block layout does not change. +Optional Docker cards (since 0.37.0, hidden by default): **Docker agents**, **Docker apps**, **Docker app requests**, **Docker hosts network**, **Docker hosts load** and **Containers**. They summarize agent connectivity, published Docker vhost health and traffic, and the host diagnostics reported by Docker/Podman agents 1.1.0+; With several agents each card can show all agents or one selected agent; see [Docker discovery](DOCKER_DISCOVERY.md#overview-cards). + +In the **Backends** table with **Table density: Ultra compact**, the backend name line under each vhost is hidden to save space; hover the vhost name (dotted underline) to see the vhost and backend names in a tooltip. + The Overview history sample count is saved in the browser immediately when the selection changes; no separate confirmation button is required. The sidebar application-status indicator runs a lightweight self-check from the live status already used by the dashboard. Green means healthy, amber means attention is needed, and red means a problem was detected; click it to see API, listener, backend and logging details. diff --git a/docs/DOCKER_DISCOVERY.md b/docs/DOCKER_DISCOVERY.md index f101dd7..d6c3006 100644 --- a/docs/DOCKER_DISCOVERY.md +++ b/docs/DOCKER_DISCOVERY.md @@ -4,7 +4,7 @@ RustProxy discovers published Docker services through a **separate read-only Doc ## Set up a Docker host -Install the **optional Docker agent on each Linux Docker host**, not on the RustProxy server. It is distributed as a separate `rustproxy-docker-agent` DEB/RPM package and is **not built as FreeBSD `pkg`**. Docker Engine, systemd and access to `/var/run/docker.sock` are required at runtime. +Install the **optional Docker agent on each Linux Docker host**, not on the RustProxy server. It is distributed as a separate `rustproxy-docker-agent` DEB/RPM package and is **not built as FreeBSD `pkg`**. Docker Engine **or Podman**, systemd and access to the container API socket (`/var/run/docker.sock`, `/run/podman/podman.sock` or a rootless `$XDG_RUNTIME_DIR/podman/podman.sock`) are required at runtime. The agent detects the socket automatically (`RUSTPROXY_DOCKER_SOCKET=auto`); see [docker-agent/README.md](../docker-agent/README.md#podman) for Podman socket permissions. ### Option A: prebuilt DEB/RPM (recommended) @@ -39,8 +39,66 @@ Go 1.22+ is required only for the manual build, not for a DEB/RPM installation. ### Connect to RustProxy 1. Allow port `9876` **only from the RustProxy server** in the Docker-host firewall. The default example listens on `0.0.0.0:9876`. -2. In **Settings → Docker agents**, create an agent with an endpoint such as `https://10.10.0.21:9876`, its Bearer token and certificate SHA-256 fingerprint, base domain, selected listener IDs, and optional certificate/ACL/default backend IP. -3. Use **Docker vhosts → Refresh agents** and check that discovery succeeds before publishing. +2. On the Docker host run `sudo rustproxy-docker-agent provision-code` (agent 1.1.0+). It prints one `RPDA1-…` code with the HTTPS endpoint, the Bearer token and the certificate SHA-256 fingerprint. The code **contains the secret token**; paste it only into the panel. Use `--endpoint-host` to put a different host/IP in the code. +3. In **Settings → Docker agents** press **Paste provisioning code** (or open **Provisioning code** in an existing agent to update a rotated token) and paste it. The panel fills in the name, the agent ID (generated from the name like Vhost IDs, editable until saved), endpoint, token and fingerprint. Older agents: enter endpoint, token and fingerprint manually. +4. Assign **Domains** (at least one; the first, marked ★, is the master domain for new Docker vhosts — click ★ on another domain to make it the master), choose **Certificates** (*Automatic* or a list of certificates), the listener IDs and optional ACL profiles and **Default backend IP**, then save. +5. Use **Docker vhosts → Refresh agents** and check that discovery succeeds before publishing. + +### Domains + +An agent has a list of DNS suffixes (`domains`, up to 16), picked in the same searchable multi-select as ACL profiles; type a new domain in the search box and press Enter to add it. Suggestions come from other agents and from wildcard certificates. Every published Docker vhost selects its **master domain** from this list (default: the first domain), so a newly published service is reachable immediately as `.`. **Aliases** may be short labels (expanded below the master domain, or below another agent domain chosen next to the alias input) or full names, which the panel only accepts inside one of the agent domains. Configurations from before 0.37.0 with a single `base_domain` are migrated to `domains: [base_domain]` on the next save; nothing else changes. + +### Certificates + +- **Automatic** (no certificate selected, the default): generated vhosts behave like a Vhost left on *Global SNI / default certificate* — every requested name gets the stored certificate whose SNI/SAN names cover it. +- **Selected certificates**: each generated vhost uses the selected certificate covering **all** its names (exact names beat wildcards, then the narrowest certificate). If none covers them, it falls back to the generic SNI/default certificate, so each name can still be served by the matching stored certificate. The per-service editor shows which certificate will be used. *Accept certificate/domain mismatch* forces the first selected certificate when none covers the names. + +A previously selected single `certificate_id` is migrated to `certificate_ids: [certificate_id]`. + +### Default backend IP + +The agent default backend IP is chosen from the **addresses the agent detected** (interface, scope and source are shown) or entered as **Custom address…**. *Automatic* keeps the per-service choice (bind address, primary IP, detected addresses). The list fills after the first successful poll. + +### Host diagnostics + +Agents 1.1.0+ report host data when RustProxy 0.37.0+ asks for it: OS and kernel, architecture, Docker/Podman runtime and version, uptime, load average, CPU usage, memory, swap, disk usage of the container data directory, host network totals and current rates (container/virtual interfaces excluded) and running/total container and image counts. They are shown in **Docker vhosts → Agent details → Host system** and in a compact strip in **Settings → Docker agents**. Values an agent does not send are not shown; older agents show none. Disable reporting on the agent with `RUSTPROXY_DOCKER_SYSTEM_INFO=false`. + +### Alerts + +RustProxy turns agent and host problems into ordinary alerts, using only the latest agent poll (nothing is kept over time): an **agent that could not be reached at the last check** (severity error), **disk** or **memory** use at or above the threshold (default 90% / 95%), **load per CPU** (the host's own 5-minute load average divided by logical CPUs) at or above the threshold (default 2.0), a **published service that disappeared from the inventory**, a published **container that is unhealthy, restarting, exited or dead**, and **container labels** that could not be published. Alerts appear as a **Docker** entry in the application status in the sidebar (amber for warnings, red for errors), as a notification when a new alert appears, as a list at the top of **Docker vhosts**, as `Docker alert raised` / `Docker alert cleared` log lines and as Prometheus `rust_proxy_docker_alert{agent,kind,severity,service}`. Configure them under **Settings → Docker agents → Alerts**; switching alerts off removes them everywhere. For alerts over longer periods use Prometheus/Grafana with the `rust_proxy_docker_*` metrics. + +### Publishing from container labels + +Enable **Publish from container labels** on an agent to publish containers that carry `rustproxy.enable=true` without opening the panel: + +```yaml +services: + shop: + image: nginx + ports: ["18080:80"] + labels: + rustproxy.enable: "true" + rustproxy.host: shop # label or full name inside the agent domains + rustproxy.domain: example.org # master domain, one of the agent domains + rustproxy.aliases: www,shop.lab.example.com + rustproxy.scheme: http # or https + rustproxy.port: "80" # container port to publish when several are exposed + rustproxy.force_ssl: "true" +``` + +Also supported: `rustproxy.websockets`, `rustproxy.cache`, `rustproxy.compression` and `rustproxy.preserve_host` (`true`/`false`). Labels never leave the agent domains, never take a name already used by a vhost, redirect, 404 host or another Docker service and never override a manual setting for the same service. Invalid labels produce a **LABEL ERROR** badge and an alert instead of a vhost. Label publications use the agent defaults (listeners, certificates, ACL profiles, default backend IP). To customise one, open it and press **Apply changes** (it becomes a manual setting); switching **Publish** off stores a disabled manual override. Labels are read only from agents 1.1.0+. The option is off by default because anyone who can start containers on that host can then publish names inside the agent domains. + +### Container state and history + +Agents 1.1.0+ report per published container its state and health check, CPU usage, memory (without page cache) with its limit and restart count; the service row shows them and Prometheus exports `rust_proxy_docker_container_*`. Containers whose image defines no `HEALTHCHECK` are shown as *no health check* (`health: "none"`) and are judged only by their state (running is fine; restarting, exited or dead raise an alert). The small CPU, memory, load and network charts in **Agent details** are sampled in the browser from the agent polls while the page is open, like the other panel charts; RustProxy does not store history. + +### Test connection and one-time codes + +**Test connection** in each agent runs one inventory request with the values in the form, before saving. `sudo rustproxy-docker-agent provision-code` prints a **one-time code** by default: it holds the endpoint, the certificate pin and a single-use enrollment secret valid for 15 minutes (`--ttl 1h` to change), not the token. When you paste it, RustProxy connects to the agent over the pinned HTTPS connection, redeems the secret and fills in the permanent token; the code cannot be used again. The agent service must be running. `provision-code --static` prints the previous reusable code that contains the token (also needed for plain-HTTP agents). + +### Overview cards + +Six optional Overview cards (hidden by default; enable them in the Overview layout editor or **Settings → Appearance → Dashboard layout**): **Docker agents** (connected/enabled), **Docker apps** (published vhosts with a healthy backend, down, checking, missing and discovered services), **Docker app requests** (request rate across all Docker vhosts with a chart), **Docker hosts network** (combined host RX/TX rate with a chart), **Docker hosts load** (CPU/memory bars and load per host) and **Containers** (running/total, images, Docker/Podman host count). They read the compact `docker` object in `/api/status` and the live view. Every card exists four times (*Docker hosts load*, *Docker hosts load #2* … *#4*, likewise for the others), so you can place the same card once per agent next to each other. With two or more agents each card has an agent selector — **All agents** or a single agent — so you can monitor agents separately or together. The selector is shown in the card and next to the card in the hidden-cards list of the layout editors, so the agent can be chosen when the card is added. The choice is stored per administrator (`docker_widget_agents` in `/api/preferences`); a card whose agent was removed falls back to all agents. The self-signed certificate is persistent. RustProxy pins its exact fingerprint; if replaced, update the pin. A trusted CA-issued certificate can use normal CA and hostname verification instead. Plain HTTP is available only by explicit opt-out and exposes the token in transit. @@ -70,16 +128,16 @@ In **Docker vhosts**, select the service and set: | Option | Guidance | |---|---| -| **Hostname / aliases** | By default, the sanitized Docker container name expands under the agent base domain, without an image or port suffix. A custom short name or full FQDN overrides it, and aliases remain configurable. Containers exposing multiple published TCP ports require distinct manually assigned hostnames to publish both ports. Configure public DNS separately. | +| **Hostname / master domain / aliases** | By default, the sanitized Docker container name expands under the selected master domain (one of the agent domains), without an image or port suffix. A custom short name or a full name inside the agent domains overrides it; aliases may use any agent domain. Containers exposing multiple published TCP ports require distinct manually assigned hostnames to publish both ports. Configure public DNS separately. | | **Backend IP/port** | Pick a detected, reachable Docker-host address or the configured automatic option. Docker host/firewall binding must permit RustProxy to connect. | | **HTTP / HTTPS upstream** | Match the container's actual service protocol; review origin TLS verification and Host behavior. | -| **Frontend listeners / certificate** | Selected through the agent defaults and RustProxy configuration; ensure certificate covers the generated name. | +| **Frontend listeners / certificate** | Selected through the agent defaults: automatic SNI or the agent's certificate list (see [Certificates](#certificates)); the editor shows the certificate that will be used. | | **Frontend protocols** | HTTP/1.1 is always available. Enable/disable HTTP/2 and HTTP/3 independently per Docker vhost (both enabled by default). H2/H3 require corresponding frontend listener support; switching them does not change the selected HTTP/HTTPS backend scheme. H3 disabled also removes its advertisement. | | **Force HTTPS / WebSockets** | Enable only when needed and when the right frontend listeners exist. | | **Cache / compression / transforms** | Optional; obey the global limits and privacy policy of the application. | | **Health / ACL / timeouts** | Select up to eight reusable ACL profiles per app or inherit the agent's defaults. A searchable multi-select previews the profile ID, default action, IP rules and country filters; selected profiles appear as removable badges. Optional inline ACL remains independently enforced. Explicit denies and country blocks beat merged allows. Test allowed and blocked clients. | -To deliberately assign a domain not covered by the agent's **named frontend certificate**, enable **Accept certificate/domain mismatch** immediately below **Backend host IP** in the per-service editor and confirm the risk. This records `allow_certificate_mismatch: true` on that publication only. Without consent, the server rejects the incompatible mapping. The client browser may still reject the TLS handshake; a matching SAN certificate is strongly preferred. The agent's own outbound TLS fingerprint validation is unaffected. +To deliberately assign a domain not covered by any of the agent's **selected certificates**, enable **Accept certificate/domain mismatch** immediately below **Backend host IP** in the per-service editor and confirm the risk. This records `allow_certificate_mismatch: true` on that publication only. Without consent, the server rejects the incompatible mapping. The client browser may still reject the TLS handshake; a matching SAN certificate is strongly preferred. The agent's own outbound TLS fingerprint validation is unaffected. Use the per-service **Publish** on/off switch to expose or remove the generated Vhost; toggling it saves immediately. Test the resulting hostname with **Open app**. Edits to an already published service use its own **Apply changes** action; switching Publish off removes the proxy publication but does not stop the Docker container. Hidden rows in the page are only a browser view preference, not a security policy. @@ -102,7 +160,9 @@ The Docker request-rate chart uses the **same adaptive Y range as ordinary Vhost - **WAITING:** first poll not yet observed; refresh and inspect the agent endpoint. - **Agent error:** verify firewall, TLS fingerprint/CA, bearer token, service state, advertised host and TCP route. - **503 generated Vhost:** verify running container, published TCP port, selected IP/bind address, backend protocol and health check. -- **Wrong application hostname:** check base-domain expansion, aliases, DNS and conflicting ordinary Vhosts. +- **Wrong application hostname:** check the master domain, alias expansion, DNS and conflicting ordinary Vhosts. +- **Invalid provisioning code:** copy the whole `RPDA1-…` line; codes from agents older than 1.1.0 do not exist — enter the values manually. +- **No host diagnostics:** the agent is older than 1.1.0, `RUSTPROXY_DOCKER_SYSTEM_INFO=false` is set, or the value cannot be read on that host. - **Docker service not listed:** agent reports only eligible running containers with published non-loopback TCP bindings. For agent operations and its security model see `docker-agent/README.md`. For normal routing, health and cache controls see [Vhosts](VHOSTS.md) and [Cache](CACHE.md). diff --git a/docs/FEATURES.md b/docs/FEATURES.md index a238e94..a53a50a 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -92,7 +92,7 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se - Configuration stored in SQLite or in a JSON file, with validation before activation and hot reload. - Revision history with diff and one-click restore. - Encrypted full backups and validated offline restore; encrypted Secret Store for credentials. -- Docker discovery through a separate agent: publish containers as Vhosts with one switch. +- Docker and Podman discovery through a separate agent: publish containers as Vhosts with one switch, one-time agent provisioning codes, publishing from container labels, multiple domains and certificate lists per agent, host and container diagnostics with history, Docker alerts, Prometheus host metrics and optional Docker Overview cards; the Grafana dashboard covers several RustProxy servers. - Nginx Proxy Manager import with a dry-run plan. - Managed install/update scripts with rollback, DEB/RPM packages, Docker image and an OPNsense plugin. - Panel in English and Polish, light and dark themes, adjustable density and corner style, plus a default-on stable dialog position option for tabbed editors. diff --git a/grafana/README.md b/grafana/README.md index 6340695..ea69e40 100644 --- a/grafana/README.md +++ b/grafana/README.md @@ -12,6 +12,29 @@ latency, backend health/EWMA latency/active work, traffic, probe age and upstrea variables **Docker agent** and **Docker service** filter only this section, which keeps multi-agent installations readable without changing the ordinary vhost panels. +**Several RustProxy servers.** Every query filters by the **Job** and +**RustProxy server** (`instance`) variables, both multi-select with *All*. Totals +sum the selected servers; the **RustProxy servers** row at the top shows a table +with one row per server (version, uptime, request and error rate, active +exchanges, RSS, CPU), scrape targets that are down and per-server request, +error, active, CPU and RSS time series. Scrape each server as its own target +(same job, different `instance`), for example: + +```yaml +scrape_configs: + - job_name: rustproxy + static_configs: + - targets: ["proxy-a.example.net:9191", "proxy-b.example.net:9191"] +``` + +The **Docker hosts and alerts** row (RustProxy 0.37.0+, Docker agent 1.1.0+) +uses `rust_proxy_docker_agent_up`, `rust_proxy_docker_host_*`, +`rust_proxy_docker_container_*` and `rust_proxy_docker_alert`: agents up, +active alerts with a table (agent offline, disk/memory/load thresholds, missing +published service, unhealthy container, invalid labels), host CPU, memory, load +per CPU, disk, network and containers per agent, and the top containers by CPU +and memory. + The **Web Server** row adds header-ready request rates, status-class and static/PHP/other donut breakdowns, error percentage, response-header latency, payload byte rates, and downstream compression by codec. **PHP-FPM / FastCGI** diff --git a/grafana/rustproxy-overview.json b/grafana/rustproxy-overview.json index da4d141..6f86dbe 100644 --- a/grafana/rustproxy-overview.json +++ b/grafana/rustproxy-overview.json @@ -10,9 +10,9 @@ "liveNow": false, "panels": [ { - "id": 1, + "id": 134, "type": "row", - "title": "Overview", + "title": "RustProxy servers", "collapsed": false, "gridPos": { "h": 1, @@ -23,107 +23,19 @@ "panels": [] }, { - "id": 2, + "id": 135, "type": "stat", - "title": "Request rate", + "title": "Servers reporting", "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" }, "gridPos": { "h": 5, - "w": 6, + "w": 4, "x": 0, "y": 1 }, - "fieldConfig": { - "defaults": { - "unit": "reqps", - "custom": {} - }, - "overrides": [] - }, - "options": { - "reduceOptions": { - "values": false, - "calcs": [ - "lastNotNull" - ], - "fields": "" - }, - "orientation": "auto", - "textMode": "auto", - "colorMode": "value", - "graphMode": "area", - "justifyMode": "auto" - }, - "targets": [ - { - "refId": "A", - "expr": "sum(rate(rust_proxy_requests_total[$__rate_interval]))", - "legendFormat": "req/s", - "range": true - } - ] - }, - { - "id": 3, - "type": "stat", - "title": "5xx / errors rate", - "datasource": { - "type": "prometheus", - "uid": "${DS_PROMETHEUS}" - }, - "gridPos": { - "h": 5, - "w": 6, - "x": 6, - "y": 1 - }, - "fieldConfig": { - "defaults": { - "unit": "ops", - "custom": {} - }, - "overrides": [] - }, - "options": { - "reduceOptions": { - "values": false, - "calcs": [ - "lastNotNull" - ], - "fields": "" - }, - "orientation": "auto", - "textMode": "auto", - "colorMode": "value", - "graphMode": "area", - "justifyMode": "auto" - }, - "targets": [ - { - "refId": "A", - "expr": "sum(rate(rust_proxy_errors_total[$__rate_interval]))", - "legendFormat": "errors/s", - "range": true - } - ] - }, - { - "id": 4, - "type": "stat", - "title": "Active exchanges", - "datasource": { - "type": "prometheus", - "uid": "${DS_PROMETHEUS}" - }, - "gridPos": { - "h": 5, - "w": 6, - "x": 12, - "y": 1 - }, "fieldConfig": { "defaults": { "unit": "short", @@ -148,7 +60,673 @@ "targets": [ { "refId": "A", - "expr": "sum(rust_proxy_requests_active)", + "expr": "count(rust_proxy_build_info{job=~\"$job\",instance=~\"$instance\"})", + "legendFormat": "", + "range": true + } + ], + "description": "RustProxy instances matching the Job/RustProxy server filters." + }, + { + "id": 136, + "type": "stat", + "title": "Servers down", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 5, + "w": 4, + "x": 4, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": {}, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 1 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "values": false, + "calcs": [ + "lastNotNull" + ], + "fields": "" + }, + "orientation": "auto", + "textMode": "auto", + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto" + }, + "targets": [ + { + "refId": "A", + "expr": "count(up{job=~\"$job\",instance=~\"$instance\"} == 0) or vector(0)", + "legendFormat": "", + "range": true + } + ], + "description": "Scrape targets of the selected jobs whose last scrape failed." + }, + { + "id": 137, + "type": "table", + "title": "Servers", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 10, + "w": 16, + "x": 8, + "y": 1 + }, + "fieldConfig": { + "defaults": { + "custom": { + "align": "auto", + "cellOptions": { + "type": "auto" + } + } + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "Uptime" + }, + "properties": [ + { + "id": "unit", + "value": "s" + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "Requests/s" + }, + "properties": [ + { + "id": "unit", + "value": "reqps" + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "Errors/s" + }, + "properties": [ + { + "id": "unit", + "value": "reqps" + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "RSS" + }, + "properties": [ + { + "id": "unit", + "value": "bytes" + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "CPU %" + }, + "properties": [ + { + "id": "unit", + "value": "percent" + } + ] + } + ] + }, + "options": { + "showHeader": true, + "cellHeight": "sm", + "footer": { + "show": false + } + }, + "targets": [ + { + "refId": "A", + "expr": "max by (instance, version) (rust_proxy_build_info{job=~\"$job\",instance=~\"$instance\"})", + "format": "table", + "instant": true, + "range": false + }, + { + "refId": "B", + "expr": "max by (instance) (rust_proxy_uptime_seconds{job=~\"$job\",instance=~\"$instance\"})", + "format": "table", + "instant": true, + "range": false + }, + { + "refId": "C", + "expr": "sum by (instance) (rate(rust_proxy_requests_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", + "format": "table", + "instant": true, + "range": false + }, + { + "refId": "D", + "expr": "sum by (instance) (rate(rust_proxy_errors_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", + "format": "table", + "instant": true, + "range": false + }, + { + "refId": "E", + "expr": "sum by (instance) (rust_proxy_requests_active{job=~\"$job\",instance=~\"$instance\"})", + "format": "table", + "instant": true, + "range": false + }, + { + "refId": "F", + "expr": "max by (instance) (rust_proxy_process_rss_bytes{job=~\"$job\",instance=~\"$instance\"})", + "format": "table", + "instant": true, + "range": false + }, + { + "refId": "G", + "expr": "max by (instance) (rust_proxy_process_cpu_percent{job=~\"$job\",instance=~\"$instance\"})", + "format": "table", + "instant": true, + "range": false + } + ], + "transformations": [ + { + "id": "merge", + "options": {} + }, + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "__name__": true, + "Value #A": true + }, + "renameByName": { + "instance": "Server", + "version": "Version", + "Value #A": "", + "Value #B": "Uptime", + "Value #C": "Requests/s", + "Value #D": "Errors/s", + "Value #E": "Active", + "Value #F": "RSS", + "Value #G": "CPU %" + } + } + } + ], + "description": "One row per RustProxy server; select servers with the RustProxy server variable." + }, + { + "id": 138, + "type": "stat", + "title": "Total request rate", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 5, + "w": 8, + "x": 0, + "y": 6 + }, + "fieldConfig": { + "defaults": { + "unit": "reqps", + "custom": {} + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "values": false, + "calcs": [ + "lastNotNull" + ], + "fields": "" + }, + "orientation": "auto", + "textMode": "auto", + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto" + }, + "targets": [ + { + "refId": "A", + "expr": "sum(rate(rust_proxy_requests_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", + "legendFormat": "", + "range": true + } + ] + }, + { + "id": 139, + "type": "timeseries", + "title": "Request rate by server", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 11 + }, + "fieldConfig": { + "defaults": { + "unit": "reqps", + "custom": { + "drawStyle": "line", + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (instance) (rate(rust_proxy_requests_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", + "legendFormat": "{{instance}}", + "range": true + } + ] + }, + { + "id": 140, + "type": "timeseries", + "title": "Errors by server", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 11 + }, + "fieldConfig": { + "defaults": { + "unit": "reqps", + "custom": { + "drawStyle": "line", + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (instance) (rate(rust_proxy_errors_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", + "legendFormat": "{{instance}}", + "range": true + } + ] + }, + { + "id": 141, + "type": "timeseries", + "title": "Active exchanges by server", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 19 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "drawStyle": "line", + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (instance) (rust_proxy_requests_active{job=~\"$job\",instance=~\"$instance\"})", + "legendFormat": "{{instance}}", + "range": true + } + ] + }, + { + "id": 142, + "type": "timeseries", + "title": "Process CPU by server", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 19 + }, + "fieldConfig": { + "defaults": { + "unit": "percent", + "custom": { + "drawStyle": "line", + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "expr": "max by (instance) (rust_proxy_process_cpu_percent{job=~\"$job\",instance=~\"$instance\"})", + "legendFormat": "{{instance}}", + "range": true + } + ] + }, + { + "id": 143, + "type": "timeseries", + "title": "Process RSS by server", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 19 + }, + "fieldConfig": { + "defaults": { + "unit": "bytes", + "custom": { + "drawStyle": "line", + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "expr": "max by (instance) (rust_proxy_process_rss_bytes{job=~\"$job\",instance=~\"$instance\"})", + "legendFormat": "{{instance}}", + "range": true + } + ] + }, + { + "id": 1, + "type": "row", + "title": "Overview", + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 27 + }, + "panels": [] + }, + { + "id": 2, + "type": "stat", + "title": "Request rate", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 5, + "w": 6, + "x": 0, + "y": 28 + }, + "fieldConfig": { + "defaults": { + "unit": "reqps", + "custom": {} + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "values": false, + "calcs": [ + "lastNotNull" + ], + "fields": "" + }, + "orientation": "auto", + "textMode": "auto", + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto" + }, + "targets": [ + { + "refId": "A", + "expr": "sum(rate(rust_proxy_requests_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", + "legendFormat": "req/s", + "range": true + } + ] + }, + { + "id": 3, + "type": "stat", + "title": "5xx / errors rate", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 5, + "w": 6, + "x": 6, + "y": 28 + }, + "fieldConfig": { + "defaults": { + "unit": "ops", + "custom": {} + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "values": false, + "calcs": [ + "lastNotNull" + ], + "fields": "" + }, + "orientation": "auto", + "textMode": "auto", + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto" + }, + "targets": [ + { + "refId": "A", + "expr": "sum(rate(rust_proxy_errors_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", + "legendFormat": "errors/s", + "range": true + } + ] + }, + { + "id": 4, + "type": "stat", + "title": "Active exchanges", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 5, + "w": 6, + "x": 12, + "y": 28 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": {} + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "values": false, + "calcs": [ + "lastNotNull" + ], + "fields": "" + }, + "orientation": "auto", + "textMode": "auto", + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto" + }, + "targets": [ + { + "refId": "A", + "expr": "sum(rust_proxy_requests_active{job=~\"$job\",instance=~\"$instance\"})", "legendFormat": "active", "range": true } @@ -166,7 +744,7 @@ "h": 5, "w": 6, "x": 18, - "y": 1 + "y": 28 }, "fieldConfig": { "defaults": { @@ -192,7 +770,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_process_rss_bytes", + "expr": "rust_proxy_process_rss_bytes{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "RSS", "range": true } @@ -210,7 +788,7 @@ "h": 7, "w": 12, "x": 0, - "y": 6 + "y": 33 }, "fieldConfig": { "defaults": { @@ -241,25 +819,25 @@ "targets": [ { "refId": "A", - "expr": "sum(rate(rust_proxy_requests_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_requests_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "requests/s", "range": true }, { "refId": "B", - "expr": "sum(rate(rust_proxy_requests_completed_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_requests_completed_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "completed/s", "range": true }, { "refId": "C", - "expr": "sum(rate(rust_proxy_errors_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_errors_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "errors/s", "range": true }, { "refId": "D", - "expr": "sum(rate(rust_proxy_requests_rejected_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_requests_rejected_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "rejected/s", "range": true } @@ -277,7 +855,7 @@ "h": 7, "w": 12, "x": 12, - "y": 6 + "y": 33 }, "fieldConfig": { "defaults": { @@ -308,7 +886,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (class) (rate(rust_proxy_responses_total[$__rate_interval]))", + "expr": "sum by (class) (rate(rust_proxy_responses_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "{{class}}", "range": true } @@ -326,7 +904,7 @@ "h": 5, "w": 6, "x": 0, - "y": 13 + "y": 40 }, "fieldConfig": { "defaults": { @@ -352,7 +930,7 @@ "targets": [ { "refId": "A", - "expr": "max by (version) (rust_proxy_build_info)", + "expr": "max by (version) (rust_proxy_build_info{job=~\"$job\",instance=~\"$instance\"})", "legendFormat": "{{version}}", "range": true } @@ -371,7 +949,7 @@ "h": 5, "w": 6, "x": 6, - "y": 13 + "y": 40 }, "fieldConfig": { "defaults": { @@ -397,7 +975,7 @@ "targets": [ { "refId": "A", - "expr": "min(rust_proxy_uptime_seconds)", + "expr": "min(rust_proxy_uptime_seconds{job=~\"$job\",instance=~\"$instance\"})", "legendFormat": "uptime", "range": true } @@ -416,7 +994,7 @@ "h": 5, "w": 6, "x": 12, - "y": 13 + "y": 40 }, "fieldConfig": { "defaults": { @@ -447,7 +1025,7 @@ "targets": [ { "refId": "A", - "expr": "100 * (sum(rust_proxy_request_capacity) - sum(rust_proxy_request_permits_available)) / clamp_min(sum(rust_proxy_request_capacity), 1)", + "expr": "100 * (sum(rust_proxy_request_capacity{job=~\"$job\",instance=~\"$instance\"}) - sum(rust_proxy_request_permits_available{job=~\"$job\",instance=~\"$instance\"})) / clamp_min(sum(rust_proxy_request_capacity{job=~\"$job\",instance=~\"$instance\"}), 1)", "legendFormat": "in use", "range": true } @@ -478,7 +1056,7 @@ "h": 5, "w": 6, "x": 18, - "y": 13 + "y": 40 }, "fieldConfig": { "defaults": { @@ -532,7 +1110,7 @@ "targets": [ { "refId": "A", - "expr": "max(rust_proxy_restart_required)", + "expr": "max(rust_proxy_restart_required{job=~\"$job\",instance=~\"$instance\"})", "legendFormat": "required", "range": true } @@ -548,7 +1126,7 @@ "h": 1, "w": 24, "x": 0, - "y": 18 + "y": 45 }, "panels": [] }, @@ -564,7 +1142,7 @@ "h": 7, "w": 12, "x": 0, - "y": 19 + "y": 46 }, "fieldConfig": { "defaults": { @@ -595,7 +1173,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (vhost) (rate(rust_proxy_vhost_requests_total[$__rate_interval]))", + "expr": "sum by (vhost) (rate(rust_proxy_vhost_requests_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "{{vhost}}", "range": true } @@ -613,7 +1191,7 @@ "h": 7, "w": 12, "x": 12, - "y": 19 + "y": 46 }, "fieldConfig": { "defaults": { @@ -644,7 +1222,7 @@ "targets": [ { "refId": "A", - "expr": "histogram_quantile(0.95, sum by (le,vhost) (rate(rust_proxy_vhost_exchange_duration_seconds_bucket[$__rate_interval])))", + "expr": "histogram_quantile(0.95, sum by (le,vhost) (rate(rust_proxy_vhost_exchange_duration_seconds_bucket{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])))", "legendFormat": "{{vhost}}", "range": true } @@ -662,7 +1240,7 @@ "h": 7, "w": 8, "x": 0, - "y": 26 + "y": 53 }, "fieldConfig": { "defaults": { @@ -693,7 +1271,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_backend_up", + "expr": "rust_proxy_backend_up{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "{{vhost}} / {{backend}}", "range": true } @@ -711,7 +1289,7 @@ "h": 7, "w": 8, "x": 8, - "y": 26 + "y": 53 }, "fieldConfig": { "defaults": { @@ -742,7 +1320,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_backend_latency_seconds", + "expr": "rust_proxy_backend_latency_seconds{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "{{vhost}} / {{backend}}", "range": true } @@ -760,7 +1338,7 @@ "h": 7, "w": 8, "x": 16, - "y": 26 + "y": 53 }, "fieldConfig": { "defaults": { @@ -791,7 +1369,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_backend_active_exchanges", + "expr": "rust_proxy_backend_active_exchanges{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "{{vhost}} / {{backend}}", "range": true } @@ -809,7 +1387,7 @@ "h": 7, "w": 12, "x": 0, - "y": 33 + "y": 60 }, "fieldConfig": { "defaults": { @@ -840,7 +1418,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (vhost,backend) (rate(rust_proxy_backend_errors_total[$__rate_interval]))", + "expr": "sum by (vhost,backend) (rate(rust_proxy_backend_errors_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "{{vhost}} / {{backend}}", "range": true } @@ -858,7 +1436,7 @@ "h": 7, "w": 12, "x": 12, - "y": 33 + "y": 60 }, "fieldConfig": { "defaults": { @@ -889,7 +1467,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_backend_traffic_bytes_per_second", + "expr": "rust_proxy_backend_traffic_bytes_per_second{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "{{vhost}} / {{backend}}", "range": true } @@ -907,7 +1485,7 @@ "h": 7, "w": 8, "x": 0, - "y": 40 + "y": 67 }, "fieldConfig": { "defaults": { @@ -938,13 +1516,13 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_backend_upstream_client_generation", + "expr": "rust_proxy_backend_upstream_client_generation{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "{{vhost}} / {{backend}} generation", "range": true }, { "refId": "B", - "expr": "rust_proxy_backend_upstream_client_generation_requests", + "expr": "rust_proxy_backend_upstream_client_generation_requests{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "{{vhost}} / {{backend}} requests", "range": true } @@ -963,7 +1541,7 @@ "h": 7, "w": 8, "x": 8, - "y": 40 + "y": 67 }, "fieldConfig": { "defaults": { @@ -994,7 +1572,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_backend_upstream_client_generation_age_seconds", + "expr": "rust_proxy_backend_upstream_client_generation_age_seconds{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "{{vhost}} / {{backend}}", "range": true } @@ -1013,7 +1591,7 @@ "h": 7, "w": 8, "x": 16, - "y": 40 + "y": 67 }, "fieldConfig": { "defaults": { @@ -1044,19 +1622,19 @@ "targets": [ { "refId": "A", - "expr": "sum by (vhost,backend) (rate(rust_proxy_backend_retry_attempts_total[$__rate_interval]))", + "expr": "sum by (vhost,backend) (rate(rust_proxy_backend_retry_attempts_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "{{vhost}} / {{backend}} retry attempts", "range": true }, { "refId": "B", - "expr": "sum by (vhost,backend) (rate(rust_proxy_backend_retry_successes_total[$__rate_interval]))", + "expr": "sum by (vhost,backend) (rate(rust_proxy_backend_retry_successes_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "{{vhost}} / {{backend}} retry successes", "range": true }, { "refId": "C", - "expr": "sum by (vhost,backend) (rate(rust_proxy_backend_upstream_client_rotations_total[$__rate_interval]))", + "expr": "sum by (vhost,backend) (rate(rust_proxy_backend_upstream_client_rotations_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "{{vhost}} / {{backend}} client rotations", "range": true } @@ -1075,7 +1653,7 @@ "h": 7, "w": 12, "x": 0, - "y": 47 + "y": 74 }, "fieldConfig": { "defaults": { @@ -1106,13 +1684,13 @@ "targets": [ { "refId": "A", - "expr": "sum by (vhost,backend) (rate(rust_proxy_backend_queue_timeouts_total[$__rate_interval]))", + "expr": "sum by (vhost,backend) (rate(rust_proxy_backend_queue_timeouts_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "{{vhost}} / {{backend}} queue timeout", "range": true }, { "refId": "B", - "expr": "sum by (vhost,backend) (rate(rust_proxy_backend_capacity_rejections_total[$__rate_interval]))", + "expr": "sum by (vhost,backend) (rate(rust_proxy_backend_capacity_rejections_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "{{vhost}} / {{backend}} capacity rejection", "range": true } @@ -1131,7 +1709,7 @@ "h": 7, "w": 12, "x": 12, - "y": 47 + "y": 74 }, "fieldConfig": { "defaults": { @@ -1164,7 +1742,7 @@ "targets": [ { "refId": "A", - "expr": "(100 * rust_proxy_backend_active_exchanges / clamp_min(rust_proxy_backend_max_concurrent_requests,1)) and on(vhost,backend) (rust_proxy_backend_max_concurrent_requests > 0)", + "expr": "(100 * rust_proxy_backend_active_exchanges{job=~\"$job\",instance=~\"$instance\"} / clamp_min(rust_proxy_backend_max_concurrent_requests{job=~\"$job\",instance=~\"$instance\"},1)) and on(vhost,backend) (rust_proxy_backend_max_concurrent_requests{job=~\"$job\",instance=~\"$instance\"} > 0)", "legendFormat": "{{vhost}} / {{backend}}", "range": true } @@ -1180,7 +1758,7 @@ "h": 1, "w": 24, "x": 0, - "y": 54 + "y": 81 }, "panels": [] }, @@ -1196,7 +1774,7 @@ "h": 5, "w": 6, "x": 0, - "y": 55 + "y": 82 }, "fieldConfig": { "defaults": { @@ -1222,7 +1800,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_docker_agents_configured", + "expr": "rust_proxy_docker_agents_configured{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "value", "range": true } @@ -1240,7 +1818,7 @@ "h": 5, "w": 6, "x": 6, - "y": 55 + "y": 82 }, "fieldConfig": { "defaults": { @@ -1266,7 +1844,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_docker_vhosts_configured", + "expr": "rust_proxy_docker_vhosts_configured{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "value", "range": true } @@ -1284,7 +1862,7 @@ "h": 5, "w": 6, "x": 12, - "y": 55 + "y": 82 }, "fieldConfig": { "defaults": { @@ -1310,7 +1888,7 @@ "targets": [ { "refId": "A", - "expr": "sum(rust_proxy_docker_vhost_enabled{agent=~\"$docker_agent\",service=~\"$docker_service\"})", + "expr": "sum(rust_proxy_docker_vhost_enabled{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"})", "legendFormat": "value", "range": true } @@ -1328,7 +1906,7 @@ "h": 5, "w": 6, "x": 18, - "y": 55 + "y": 82 }, "fieldConfig": { "defaults": { @@ -1354,7 +1932,7 @@ "targets": [ { "refId": "A", - "expr": "sum(rust_proxy_docker_backend_pool_ready{agent=~\"$docker_agent\",service=~\"$docker_service\"})", + "expr": "sum(rust_proxy_docker_backend_pool_ready{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"})", "legendFormat": "value", "range": true } @@ -1372,7 +1950,7 @@ "h": 7, "w": 8, "x": 0, - "y": 60 + "y": 87 }, "fieldConfig": { "defaults": { @@ -1403,7 +1981,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (agent,service) (rate(rust_proxy_docker_vhost_requests_total{agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", + "expr": "sum by (agent,service) (rate(rust_proxy_docker_vhost_requests_total{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", "legendFormat": "{{agent}} / {{service}}", "range": true } @@ -1421,7 +1999,7 @@ "h": 7, "w": 8, "x": 8, - "y": 60 + "y": 87 }, "fieldConfig": { "defaults": { @@ -1452,13 +2030,13 @@ "targets": [ { "refId": "A", - "expr": "sum by (agent,service) (rate(rust_proxy_docker_vhost_errors_total{agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", + "expr": "sum by (agent,service) (rate(rust_proxy_docker_vhost_errors_total{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", "legendFormat": "{{agent}} / {{service}} errors", "range": true }, { "refId": "B", - "expr": "sum by (agent,service) (rate(rust_proxy_docker_vhost_rejected_total{agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", + "expr": "sum by (agent,service) (rate(rust_proxy_docker_vhost_rejected_total{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", "legendFormat": "{{agent}} / {{service}} rejected", "range": true } @@ -1476,7 +2054,7 @@ "h": 7, "w": 8, "x": 16, - "y": 60 + "y": 87 }, "fieldConfig": { "defaults": { @@ -1507,7 +2085,7 @@ "targets": [ { "refId": "A", - "expr": "histogram_quantile(0.95, sum by (le,agent,service) (rate(rust_proxy_docker_vhost_exchange_duration_seconds_bucket{agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval])))", + "expr": "histogram_quantile(0.95, sum by (le,agent,service) (rate(rust_proxy_docker_vhost_exchange_duration_seconds_bucket{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval])))", "legendFormat": "{{agent}} / {{service}}", "range": true } @@ -1525,7 +2103,7 @@ "h": 7, "w": 8, "x": 0, - "y": 67 + "y": 94 }, "fieldConfig": { "defaults": { @@ -1556,7 +2134,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_docker_backend_up{agent=~\"$docker_agent\",service=~\"$docker_service\"}", + "expr": "rust_proxy_docker_backend_up{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"}", "legendFormat": "{{agent}} / {{service}} / {{backend}}", "range": true } @@ -1574,7 +2152,7 @@ "h": 7, "w": 8, "x": 8, - "y": 67 + "y": 94 }, "fieldConfig": { "defaults": { @@ -1605,7 +2183,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_docker_backend_ewma_latency_seconds{agent=~\"$docker_agent\",service=~\"$docker_service\"}", + "expr": "rust_proxy_docker_backend_ewma_latency_seconds{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"}", "legendFormat": "{{agent}} / {{service}} / {{backend}}", "range": true } @@ -1623,7 +2201,7 @@ "h": 7, "w": 8, "x": 16, - "y": 67 + "y": 94 }, "fieldConfig": { "defaults": { @@ -1654,7 +2232,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_docker_backend_active_exchanges{agent=~\"$docker_agent\",service=~\"$docker_service\"}", + "expr": "rust_proxy_docker_backend_active_exchanges{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"}", "legendFormat": "{{agent}} / {{service}} / {{backend}}", "range": true } @@ -1672,7 +2250,7 @@ "h": 7, "w": 8, "x": 0, - "y": 74 + "y": 101 }, "fieldConfig": { "defaults": { @@ -1703,7 +2281,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (agent,service,backend) (rate(rust_proxy_docker_backend_errors_total{agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", + "expr": "sum by (agent,service,backend) (rate(rust_proxy_docker_backend_errors_total{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", "legendFormat": "{{agent}} / {{service}} / {{backend}}", "range": true } @@ -1721,7 +2299,7 @@ "h": 7, "w": 8, "x": 8, - "y": 74 + "y": 101 }, "fieldConfig": { "defaults": { @@ -1752,13 +2330,13 @@ "targets": [ { "refId": "A", - "expr": "sum by (agent,service,backend) (rate(rust_proxy_docker_backend_bytes_in_total{agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", + "expr": "sum by (agent,service,backend) (rate(rust_proxy_docker_backend_bytes_in_total{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", "legendFormat": "{{agent}} / {{service}} / {{backend}} in", "range": true }, { "refId": "B", - "expr": "sum by (agent,service,backend) (rate(rust_proxy_docker_backend_bytes_out_total{agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", + "expr": "sum by (agent,service,backend) (rate(rust_proxy_docker_backend_bytes_out_total{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", "legendFormat": "{{agent}} / {{service}} / {{backend}} out", "range": true } @@ -1776,7 +2354,7 @@ "h": 7, "w": 8, "x": 16, - "y": 74 + "y": 101 }, "fieldConfig": { "defaults": { @@ -1807,7 +2385,7 @@ "targets": [ { "refId": "A", - "expr": "time() - rust_proxy_docker_backend_last_probe_timestamp_seconds{agent=~\"$docker_agent\",service=~\"$docker_service\"}", + "expr": "time() - rust_proxy_docker_backend_last_probe_timestamp_seconds{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"}", "legendFormat": "{{agent}} / {{service}} / {{backend}}", "range": true } @@ -1825,7 +2403,7 @@ "h": 7, "w": 8, "x": 0, - "y": 81 + "y": 108 }, "fieldConfig": { "defaults": { @@ -1856,13 +2434,13 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_docker_backend_upstream_client_generation{agent=~\"$docker_agent\",service=~\"$docker_service\"}", + "expr": "rust_proxy_docker_backend_upstream_client_generation{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"}", "legendFormat": "{{agent}} / {{service}} / {{backend}} generation", "range": true }, { "refId": "B", - "expr": "rust_proxy_docker_backend_upstream_client_generation_requests{agent=~\"$docker_agent\",service=~\"$docker_service\"}", + "expr": "rust_proxy_docker_backend_upstream_client_generation_requests{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"}", "legendFormat": "{{agent}} / {{service}} / {{backend}} requests", "range": true } @@ -1881,7 +2459,7 @@ "h": 7, "w": 8, "x": 8, - "y": 81 + "y": 108 }, "fieldConfig": { "defaults": { @@ -1912,7 +2490,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_docker_backend_upstream_client_generation_age_seconds{agent=~\"$docker_agent\",service=~\"$docker_service\"}", + "expr": "rust_proxy_docker_backend_upstream_client_generation_age_seconds{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"}", "legendFormat": "{{agent}} / {{service}} / {{backend}}", "range": true } @@ -1931,7 +2509,7 @@ "h": 7, "w": 8, "x": 16, - "y": 81 + "y": 108 }, "fieldConfig": { "defaults": { @@ -1962,19 +2540,19 @@ "targets": [ { "refId": "A", - "expr": "sum by (agent,service,backend) (rate(rust_proxy_docker_backend_retry_attempts_total{agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", + "expr": "sum by (agent,service,backend) (rate(rust_proxy_docker_backend_retry_attempts_total{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", "legendFormat": "{{agent}} / {{service}} / {{backend}} retry attempts", "range": true }, { "refId": "B", - "expr": "sum by (agent,service,backend) (rate(rust_proxy_docker_backend_retry_successes_total{agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", + "expr": "sum by (agent,service,backend) (rate(rust_proxy_docker_backend_retry_successes_total{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", "legendFormat": "{{agent}} / {{service}} / {{backend}} retry successes", "range": true }, { "refId": "C", - "expr": "sum by (agent,service,backend) (rate(rust_proxy_docker_backend_upstream_client_rotations_total{agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", + "expr": "sum by (agent,service,backend) (rate(rust_proxy_docker_backend_upstream_client_rotations_total{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", "legendFormat": "{{agent}} / {{service}} / {{backend}} client rotations", "range": true } @@ -1993,7 +2571,7 @@ "h": 7, "w": 12, "x": 0, - "y": 88 + "y": 115 }, "fieldConfig": { "defaults": { @@ -2024,13 +2602,13 @@ "targets": [ { "refId": "A", - "expr": "sum by (agent,service,backend) (rate(rust_proxy_docker_backend_queue_timeouts_total{agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", + "expr": "sum by (agent,service,backend) (rate(rust_proxy_docker_backend_queue_timeouts_total{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", "legendFormat": "{{agent}} / {{service}} / {{backend}} queue timeout", "range": true }, { "refId": "B", - "expr": "sum by (agent,service,backend) (rate(rust_proxy_docker_backend_capacity_rejections_total{agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", + "expr": "sum by (agent,service,backend) (rate(rust_proxy_docker_backend_capacity_rejections_total{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"}[$__rate_interval]))", "legendFormat": "{{agent}} / {{service}} / {{backend}} capacity rejection", "range": true } @@ -2049,7 +2627,7 @@ "h": 7, "w": 12, "x": 12, - "y": 88 + "y": 115 }, "fieldConfig": { "defaults": { @@ -2082,7 +2660,7 @@ "targets": [ { "refId": "A", - "expr": "(100 * rust_proxy_docker_backend_active_exchanges{agent=~\"$docker_agent\",service=~\"$docker_service\"} / clamp_min(rust_proxy_docker_backend_max_concurrent_requests{agent=~\"$docker_agent\",service=~\"$docker_service\"},1)) and on(agent,service,vhost,backend) (rust_proxy_docker_backend_max_concurrent_requests{agent=~\"$docker_agent\",service=~\"$docker_service\"} > 0)", + "expr": "(100 * rust_proxy_docker_backend_active_exchanges{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"} / clamp_min(rust_proxy_docker_backend_max_concurrent_requests{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"},1)) and on(agent,service,vhost,backend) (rust_proxy_docker_backend_max_concurrent_requests{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",service=~\"$docker_service\"} > 0)", "legendFormat": "{{agent}} / {{service}} / {{backend}}", "range": true } @@ -2098,7 +2676,7 @@ "h": 1, "w": 24, "x": 0, - "y": 95 + "y": 122 }, "panels": [] }, @@ -2114,7 +2692,7 @@ "h": 5, "w": 6, "x": 0, - "y": 96 + "y": 123 }, "fieldConfig": { "defaults": { @@ -2140,7 +2718,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_cache_resident_bytes", + "expr": "rust_proxy_cache_resident_bytes{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "hot", "range": true } @@ -2158,7 +2736,7 @@ "h": 5, "w": 6, "x": 6, - "y": 96 + "y": 123 }, "fieldConfig": { "defaults": { @@ -2184,7 +2762,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_cache_transient_bytes", + "expr": "rust_proxy_cache_transient_bytes{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "transient", "range": true } @@ -2202,7 +2780,7 @@ "h": 5, "w": 6, "x": 12, - "y": 96 + "y": 123 }, "fieldConfig": { "defaults": { @@ -2228,7 +2806,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_cache_cold_bytes", + "expr": "rust_proxy_cache_cold_bytes{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "cold", "range": true } @@ -2246,7 +2824,7 @@ "h": 5, "w": 6, "x": 18, - "y": 96 + "y": 123 }, "fieldConfig": { "defaults": { @@ -2272,7 +2850,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_cache_entries", + "expr": "rust_proxy_cache_entries{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "hot objects", "range": true } @@ -2290,7 +2868,7 @@ "h": 7, "w": 12, "x": 0, - "y": 101 + "y": 128 }, "fieldConfig": { "defaults": { @@ -2321,25 +2899,25 @@ "targets": [ { "refId": "A", - "expr": "rate(rust_proxy_cache_hits_total[$__rate_interval])", + "expr": "rate(rust_proxy_cache_hits_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "legendFormat": "HIT/s", "range": true }, { "refId": "B", - "expr": "rate(rust_proxy_cache_misses_total[$__rate_interval])", + "expr": "rate(rust_proxy_cache_misses_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "legendFormat": "MISS/s", "range": true }, { "refId": "C", - "expr": "rate(rust_proxy_cache_bypasses_total[$__rate_interval])", + "expr": "rate(rust_proxy_cache_bypasses_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "legendFormat": "BYPASS/s", "range": true }, { "refId": "D", - "expr": "rate(rust_proxy_cache_rejected_fills_total[$__rate_interval])", + "expr": "rate(rust_proxy_cache_rejected_fills_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "legendFormat": "rejected fills/s", "range": true } @@ -2357,7 +2935,7 @@ "h": 7, "w": 12, "x": 12, - "y": 101 + "y": 128 }, "fieldConfig": { "defaults": { @@ -2388,25 +2966,25 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_cache_fill_bytes_active", + "expr": "rust_proxy_cache_fill_bytes_active{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "fill", "range": true }, { "refId": "B", - "expr": "rust_proxy_cache_cold_queue_bytes", + "expr": "rust_proxy_cache_cold_queue_bytes{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "cold queue", "range": true }, { "refId": "C", - "expr": "rust_proxy_cache_cold_write_bytes_active", + "expr": "rust_proxy_cache_cold_write_bytes_active{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "cold write", "range": true }, { "refId": "D", - "expr": "rust_proxy_cache_cold_read_bytes_active", + "expr": "rust_proxy_cache_cold_read_bytes_active{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "cold read", "range": true } @@ -2424,7 +3002,7 @@ "h": 7, "w": 12, "x": 0, - "y": 108 + "y": 135 }, "fieldConfig": { "defaults": { @@ -2455,31 +3033,31 @@ "targets": [ { "refId": "A", - "expr": "rate(rust_proxy_cache_cold_hits_total[$__rate_interval])", + "expr": "rate(rust_proxy_cache_cold_hits_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "legendFormat": "cold hits/s", "range": true }, { "refId": "B", - "expr": "rate(rust_proxy_cache_cold_promotions_total[$__rate_interval])", + "expr": "rate(rust_proxy_cache_cold_promotions_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "legendFormat": "cold->hot/s", "range": true }, { "refId": "C", - "expr": "rate(rust_proxy_cache_hot_demotions_total[$__rate_interval])", + "expr": "rate(rust_proxy_cache_hot_demotions_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "legendFormat": "hot->cold/s", "range": true }, { "refId": "D", - "expr": "rate(rust_proxy_cache_cold_evictions_total[$__rate_interval])", + "expr": "rate(rust_proxy_cache_cold_evictions_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "legendFormat": "cold evictions/s", "range": true }, { "refId": "E", - "expr": "rate(rust_proxy_cache_cold_errors_total[$__rate_interval])", + "expr": "rate(rust_proxy_cache_cold_errors_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "legendFormat": "cold errors/s", "range": true } @@ -2497,7 +3075,7 @@ "h": 7, "w": 12, "x": 12, - "y": 108 + "y": 135 }, "fieldConfig": { "defaults": { @@ -2528,7 +3106,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_cache_domain_hit_ratio", + "expr": "rust_proxy_cache_domain_hit_ratio{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "{{vhost}} / {{domain}}", "range": true } @@ -2546,7 +3124,7 @@ "h": 5, "w": 6, "x": 0, - "y": 115 + "y": 142 }, "fieldConfig": { "defaults": { @@ -2577,7 +3155,7 @@ "targets": [ { "refId": "A", - "expr": "100 * sum(rust_proxy_cache_resident_bytes) / clamp_min(sum(rust_proxy_cache_hot_limit_bytes),1)", + "expr": "100 * sum(rust_proxy_cache_resident_bytes{job=~\"$job\",instance=~\"$instance\"}) / clamp_min(sum(rust_proxy_cache_hot_limit_bytes{job=~\"$job\",instance=~\"$instance\"}),1)", "legendFormat": "used", "range": true } @@ -2608,7 +3186,7 @@ "h": 5, "w": 6, "x": 6, - "y": 115 + "y": 142 }, "fieldConfig": { "defaults": { @@ -2639,7 +3217,7 @@ "targets": [ { "refId": "A", - "expr": "100 * sum(rust_proxy_cache_transient_bytes) / clamp_min(sum(rust_proxy_cache_transient_limit_bytes),1)", + "expr": "100 * sum(rust_proxy_cache_transient_bytes{job=~\"$job\",instance=~\"$instance\"}) / clamp_min(sum(rust_proxy_cache_transient_limit_bytes{job=~\"$job\",instance=~\"$instance\"}),1)", "legendFormat": "used", "range": true } @@ -2670,7 +3248,7 @@ "h": 5, "w": 6, "x": 12, - "y": 115 + "y": 142 }, "fieldConfig": { "defaults": { @@ -2701,7 +3279,7 @@ "targets": [ { "refId": "A", - "expr": "100 * sum(rust_proxy_cache_cold_bytes) / clamp_min(sum(rust_proxy_cache_cold_limit_bytes),1)", + "expr": "100 * sum(rust_proxy_cache_cold_bytes{job=~\"$job\",instance=~\"$instance\"}) / clamp_min(sum(rust_proxy_cache_cold_limit_bytes{job=~\"$job\",instance=~\"$instance\"}),1)", "legendFormat": "used", "range": true } @@ -2732,7 +3310,7 @@ "h": 5, "w": 6, "x": 18, - "y": 115 + "y": 142 }, "fieldConfig": { "defaults": { @@ -2763,7 +3341,7 @@ "targets": [ { "refId": "A", - "expr": "100 * sum(rust_proxy_cache_cold_queue_bytes) / clamp_min(sum(rust_proxy_cache_cold_queue_limit_bytes),1)", + "expr": "100 * sum(rust_proxy_cache_cold_queue_bytes{job=~\"$job\",instance=~\"$instance\"}) / clamp_min(sum(rust_proxy_cache_cold_queue_limit_bytes{job=~\"$job\",instance=~\"$instance\"}),1)", "legendFormat": "used", "range": true } @@ -2794,7 +3372,7 @@ "h": 7, "w": 12, "x": 0, - "y": 120 + "y": 147 }, "fieldConfig": { "defaults": { @@ -2825,25 +3403,25 @@ "targets": [ { "refId": "A", - "expr": "sum(rate(rust_proxy_cache_memory_pressure_rejections_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_cache_memory_pressure_rejections_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "memory pressure rejects/s", "range": true }, { "refId": "B", - "expr": "sum(rate(rust_proxy_cache_hot_eviction_limited_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_cache_hot_eviction_limited_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "hot eviction limited/s", "range": true }, { "refId": "C", - "expr": "sum(rate(rust_proxy_cache_cold_queue_dropped_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_cache_cold_queue_dropped_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "cold queue drops/s", "range": true }, { "refId": "D", - "expr": "sum(rate(rust_proxy_cache_collapse_timeouts_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_cache_collapse_timeouts_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "collapsed fill timeouts/s", "range": true } @@ -2862,7 +3440,7 @@ "h": 7, "w": 12, "x": 12, - "y": 120 + "y": 147 }, "fieldConfig": { "defaults": { @@ -2893,25 +3471,25 @@ "targets": [ { "refId": "A", - "expr": "sum(rate(rust_proxy_cache_collapsed_fills_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_cache_collapsed_fills_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "collapsed fills/s", "range": true }, { "refId": "B", - "expr": "sum(rate(rust_proxy_cache_proactive_scheduled_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_cache_proactive_scheduled_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "proactive scheduled/s", "range": true }, { "refId": "C", - "expr": "sum(rate(rust_proxy_cache_proactive_started_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_cache_proactive_started_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "proactive started/s", "range": true }, { "refId": "D", - "expr": "sum(rate(rust_proxy_cache_proactive_skipped_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_cache_proactive_skipped_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "proactive skipped/s", "range": true } @@ -2927,7 +3505,7 @@ "h": 1, "w": 24, "x": 0, - "y": 127 + "y": 154 }, "panels": [] }, @@ -2943,7 +3521,7 @@ "h": 8, "w": 12, "x": 0, - "y": 128 + "y": 155 }, "fieldConfig": { "defaults": { @@ -2974,37 +3552,37 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_process_rss_bytes", + "expr": "rust_proxy_process_rss_bytes{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "RSS total", "range": true }, { "refId": "B", - "expr": "rust_proxy_process_rss_anon_bytes", + "expr": "rust_proxy_process_rss_anon_bytes{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "RSS anon", "range": true }, { "refId": "C", - "expr": "rust_proxy_process_rss_file_bytes", + "expr": "rust_proxy_process_rss_file_bytes{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "RSS file", "range": true }, { "refId": "D", - "expr": "rust_proxy_process_rss_shmem_bytes", + "expr": "rust_proxy_process_rss_shmem_bytes{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "RSS shmem", "range": true }, { "refId": "E", - "expr": "rust_proxy_process_data_bytes", + "expr": "rust_proxy_process_data_bytes{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "VmData", "range": true }, { "refId": "F", - "expr": "rust_proxy_process_swap_bytes", + "expr": "rust_proxy_process_swap_bytes{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "swap", "range": true } @@ -3022,7 +3600,7 @@ "h": 8, "w": 12, "x": 12, - "y": 128 + "y": 155 }, "fieldConfig": { "defaults": { @@ -3053,13 +3631,13 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_cgroup_memory_current_bytes", + "expr": "rust_proxy_cgroup_memory_current_bytes{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "current", "range": true }, { "refId": "B", - "expr": "rust_proxy_cgroup_memory_max_bytes", + "expr": "rust_proxy_cgroup_memory_max_bytes{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "max", "range": true } @@ -3077,7 +3655,7 @@ "h": 7, "w": 8, "x": 0, - "y": 136 + "y": 163 }, "fieldConfig": { "defaults": { @@ -3108,13 +3686,13 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_process_cpu_percent", + "expr": "rust_proxy_process_cpu_percent{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "process", "range": true }, { "refId": "B", - "expr": "rust_proxy_system_cpu_percent", + "expr": "rust_proxy_system_cpu_percent{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "system", "range": true } @@ -3132,7 +3710,7 @@ "h": 7, "w": 8, "x": 8, - "y": 136 + "y": 163 }, "fieldConfig": { "defaults": { @@ -3163,19 +3741,19 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_system_load1", + "expr": "rust_proxy_system_load1{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "load1", "range": true }, { "refId": "B", - "expr": "rust_proxy_system_load5", + "expr": "rust_proxy_system_load5{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "load5", "range": true }, { "refId": "C", - "expr": "rust_proxy_system_load15", + "expr": "rust_proxy_system_load15{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "load15", "range": true } @@ -3193,7 +3771,7 @@ "h": 7, "w": 8, "x": 16, - "y": 136 + "y": 163 }, "fieldConfig": { "defaults": { @@ -3224,13 +3802,13 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_process_open_fds", + "expr": "rust_proxy_process_open_fds{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "open FDs", "range": true }, { "refId": "B", - "expr": "rust_proxy_process_threads", + "expr": "rust_proxy_process_threads{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "threads", "range": true } @@ -3248,7 +3826,7 @@ "h": 7, "w": 12, "x": 0, - "y": 143 + "y": 170 }, "fieldConfig": { "defaults": { @@ -3279,13 +3857,13 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_system_network_rx_bytes_per_second", + "expr": "rust_proxy_system_network_rx_bytes_per_second{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "RX", "range": true }, { "refId": "B", - "expr": "rust_proxy_system_network_tx_bytes_per_second", + "expr": "rust_proxy_system_network_tx_bytes_per_second{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "TX", "range": true } @@ -3303,7 +3881,7 @@ "h": 7, "w": 12, "x": 12, - "y": 143 + "y": 170 }, "fieldConfig": { "defaults": { @@ -3334,13 +3912,13 @@ "targets": [ { "refId": "A", - "expr": "clamp_min(deriv(rust_proxy_process_read_bytes[$__rate_interval]), 0)", + "expr": "clamp_min(deriv(rust_proxy_process_read_bytes{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]), 0)", "legendFormat": "read", "range": true }, { "refId": "B", - "expr": "clamp_min(deriv(rust_proxy_process_write_bytes[$__rate_interval]), 0)", + "expr": "clamp_min(deriv(rust_proxy_process_write_bytes{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]), 0)", "legendFormat": "write", "range": true } @@ -3356,7 +3934,7 @@ "h": 1, "w": 24, "x": 0, - "y": 150 + "y": 177 }, "panels": [] }, @@ -3372,7 +3950,7 @@ "h": 7, "w": 8, "x": 0, - "y": 151 + "y": 178 }, "fieldConfig": { "defaults": { @@ -3403,19 +3981,19 @@ "targets": [ { "refId": "A", - "expr": "rate(rust_proxy_http1_requests_total[$__rate_interval])", + "expr": "rate(rust_proxy_http1_requests_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "legendFormat": "HTTP/1.1", "range": true }, { "refId": "B", - "expr": "rate(rust_proxy_http2_requests_total[$__rate_interval])", + "expr": "rate(rust_proxy_http2_requests_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "legendFormat": "HTTP/2", "range": true }, { "refId": "C", - "expr": "rate(rust_proxy_http3_requests_total[$__rate_interval])", + "expr": "rate(rust_proxy_http3_requests_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "legendFormat": "HTTP/3", "range": true } @@ -3433,7 +4011,7 @@ "h": 7, "w": 8, "x": 8, - "y": 151 + "y": 178 }, "fieldConfig": { "defaults": { @@ -3464,13 +4042,13 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_connections_active", + "expr": "rust_proxy_connections_active{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "all active", "range": true }, { "refId": "B", - "expr": "rust_proxy_http3_active_connections", + "expr": "rust_proxy_http3_active_connections{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "H3 active", "range": true } @@ -3488,7 +4066,7 @@ "h": 7, "w": 8, "x": 16, - "y": 151 + "y": 178 }, "fieldConfig": { "defaults": { @@ -3519,13 +4097,13 @@ "targets": [ { "refId": "A", - "expr": "rate(rust_proxy_tls_handshake_errors_total[$__rate_interval])", + "expr": "rate(rust_proxy_tls_handshake_errors_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "legendFormat": "TLS handshake errors/s", "range": true }, { "refId": "B", - "expr": "rate(rust_proxy_http3_rejected_connections_total[$__rate_interval])", + "expr": "rate(rust_proxy_http3_rejected_connections_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "legendFormat": "H3 rejects/s", "range": true } @@ -3543,7 +4121,7 @@ "h": 7, "w": 12, "x": 0, - "y": 158 + "y": 185 }, "fieldConfig": { "defaults": { @@ -3574,7 +4152,7 @@ "targets": [ { "refId": "A", - "expr": "sum(rust_proxy_websocket_tunnels_active)", + "expr": "sum(rust_proxy_websocket_tunnels_active{job=~\"$job\",instance=~\"$instance\"})", "legendFormat": "active", "range": true } @@ -3593,7 +4171,7 @@ "h": 7, "w": 12, "x": 12, - "y": 158 + "y": 185 }, "fieldConfig": { "defaults": { @@ -3624,25 +4202,25 @@ "targets": [ { "refId": "A", - "expr": "rate(rust_proxy_compression_gzip_total[$__rate_interval])", + "expr": "rate(rust_proxy_compression_gzip_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "legendFormat": "gzip/s", "range": true }, { "refId": "B", - "expr": "rate(rust_proxy_compression_br_total[$__rate_interval])", + "expr": "rate(rust_proxy_compression_br_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "legendFormat": "br/s", "range": true }, { "refId": "C", - "expr": "rate(rust_proxy_compression_zstd_total[$__rate_interval])", + "expr": "rate(rust_proxy_compression_zstd_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "legendFormat": "zstd/s", "range": true }, { "refId": "D", - "expr": "rate(rust_proxy_compression_deflate_total[$__rate_interval])", + "expr": "rate(rust_proxy_compression_deflate_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval])", "legendFormat": "deflate/s", "range": true } @@ -3660,7 +4238,7 @@ "h": 7, "w": 12, "x": 0, - "y": 165 + "y": 192 }, "fieldConfig": { "defaults": { @@ -3691,19 +4269,19 @@ "targets": [ { "refId": "A", - "expr": "sum(rate(rust_proxy_websocket_tunnels_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_websocket_tunnels_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "opened/s", "range": true }, { "refId": "B", - "expr": "sum(rate(rust_proxy_websocket_errors_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_websocket_errors_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "transport errors/s", "range": true }, { "refId": "C", - "expr": "sum(rate(rust_proxy_websocket_handshake_errors_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_websocket_handshake_errors_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "handshake errors/s", "range": true } @@ -3722,7 +4300,7 @@ "h": 7, "w": 12, "x": 12, - "y": 165 + "y": 192 }, "fieldConfig": { "defaults": { @@ -3753,19 +4331,19 @@ "targets": [ { "refId": "A", - "expr": "sum(rust_proxy_websocket_h1_tunnels_active)", + "expr": "sum(rust_proxy_websocket_h1_tunnels_active{job=~\"$job\",instance=~\"$instance\"})", "legendFormat": "HTTP/1.1", "range": true }, { "refId": "B", - "expr": "sum(rust_proxy_websocket_h2_rfc8441_tunnels_active)", + "expr": "sum(rust_proxy_websocket_h2_rfc8441_tunnels_active{job=~\"$job\",instance=~\"$instance\"})", "legendFormat": "HTTP/2 RFC 8441", "range": true }, { "refId": "C", - "expr": "sum(rust_proxy_websocket_h3_rfc9220_tunnels_active)", + "expr": "sum(rust_proxy_websocket_h3_rfc9220_tunnels_active{job=~\"$job\",instance=~\"$instance\"})", "legendFormat": "HTTP/3 RFC 9220", "range": true } @@ -3781,7 +4359,7 @@ "h": 1, "w": 24, "x": 0, - "y": 172 + "y": 199 }, "panels": [] }, @@ -3797,7 +4375,7 @@ "h": 7, "w": 12, "x": 0, - "y": 173 + "y": 200 }, "fieldConfig": { "defaults": { @@ -3828,7 +4406,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (stream, protocol) (rust_proxy_stream_active)", + "expr": "sum by (stream, protocol) (rust_proxy_stream_active{job=~\"$job\",instance=~\"$instance\"})", "legendFormat": "{{stream}} ({{protocol}})", "range": true } @@ -3847,7 +4425,7 @@ "h": 7, "w": 12, "x": 12, - "y": 173 + "y": 200 }, "fieldConfig": { "defaults": { @@ -3878,13 +4456,13 @@ "targets": [ { "refId": "A", - "expr": "sum by (stream) (rate(rust_proxy_stream_bytes_in_total[$__rate_interval]))", + "expr": "sum by (stream) (rate(rust_proxy_stream_bytes_in_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "{{stream}} in", "range": true }, { "refId": "B", - "expr": "sum by (stream) (rate(rust_proxy_stream_bytes_out_total[$__rate_interval]))", + "expr": "sum by (stream) (rate(rust_proxy_stream_bytes_out_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "{{stream}} out", "range": true } @@ -3902,7 +4480,7 @@ "h": 7, "w": 8, "x": 0, - "y": 180 + "y": 207 }, "fieldConfig": { "defaults": { @@ -3933,19 +4511,19 @@ "targets": [ { "refId": "A", - "expr": "sum by (stream,protocol) (rate(rust_proxy_stream_sessions_total[$__rate_interval]))", + "expr": "sum by (stream,protocol) (rate(rust_proxy_stream_sessions_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "{{stream}} ({{protocol}}) started", "range": true }, { "refId": "B", - "expr": "sum by (stream,protocol) (rate(rust_proxy_stream_errors_total[$__rate_interval]))", + "expr": "sum by (stream,protocol) (rate(rust_proxy_stream_errors_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "{{stream}} ({{protocol}}) errors", "range": true }, { "refId": "C", - "expr": "sum by (stream,protocol) (rate(rust_proxy_stream_rejected_total[$__rate_interval]))", + "expr": "sum by (stream,protocol) (rate(rust_proxy_stream_rejected_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "{{stream}} ({{protocol}}) rejected", "range": true } @@ -3964,7 +4542,7 @@ "h": 7, "w": 8, "x": 8, - "y": 180 + "y": 207 }, "fieldConfig": { "defaults": { @@ -4025,7 +4603,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_stream_backend_health_state", + "expr": "rust_proxy_stream_backend_health_state{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "{{stream}} ({{protocol}}) / {{backend}}", "range": true } @@ -4044,7 +4622,7 @@ "h": 7, "w": 8, "x": 16, - "y": 180 + "y": 207 }, "fieldConfig": { "defaults": { @@ -4077,7 +4655,7 @@ "targets": [ { "refId": "A", - "expr": "100 * rust_proxy_stream_active / clamp_min(rust_proxy_stream_max_connections,1)", + "expr": "100 * rust_proxy_stream_active{job=~\"$job\",instance=~\"$instance\"} / clamp_min(rust_proxy_stream_max_connections{job=~\"$job\",instance=~\"$instance\"},1)", "legendFormat": "{{stream}} ({{protocol}})", "range": true } @@ -4096,7 +4674,7 @@ "h": 7, "w": 12, "x": 0, - "y": 187 + "y": 214 }, "fieldConfig": { "defaults": { @@ -4127,7 +4705,7 @@ "targets": [ { "refId": "A", - "expr": "sum(rust_proxy_log_sink_queue_capacity)", + "expr": "sum(rust_proxy_log_sink_queue_capacity{job=~\"$job\",instance=~\"$instance\"})", "legendFormat": "queue capacity", "range": true } @@ -4146,7 +4724,7 @@ "h": 7, "w": 12, "x": 12, - "y": 187 + "y": 214 }, "fieldConfig": { "defaults": { @@ -4177,7 +4755,7 @@ "targets": [ { "refId": "A", - "expr": "sum(rate(rust_proxy_admin_requests_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_admin_requests_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "admin requests/s", "range": true } @@ -4196,7 +4774,7 @@ "h": 7, "w": 12, "x": 0, - "y": 194 + "y": 221 }, "fieldConfig": { "defaults": { @@ -4227,19 +4805,19 @@ "targets": [ { "refId": "A", - "expr": "sum(rate(rust_proxy_log_sink_sent_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_log_sink_sent_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "delivered/s", "range": true }, { "refId": "B", - "expr": "sum(rate(rust_proxy_log_sink_queue_dropped_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_log_sink_queue_dropped_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "dropped/s", "range": true }, { "refId": "C", - "expr": "sum(rate(rust_proxy_log_sink_errors_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_log_sink_errors_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "delivery errors/s", "range": true } @@ -4258,7 +4836,7 @@ "h": 7, "w": 12, "x": 12, - "y": 194 + "y": 221 }, "fieldConfig": { "defaults": { @@ -4289,19 +4867,19 @@ "targets": [ { "refId": "A", - "expr": "sum(rust_proxy_request_capacity)", + "expr": "sum(rust_proxy_request_capacity{job=~\"$job\",instance=~\"$instance\"})", "legendFormat": "capacity", "range": true }, { "refId": "B", - "expr": "sum(rust_proxy_request_permits_available)", + "expr": "sum(rust_proxy_request_permits_available{job=~\"$job\",instance=~\"$instance\"})", "legendFormat": "available", "range": true }, { "refId": "C", - "expr": "sum(rust_proxy_request_capacity - rust_proxy_request_permits_available)", + "expr": "sum(rust_proxy_request_capacity{job=~\"$job\",instance=~\"$instance\"} - rust_proxy_request_permits_available{job=~\"$job\",instance=~\"$instance\"})", "legendFormat": "in use", "range": true } @@ -4317,7 +4895,7 @@ "h": 1, "w": 24, "x": 0, - "y": 201 + "y": 228 }, "panels": [] }, @@ -4333,7 +4911,7 @@ "h": 7, "w": 12, "x": 0, - "y": 202 + "y": 229 }, "fieldConfig": { "defaults": { @@ -4364,43 +4942,43 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_vhosts_configured", + "expr": "rust_proxy_vhosts_configured{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "vhosts", "range": true }, { "refId": "B", - "expr": "rust_proxy_redirect_hosts_configured", + "expr": "rust_proxy_redirect_hosts_configured{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "redirects", "range": true }, { "refId": "C", - "expr": "rust_proxy_not_found_hosts_configured", + "expr": "rust_proxy_not_found_hosts_configured{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "404 hosts", "range": true }, { "refId": "D", - "expr": "rust_proxy_stream_hosts_configured", + "expr": "rust_proxy_stream_hosts_configured{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "streams", "range": true }, { "refId": "E", - "expr": "rust_proxy_certificates_configured", + "expr": "rust_proxy_certificates_configured{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "certificates", "range": true }, { "refId": "F", - "expr": "rust_proxy_acl_profiles_configured", + "expr": "rust_proxy_acl_profiles_configured{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "ACL profiles", "range": true }, { "refId": "G", - "expr": "rust_proxy_web_services_configured", + "expr": "rust_proxy_web_services_configured{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "web services", "range": true } @@ -4418,7 +4996,7 @@ "h": 7, "w": 12, "x": 12, - "y": 202 + "y": 229 }, "fieldConfig": { "defaults": { @@ -4449,7 +5027,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_listener_protocol_enabled", + "expr": "rust_proxy_listener_protocol_enabled{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "{{address}} / {{protocol}}", "range": true } @@ -4464,7 +5042,7 @@ "h": 1, "w": 24, "x": 0, - "y": 209 + "y": 236 }, "panels": [] }, @@ -4506,13 +5084,13 @@ "h": 7, "w": 12, "x": 0, - "y": 210 + "y": 237 }, "description": "Seconds until the observed certificate notAfter timestamp.", "targets": [ { "refId": "A", - "expr": "rust_proxy_certificate_renewal_not_after_timestamp_seconds - time()", + "expr": "rust_proxy_certificate_renewal_not_after_timestamp_seconds{job=~\"$job\",instance=~\"$instance\"} - time()", "legendFormat": "{{certificate}}", "range": true } @@ -4556,12 +5134,12 @@ "h": 7, "w": 6, "x": 12, - "y": 210 + "y": 237 }, "targets": [ { "refId": "A", - "expr": "rust_proxy_certificate_renewal_failures", + "expr": "rust_proxy_certificate_renewal_failures{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "{{certificate}}", "range": true } @@ -4579,7 +5157,7 @@ "h": 7, "w": 6, "x": 18, - "y": 210 + "y": 237 }, "fieldConfig": { "defaults": { @@ -4605,7 +5183,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_geoip_loaded", + "expr": "rust_proxy_geoip_loaded{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "loaded", "range": true } @@ -4617,7 +5195,7 @@ "h": 1, "w": 24, "x": 0, - "y": 217 + "y": 244 }, "id": 51, "panels": [], @@ -4687,7 +5265,7 @@ "h": 7, "w": 8, "x": 0, - "y": 218 + "y": 245 }, "id": 52, "options": { @@ -4711,7 +5289,7 @@ "uid": "${DS_PROMETHEUS}" }, "editorMode": "code", - "expr": "rust_proxy_backend_ewma_latency_seconds", + "expr": "rust_proxy_backend_ewma_latency_seconds{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "{{vhost}} / {{backend}}", "range": true, "refId": "A" @@ -4783,7 +5361,7 @@ "h": 7, "w": 8, "x": 8, - "y": 218 + "y": 245 }, "id": 53, "options": { @@ -4807,7 +5385,7 @@ "uid": "${DS_PROMETHEUS}" }, "editorMode": "code", - "expr": "rust_proxy_backend_passive_failures", + "expr": "rust_proxy_backend_passive_failures{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "{{vhost}} / {{backend}}", "range": true, "refId": "A" @@ -4818,7 +5396,7 @@ "uid": "${DS_PROMETHEUS}" }, "editorMode": "code", - "expr": "rust_proxy_backend_consecutive_failures", + "expr": "rust_proxy_backend_consecutive_failures{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "consecutive {{vhost}} / {{backend}}", "range": true, "refId": "B" @@ -4890,7 +5468,7 @@ "h": 7, "w": 8, "x": 16, - "y": 218 + "y": 245 }, "id": 54, "options": { @@ -4914,7 +5492,7 @@ "uid": "${DS_PROMETHEUS}" }, "editorMode": "code", - "expr": "time() - rust_proxy_backend_last_probe_timestamp_seconds", + "expr": "time() - rust_proxy_backend_last_probe_timestamp_seconds{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "{{vhost}} / {{backend}}", "range": true, "refId": "A" @@ -4929,7 +5507,7 @@ "h": 1, "w": 24, "x": 0, - "y": 225 + "y": 252 }, "id": 55, "panels": [], @@ -4999,7 +5577,7 @@ "h": 7, "w": 12, "x": 0, - "y": 226 + "y": 253 }, "id": 56, "options": { @@ -5023,7 +5601,7 @@ "uid": "${DS_PROMETHEUS}" }, "editorMode": "code", - "expr": "rust_proxy_certificate_renewal_next_check_timestamp_seconds - time()", + "expr": "rust_proxy_certificate_renewal_next_check_timestamp_seconds{job=~\"$job\",instance=~\"$instance\"} - time()", "legendFormat": "next check {{certificate}}", "range": true, "refId": "A" @@ -5034,7 +5612,7 @@ "uid": "${DS_PROMETHEUS}" }, "editorMode": "code", - "expr": "time() - rust_proxy_certificate_renewal_last_checked_timestamp_seconds", + "expr": "time() - rust_proxy_certificate_renewal_last_checked_timestamp_seconds{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "since check {{certificate}}", "range": true, "refId": "B" @@ -5106,7 +5684,7 @@ "h": 7, "w": 12, "x": 12, - "y": 226 + "y": 253 }, "id": 57, "options": { @@ -5130,7 +5708,7 @@ "uid": "${DS_PROMETHEUS}" }, "editorMode": "code", - "expr": "rust_proxy_certificate_renewal_status_info", + "expr": "rust_proxy_certificate_renewal_status_info{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "{{certificate}} / {{status}}", "range": true, "refId": "A" @@ -5141,7 +5719,7 @@ "uid": "${DS_PROMETHEUS}" }, "editorMode": "code", - "expr": "rust_proxy_certificate_auto_renew_enabled", + "expr": "rust_proxy_certificate_auto_renew_enabled{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "auto renew {{certificate}}", "range": true, "refId": "B" @@ -5159,7 +5737,7 @@ "h": 1, "w": 24, "x": 0, - "y": 233 + "y": 260 }, "panels": [] }, @@ -5175,7 +5753,7 @@ "h": 7, "w": 6, "x": 0, - "y": 234 + "y": 261 }, "fieldConfig": { "defaults": { @@ -5201,7 +5779,7 @@ "targets": [ { "refId": "A", - "expr": "sum(rate(rust_proxy_traffic_source_requests_total{vhost=~\"$traffic_vhost\",source=\"web_server\"}[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_traffic_source_requests_total{job=~\"$job\",instance=~\"$instance\",vhost=~\"$traffic_vhost\",source=\"web_server\"}[$__rate_interval]))", "legendFormat": "web server", "range": true } @@ -5219,7 +5797,7 @@ "h": 7, "w": 6, "x": 6, - "y": 234 + "y": 261 }, "fieldConfig": { "defaults": { @@ -5245,7 +5823,7 @@ "targets": [ { "refId": "A", - "expr": "rust_proxy_traffic_queue_dropped_total", + "expr": "rust_proxy_traffic_queue_dropped_total{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "dropped", "range": true } @@ -5263,7 +5841,7 @@ "h": 7, "w": 6, "x": 12, - "y": 234 + "y": 261 }, "fieldConfig": { "defaults": { @@ -5288,7 +5866,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (country) (rust_proxy_traffic_country_requests{vhost=~\"$traffic_vhost\"})", + "expr": "sum by (country) (rust_proxy_traffic_country_requests{job=~\"$job\",instance=~\"$instance\",vhost=~\"$traffic_vhost\"})", "legendFormat": "{{country}}", "range": false, "instant": true @@ -5308,7 +5886,7 @@ "h": 7, "w": 6, "x": 18, - "y": 234 + "y": 261 }, "fieldConfig": { "defaults": { @@ -5333,7 +5911,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (family) (rust_proxy_traffic_user_agent_family_requests_total{vhost=~\"$traffic_vhost\"})", + "expr": "sum by (family) (rust_proxy_traffic_user_agent_family_requests_total{job=~\"$job\",instance=~\"$instance\",vhost=~\"$traffic_vhost\"})", "legendFormat": "{{family}}", "range": false, "instant": true @@ -5353,7 +5931,7 @@ "h": 7, "w": 12, "x": 0, - "y": 241 + "y": 268 }, "fieldConfig": { "defaults": { @@ -5384,7 +5962,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (source) (rate(rust_proxy_traffic_source_requests_total{vhost=~\"$traffic_vhost\"}[$__rate_interval]))", + "expr": "sum by (source) (rate(rust_proxy_traffic_source_requests_total{job=~\"$job\",instance=~\"$instance\",vhost=~\"$traffic_vhost\"}[$__rate_interval]))", "legendFormat": "{{source}}", "range": true } @@ -5402,7 +5980,7 @@ "h": 7, "w": 12, "x": 12, - "y": 241 + "y": 268 }, "fieldConfig": { "defaults": { @@ -5433,7 +6011,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (method) (rate(rust_proxy_traffic_method_requests_total{vhost=~\"$traffic_vhost\"}[$__rate_interval]))", + "expr": "sum by (method) (rate(rust_proxy_traffic_method_requests_total{job=~\"$job\",instance=~\"$instance\",vhost=~\"$traffic_vhost\"}[$__rate_interval]))", "legendFormat": "{{method}}", "range": true } @@ -5451,7 +6029,7 @@ "h": 7, "w": 12, "x": 0, - "y": 248 + "y": 275 }, "fieldConfig": { "defaults": { @@ -5482,7 +6060,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (class) (rate(rust_proxy_traffic_status_class_requests_total{vhost=~\"$traffic_vhost\"}[$__rate_interval]))", + "expr": "sum by (class) (rate(rust_proxy_traffic_status_class_requests_total{job=~\"$job\",instance=~\"$instance\",vhost=~\"$traffic_vhost\"}[$__rate_interval]))", "legendFormat": "{{class}}", "range": true } @@ -5500,7 +6078,7 @@ "h": 7, "w": 12, "x": 12, - "y": 248 + "y": 275 }, "fieldConfig": { "defaults": { @@ -5531,7 +6109,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (cache) (rate(rust_proxy_traffic_cache_requests_total{vhost=~\"$traffic_vhost\"}[$__rate_interval]))", + "expr": "sum by (cache) (rate(rust_proxy_traffic_cache_requests_total{job=~\"$job\",instance=~\"$instance\",vhost=~\"$traffic_vhost\"}[$__rate_interval]))", "legendFormat": "{{cache}}", "range": true } @@ -5549,7 +6127,7 @@ "h": 5, "w": 12, "x": 0, - "y": 255 + "y": 282 }, "fieldConfig": { "defaults": { @@ -5576,14 +6154,14 @@ }, "targets": [ { - "expr": "rust_proxy_traffic_country_capture_enabled", + "expr": "rust_proxy_traffic_country_capture_enabled{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "country capture", "refId": "A", "range": false, "instant": true }, { - "expr": "rust_proxy_traffic_user_agent_capture_enabled", + "expr": "rust_proxy_traffic_user_agent_capture_enabled{job=~\"$job\",instance=~\"$instance\"}", "legendFormat": "User-Agent capture", "refId": "B", "range": false, @@ -5604,7 +6182,7 @@ "h": 5, "w": 12, "x": 12, - "y": 255 + "y": 282 }, "fieldConfig": { "defaults": { @@ -5628,7 +6206,7 @@ }, "targets": [ { - "expr": "sum by (route) (rust_proxy_traffic_route_requests{vhost=~\"$traffic_vhost\"})", + "expr": "sum by (route) (rust_proxy_traffic_route_requests{job=~\"$job\",instance=~\"$instance\",vhost=~\"$traffic_vhost\"})", "legendFormat": "{{route}}", "refId": "A", "range": false, @@ -5646,7 +6224,7 @@ "h": 1, "w": 24, "x": 0, - "y": 260 + "y": 287 }, "panels": [] }, @@ -5662,7 +6240,7 @@ "h": 7, "w": 12, "x": 0, - "y": 261 + "y": 288 }, "fieldConfig": { "defaults": { @@ -5686,13 +6264,13 @@ "targets": [ { "refId": "A", - "expr": "sum(rate(rust_proxy_web_server_requests_total{web_service=~\"$web_service\"}[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_web_server_requests_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval]))", "legendFormat": "All WWW", "range": true }, { "refId": "B", - "expr": "sum(rate(rust_proxy_php_requests_total{web_service=~\"$web_service\"}[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_php_requests_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval]))", "legendFormat": "PHP", "range": true } @@ -5722,7 +6300,7 @@ "h": 7, "w": 12, "x": 12, - "y": 261 + "y": 288 }, "fieldConfig": { "defaults": { @@ -5746,13 +6324,13 @@ "targets": [ { "refId": "A", - "expr": "1e-3 * sum(rate(rust_proxy_web_server_response_header_duration_microseconds_total{web_service=~\"$web_service\"}[$__rate_interval])) / clamp_min(sum(rate(rust_proxy_web_server_requests_total{web_service=~\"$web_service\"}[$__rate_interval])), 1e-9)", + "expr": "1e-3 * sum(rate(rust_proxy_web_server_response_header_duration_microseconds_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval])) / clamp_min(sum(rate(rust_proxy_web_server_requests_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval])), 1e-9)", "legendFormat": "WWW mean", "range": true }, { "refId": "B", - "expr": "1e-3 * sum(rate(rust_proxy_php_response_header_duration_microseconds_total{web_service=~\"$web_service\"}[$__rate_interval])) / clamp_min(sum(rate(rust_proxy_php_requests_total{web_service=~\"$web_service\"}[$__rate_interval])), 1e-9)", + "expr": "1e-3 * sum(rate(rust_proxy_php_response_header_duration_microseconds_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval])) / clamp_min(sum(rate(rust_proxy_php_requests_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval])), 1e-9)", "legendFormat": "PHP mean", "range": true } @@ -5782,7 +6360,7 @@ "h": 7, "w": 8, "x": 0, - "y": 268 + "y": 295 }, "fieldConfig": { "defaults": { @@ -5794,7 +6372,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (class) (rate(rust_proxy_web_server_responses_total{web_service=~\"$web_service\"}[$__rate_interval]))", + "expr": "sum by (class) (rate(rust_proxy_web_server_responses_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval]))", "legendFormat": "{{class}}", "range": true } @@ -5839,7 +6417,7 @@ "h": 7, "w": 8, "x": 8, - "y": 268 + "y": 295 }, "fieldConfig": { "defaults": { @@ -5851,7 +6429,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (kind) (rate(rust_proxy_web_server_request_kind_total{web_service=~\"$web_service\"}[$__rate_interval]))", + "expr": "sum by (kind) (rate(rust_proxy_web_server_request_kind_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval]))", "legendFormat": "{{kind}}", "range": true } @@ -5896,7 +6474,7 @@ "h": 7, "w": 8, "x": 16, - "y": 268 + "y": 295 }, "fieldConfig": { "defaults": { @@ -5910,7 +6488,7 @@ "targets": [ { "refId": "A", - "expr": "100 * sum(rate(rust_proxy_web_server_responses_total{web_service=~\"$web_service\",class=\"5xx\"}[$__rate_interval])) / clamp_min(sum(rate(rust_proxy_web_server_requests_total{web_service=~\"$web_service\"}[$__rate_interval])), 1e-9)", + "expr": "100 * sum(rate(rust_proxy_web_server_responses_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\",class=\"5xx\"}[$__rate_interval])) / clamp_min(sum(rate(rust_proxy_web_server_requests_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval])), 1e-9)", "legendFormat": "5xx share", "range": true } @@ -5941,7 +6519,7 @@ "h": 7, "w": 12, "x": 0, - "y": 275 + "y": 302 }, "fieldConfig": { "defaults": { @@ -5965,13 +6543,13 @@ "targets": [ { "refId": "A", - "expr": "sum(rate(rust_proxy_web_server_response_body_bytes_total{web_service=~\"$web_service\"}[$__rate_interval])) - (sum(rate(rust_proxy_php_response_body_bytes_total{web_service=~\"$web_service\"}[$__rate_interval])) or vector(0))", + "expr": "sum(rate(rust_proxy_web_server_response_body_bytes_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval])) - (sum(rate(rust_proxy_php_response_body_bytes_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval])) or vector(0))", "legendFormat": "Non-PHP", "range": true }, { "refId": "B", - "expr": "sum(rate(rust_proxy_php_response_body_bytes_total{web_service=~\"$web_service\"}[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_php_response_body_bytes_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval]))", "legendFormat": "PHP", "range": true } @@ -6001,7 +6579,7 @@ "h": 7, "w": 12, "x": 12, - "y": 275 + "y": 302 }, "fieldConfig": { "defaults": { @@ -6025,7 +6603,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (class) (rate(rust_proxy_web_server_responses_total{web_service=~\"$web_service\"}[$__rate_interval]))", + "expr": "sum by (class) (rate(rust_proxy_web_server_responses_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval]))", "legendFormat": "{{class}}", "range": true } @@ -6052,7 +6630,7 @@ "h": 1, "w": 24, "x": 0, - "y": 282 + "y": 309 }, "panels": [] }, @@ -6068,7 +6646,7 @@ "h": 6, "w": 6, "x": 0, - "y": 283 + "y": 310 }, "fieldConfig": { "defaults": { @@ -6080,7 +6658,7 @@ "targets": [ { "refId": "A", - "expr": "sum(rate(rust_proxy_php_requests_total{web_service=~\"$web_service\"}[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_php_requests_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval]))", "legendFormat": "PHP/s", "range": true } @@ -6113,7 +6691,7 @@ "h": 6, "w": 6, "x": 6, - "y": 283 + "y": 310 }, "fieldConfig": { "defaults": { @@ -6127,7 +6705,7 @@ "targets": [ { "refId": "A", - "expr": "100 * sum(rust_proxy_php_concurrency_in_use{web_service=~\"$web_service\"}) / clamp_min(sum(rust_proxy_php_concurrency_limit{web_service=~\"$web_service\"}),1)", + "expr": "100 * sum(rust_proxy_php_concurrency_in_use{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}) / clamp_min(sum(rust_proxy_php_concurrency_limit{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}),1)", "legendFormat": "RustProxy permits", "range": true } @@ -6158,7 +6736,7 @@ "h": 6, "w": 12, "x": 12, - "y": 283 + "y": 310 }, "fieldConfig": { "defaults": { @@ -6182,19 +6760,19 @@ "targets": [ { "refId": "A", - "expr": "sum(rust_proxy_php_concurrency_in_use{web_service=~\"$web_service\"})", + "expr": "sum(rust_proxy_php_concurrency_in_use{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"})", "legendFormat": "In use", "range": true }, { "refId": "B", - "expr": "sum(rust_proxy_php_concurrency_available{web_service=~\"$web_service\"})", + "expr": "sum(rust_proxy_php_concurrency_available{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"})", "legendFormat": "Available", "range": true }, { "refId": "C", - "expr": "sum(rust_proxy_php_concurrency_limit{web_service=~\"$web_service\"})", + "expr": "sum(rust_proxy_php_concurrency_limit{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"})", "legendFormat": "Limit", "range": true } @@ -6224,7 +6802,7 @@ "h": 7, "w": 12, "x": 0, - "y": 289 + "y": 316 }, "fieldConfig": { "defaults": { @@ -6248,7 +6826,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (reason) (rate(rust_proxy_php_failures_total{web_service=~\"$web_service\"}[$__rate_interval]))", + "expr": "sum by (reason) (rate(rust_proxy_php_failures_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval]))", "legendFormat": "{{reason}}", "range": true } @@ -6278,7 +6856,7 @@ "h": 7, "w": 12, "x": 12, - "y": 289 + "y": 316 }, "fieldConfig": { "defaults": { @@ -6290,7 +6868,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (class) (rate(rust_proxy_php_responses_total{web_service=~\"$web_service\"}[$__rate_interval]))", + "expr": "sum by (class) (rate(rust_proxy_php_responses_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval]))", "legendFormat": "{{class}}", "range": true } @@ -6332,7 +6910,7 @@ "h": 1, "w": 24, "x": 0, - "y": 296 + "y": 323 }, "panels": [] }, @@ -6348,7 +6926,7 @@ "h": 7, "w": 12, "x": 0, - "y": 297 + "y": 324 }, "fieldConfig": { "defaults": { @@ -6360,7 +6938,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (web_service) (rate(rust_proxy_web_server_requests_total{web_service=~\"$web_service\"}[$__rate_interval]))", + "expr": "sum by (web_service) (rate(rust_proxy_web_server_requests_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval]))", "legendFormat": "{{web_service}}", "range": true } @@ -6391,7 +6969,7 @@ "h": 7, "w": 12, "x": 12, - "y": 297 + "y": 324 }, "fieldConfig": { "defaults": { @@ -6415,7 +6993,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (method) (rate(rust_proxy_web_server_methods_total{web_service=~\"$web_service\"}[$__rate_interval]))", + "expr": "sum by (method) (rate(rust_proxy_web_server_methods_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval]))", "legendFormat": "{{method}}", "range": true } @@ -6445,7 +7023,7 @@ "h": 7, "w": 12, "x": 0, - "y": 304 + "y": 331 }, "fieldConfig": { "defaults": { @@ -6469,7 +7047,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (status) (rate(rust_proxy_web_server_status_code_total{web_service=~\"$web_service\"}[$__rate_interval]))", + "expr": "sum by (status) (rate(rust_proxy_web_server_status_code_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval]))", "legendFormat": "{{status}}", "range": true } @@ -6499,7 +7077,7 @@ "h": 7, "w": 12, "x": 12, - "y": 304 + "y": 331 }, "fieldConfig": { "defaults": { @@ -6523,7 +7101,7 @@ "targets": [ { "refId": "A", - "expr": "sum by (web_service) (rate(rust_proxy_php_failures_total{web_service=~\"$web_service\"}[$__rate_interval]))", + "expr": "sum by (web_service) (rate(rust_proxy_php_failures_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval]))", "legendFormat": "{{web_service}}", "range": true } @@ -6550,7 +7128,7 @@ "h": 1, "w": 24, "x": 0, - "y": 311 + "y": 338 }, "panels": [] }, @@ -6566,7 +7144,7 @@ "h": 7, "w": 12, "x": 0, - "y": 312 + "y": 339 }, "fieldConfig": { "defaults": { @@ -6590,13 +7168,13 @@ "targets": [ { "refId": "A", - "expr": "sum(rate(rust_proxy_cache_hits_total[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_cache_hits_total{job=~\"$job\",instance=~\"$instance\"}[$__rate_interval]))", "legendFormat": "Cache HIT/s", "range": true }, { "refId": "B", - "expr": "sum(rate(rust_proxy_php_requests_total{web_service=~\"$web_service\"}[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_php_requests_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval]))", "legendFormat": "PHP/s", "range": true } @@ -6626,7 +7204,7 @@ "h": 7, "w": 12, "x": 12, - "y": 312 + "y": 339 }, "fieldConfig": { "defaults": { @@ -6650,13 +7228,13 @@ "targets": [ { "refId": "A", - "expr": "sum(rate(rust_proxy_web_server_responses_total{web_service=~\"$web_service\",class=\"5xx\"}[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_web_server_responses_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\",class=\"5xx\"}[$__rate_interval]))", "legendFormat": "WWW 5xx/s", "range": true }, { "refId": "B", - "expr": "sum(rate(rust_proxy_php_failures_total{web_service=~\"$web_service\",reason=~\".*timeout\"}[$__rate_interval]))", + "expr": "sum(rate(rust_proxy_php_failures_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\",reason=~\".*timeout\"}[$__rate_interval]))", "legendFormat": "PHP timeouts/s", "range": true } @@ -6686,7 +7264,7 @@ "h": 7, "w": 12, "x": 0, - "y": 319 + "y": 346 }, "fieldConfig": { "defaults": { @@ -6711,12 +7289,830 @@ "targets": [ { "refId": "A", - "expr": "sum by (encoding) (rate(rust_proxy_web_server_compression_total{web_service=~\"$web_service\"}[$__rate_interval]))", + "expr": "sum by (encoding) (rate(rust_proxy_web_server_compression_total{job=~\"$job\",instance=~\"$instance\",web_service=~\"$web_service\"}[$__rate_interval]))", "legendFormat": "{{encoding}}", "range": true } ], "description": "Only downstream compression performed by RustProxy; already precompressed files are not counted." + }, + { + "id": 144, + "type": "row", + "title": "Docker hosts and alerts", + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 353 + }, + "panels": [] + }, + { + "id": 145, + "type": "stat", + "title": "Docker agents up", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 5, + "w": 4, + "x": 0, + "y": 354 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": {} + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "values": false, + "calcs": [ + "lastNotNull" + ], + "fields": "" + }, + "orientation": "auto", + "textMode": "auto", + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto" + }, + "targets": [ + { + "refId": "A", + "expr": "sum(rust_proxy_docker_agent_up{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"})", + "legendFormat": "", + "range": true + } + ], + "description": "Agents whose last poll succeeded." + }, + { + "id": 146, + "type": "stat", + "title": "Active Docker alerts", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 5, + "w": 4, + "x": 4, + "y": 354 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": {}, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "orange", + "value": 1 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "values": false, + "calcs": [ + "lastNotNull" + ], + "fields": "" + }, + "orientation": "auto", + "textMode": "auto", + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto" + }, + "targets": [ + { + "refId": "A", + "expr": "sum(rust_proxy_docker_alerts_active{job=~\"$job\",instance=~\"$instance\"})", + "legendFormat": "", + "range": true + } + ] + }, + { + "id": 147, + "type": "stat", + "title": "Running containers", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 5, + "w": 4, + "x": 8, + "y": 354 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": {} + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "values": false, + "calcs": [ + "lastNotNull" + ], + "fields": "" + }, + "orientation": "auto", + "textMode": "auto", + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto" + }, + "targets": [ + { + "refId": "A", + "expr": "sum(rust_proxy_docker_host_containers_running{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"})", + "legendFormat": "", + "range": true + } + ] + }, + { + "id": 148, + "type": "table", + "title": "Docker alerts", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 10, + "w": 12, + "x": 12, + "y": 354 + }, + "fieldConfig": { + "defaults": { + "custom": { + "align": "auto", + "cellOptions": { + "type": "auto" + } + } + }, + "overrides": [] + }, + "options": { + "showHeader": true, + "cellHeight": "sm", + "footer": { + "show": false + } + }, + "targets": [ + { + "refId": "A", + "expr": "max by (instance, agent, kind, severity, service) (rust_proxy_docker_alert{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"})", + "format": "table", + "instant": true, + "range": false + } + ], + "transformations": [ + { + "id": "merge", + "options": {} + }, + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "__name__": true, + "Value": true + }, + "renameByName": { + "instance": "RustProxy", + "agent": "Agent", + "kind": "Alert", + "severity": "Severity", + "service": "Service", + "Value": "" + } + } + } + ], + "description": "Agent offline, disk/memory/load thresholds, missing published service, unhealthy container and invalid labels." + }, + { + "id": 149, + "type": "stat", + "title": "Busiest host CPU", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 5, + "w": 6, + "x": 0, + "y": 359 + }, + "fieldConfig": { + "defaults": { + "unit": "percent", + "custom": {}, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "orange", + "value": 75 + }, + { + "color": "red", + "value": 90 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "values": false, + "calcs": [ + "lastNotNull" + ], + "fields": "" + }, + "orientation": "auto", + "textMode": "auto", + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto" + }, + "targets": [ + { + "refId": "A", + "expr": "max(rust_proxy_docker_host_cpu_percent{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"})", + "legendFormat": "", + "range": true + } + ] + }, + { + "id": 150, + "type": "stat", + "title": "Fullest disk", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 5, + "w": 6, + "x": 6, + "y": 359 + }, + "fieldConfig": { + "defaults": { + "unit": "percent", + "custom": {}, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "orange", + "value": 80 + }, + { + "color": "red", + "value": 90 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "values": false, + "calcs": [ + "lastNotNull" + ], + "fields": "" + }, + "orientation": "auto", + "textMode": "auto", + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto" + }, + "targets": [ + { + "refId": "A", + "expr": "max(100 * (1 - rust_proxy_docker_host_disk_free_bytes{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"} / rust_proxy_docker_host_disk_total_bytes{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"}))", + "legendFormat": "", + "range": true + } + ] + }, + { + "id": 151, + "type": "timeseries", + "title": "Docker host CPU", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 364 + }, + "fieldConfig": { + "defaults": { + "unit": "percent", + "custom": { + "drawStyle": "line", + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "expr": "max by (agent) (rust_proxy_docker_host_cpu_percent{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"})", + "legendFormat": "{{agent}}", + "range": true + } + ] + }, + { + "id": 152, + "type": "timeseries", + "title": "Docker host memory used", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 364 + }, + "fieldConfig": { + "defaults": { + "unit": "percent", + "custom": { + "drawStyle": "line", + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "expr": "max by (agent) (100 * (1 - rust_proxy_docker_host_memory_available_bytes{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"} / rust_proxy_docker_host_memory_total_bytes{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"}))", + "legendFormat": "{{agent}}", + "range": true + } + ] + }, + { + "id": 153, + "type": "timeseries", + "title": "Docker host load per CPU", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 364 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "drawStyle": "line", + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "expr": "max by (agent) (rust_proxy_docker_host_load{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",period=\"5m\"} / rust_proxy_docker_host_cpu_count{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"})", + "legendFormat": "{{agent}}", + "range": true + } + ] + }, + { + "id": 154, + "type": "timeseries", + "title": "Docker host disk used", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 372 + }, + "fieldConfig": { + "defaults": { + "unit": "percent", + "custom": { + "drawStyle": "line", + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "expr": "max by (agent) (100 * (1 - rust_proxy_docker_host_disk_free_bytes{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"} / rust_proxy_docker_host_disk_total_bytes{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"}))", + "legendFormat": "{{agent}}", + "range": true + } + ] + }, + { + "id": 155, + "type": "timeseries", + "title": "Docker host network", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 372 + }, + "fieldConfig": { + "defaults": { + "unit": "Bps", + "custom": { + "drawStyle": "line", + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "expr": "max by (agent) (rust_proxy_docker_host_network_receive_bytes_per_second{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"})", + "legendFormat": "{{agent}} RX", + "range": true + }, + { + "refId": "B", + "expr": "-max by (agent) (rust_proxy_docker_host_network_transmit_bytes_per_second{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"})", + "legendFormat": "{{agent}} TX", + "range": true + } + ], + "description": "Receive positive, transmit negative." + }, + { + "id": 156, + "type": "timeseries", + "title": "Containers by host", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 372 + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "drawStyle": "line", + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "expr": "max by (agent) (rust_proxy_docker_host_containers_running{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"})", + "legendFormat": "{{agent}} running", + "range": true + }, + { + "refId": "B", + "expr": "max by (agent) (rust_proxy_docker_host_containers{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"})", + "legendFormat": "{{agent}} total", + "range": true + } + ] + }, + { + "id": 157, + "type": "timeseries", + "title": "Top container CPU", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 380 + }, + "fieldConfig": { + "defaults": { + "unit": "percent", + "custom": { + "drawStyle": "line", + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "expr": "topk(10, max by (agent, container) (rust_proxy_docker_container_cpu_percent{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"}))", + "legendFormat": "{{agent}}/{{container}}", + "range": true + } + ] + }, + { + "id": 158, + "type": "timeseries", + "title": "Top container memory", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 380 + }, + "fieldConfig": { + "defaults": { + "unit": "bytes", + "custom": { + "drawStyle": "line", + "lineWidth": 1, + "fillOpacity": 10, + "showPoints": "never", + "stacking": { + "mode": "none" + } + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "targets": [ + { + "refId": "A", + "expr": "topk(10, max by (agent, container) (rust_proxy_docker_container_memory_bytes{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"}))", + "legendFormat": "{{agent}}/{{container}}", + "range": true + } + ] + }, + { + "id": 159, + "type": "table", + "title": "Unhealthy containers", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 380 + }, + "fieldConfig": { + "defaults": { + "custom": { + "align": "auto", + "cellOptions": { + "type": "auto" + } + } + }, + "overrides": [] + }, + "options": { + "showHeader": true, + "cellHeight": "sm", + "footer": { + "show": false + } + }, + "targets": [ + { + "refId": "A", + "expr": "max by (agent, container, state, health) (rust_proxy_docker_container_state_info{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"}) and on (agent, container) (max by (agent, container, state, health) (rust_proxy_docker_container_state_info{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",health=\"unhealthy\"}) or max by (agent, container, state, health) (rust_proxy_docker_container_state_info{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\",state=~\"restarting|exited|dead\"}))", + "format": "table", + "instant": true, + "range": false + } + ], + "transformations": [ + { + "id": "merge", + "options": {} + }, + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "__name__": true, + "Value": true + }, + "renameByName": { + "agent": "Agent", + "container": "Container", + "state": "State", + "health": "Health", + "Value": "" + } + } + } + ] } ], "refresh": "15s", @@ -6740,6 +8136,66 @@ "hide": 0, "refresh": 1 }, + { + "name": "job", + "label": "Job", + "type": "query", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "query": { + "qryType": 1, + "query": "rust_proxy_build_info", + "label": "job", + "refId": "PrometheusVariableQueryEditor-VariableQuery" + }, + "definition": "label_values(rust_proxy_build_info, job)", + "current": { + "selected": false, + "text": "All", + "value": "$__all" + }, + "hide": 0, + "includeAll": true, + "allValue": ".*", + "multi": true, + "options": [], + "refresh": 2, + "regex": "", + "skipUrlSync": false, + "sort": 1 + }, + { + "name": "instance", + "label": "RustProxy server", + "type": "query", + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "query": { + "qryType": 1, + "query": "rust_proxy_build_info{job=~\"$job\"}", + "label": "instance", + "refId": "PrometheusVariableQueryEditor-VariableQuery" + }, + "definition": "label_values(rust_proxy_build_info{job=~\"$job\"}, instance)", + "current": { + "selected": false, + "text": "All", + "value": "$__all" + }, + "hide": 0, + "includeAll": true, + "allValue": ".*", + "multi": true, + "options": [], + "refresh": 2, + "regex": "", + "skipUrlSync": false, + "sort": 1 + }, { "name": "traffic_vhost", "label": "Traffic vhost", @@ -6750,11 +8206,11 @@ }, "query": { "qryType": 1, - "query": "rust_proxy_traffic_requests_total", + "query": "rust_proxy_traffic_requests_total{job=~\"$job\",instance=~\"$instance\"}", "label": "vhost", "refId": "PrometheusVariableQueryEditor-VariableQuery" }, - "definition": "label_values(rust_proxy_traffic_requests_total, vhost)", + "definition": "label_values(rust_proxy_traffic_requests_total{job=~\"$job\",instance=~\"$instance\"}, vhost)", "current": { "selected": false, "text": "All", @@ -6780,11 +8236,11 @@ }, "query": { "qryType": 1, - "query": "rust_proxy_docker_agent_enabled", + "query": "rust_proxy_docker_agent_enabled{job=~\"$job\",instance=~\"$instance\"}", "label": "agent", "refId": "PrometheusVariableQueryEditor-VariableQuery" }, - "definition": "label_values(rust_proxy_docker_agent_enabled, agent)", + "definition": "label_values(rust_proxy_docker_agent_enabled{job=~\"$job\",instance=~\"$instance\"}, agent)", "current": { "selected": false, "text": "All", @@ -6810,11 +8266,11 @@ }, "query": { "qryType": 1, - "query": "rust_proxy_docker_vhost_enabled{agent=~\"$docker_agent\"}", + "query": "rust_proxy_docker_vhost_enabled{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"}", "label": "service", "refId": "PrometheusVariableQueryEditor-VariableQuery" }, - "definition": "label_values(rust_proxy_docker_vhost_enabled{agent=~\"$docker_agent\"}, service)", + "definition": "label_values(rust_proxy_docker_vhost_enabled{job=~\"$job\",instance=~\"$instance\",agent=~\"$docker_agent\"}, service)", "current": { "selected": false, "text": "All", @@ -6840,11 +8296,11 @@ }, "query": { "qryType": 1, - "query": "rust_proxy_web_server_requests_total", + "query": "rust_proxy_web_server_requests_total{job=~\"$job\",instance=~\"$instance\"}", "label": "web_service", "refId": "PrometheusVariableQueryEditor-VariableQuery" }, - "definition": "label_values(rust_proxy_web_server_requests_total, web_service)", + "definition": "label_values(rust_proxy_web_server_requests_total{job=~\"$job\",instance=~\"$instance\"}, web_service)", "current": { "selected": false, "text": "All", @@ -6870,7 +8326,7 @@ "timezone": "browser", "title": "RustProxy 0.34.15 - Operations", "uid": "rustproxy-0170", - "version": 7, + "version": 8, "weekStart": "", - "description": "RustProxy 0.34.15 Prometheus operations dashboard: traffic and errors, vhosts and backends, Docker discovery, cache capacity and pressure, process and system diagnostics, HTTP/2, HTTP/3, TLS, WebSockets, Layer-4 streams, log sinks, Web Server and PHP-FPM. Some metrics are optional depending on exporter collector settings and enabled services." -} \ No newline at end of file + "description": "RustProxy 0.34.15 Prometheus operations dashboard: traffic and errors, vhosts and backends, Docker discovery, cache capacity and pressure, process and system diagnostics, HTTP/2, HTTP/3, TLS, WebSockets, Layer-4 streams, log sinks, Web Server and PHP-FPM. Some metrics are optional depending on exporter collector settings and enabled services. Supports several RustProxy servers (Job / RustProxy server variables) and Docker/Podman host diagnostics and alerts." +} diff --git a/integrations/routeros-oci-build/README.md b/integrations/routeros-oci-build/README.md index 16222b6..f66a201 100644 --- a/integrations/routeros-oci-build/README.md +++ b/integrations/routeros-oci-build/README.md @@ -77,10 +77,10 @@ ENV_FILE=integrations/routeros-oci-build/.env \ bash integrations/routeros-oci-build/build-routeros-oci.sh push ``` -For example, with RustProxy version `0.36.13` and the defaults this publishes: +For example, with RustProxy version `0.37.0` and the defaults this publishes: ```text -oci.example.net/network/rustproxy:0.36.13 +oci.example.net/network/rustproxy:0.37.0 oci.example.net/network/rustproxy:latest oci.example.net/network/rustproxy:routeros ``` diff --git a/langs/en_US.json b/langs/en_US.json index 7392294..2dbff43 100644 --- a/langs/en_US.json +++ b/langs/en_US.json @@ -1564,15 +1564,15 @@ "prometheusTrustedNoTokenHelp": "Clients still must match Allowed client CIDRs. Enable only on a private, trusted monitoring network; forwarded headers are never trusted for this check.", "docker-vhosts": "Docker vhosts", "docker-vhostsTitle": "Docker services, named.", - "docker-vhostsDescription": "Discover published Docker ports and map services to base-domain names, custom domains and aliases without copying observed state into SQLite.", + "docker-vhostsDescription": "Discover published Docker and Podman ports and map services to names under the agent domains, with aliases, without copying observed state into SQLite.", "dockerVhosts": "Docker vhosts", - "dockerVhostsIntro": "Published TCP ports discovered by configured Docker agents. Map each service to a short name under the agent base domain or to any FQDN, add aliases, choose the Docker host IP, and inspect or tune live backend health.", + "dockerVhostsIntro": "Published TCP ports discovered by configured Docker/Podman agents. Map each service to a name under one of the agent domains (its master domain), add aliases, choose the Docker host IP, and inspect or tune live backend health for every published service.", "dockerDiscovery": "DOCKER DISCOVERY", "dockerRefresh": "Refresh agents", "dockerAgentsSettings": "Docker agents settings", "dockerAgents": "Docker agents", "dockerDesiredState": "DESIRED STATE / SQLITE", - "dockerAgentsHelp": "Configure one agent per Docker host. HTTPS with a persistent self-signed certificate is the agent default; paste its SHA-256 fingerprint to pin it. Each agent keeps its own base domain and optional default backend IP.", + "dockerAgentsHelp": "Configure one agent per Docker or Podman host. Paste the provisioning code printed by \"rustproxy-docker-agent provision-code\" to fill in the endpoint, token and pinned certificate at once. Each agent has its own domains, certificates and optional default backend IP.", "dockerAgentAdd": "Add Docker agent", "dockerAgentsSave": "Save and connect agents", "dockerAgent": "DOCKER AGENT", @@ -1581,7 +1581,7 @@ "dockerAgentName": "Display name", "dockerAgentEndpoint": "Agent endpoint", "dockerAgentToken": "Bearer token", - "dockerBaseDomain": "Base domain", + "dockerBaseDomain": "Domains", "dockerTargetOverride": "Target IP override", "dockerTargetAuto": "automatic", "dockerListeners": "Listeners", @@ -1604,10 +1604,10 @@ "dockerDefaultTarget": "Default backend IP", "dockerDetectedIps": "Detected host IPs", "dockerHostname": "Hostname", - "dockerHostnameHelp": "Short names use {domain}; a full FQDN uses its own domain.", + "dockerHostnameHelp": "Short names use .{domain}; a full name must be inside the agent domains.", "dockerAliases": "Aliases", "dockerAliasAdd": "Add alias", - "dockerAliasesHelp": "Add aliases with Enter or comma. Short names use the agent base domain; full FQDNs are kept as entered.", + "dockerAliasesHelp": "Add aliases with Enter or comma. Short names use the master domain (or the domain chosen next to the input); full names must be inside the agent domains.", "dockerBackendIp": "Backend host IP", "dockerBackendIpAuto": "Auto / agent default", "dockerBackendScheme": "Backend protocol", @@ -3096,6 +3096,133 @@ "dashboardPresetsConflict": "Preset already exists or was removed. Refresh and try again.", "overviewLayoutInlineDragging": "Dragging: drop the block on the dashed frame. Esc restores its previous position.", "overviewLayoutInlineCompact": "Fill gaps", - "overviewLayoutInlineCompactHint": "Move blocks into empty grid space once (you can still cancel before saving)" + "overviewLayoutInlineCompactHint": "Move blocks into empty grid space once (you can still cancel before saving)", + "choicePickerAddHint": "Press Enter to add \"{value}\"", + "choicePickerEmpty": "Nothing to choose yet", + "dockerAgentDiagnostics": "Agent diagnostics", + "dockerAgentSystem": "Host system", + "dockerAliasDomain": "Domain for short aliases", + "dockerAliasOutsideDomains": "{host} is outside this agent's domains ({domains})", + "dockerCertificateAuto": "Automatic (global SNI / default certificate)", + "dockerCertificateAutoHelp": "Each name gets a certificate from the stored certificates by SNI, like a vhost left on the global default.", + "dockerCertificateHintAuto": "Certificate: automatic (SNI)", + "dockerCertificateHintForced": "No selected certificate covers these names; {id} is forced", + "dockerCertificateHintGeneric": "No selected certificate covers these names; the generic SNI/default certificate is used", + "dockerCertificateHintMatched": "Certificate: {id} (covers all names)", + "dockerCertificateSelected": "Selected certificates", + "dockerCertificateSelectedHelp": "A generated vhost uses the selected certificate that covers all its names (exact names win, then the narrowest); otherwise the generic SNI/default certificate.", + "dockerCertificateUnknown": "Certificate not found", + "dockerCertificates": "Certificates", + "dockerCertificatesChoose": "Choose certificates", + "dockerCertificatesEmpty": "No certificates are stored yet", + "dockerCertificatesNone": "No certificate selected", + "dockerCertificatesRequired": "Select at least one certificate or switch to automatic mode", + "dockerCertificatesSelected": "{count} certificates selected", + "dockerDefaultTargetHelp": "Address used for every Docker vhost of this agent unless a service picks its own. Automatic chooses per service from the detected host addresses.", + "dockerDomainInvalid": "Invalid domain", + "dockerDomainMaster": "Master domain: default for new Docker vhosts", + "dockerDomainMasterShort": "master", + "dockerDomains": "Domains", + "dockerDomainsAddHint": "Press Enter to add domain \"{value}\"", + "dockerDomainsChoose": "Choose or type domains", + "dockerDomainsEmpty": "Type a domain such as docker1.lab.local and press Enter", + "dockerDomainsHelp": "DNS suffixes this agent may publish under. The first (★) is the master domain used by new Docker vhosts; click ★ on another domain to make it the master. Every Docker vhost can still pick its own master domain and aliases from this list.", + "dockerDomainsNone": "No domain assigned", + "dockerDomainsRequired": "Assign at least one domain to the agent", + "dockerDomainsSearch": "Search or type a new domain", + "dockerDomainsSelected": "{count} domains", + "dockerMasterDomain": "Master domain", + "dockerProvisionAdd": "Paste provisioning code", + "dockerProvisionApplied": "Filled from the provisioning code: {endpoint}. Review and save.", + "dockerProvisionHelp": "Run \"sudo rustproxy-docker-agent provision-code\" on the Docker host and paste the RPDA1-… code. One-time codes are redeemed at the agent right away (the token never appears in the code); --static codes contain the secret token.", + "dockerProvisionInvalid": "This is not a valid RPDA1 provisioning code", + "dockerProvisionSummary": "endpoint, token and certificate pin in one paste", + "dockerProvisionTitle": "Provisioning code", + "dockerSystemContainers": "Containers", + "dockerSystemContainersHelp": "Running / all containers", + "dockerSystemCores": "cores", + "dockerSystemCpu": "CPU", + "dockerSystemCpus": "CPUs", + "dockerSystemDisk": "Disk", + "dockerSystemImages": "Images", + "dockerSystemKernel": "Kernel", + "dockerSystemLoad": "Load", + "dockerSystemLoadPerCpu": "load per CPU", + "dockerSystemMemory": "Memory", + "dockerSystemNetwork": "Network", + "dockerSystemNetworkTotal": "Total since boot", + "dockerSystemOs": "System", + "dockerSystemRatePending": "measuring…", + "dockerSystemRuntime": "Runtime", + "dockerSystemSwap": "Swap", + "dockerSystemUptime": "Uptime", + "dockerTargetAutoDetected": "Automatic (per service)", + "dockerTargetCustom": "Custom address…", + "dockerTargetCustomRequired": "Enter the custom backend IP address", + "dockerTargetNoDetected": "No addresses detected yet: save the agent and refresh to list them", + "dockerWidgetAgents": "Docker agents", + "dockerWidgetAgentsDescription": "Connected Docker/Podman agents out of the enabled ones.", + "dockerWidgetApps": "Docker apps", + "dockerWidgetAppsDescription": "Published Docker vhosts whose backend is up, with down, pending and missing services.", + "dockerWidgetAttention": "need attention", + "dockerWidgetBusiestCpu": "Busiest host CPU", + "dockerWidgetContainers": "Containers", + "dockerWidgetContainersDescription": "Running and total containers on all Docker/Podman hosts.", + "dockerWidgetDiscovered": "discovered", + "dockerWidgetDown": "down", + "dockerWidgetLoad": "Docker hosts load", + "dockerWidgetLoadDescription": "CPU, memory and load average of every Docker/Podman host.", + "dockerWidgetMissing": "missing", + "dockerWidgetNetwork": "Docker hosts network", + "dockerWidgetNetworkDescription": "Combined host network receive/transmit rate reported by the agents.", + "dockerWidgetNoSystem": "Agent does not report host data", + "dockerWidgetNoTraffic": "No published Docker app traffic yet", + "dockerWidgetOnline": "online", + "dockerWidgetPending": "checking", + "dockerWidgetRequests": "Docker app requests", + "dockerWidgetRequestsDescription": "Request rate across all published Docker vhosts.", + "dockerWidgetRunning": "running", + "dockerWidgetUnavailable": "No Docker agents", + "dockerWidgetScope": "Docker agent shown by this card", + "dockerWidgetScopeAll": "All agents", + "dockerDomainMakeMaster": "Make master domain", + "dockerAlertAgentOffline": "{agent}: agent unreachable at the last check (last success {since}): {message}", + "dockerAlertContainerUnhealthy": "{agent}: container of {service} is {message}", + "dockerAlertDisk": "Disk usage alert (%)", + "dockerAlertDiskHigh": "{agent}: disk {value}% used (limit {threshold}%)", + "dockerAlertEnabled": "Docker alerts", + "dockerAlertLabelInvalid": "{agent}: labels of {service} were not published: {message}", + "dockerAlertLoad": "Load per CPU alert (5 min)", + "dockerAlertLoadHigh": "{agent}: load per CPU {value} (limit {threshold})", + "dockerAlertMemory": "Memory usage alert (%)", + "dockerAlertMemoryHigh": "{agent}: memory {value}% used (limit {threshold}%)", + "dockerAlertServiceMissing": "Published service disappeared from the inventory", + "dockerAlertServiceMissingText": "{agent}: published service {service} disappeared from the inventory", + "dockerAlertSettings": "Alerts", + "dockerAlertSettingsHelp": "Shown in the application status, as notifications and on Docker vhosts; also exported to Prometheus", + "dockerAlertUnhealthy": "Unhealthy or restarting container", + "dockerAlertsHealth": "Docker", + "dockerAlertsHelp": "Thresholds: Settings → Docker agents → Alerts", + "dockerAlertsNone": "No Docker alerts", + "dockerAlertsTitle": "Docker alerts: {count}", + "dockerContainerRestarts": "restarts", + "dockerContainerStarted": "Started", + "dockerLabelIssue": "LABEL ERROR", + "dockerLabelPublish": "Publish from container labels", + "dockerLabelPublishHelp": "Containers with rustproxy.enable=true are published automatically (rustproxy.host, .domain, .aliases, .scheme, .port, .force_ssl, .websockets, .cache, .compression, .preserve_host). Names must stay inside the agent domains; a manual setting always wins.", + "dockerLabelPublished": "LABELS", + "dockerLabelPublishedHelp": "Published automatically from rustproxy.* container labels. Apply changes to take it over as a manual setting; switching Publish off stores a manual override.", + "dockerProvisionEnrolling": "Redeeming the one-time code at the agent…", + "dockerProvisionExpired": "This one-time code has expired; run provision-code again", + "dockerSystemHistory": "since the page was opened: {minutes} min", + "dockerTestConnection": "Test connection", + "dockerTestFailed": "Connection failed", + "dockerTestOk": "OK: {host}, agent {version}, {services} services, {ms} ms", + "dockerTestRunning": "Testing…", + "dockerContainerHealthy": "healthy", + "dockerContainerUnhealthy": "unhealthy", + "dockerContainerHealthStarting": "health check starting", + "dockerContainerNoHealthcheck": "no health check", + "dockerContainerNoHealthcheckHelp": "The image defines no HEALTHCHECK; only the container state is known. Add a healthcheck to the container to get health alerts." } -} \ No newline at end of file +} diff --git a/langs/pl_pl.json b/langs/pl_pl.json index 7ed8384..ddafda3 100644 --- a/langs/pl_pl.json +++ b/langs/pl_pl.json @@ -1564,15 +1564,15 @@ "prometheusTrustedNoTokenHelp": "Klient nadal musi pasować do listy dozwolonych CIDR. Włączaj tylko w prywatnej, zaufanej sieci monitoringu; nagłówki przekazywane nie są używane do tej decyzji.", "docker-vhosts": "Docker vhosty", "docker-vhostsTitle": "Usługi Dockera pod nazwami.", - "docker-vhostsDescription": "Wykrywaj wystawione porty Dockera i mapuj uslugi na nazwy w domenie agenta, wlasne domeny oraz aliasy bez zapisywania obserwowanego stanu do SQLite.", + "docker-vhostsDescription": "Wykrywaj opublikowane porty Docker i Podman i mapuj usługi na nazwy w domenach agenta, z aliasami, bez kopiowania obserwowanego stanu do SQLite.", "dockerVhosts": "Docker vhosty", - "dockerVhostsIntro": "Wystawione porty TCP wykryte przez skonfigurowane agenty Dockera. Dla każdej usługi ustaw krótką nazwę w domenie agenta albo dowolny FQDN, dodaj aliasy, wybierz IP hosta Dockera oraz sprawdzaj i konfiguruj stan backendu na żywo.", + "dockerVhostsIntro": "Opublikowane porty TCP wykryte przez skonfigurowanych agentów Docker/Podman. Przypisz każdej usłudze nazwę w jednej z domen agenta (jej domenie master), dodaj aliasy, wybierz IP hosta Docker oraz sprawdzaj i dostrajaj stan backendu każdej opublikowanej usługi.", "dockerDiscovery": "WYKRYWANIE DOCKERA", "dockerRefresh": "Odśwież agentów", "dockerAgentsSettings": "Ustawienia agentów Dockera", "dockerAgents": "Agenty Dockera", "dockerDesiredState": "STAN ŻĄDANY / SQLITE", - "dockerAgentsHelp": "Skonfiguruj osobnego agenta dla każdego hosta Dockera. Domyślnie agent używa HTTPS ze stałym certyfikatem self-signed; wklej jego fingerprint SHA-256, aby przypiąć certyfikat. Każdy agent ma własną domenę bazową i opcjonalne domyślne IP backendu.", + "dockerAgentsHelp": "Skonfiguruj jednego agenta na każdy host Docker lub Podman. Wklej kod provisioningu wypisany przez \"rustproxy-docker-agent provision-code\", aby od razu uzupełnić endpoint, token i przypięty certyfikat. Każdy agent ma własne domeny, certyfikaty i opcjonalny domyślny adres IP backendu.", "dockerAgentAdd": "Dodaj agenta Dockera", "dockerAgentsSave": "Zapisz i połącz agentów", "dockerAgent": "AGENT DOCKERA", @@ -1581,7 +1581,7 @@ "dockerAgentName": "Nazwa wyświetlana", "dockerAgentEndpoint": "Adres agenta", "dockerAgentToken": "Token Bearer", - "dockerBaseDomain": "Domena bazowa", + "dockerBaseDomain": "Domeny", "dockerTargetOverride": "Nadpisanie IP docelowego", "dockerTargetAuto": "automatyczne", "dockerListeners": "Listenery", @@ -1604,10 +1604,10 @@ "dockerDefaultTarget": "Domyslne IP backendu", "dockerDetectedIps": "Wykryte adresy IP hosta", "dockerHostname": "Nazwa hosta", - "dockerHostnameHelp": "Krotka nazwa uzyje {domain}; pelny FQDN uzyje wlasnej domeny.", + "dockerHostnameHelp": "Krótkie nazwy używają .{domain}; pełna nazwa musi należeć do domen agenta.", "dockerAliases": "Aliasy", "dockerAliasAdd": "Dodaj alias", - "dockerAliasesHelp": "Dodawaj aliasy klawiszem Enter lub przecinkiem. Krótkie nazwy użyją domeny bazowej agenta, a pełne FQDN pozostaną bez zmian.", + "dockerAliasesHelp": "Dodawaj aliasy klawiszem Enter lub przecinkiem. Krótkie nazwy używają domeny master (lub domeny wybranej obok pola); pełne nazwy muszą należeć do domen agenta.", "dockerBackendIp": "IP hosta backendu", "dockerBackendIpAuto": "Auto / domyslne agenta", "dockerBackendScheme": "Protokol backendu", @@ -3096,6 +3096,133 @@ "dashboardPresetsConflict": "Preset już istnieje lub został usunięty. Odśwież listę i spróbuj ponownie.", "overviewLayoutInlineDragging": "Przeciąganie: upuść blok w miejscu ramki. Esc przywraca poprzednią pozycję.", "overviewLayoutInlineCompact": "Uzupełnij luki", - "overviewLayoutInlineCompactHint": "Dosuń bloki w puste miejsca siatki (jednorazowo, przed zapisaniem możesz to anulować)" + "overviewLayoutInlineCompactHint": "Dosuń bloki w puste miejsca siatki (jednorazowo, przed zapisaniem możesz to anulować)", + "choicePickerAddHint": "Naciśnij Enter, aby dodać \"{value}\"", + "choicePickerEmpty": "Brak pozycji do wyboru", + "dockerAgentDiagnostics": "Diagnostyka agenta", + "dockerAgentSystem": "System hosta", + "dockerAliasDomain": "Domena dla krótkich aliasów", + "dockerAliasOutsideDomains": "{host} jest poza domenami tego agenta ({domains})", + "dockerCertificateAuto": "Automatycznie (globalne SNI / domyślny certyfikat)", + "dockerCertificateAutoHelp": "Każda nazwa dostaje certyfikat z zapisanych certyfikatów według SNI, jak vhost ustawiony na globalny domyślny.", + "dockerCertificateHintAuto": "Certyfikat: automatycznie (SNI)", + "dockerCertificateHintForced": "Żaden wybrany certyfikat nie obejmuje tych nazw; wymuszony {id}", + "dockerCertificateHintGeneric": "Żaden wybrany certyfikat nie obejmuje tych nazw; użyty zostanie ogólny certyfikat SNI/domyślny", + "dockerCertificateHintMatched": "Certyfikat: {id} (obejmuje wszystkie nazwy)", + "dockerCertificateSelected": "Wybrane certyfikaty", + "dockerCertificateSelectedHelp": "Wygenerowany vhost używa wybranego certyfikatu obejmującego wszystkie jego nazwy (pierwszeństwo mają dokładne nazwy, potem najwęższy); w przeciwnym razie ogólnego certyfikatu SNI/domyślnego.", + "dockerCertificateUnknown": "Nie znaleziono certyfikatu", + "dockerCertificates": "Certyfikaty", + "dockerCertificatesChoose": "Wybierz certyfikaty", + "dockerCertificatesEmpty": "Nie ma jeszcze zapisanych certyfikatów", + "dockerCertificatesNone": "Nie wybrano certyfikatu", + "dockerCertificatesRequired": "Wybierz co najmniej jeden certyfikat albo przełącz na tryb automatyczny", + "dockerCertificatesSelected": "Wybrane certyfikaty: {count}", + "dockerDefaultTargetHelp": "Adres używany przez wszystkie vhosty Docker tego agenta, chyba że usługa wybierze własny. Automatycznie wybiera dla każdej usługi spośród wykrytych adresów hosta.", + "dockerDomainInvalid": "Nieprawidłowa domena", + "dockerDomainMaster": "Domena master: domyślna dla nowych vhostów Docker", + "dockerDomainMasterShort": "master", + "dockerDomains": "Domeny", + "dockerDomainsAddHint": "Naciśnij Enter, aby dodać domenę \"{value}\"", + "dockerDomainsChoose": "Wybierz lub wpisz domeny", + "dockerDomainsEmpty": "Wpisz domenę, np. docker1.lab.local, i naciśnij Enter", + "dockerDomainsHelp": "Sufiksy DNS, pod którymi agent może publikować. Pierwsza (★) to domena master używana przez nowe vhosty Docker; kliknij ★ przy innej domenie, aby ustawić ją jako master. Każdy vhost Docker może też wybrać z tej listy własną domenę master i aliasy.", + "dockerDomainsNone": "Brak przypisanej domeny", + "dockerDomainsRequired": "Przypisz agentowi co najmniej jedną domenę", + "dockerDomainsSearch": "Szukaj lub wpisz nową domenę", + "dockerDomainsSelected": "Domeny: {count}", + "dockerMasterDomain": "Domena master", + "dockerProvisionAdd": "Wklej kod provisioningu", + "dockerProvisionApplied": "Uzupełniono z kodu provisioningu: {endpoint}. Sprawdź i zapisz.", + "dockerProvisionHelp": "Uruchom \"sudo rustproxy-docker-agent provision-code\" na hoście Docker i wklej kod RPDA1-…. Kod jednorazowy jest od razu realizowany u agenta (token nie występuje w kodzie); kody --static zawierają tajny token.", + "dockerProvisionInvalid": "To nie jest prawidłowy kod provisioningu RPDA1", + "dockerProvisionSummary": "endpoint, token i przypięty certyfikat jednym wklejeniem", + "dockerProvisionTitle": "Kod provisioningu", + "dockerSystemContainers": "Kontenery", + "dockerSystemContainersHelp": "Działające / wszystkie kontenery", + "dockerSystemCores": "rdzeni", + "dockerSystemCpu": "CPU", + "dockerSystemCpus": "CPU", + "dockerSystemDisk": "Dysk", + "dockerSystemImages": "Obrazy", + "dockerSystemKernel": "Jądro", + "dockerSystemLoad": "Obciążenie", + "dockerSystemLoadPerCpu": "obciążenie na CPU", + "dockerSystemMemory": "Pamięć", + "dockerSystemNetwork": "Sieć", + "dockerSystemNetworkTotal": "Łącznie od startu", + "dockerSystemOs": "System", + "dockerSystemRatePending": "pomiar…", + "dockerSystemRuntime": "Środowisko", + "dockerSystemSwap": "Swap", + "dockerSystemUptime": "Czas pracy", + "dockerTargetAutoDetected": "Automatycznie (dla każdej usługi)", + "dockerTargetCustom": "Własny adres…", + "dockerTargetCustomRequired": "Wpisz własny adres IP backendu", + "dockerTargetNoDetected": "Nie wykryto jeszcze adresów: zapisz agenta i odśwież, aby je wyświetlić", + "dockerWidgetAgents": "Agenci Docker", + "dockerWidgetAgentsDescription": "Połączeni agenci Docker/Podman spośród włączonych.", + "dockerWidgetApps": "Aplikacje Docker", + "dockerWidgetAppsDescription": "Opublikowane vhosty Docker z działającym backendem oraz niedziałające, sprawdzane i brakujące usługi.", + "dockerWidgetAttention": "wymaga uwagi", + "dockerWidgetBusiestCpu": "Najbardziej obciążony CPU hosta", + "dockerWidgetContainers": "Kontenery", + "dockerWidgetContainersDescription": "Działające i wszystkie kontenery na hostach Docker/Podman.", + "dockerWidgetDiscovered": "wykrytych", + "dockerWidgetDown": "nie działa", + "dockerWidgetLoad": "Obciążenie hostów Docker", + "dockerWidgetLoadDescription": "CPU, pamięć i średnie obciążenie każdego hosta Docker/Podman.", + "dockerWidgetMissing": "brakujących", + "dockerWidgetNetwork": "Sieć hostów Docker", + "dockerWidgetNetworkDescription": "Łączny ruch sieciowy odbierany/wysyłany przez hosty, raportowany przez agentów.", + "dockerWidgetNoSystem": "Agent nie raportuje danych hosta", + "dockerWidgetNoTraffic": "Brak ruchu do opublikowanych aplikacji Docker", + "dockerWidgetOnline": "online", + "dockerWidgetPending": "sprawdzane", + "dockerWidgetRequests": "Żądania aplikacji Docker", + "dockerWidgetRequestsDescription": "Liczba żądań na sekundę dla wszystkich opublikowanych vhostów Docker.", + "dockerWidgetRunning": "działające", + "dockerWidgetUnavailable": "Brak agentów Docker", + "dockerWidgetScope": "Agent Docker pokazywany przez tę kartę", + "dockerWidgetScopeAll": "Wszyscy agenci", + "dockerDomainMakeMaster": "Ustaw jako domenę master", + "dockerAlertAgentOffline": "{agent}: agent nieosiągalny przy ostatnim sprawdzeniu (ostatni sukces {since}): {message}", + "dockerAlertContainerUnhealthy": "{agent}: kontener usługi {service} jest w stanie {message}", + "dockerAlertDisk": "Alert zajętości dysku (%)", + "dockerAlertDiskHigh": "{agent}: dysk zajęty w {value}% (próg {threshold}%)", + "dockerAlertEnabled": "Alerty Docker", + "dockerAlertLabelInvalid": "{agent}: etykiety usługi {service} nie zostały opublikowane: {message}", + "dockerAlertLoad": "Alert obciążenia na CPU (5 min)", + "dockerAlertLoadHigh": "{agent}: obciążenie na CPU {value} (próg {threshold})", + "dockerAlertMemory": "Alert zajętości pamięci (%)", + "dockerAlertMemoryHigh": "{agent}: pamięć zajęta w {value}% (próg {threshold}%)", + "dockerAlertServiceMissing": "Opublikowana usługa zniknęła z inwentarza", + "dockerAlertServiceMissingText": "{agent}: opublikowana usługa {service} zniknęła z inwentarza", + "dockerAlertSettings": "Alerty", + "dockerAlertSettingsHelp": "Widoczne w statusie aplikacji, jako powiadomienia i w Docker vhosts; eksportowane też do Prometheusa", + "dockerAlertUnhealthy": "Niezdrowy lub restartujący się kontener", + "dockerAlertsHealth": "Docker", + "dockerAlertsHelp": "Progi: Ustawienia → Agenci Docker → Alerty", + "dockerAlertsNone": "Brak alertów Docker", + "dockerAlertsTitle": "Alerty Docker: {count}", + "dockerContainerRestarts": "restarty", + "dockerContainerStarted": "Uruchomiony", + "dockerLabelIssue": "BŁĄD ETYKIET", + "dockerLabelPublish": "Publikuj z etykiet kontenerów", + "dockerLabelPublishHelp": "Kontenery z rustproxy.enable=true są publikowane automatycznie (rustproxy.host, .domain, .aliases, .scheme, .port, .force_ssl, .websockets, .cache, .compression, .preserve_host). Nazwy muszą należeć do domen agenta; ręczne ustawienie zawsze ma pierwszeństwo.", + "dockerLabelPublished": "ETYKIETY", + "dockerLabelPublishedHelp": "Opublikowane automatycznie z etykiet rustproxy.* kontenera. Zastosuj zmiany, aby przejąć je jako ręczne ustawienie; wyłączenie Publikuj zapisuje ręczne nadpisanie.", + "dockerProvisionEnrolling": "Realizuję jednorazowy kod u agenta…", + "dockerProvisionExpired": "Ten jednorazowy kod wygasł; uruchom provision-code ponownie", + "dockerSystemHistory": "od otwarcia strony: {minutes} min", + "dockerTestConnection": "Testuj połączenie", + "dockerTestFailed": "Połączenie nieudane", + "dockerTestOk": "OK: {host}, agent {version}, usług: {services}, {ms} ms", + "dockerTestRunning": "Testuję…", + "dockerContainerHealthy": "zdrowy", + "dockerContainerUnhealthy": "niezdrowy", + "dockerContainerHealthStarting": "healthcheck startuje", + "dockerContainerNoHealthcheck": "brak healthchecka", + "dockerContainerNoHealthcheckHelp": "Obraz nie definiuje HEALTHCHECK; znany jest tylko stan kontenera. Dodaj healthcheck do kontenera, aby dostawać alerty o jego zdrowiu." } -} \ No newline at end of file +} diff --git a/src/admin/openapi.json b/src/admin/openapi.json index 9af059c..9aecb0b 100644 --- a/src/admin/openapi.json +++ b/src/admin/openapi.json @@ -2,7 +2,7 @@ "openapi": "3.0.3", "info": { "title": "RustProxy Administration API", - "version": "0.36.13", + "version": "0.37.0", "description": "Administration API for the active panel origin. Sign in through the panel; the same-origin HttpOnly cookie authenticates all private operations. Mutations also require the exact Origin, X-RustProxy-Request: 1 and a session-bound X-CSRF-Token. Loopback HTTP is the default; Settings can enable HTTPS before using a non-loopback administration bind. This document contains no live configuration or credentials. Object schemas marked extensible are summaries: full configuration validation is authoritative in Rust. The API also permits explicitly scoped GeneralApiBearer tokens on a narrow route allowlist, with RO/RW and source CIDR checks; API-token management and Prometheus-token management are browser-session-only." }, "servers": [ @@ -1703,6 +1703,67 @@ }, "description": "Configured Docker runtime pool IDs mapped to their primary proxied hostname." }, + "docker": { + "type": "object", + "nullable": true, + "description": "Compact Docker agent summary for the optional Overview Docker cards (null without agents). Also included in the live view.", + "properties": { + "agents": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "observed": { + "type": "boolean" + }, + "ok": { + "type": "boolean" + }, + "checked_at_unix_ms": { + "type": "integer", + "nullable": true + }, + "services": { + "type": "integer", + "nullable": true + }, + "published_pool_ids": { + "type": "array", + "items": { + "type": "string" + } + }, + "missing_services": { + "type": "integer" + }, + "system": { + "nullable": true, + "allOf": [ + { + "$ref": "#/components/schemas/DockerSystemInfo" + } + ] + } + } + } + }, + "alerts": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DockerAlert" + } + } + } + }, "software_update": { "type": "object", "properties": { @@ -3136,7 +3197,13 @@ "hostname": { "type": "string", "maxLength": 253, - "description": "Primary Docker vhost name. A single DNS label is expanded under the agent base_domain; an FQDN is used as-is." + "description": "Primary Docker vhost name. A single DNS label is expanded under the assignment's master domain; an FQDN is used as-is (the panel requires it to be inside the agent domains)." + }, + "domain": { + "type": "string", + "maxLength": 253, + "nullable": true, + "description": "Master domain of this assignment; must be one of the agent domains. Defaults to the first agent domain." }, "aliases": { "type": "array", @@ -3144,7 +3211,7 @@ "type": "string", "maxLength": 253 }, - "description": "Additional labels or FQDN aliases for the same dynamic vhost." + "description": "Additional labels or FQDN aliases for the same dynamic vhost. Labels are expanded under the master domain." }, "target_ip": { "type": "string", @@ -3302,9 +3369,20 @@ "maxLength": 512, "description": "Bearer token shared only with this Docker agent." }, + "domains": { + "type": "array", + "minItems": 1, + "maxItems": 16, + "items": { + "type": "string", + "maxLength": 253 + }, + "description": "DNS suffixes assigned to this agent (since 0.37.0), such as docker1.lab.local or example.com. The first entry is the default master domain of new assignments. Short Docker vhost names and aliases are expanded below the assignment's master domain." + }, "base_domain": { "type": "string", - "description": "Per-agent DNS suffix such as docker1.lab.local. Short Docker vhost names are expanded below this domain; full FQDNs may use any operator-controlled domain." + "deprecated": true, + "description": "Legacy single DNS suffix (before 0.37.0). Accepted on input and migrated into domains; no longer written." }, "default_target_ip": { "type": "string", @@ -3339,11 +3417,21 @@ "default": 30, "description": "How often RustProxy polls this agent for Docker inventory. Manual refresh bypasses this interval." }, + "certificate_ids": { + "type": "array", + "maxItems": 32, + "items": { + "type": "string", + "maxLength": 64 + }, + "description": "Certificates RustProxy may use for this agent's vhosts. Empty means automatic selection (global SNI / default certificate). Otherwise each generated vhost uses the listed certificate covering all its names (exact names win, then the narrowest certificate); when none covers them the generic SNI/default certificate is used, unless the assignment forces a mismatch (then the first listed certificate)." + }, "certificate_id": { "type": "string", "nullable": true, "maxLength": 64, - "description": "Optional configured TLS certificate assigned to every generated vhost for this Docker agent." + "description": "Legacy single certificate (before 0.37.0). Accepted on input and migrated into certificate_ids; no longer written.", + "deprecated": true }, "acl_profile_id": { "type": "string", @@ -3359,6 +3447,11 @@ "maxLength": 64 }, "description": "Up to 8 additional reusable ACL profiles. Explicit IP denies and country blocks beat all allows; otherwise explicit allows combine as OR; unmatched defaults require unanimous allow. Legacy acl_profile_id is still honored. Inline and global policies remain cumulative." + }, + "label_publish": { + "type": "boolean", + "default": false, + "description": "Publish containers with the rustproxy.enable=true label automatically (rustproxy.host, domain, aliases, scheme, port, force_ssl, websockets, cache, compression, preserve_host). Names must stay inside the agent domains and must not collide with existing hosts; an explicit assignment for the same service always wins." } }, "required": [ @@ -3366,7 +3459,6 @@ "name", "endpoint", "token", - "base_domain", "listener_ids" ] }, @@ -3380,6 +3472,9 @@ "items": { "$ref": "#/components/schemas/DockerAgent" } + }, + "alerts": { + "$ref": "#/components/schemas/DockerAlertSettings" } } }, @@ -3416,6 +3511,21 @@ "items": { "$ref": "#/components/schemas/DockerBinding" } + }, + "labels": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "rustproxy.* container labels (agent 1.1.0+, only with ?system=1)." + }, + "container": { + "allOf": [ + { + "$ref": "#/components/schemas/DockerContainerState" + } + ], + "description": "Container state, health, restarts, CPU and memory (agent 1.1.0+)." } }, "required": [ @@ -3467,6 +3577,14 @@ "certificate_sha256": { "type": "string", "description": "SHA-256 fingerprint of the certificate used by the agent HTTPS listener. Empty only when the agent is intentionally running without TLS." + }, + "system": { + "nullable": true, + "allOf": [ + { + "$ref": "#/components/schemas/DockerSystemInfo" + } + ] } }, "required": [ @@ -3505,6 +3623,10 @@ } ], "nullable": true + }, + "last_ok_unix_ms": { + "type": "integer", + "nullable": true } }, "required": [ @@ -3534,6 +3656,29 @@ "items": { "$ref": "#/components/schemas/DockerPoolRoute" } + }, + "alerts": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DockerAlert" + } + }, + "label_issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "agent_id": { + "type": "string" + }, + "service_key": { + "type": "string" + }, + "error": { + "type": "string" + } + } + } } }, "required": [ @@ -3678,6 +3823,22 @@ }, "pool_id": { "type": "string" + }, + "source": { + "type": "string", + "enum": [ + "labels" + ], + "description": "Present for services published from container labels." + }, + "assignment": { + "$ref": "#/components/schemas/DockerAssignment" + }, + "hosts": { + "type": "array", + "items": { + "type": "string" + } } }, "required": [ @@ -3945,6 +4106,30 @@ "stream_traffic", "stream_sessions", "stream_backend_health", + "docker_agents", + "docker_apps", + "docker_requests", + "docker_host_network", + "docker_host_load", + "docker_containers", + "docker_agents_2", + "docker_apps_2", + "docker_requests_2", + "docker_host_network_2", + "docker_host_load_2", + "docker_containers_2", + "docker_agents_3", + "docker_apps_3", + "docker_requests_3", + "docker_host_network_3", + "docker_host_load_3", + "docker_containers_3", + "docker_agents_4", + "docker_apps_4", + "docker_requests_4", + "docker_host_network_4", + "docker_host_load_4", + "docker_containers_4", "backend_health", "backend_activity", "backend_errors", @@ -4033,6 +4218,30 @@ "stream_traffic", "stream_sessions", "stream_backend_health", + "docker_agents", + "docker_apps", + "docker_requests", + "docker_host_network", + "docker_host_load", + "docker_containers", + "docker_agents_2", + "docker_apps_2", + "docker_requests_2", + "docker_host_network_2", + "docker_host_load_2", + "docker_containers_2", + "docker_agents_3", + "docker_apps_3", + "docker_requests_3", + "docker_host_network_3", + "docker_host_load_3", + "docker_containers_3", + "docker_agents_4", + "docker_apps_4", + "docker_requests_4", + "docker_host_network_4", + "docker_host_load_4", + "docker_containers_4", "backend_health", "backend_activity", "backend_errors", @@ -4148,6 +4357,30 @@ "stream_traffic", "stream_sessions", "stream_backend_health", + "docker_agents", + "docker_apps", + "docker_requests", + "docker_host_network", + "docker_host_load", + "docker_containers", + "docker_agents_2", + "docker_apps_2", + "docker_requests_2", + "docker_host_network_2", + "docker_host_load_2", + "docker_containers_2", + "docker_agents_3", + "docker_apps_3", + "docker_requests_3", + "docker_host_network_3", + "docker_host_load_3", + "docker_containers_3", + "docker_agents_4", + "docker_apps_4", + "docker_requests_4", + "docker_host_network_4", + "docker_host_load_4", + "docker_containers_4", "backend_health", "backend_activity", "backend_errors", @@ -4224,6 +4457,30 @@ "stream_traffic", "stream_sessions", "stream_backend_health", + "docker_agents", + "docker_apps", + "docker_requests", + "docker_host_network", + "docker_host_load", + "docker_containers", + "docker_agents_2", + "docker_apps_2", + "docker_requests_2", + "docker_host_network_2", + "docker_host_load_2", + "docker_containers_2", + "docker_agents_3", + "docker_apps_3", + "docker_requests_3", + "docker_host_network_3", + "docker_host_load_3", + "docker_containers_3", + "docker_agents_4", + "docker_apps_4", + "docker_requests_4", + "docker_host_network_4", + "docker_host_load_4", + "docker_containers_4", "backend_health", "backend_activity", "backend_errors", @@ -4514,6 +4771,14 @@ "type": "boolean", "default": true, "description": "Account-scoped Stored Logs sort direction." + }, + "docker_widget_agents": { + "type": "object", + "additionalProperties": { + "type": "string", + "maxLength": 64 + }, + "description": "Account-scoped agent shown by each optional Docker Overview card (card ID → Docker agent ID). A missing card uses all agents." } }, "required": [ @@ -8077,6 +8342,213 @@ "section", "value" ] + }, + "DockerSystemInfo": { + "type": "object", + "description": "Optional host diagnostics reported by Docker agent 1.1.0+ when RustProxy 0.37.0+ requests /v1/inventory?system=1. Every field is optional; unknown fields are ignored.", + "properties": { + "os": { + "type": "string" + }, + "kernel": { + "type": "string" + }, + "arch": { + "type": "string" + }, + "runtime": { + "type": "string", + "description": "docker or podman" + }, + "runtime_version": { + "type": "string" + }, + "uptime_seconds": { + "type": "integer", + "minimum": 0 + }, + "load1": { + "type": "number" + }, + "load5": { + "type": "number" + }, + "load15": { + "type": "number" + }, + "cpu_count": { + "type": "integer", + "minimum": 0 + }, + "cpu_percent": { + "type": "number", + "description": "Host CPU usage between two inventory requests (0-100)." + }, + "memory_total_bytes": { + "type": "integer", + "minimum": 0 + }, + "memory_available_bytes": { + "type": "integer", + "minimum": 0 + }, + "swap_total_bytes": { + "type": "integer", + "minimum": 0 + }, + "swap_free_bytes": { + "type": "integer", + "minimum": 0 + }, + "disk_total_bytes": { + "type": "integer", + "minimum": 0, + "description": "Container data directory filesystem (or /)." + }, + "disk_free_bytes": { + "type": "integer", + "minimum": 0 + }, + "network_rx_bytes": { + "type": "integer", + "minimum": 0, + "description": "Host interfaces without loopback and container/virtual links." + }, + "network_tx_bytes": { + "type": "integer", + "minimum": 0 + }, + "network_rx_bytes_per_second": { + "type": "number" + }, + "network_tx_bytes_per_second": { + "type": "number" + }, + "containers_running": { + "type": "integer", + "minimum": 0 + }, + "containers_total": { + "type": "integer", + "minimum": 0 + }, + "images": { + "type": "integer", + "minimum": 0 + } + } + }, + "DockerAlertSettings": { + "type": "object", + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean", + "default": true + }, + "disk_percent": { + "type": "integer", + "minimum": 50, + "maximum": 100, + "default": 90 + }, + "memory_percent": { + "type": "integer", + "minimum": 50, + "maximum": 100, + "default": 95 + }, + "load_per_cpu": { + "type": "number", + "minimum": 0.1, + "maximum": 64, + "default": 2.0, + "description": "5-minute load average divided by logical CPUs." + }, + "service_missing": { + "type": "boolean", + "default": true + }, + "container_unhealthy": { + "type": "boolean", + "default": true + } + } + }, + "DockerAlert": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "severity": { + "type": "string", + "enum": [ + "warning", + "error" + ] + }, + "kind": { + "type": "string", + "enum": [ + "agent_offline", + "disk_high", + "memory_high", + "load_high", + "service_missing", + "container_unhealthy", + "label_invalid" + ] + }, + "agent_id": { + "type": "string" + }, + "agent_name": { + "type": "string" + }, + "service": { + "type": "string" + }, + "value": { + "type": "number" + }, + "threshold": { + "type": "number" + }, + "since_unix_ms": { + "type": "integer" + }, + "message": { + "type": "string" + } + } + }, + "DockerContainerState": { + "type": "object", + "properties": { + "state": { + "type": "string" + }, + "health": { + "type": "string", + "description": "healthy, unhealthy, starting, none (no HEALTHCHECK defined) or empty when unknown." + }, + "restart_count": { + "type": "integer" + }, + "cpu_percent": { + "type": "number" + }, + "memory_bytes": { + "type": "integer" + }, + "memory_limit_bytes": { + "type": "integer" + }, + "started_at": { + "type": "string" + } + } } } }, @@ -14702,6 +15174,206 @@ } ] } + }, + "/api/docker/test": { + "post": { + "summary": "Test a Docker agent connection before saving", + "tags": [ + "Docker" + ], + "operationId": "post_api_docker_test", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": false, + "required": [ + "endpoint", + "token" + ], + "properties": { + "endpoint": { + "type": "string" + }, + "token": { + "type": "string" + }, + "tls_fingerprint_sha256": { + "type": "string", + "nullable": true + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Result of one inventory request; ok=false carries the error", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "ok": { + "type": "boolean" + }, + "elapsed_ms": { + "type": "integer" + }, + "agent_version": { + "type": "string" + }, + "hostname": { + "type": "string" + }, + "services": { + "type": "integer" + }, + "certificate_sha256": { + "type": "string" + }, + "runtime": { + "type": "string", + "nullable": true + }, + "error": { + "type": "string" + } + } + } + } + } + }, + "401": { + "description": "Authentication required or revoked", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Host, origin or CSRF validation failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/api/docker/enroll": { + "post": { + "summary": "Redeem a one-time Docker agent provisioning code", + "tags": [ + "Docker" + ], + "operationId": "post_api_docker_enroll", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": false, + "required": [ + "endpoint", + "tls_fingerprint_sha256", + "enrollment_token" + ], + "properties": { + "endpoint": { + "type": "string", + "description": "https:// endpoint from the RPDA1 v2 code" + }, + "tls_fingerprint_sha256": { + "type": "string" + }, + "enrollment_token": { + "type": "string" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Permanent agent token", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "token": { + "type": "string", + "description": "Permanent Bearer token returned by the agent over the pinned TLS connection." + } + } + } + } + } + }, + "401": { + "description": "Authentication required or revoked", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Host, origin or CSRF validation failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "502": { + "description": "The agent rejected the code (expired, used or wrong) or could not be reached", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } } }, "tags": [] diff --git a/src/admin/preferences.rs b/src/admin/preferences.rs index 83ec452..862c43f 100644 --- a/src/admin/preferences.rs +++ b/src/admin/preferences.rs @@ -188,6 +188,8 @@ struct AdminPreferences { stream_list_sort: String, #[serde(default)] stream_list_descending: bool, + #[serde(default)] + docker_widget_agents: std::collections::BTreeMap, } impl Default for AdminPreferences { @@ -233,6 +235,7 @@ impl Default for AdminPreferences { notfound_list_descending: false, stream_list_sort: default_stream_list_sort(), stream_list_descending: false, + docker_widget_agents: std::collections::BTreeMap::new(), } } } @@ -416,6 +419,21 @@ fn validate_admin_preferences(preferences: &AdminPreferences) -> Result<(), ApiE "invalid dashboard card width preference".into(), )); } + if preferences.docker_widget_agents.len() > DASHBOARD_WIDGETS.len() + || preferences + .docker_widget_agents + .iter() + .any(|(widget, agent)| { + !widget.starts_with("docker_") + || !DASHBOARD_WIDGETS.iter().any(|entry| entry.id == *widget) + || !crate::config::valid_id(agent) + }) + { + return Err(ApiError( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid Docker dashboard card agent preference".into(), + )); + } if !valid_dashboard_heights(&preferences.dashboard_widget_heights) { return Err(ApiError( StatusCode::UNPROCESSABLE_ENTITY, diff --git a/src/admin/preferences_tests.rs b/src/admin/preferences_tests.rs index 6acad44..ba5af4e 100644 --- a/src/admin/preferences_tests.rs +++ b/src/admin/preferences_tests.rs @@ -361,7 +361,10 @@ fn dashboard_height_preferences_are_optional_bounded_and_reconciled() { assert!(validate_admin_preferences(&prefs).is_ok()); let stored = serde_json::to_string(&prefs).unwrap(); let recovered: AdminPreferences = serde_json::from_str(&stored).unwrap(); - assert_eq!(recovered.dashboard_widget_heights, prefs.dashboard_widget_heights); + assert_eq!( + recovered.dashboard_widget_heights, + prefs.dashboard_widget_heights + ); for rows in [0, 33] { prefs .dashboard_widget_heights @@ -407,3 +410,23 @@ fn sidebar_collapsed_defaults_off_for_new_and_legacy_documents() { assert!(on.sidebar_collapsed); assert!(validate_admin_preferences(&on).is_ok()); } + +#[test] +fn docker_widget_agents_accept_only_docker_cards_and_valid_ids() { + let legacy: AdminPreferences = serde_json::from_str("{}").unwrap(); + assert!(legacy.docker_widget_agents.is_empty()); + let mut prefs = AdminPreferences::default(); + prefs + .docker_widget_agents + .insert("docker_host_load".into(), "node1".into()); + assert!(validate_admin_preferences(&prefs).is_ok()); + prefs + .docker_widget_agents + .insert("requests".into(), "node1".into()); + assert!(validate_admin_preferences(&prefs).is_err()); + prefs.docker_widget_agents.remove("requests"); + prefs + .docker_widget_agents + .insert("docker_apps".into(), "bad id!".into()); + assert!(validate_admin_preferences(&prefs).is_err()); +} diff --git a/src/admin/router.rs b/src/admin/router.rs index 4583227..e0d2be8 100644 --- a/src/admin/router.rs +++ b/src/admin/router.rs @@ -73,6 +73,7 @@ fn admin_app_javascript() -> &'static str { include_str!("web/app/dashboard-presets.js"), include_str!("web/app/dashboard-inline-layout.js"), include_str!("web/app/stream-dashboard.js"), + include_str!("web/app/docker-dashboard.js"), include_str!("web/app/backend-dashboard.js"), include_str!("web/app/overview-extra-metrics.js"), include_str!("web/app/overview-wide-metrics.js"), @@ -174,6 +175,8 @@ pub fn router(state: Arc) -> Router { .route("/api/backends", get(backend_status)) .route("/api/docker", get(docker_status)) .route("/api/docker/refresh", post(docker_refresh)) + .route("/api/docker/test", post(docker_test)) + .route("/api/docker/enroll", post(docker_enroll)) .route("/api/certificates", get(certificate_inventory)) .route( "/api/certificates/inspect", diff --git a/src/admin/status.rs b/src/admin/status.rs index a3de71e..291afaa 100644 --- a/src/admin/status.rs +++ b/src/admin/status.rs @@ -182,7 +182,7 @@ fn status_payload(state: &App) -> Value { .iter() .filter(|assignment| assignment.enabled) { - if let Ok(hosts) = crate::docker::assignment_hosts(assignment, &agent.base_domain) { + if let Ok(hosts) = crate::docker::assignment_hosts(assignment, agent) { if let Some(host) = hosts.first() { backend_pool_domains.insert( crate::docker::generated_id(&agent.id, &assignment.service_key), @@ -193,6 +193,10 @@ fn status_payload(state: &App) -> Value { } } payload["backend_pool_domains"] = json!(backend_pool_domains); + payload["docker"] = json!(crate::docker::dashboard_summary( + &snapshot.envelope.config, + &state.docker.latest() + )); payload["backends"] = json!(snapshot .envelope .config @@ -241,38 +245,110 @@ async fn backend_status(State(state): State>) -> Json { "active_frontends":state.active_listeners, "desired_frontends":snapshot.listeners}), ) } -fn docker_runtime_views(state: &Arc) -> (Vec, Vec) { +fn docker_runtime_views(state: &Arc) -> (Vec, Vec, Value) { let snapshot = state.config.load_full(); + let config = &snapshot.envelope.config; + let observed = state.docker.latest(); + let (publications, issues) = crate::docker::label_publications(config, &observed); let mut routes = Vec::new(); let mut ids = std::collections::HashSet::new(); - for agent in &snapshot.envelope.config.docker_agents.agents { + for agent in &config.docker_agents.agents { for assignment in &agent.assignments { let pool_id = crate::docker::generated_id(&agent.id, &assignment.service_key); ids.insert(pool_id.clone()); routes.push(json!({"agent_id": &agent.id, "service_key": &assignment.service_key, "pool_id": pool_id})); } } + for publication in &publications { + let pool_id = + crate::docker::generated_id(&publication.agent_id, &publication.assignment.service_key); + ids.insert(pool_id.clone()); + routes.push(json!({"agent_id": &publication.agent_id, "service_key": &publication.assignment.service_key, "pool_id": pool_id, "source": "labels", "assignment": &publication.assignment, "hosts": &publication.hosts})); + } let pools = snapshot .pools .iter() .filter(|pool| ids.contains(&pool.id)) .map(|pool| pool.view()) .collect(); - (pools, routes) + let extras = json!({ + "label_issues": issues, + "alerts": crate::docker::alerts(config, &observed), + }); + (pools, routes, extras) } async fn docker_status(State(state): State>) -> Json { - let (pools, pool_routes) = docker_runtime_views(&state); + let (pools, pool_routes, extras) = docker_runtime_views(&state); Json( - json!({"observations": state.docker.view().await, "pools": pools, "pool_routes": pool_routes}), + json!({"observations": state.docker.view().await, "pools": pools, "pool_routes": pool_routes, "label_issues": extras["label_issues"], "alerts": extras["alerts"]}), ) } async fn docker_refresh(State(state): State>) -> Result, ApiError> { let observations = state.refresh_docker().await?; - let (pools, pool_routes) = docker_runtime_views(&state); + let (pools, pool_routes, extras) = docker_runtime_views(&state); Ok(Json( - json!({"observations": observations, "pools": pools, "pool_routes": pool_routes}), + json!({"observations": observations, "pools": pools, "pool_routes": pool_routes, "label_issues": extras["label_issues"], "alerts": extras["alerts"]}), )) } +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct DockerTestRequest { + endpoint: String, + token: String, + #[serde(default)] + tls_fingerprint_sha256: Option, +} +async fn docker_test(Json(input): Json) -> Result, ApiError> { + if input.endpoint.len() > 2048 || input.token.len() > 512 { + return Err(ApiError( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid Docker agent test request".into(), + )); + } + let started = std::time::Instant::now(); + let result = crate::docker::probe( + &input.endpoint, + &input.token, + input.tls_fingerprint_sha256.as_deref(), + ) + .await; + let elapsed_ms = started.elapsed().as_millis() as u64; + Ok(Json(match result { + Ok(inventory) => json!({ + "ok": true, + "elapsed_ms": elapsed_ms, + "agent_version": inventory.agent_version, + "hostname": inventory.hostname, + "services": inventory.services.len(), + "certificate_sha256": inventory.certificate_sha256, + "runtime": inventory.system.as_ref().map(|system| system.runtime.clone()), + }), + Err(error) => json!({"ok": false, "elapsed_ms": elapsed_ms, "error": format!("{error:#}")}), + })) +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct DockerEnrollRequest { + endpoint: String, + tls_fingerprint_sha256: String, + enrollment_token: String, +} +async fn docker_enroll(Json(input): Json) -> Result, ApiError> { + if input.endpoint.len() > 2048 || input.enrollment_token.len() > 512 { + return Err(ApiError( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid Docker agent enrollment request".into(), + )); + } + crate::docker::enroll( + &input.endpoint, + &input.tls_fingerprint_sha256, + &input.enrollment_token, + ) + .await + .map(|token| Json(json!({"token": token}))) + .map_err(|error| ApiError(StatusCode::BAD_GATEWAY, format!("{error:#}"))) +} async fn certificate_inventory(State(state): State>) -> Json { let snapshot = state.config.load_full(); let config = &snapshot.envelope.config; diff --git a/src/admin/status_live.rs b/src/admin/status_live.rs index a4fb387..1e8dfb0 100644 --- a/src/admin/status_live.rs +++ b/src/admin/status_live.rs @@ -63,6 +63,7 @@ fn live_status_payload(state: &App) -> Value { "vhost_metrics": snapshot.vhost_metrics.iter().map(|(id, metrics)| (id.clone(), metrics.view())).collect::>(), "vhost_cache_totals": state.cache.scope_totals(), "streams": {"metrics": stream_metrics}, + "docker": crate::docker::dashboard_summary(&snapshot.envelope.config, &state.docker.latest()), "logging": {"sinks": state.logs.stats(), "error_file": crate::logging::error_log_stats()} }) } diff --git a/src/admin/web/acl-picker.js b/src/admin/web/acl-picker.js index ee31c7f..47f6f8e 100644 --- a/src/admin/web/acl-picker.js +++ b/src/admin/web/acl-picker.js @@ -82,3 +82,91 @@ window.rustProxyAclPicker = (() => { } return { create, read: chosenIds, count: root => chosenIds(root).length }; })(); + +window.rustProxyChoicePicker = (() => { + function create(options) { + const limit = options.limit || 16, labels = options.labels || {}; + const label = (key, fallback) => labels[key] ? t(labels[key]) : t(fallback); + const root = el("div", undefined, `acl-picker choice-picker ${options.className || ""}`.trim()); + const details = el("details", undefined, "acl-picker-details"), summary = el("summary", undefined, "acl-picker-summary"); + const heading = el("span", "", "acl-picker-heading"), counter = el("span", "", "acl-picker-counter"); + summary.append(heading, counter); details.append(summary); + const dropdown = el("div", undefined, "acl-picker-dropdown"); + const search = el("input", "", "acl-picker-search"); search.type = "search"; search.placeholder = label("search", "aclPickerSearch"); search.setAttribute("aria-label", search.placeholder); + const optionsBox = el("div", undefined, "acl-picker-options"), empty = el("p", label("noMatches", "aclPickerNoMatches"), "fine acl-picker-empty"); + const maxHint = el("small", t("aclPickerLimit"), "fine acl-picker-limit"); + dropdown.append(search, optionsBox, empty, maxHint); details.append(dropdown); + const selectedTags = el("div", undefined, "acl-picker-selected"); root.append(details, selectedTags); + const items = [...(options.items || [])], checks = new Map(), order = []; + const addOption = (item, checked) => { + if (checks.has(item.id)) { const box = checks.get(item.id); if (checked && !box.checked) { box.checked = true; order.push(item.id); } return box; } + const row = el("label", undefined, "acl-picker-option"), check = el("input"); check.type = "checkbox"; check.value = item.id; check.checked = !!checked; + const content = el("span", undefined, "acl-picker-option-content"), headingRow = el("span", undefined, "acl-picker-option-heading"); + headingRow.append(el("strong", item.title || item.id)); + if (item.title && item.title !== item.id) headingRow.append(el("code", item.id, "acl-picker-id")); + if (item.badge) headingRow.append(el("span", item.badge, `acl-picker-policy ${item.badgeClass || "is-none"}`)); + content.append(headingRow); if (item.detail) content.append(el("small", item.detail, "acl-picker-rule-preview")); + row.append(check, content); row.dataset.search = `${item.id} ${item.title || ""} ${item.search || ""} ${item.detail || ""}`.toLocaleLowerCase(); + optionsBox.append(row); checks.set(item.id, check); if (!items.includes(item)) items.push(item); if (checked) order.push(item.id); + return check; + }; + const selected = [...new Set(options.selected || [])]; + for (const item of items.slice()) addOption(item, false); + for (const id of selected) addOption(items.find(item => item.id === id) || { id, title: id, detail: options.unknownDetail ? t(options.unknownDetail) : "" }, true); + const chosen = () => order.filter(id => checks.get(id)?.checked); + const syncSearch = () => { + const query = search.value.trim().toLocaleLowerCase(); let visible = 0; + for (const row of optionsBox.querySelectorAll(".acl-picker-option")) { row.hidden = !!query && !row.dataset.search.includes(query); if (!row.hidden) visible++; } + empty.hidden = visible > 0 || (!query && !items.length); + empty.textContent = query && options.custom ? label("addHint", "choicePickerAddHint").replace("{value}", search.value.trim()) : label("noMatches", "aclPickerNoMatches"); + if (!items.length && !query) { empty.hidden = false; empty.textContent = label("empty", "choicePickerEmpty"); } + }; + const sync = () => { + for (const [id, box] of checks) { const index = order.indexOf(id); if (box.checked && index < 0) order.push(id); if (!box.checked && index >= 0) order.splice(index, 1); } + const ids = chosen(), full = ids.length >= limit; + counter.textContent = `${ids.length}/${limit}`; + heading.textContent = ids.length ? label("selected", "aclPickerSelected").replace("{count}", ids.length) : label("choose", "aclPickerChoose"); + selectedTags.replaceChildren(); + ids.forEach((id, index) => { + const item = items.find(entry => entry.id === id), tag = el("span", undefined, `acl-picker-tag${index === 0 && options.markFirst ? " is-primary" : ""}`); + const text = el("span", item?.title || id); text.title = item?.detail || id; + if (index === 0 && options.markFirst) tag.title = t(options.markFirst); + const remove = el("button", "×", "acl-picker-remove"); remove.type = "button"; remove.setAttribute("aria-label", `${t("remove")} ${item?.title || id}`); + remove.addEventListener("click", () => { const box = checks.get(id); box.checked = false; box.dispatchEvent(new Event("change", { bubbles: true })); }); + tag.append(text); + if (index > 0 && options.markFirst && options.makeFirst) { + const promote = el("button", "★", "acl-picker-promote"); promote.type = "button"; promote.title = t(options.makeFirst); promote.setAttribute("aria-label", `${t(options.makeFirst)}: ${item?.title || id}`); + promote.addEventListener("click", () => { order.splice(order.indexOf(id), 1); order.unshift(id); sync(); root.dispatchEvent(new Event("change", { bubbles: true })); }); + tag.append(promote); + } + tag.append(remove); selectedTags.append(tag); + }); + if (!ids.length) selectedTags.append(el("span", label("none", "aclPickerNone"), "fine acl-picker-no-selection")); + for (const box of checks.values()) box.disabled = full && !box.checked; + maxHint.hidden = !full; root.dispatchEvent(new CustomEvent("choicechange", { detail: ids })); + }; + const addCustom = () => { + const raw = search.value.trim(); if (!raw || !options.custom) return; + const values = raw.split(/[\s,;]+/).filter(Boolean); + for (const value of values) { + let item; try { item = options.custom(value); } catch (error) { toast(error.message, true); return; } + if (!item) continue; + if (chosen().length >= limit && !checks.get(item.id)?.checked) { toast(t("aclPickerLimit"), true); break; } + const box = addOption(items.find(entry => entry.id === item.id) || item, false); box.checked = true; + } + search.value = ""; syncSearch(); sync(); root.dispatchEvent(new Event("change", { bubbles: true })); + }; + optionsBox.addEventListener("change", event => { if (event.target.matches('input[type="checkbox"]')) sync(); }); + search.addEventListener("input", syncSearch); + search.addEventListener("keydown", event => { + if (event.key === "Enter") { event.preventDefault(); if (options.custom) addCustom(); else { const first = [...optionsBox.querySelectorAll(".acl-picker-option:not([hidden]) input:not(:disabled)")][0]; if (first) { first.checked = !first.checked; first.dispatchEvent(new Event("change", { bubbles: true })); } } } + if (event.key === "Escape") { search.value = ""; syncSearch(); details.open = false; summary.focus(); } + }); + search.addEventListener("blur", () => { if (options.custom && search.value.trim()) addCustom(); }); + root.read = chosen; + root.setDisabled = disabled => { root.classList.toggle("is-disabled", disabled); details.open = details.open && !disabled; summary.tabIndex = disabled ? -1 : 0; summary.setAttribute("aria-disabled", String(disabled)); }; + root.select = ids => { for (const [id, box] of checks) box.checked = ids.includes(id); order.length = 0; order.push(...ids.filter(id => checks.has(id))); sync(); }; + syncSearch(); sync(); return root; + } + return { create, read: root => root?.read?.() || [] }; +})(); diff --git a/src/admin/web/app/core.js b/src/admin/web/app/core.js index 7911521..fe282fd 100644 --- a/src/admin/web/app/core.js +++ b/src/admin/web/app/core.js @@ -59,7 +59,7 @@ function translate() { window.rustProxyDrafts?.refresh(); window.rustProxyPreferences?.refreshAppearanceUi?.(); $("connection-label").textContent = t(connected ? "connected" : "disconnected"); - if (envelope) renderConfig(); renderConfigStorage(); if (latestStatus) { renderFooter(latestStatus); renderDiagnostics(latestStatus, false); window.rustProxyVhosts?.renderStatus(latestStatus); window.rustProxyDocker?.renderStatus(latestStatus); window.rustProxyStreams?.renderStatus(latestStatus); window.rustProxyStreamDashboard?.render(latestStatus); window.rustProxyBackendDashboard?.render(latestStatus, null, false); window.rustProxyExtraOverview?.render(latestStatus, false); window.rustProxyWideOverview?.render(latestStatus, false); window.rustProxyWebOverview?.render(latestStatus, false); } if (lastLogs) renderLogs(lastLogs); + if (envelope) renderConfig(); renderConfigStorage(); if (latestStatus) { renderFooter(latestStatus); renderDiagnostics(latestStatus, false); window.rustProxyVhosts?.renderStatus(latestStatus); window.rustProxyDocker?.renderStatus(latestStatus); window.rustProxyStreams?.renderStatus(latestStatus); window.rustProxyStreamDashboard?.render(latestStatus); window.rustProxyDockerDashboard?.render(latestStatus, null, false); window.rustProxyBackendDashboard?.render(latestStatus, null, false); window.rustProxyExtraOverview?.render(latestStatus, false); window.rustProxyWideOverview?.render(latestStatus, false); window.rustProxyWebOverview?.render(latestStatus, false); } if (lastLogs) renderLogs(lastLogs); syncSettingsDirtyIndicators(); window.rustProxyIcons?.refresh?.(); } @@ -170,7 +170,7 @@ function setPanel(name, navigate = true) { if (name === "web-server" && latestStatus) window.rustProxyWebServer?.renderLive?.(latestStatus, false); if (name === "settings") window.rustProxySettings?.syncLocation?.(); window.rustProxyRefresh?.setPanel(name); - if (name === "overview" && previousPanel !== name && typeof latestStatus !== "undefined" && latestStatus) { window.rustProxyStreamDashboard?.render?.(latestStatus, null, false); window.rustProxyBackendDashboard?.render?.(latestStatus, null, false); window.rustProxyExtraOverview?.render?.(latestStatus, false); window.rustProxyWideOverview?.render?.(latestStatus, false); window.rustProxyWebOverview?.render?.(latestStatus, false); } + if (name === "overview" && previousPanel !== name && typeof latestStatus !== "undefined" && latestStatus) { window.rustProxyStreamDashboard?.render?.(latestStatus, null, false); window.rustProxyDockerDashboard?.render?.(latestStatus, null, false); window.rustProxyBackendDashboard?.render?.(latestStatus, null, false); window.rustProxyExtraOverview?.render?.(latestStatus, false); window.rustProxyWideOverview?.render?.(latestStatus, false); window.rustProxyWebOverview?.render?.(latestStatus, false); } if (name === "docker-vhosts" && previousPanel !== name && authenticated && envelope) void window.rustProxyRefresh?.manual("docker"); if (name === "tls") window.rustProxyAcme?.syncLocation?.(); if (name === "filelogs") void window.rustProxyFileLogs?.refresh(); @@ -215,6 +215,7 @@ function appHealthChecks(status) { checks.push({ level: "ok", label: t("appHealthBackends"), detail: pools.length ? t("appHealthBackendsOk") : t("appHealthBackendsNone") }); } + const dockerCheck = window.rustProxyDockerDashboard?.healthCheck?.(status); if (dockerCheck) checks.push(dockerCheck); const sink = status.logging?.sinks || {}, errorFile = status.logging?.error_file || {}; const loggingDropped = (Number(sink.queue_dropped) || 0) + (Number(errorFile.queue_dropped) || 0); const loggingErrors = (Number(sink.errors) || 0) + (Number(errorFile.errors) || 0); @@ -370,7 +371,7 @@ function renderStatusNow(s, systemSample = false) { $("metric-ws-proto-h1").textContent = (Number(m.websocket_h1_active) || 0).toLocaleString(locale()); $("metric-ws-proto-h2").textContent = (Number(m.websocket_h2_active) || 0).toLocaleString(locale()); $("metric-ws-proto-h3").textContent = (Number(m.websocket_h3_active) || 0).toLocaleString(locale()); - renderFooter(s); renderDiagnostics(s, true, systemSample); window.rustProxyVhosts?.renderStatus(s); window.rustProxyDocker?.renderStatus(s); window.rustProxyStreams?.renderStatus(s); window.rustProxyStreamDashboard?.render(s); window.rustProxyBackendDashboard?.render(s); window.rustProxyExtraOverview?.render(s); window.rustProxyWideOverview?.render(s); window.rustProxyWebOverview?.render(s); window.rustProxyWebServer?.renderLive?.(s); + renderFooter(s); renderDiagnostics(s, true, systemSample); window.rustProxyVhosts?.renderStatus(s); window.rustProxyDocker?.renderStatus(s); window.rustProxyStreams?.renderStatus(s); window.rustProxyStreamDashboard?.render(s); window.rustProxyDockerDashboard?.render(s); window.rustProxyDockerDashboard?.notify?.(s); window.rustProxyBackendDashboard?.render(s); window.rustProxyExtraOverview?.render(s); window.rustProxyWideOverview?.render(s); window.rustProxyWebOverview?.render(s); window.rustProxyWebServer?.renderLive?.(s); } function renderFooter(s) { const apiLatency = lastApiLatencyMs == null ? "API -" : `API ${lastApiLatencyMs.toFixed(lastApiLatencyMs < 10 ? 1 : 0)} ms`; @@ -498,7 +499,7 @@ function lock(notify = true) { window.rustProxyInlineLayout?.cancel?.(); window.rustProxyRefresh?.stop(); const destination = pendingAuthDestination || authReturnDestination(), navigating = typeof location !== "undefined" && (location.protocol === "http:" || location.protocol === "https:"); - pendingAuthDestination = destination; if (notify) adminAuthChannel?.postMessage("locked"); $("api-docs").hidden = true; $("logs-menu").hidden = true; $("app-health-slot").hidden = true; resetAdminPreferences(); window.rustProxyCertificates?.reset(); window.rustProxySettings?.reset(); window.rustProxyTrafficPanel?.reset(); window.rustProxyCachePanel?.reset(); window.rustProxyTransformPanel?.reset(); window.rustProxyAcme?.reset(); window.rustProxyIntegrations?.reset(); window.rustProxyLogs?.reset(); window.rustProxyFileLogs?.reset(); window.rustProxyDrafts?.reset(); $("logs-open").hidden = true; $("file-logs-open").hidden = true; window.rustProxyAclProfiles?.reset(); window.rustProxyVhosts?.reset(); window.rustProxyWebServer?.reset(); window.rustProxyDocker?.reset(); window.rustProxyRedirects?.reset(); window.rustProxyNotFound?.reset(); window.rustProxyStreams?.reset(); window.rustProxyStreamDashboard?.reset(); window.rustProxyBackendDashboard?.reset(); window.rustProxyExtraOverview?.reset(); window.rustProxyWideOverview?.reset(); window.rustProxyWebOverview?.reset(); authEpoch++; stopLive(); csrf = ""; authenticated = false; sessionInfo = null; envelope = null; configStorage = null; certificateInventory = new Map(); previous = null; samples = []; protocolSamples = { h1: [], h2: [], h3: [] }; websocketProtocolSamples = { h1: [], h2: [], h3: [] }; transformSamples = []; systemSamples = []; connectionOpenSamples = []; connectionExchangeSamples = []; networkInterfaceSamples.clear(); lastLogs = null; latestStatus = null; clearSettingsDirty(); connected = false; busy = false; $("workspace").hidden = true; $("login").hidden = navigating; $("logout").hidden = true; $("password").value = ""; $("password-confirm").value = ""; $("setup-token").value = ""; $("password-form").reset(); $("config-editor").value = ""; $("logs").replaceChildren(); $("audit-rows").replaceChildren(); authMessage(""); + pendingAuthDestination = destination; if (notify) adminAuthChannel?.postMessage("locked"); $("api-docs").hidden = true; $("logs-menu").hidden = true; $("app-health-slot").hidden = true; resetAdminPreferences(); window.rustProxyCertificates?.reset(); window.rustProxySettings?.reset(); window.rustProxyTrafficPanel?.reset(); window.rustProxyCachePanel?.reset(); window.rustProxyTransformPanel?.reset(); window.rustProxyAcme?.reset(); window.rustProxyIntegrations?.reset(); window.rustProxyLogs?.reset(); window.rustProxyFileLogs?.reset(); window.rustProxyDrafts?.reset(); $("logs-open").hidden = true; $("file-logs-open").hidden = true; window.rustProxyAclProfiles?.reset(); window.rustProxyVhosts?.reset(); window.rustProxyWebServer?.reset(); window.rustProxyDocker?.reset(); window.rustProxyRedirects?.reset(); window.rustProxyNotFound?.reset(); window.rustProxyStreams?.reset(); window.rustProxyStreamDashboard?.reset(); window.rustProxyDockerDashboard?.reset(); window.rustProxyBackendDashboard?.reset(); window.rustProxyExtraOverview?.reset(); window.rustProxyWideOverview?.reset(); window.rustProxyWebOverview?.reset(); authEpoch++; stopLive(); csrf = ""; authenticated = false; sessionInfo = null; envelope = null; configStorage = null; certificateInventory = new Map(); previous = null; samples = []; protocolSamples = { h1: [], h2: [], h3: [] }; websocketProtocolSamples = { h1: [], h2: [], h3: [] }; transformSamples = []; systemSamples = []; connectionOpenSamples = []; connectionExchangeSamples = []; networkInterfaceSamples.clear(); lastLogs = null; latestStatus = null; clearSettingsDirty(); connected = false; busy = false; $("workspace").hidden = true; $("login").hidden = navigating; $("logout").hidden = true; $("password").value = ""; $("password-confirm").value = ""; $("setup-token").value = ""; $("password-form").reset(); $("config-editor").value = ""; $("logs").replaceChildren(); $("audit-rows").replaceChildren(); authMessage(""); for (const id of ["certificate-list", "host-policy-list"]) { $(id)?.replaceChildren(); } $("workspace").querySelectorAll("form").forEach(form => form.reset()); $("workspace").querySelectorAll("input:not([type=checkbox]):not([type=radio]),textarea").forEach(input => { input.value = ""; }); diff --git a/src/admin/web/app/dashboard-inline-layout.js b/src/admin/web/app/dashboard-inline-layout.js index f31426b..6b1ef08 100644 --- a/src/admin/web/app/dashboard-inline-layout.js +++ b/src/admin/web/app/dashboard-inline-layout.js @@ -44,7 +44,9 @@ window.rustProxyInlineLayout = (() => { nodeFor(id)?.querySelector(".overview-inline-grip")?.focus(); }); const item = el("div", undefined, "overview-inline-hidden-item"); - item.append(el("span", label(id)), dashboardWidgetTypeBadge(id), add); + item.append(el("span", label(id)), dashboardWidgetTypeBadge(id)); + const scope = window.rustProxyDockerDashboard?.scopeControl?.(id); if (scope) item.append(scope); + item.append(add); return item; }) : [el("span", t("overviewLayoutInlineHiddenEmpty"), "fine")])); } diff --git a/src/admin/web/app/dashboard-layout-editor.js b/src/admin/web/app/dashboard-layout-editor.js index 77c1964..55a8dbb 100644 --- a/src/admin/web/app/dashboard-layout-editor.js +++ b/src/admin/web/app/dashboard-layout-editor.js @@ -34,7 +34,7 @@ window.rustProxyDashboardLayout = (() => { } function label(id) { const widget = ADMIN_DASHBOARD_BY_ID.get(id); - return widget ? t(widget.label_key) : id; + return widget ? `${t(widget.label_key)}${widget.instance > 1 ? ` #${widget.instance}` : ""}` : id; } function visibleIds() { return dashboardVisualOrder(draft.order, draft.sizes) @@ -196,7 +196,9 @@ window.rustProxyDashboardLayout = (() => { add.type = "button"; add.setAttribute("aria-label", `${t("overviewLayoutEditorShow")}: ${label(id)}`); add.addEventListener("click", () => { draft.hidden.delete(id); render(); }); - item.append(name, dashboardWidgetTypeBadge(id), add); + item.append(name, dashboardWidgetTypeBadge(id)); + const scope = window.rustProxyDockerDashboard?.scopeControl?.(id); if (scope) item.append(scope); + item.append(add); return item; }); hiddenRoot.replaceChildren(...(hiddenItems.length || query ? hiddenItems : [el("p", t("overviewLayoutEditorHiddenEmpty"), "fine")])); diff --git a/src/admin/web/app/docker-dashboard.js b/src/admin/web/app/docker-dashboard.js new file mode 100644 index 0000000..e12bf17 --- /dev/null +++ b/src/admin/web/app/docker-dashboard.js @@ -0,0 +1,179 @@ +window.rustProxyDockerDashboard = (() => { + const BASES = ["docker_agents", "docker_apps", "docker_requests", "docker_host_network", "docker_host_load", "docker_containers"]; + const INSTANCES = 4; + const ids = BASES.flatMap(base => Array.from({ length: INSTANCES }, (_, index) => index ? `${base}_${index + 1}` : base)); + const baseOf = id => id.replace(/_[2-9]$/, ""); + const suffixOf = id => { const match = id.match(/_([2-9])$/); return match ? `-i${match[1]}` : ""; }; + const series = new Map(); + const chart = id => { if (!series.has(id)) series.set(id, { last: null, points: [], rx: [], tx: [] }); return series.get(id); }; + const configuredAgents = () => (envelope?.config?.docker_agents?.agents || []).filter(agent => agent.enabled !== false); + const scopes = () => window.rustProxyPreferences?.current?.()?.docker_widget_agents || {}; + function scopeOf(id) { const agent = scopes()[id]; return agent && configuredAgents().some(item => item.id === agent) ? agent : ""; } + async function setScope(id, agent) { + const next = { ...scopes() }; if (agent) next[id] = agent; else delete next[id]; + series.delete(id); clearChart(id); + try { await window.rustProxyPreferences.update({ docker_widget_agents: next }); } catch (error) { if (error?.status !== 401) toast(error.message, true); } + syncCardControls(); + if (typeof latestStatus !== "undefined" && latestStatus) render(latestStatus, null, false); + } + function scopeControl(id, className = "docker-widget-scope") { + if (!ids.includes(id)) return null; + const agents = configuredAgents(); if (agents.length < 2) return null; + const select = el("select", undefined, className); select.setAttribute("aria-label", t("dockerWidgetScope")); select.title = t("dockerWidgetScope"); + const all = el("option", t("dockerWidgetScopeAll")); all.value = ""; select.append(all); + for (const agent of agents) { const option = el("option", agent.name || agent.id); option.value = agent.id; select.append(option); } + select.value = scopeOf(id); + select.addEventListener("change", () => void setScope(id, select.value)); + return select; + } + const card = id => document.querySelector(`[data-dashboard-widget="${id}"]`); + const shown = id => card(id) && !card(id).hidden; + function syncCardControls() { + for (const id of ids) { + const node = card(id); if (!node) continue; + const instance = id.match(/_([2-9])$/)?.[1]; if (instance) node.querySelector(":scope > span")?.setAttribute("data-instance", instance); + const signature = `${configuredAgents().map(agent => `${agent.id}:${agent.name}`).join("|")}#${scopeOf(id)}`; + if (node.dataset.dockerScope === signature) continue; + node.dataset.dockerScope = signature; + node.querySelector(":scope > .docker-widget-scope")?.remove(); + const control = scopeControl(id); if (control) node.querySelector(":scope > span")?.after(control); + } + } + let wasVisible = false; + const set = (id, value) => { const node = $(id); if (node) node.textContent = value; }; + const has = value => value !== undefined && value !== null; + function clearChart(id) { + const sfx = suffixOf(id), lines = { docker_requests: ["docker-dashboard-requests-line"], docker_host_network: ["docker-dashboard-rx", "docker-dashboard-tx"] }[baseOf(id)] || []; + for (const line of lines) $(`${line}${sfx}`)?.setAttribute("points", "0,55 300,55"); + } + function clearCharts() { series.clear(); for (const id of ids) clearChart(id); } + function syncVisibility(hiddenOverride = null) { + const prefs = window.rustProxyPreferences?.current?.(); + const hidden = new Set(hiddenOverride ?? window.rustProxyInlineLayout?.currentDraft?.()?.hidden + ?? prefs?.dashboard_hidden_widgets ?? ADMIN_APPEARANCE_DEFAULTS.dashboard_hidden_widgets); + for (const id of ids) if (card(id)) card(id).hidden = hidden.has(id); + for (const id of ids) if (!shown(id) && series.has(id)) { series.delete(id); clearChart(id); } + wasVisible = ids.some(shown); + } + function line(points, peak) { + return points.map((value, i) => `${i * 300 / Math.max(1, points.length - 1)},${55 - value / Math.max(1, peak) * 50}`).join(" "); + } + function push(list, value) { list.push(value); if (list.length > window.rustProxyOverviewSamples.getLimit()) list.shift(); } + function unavailable(id) { + const sfx = suffixOf(id), base = baseOf(id); + if (base === "docker_host_network") { set(`docker-dashboard-network${sfx}`, "-"); set(`docker-dashboard-rx-rate${sfx}`, "-"); set(`docker-dashboard-tx-rate${sfx}`, "-"); } + else { const name = { docker_agents: "agents", docker_apps: "apps", docker_requests: "requests", docker_host_load: "load", docker_containers: "containers" }[base]; set(`docker-dashboard-${name}${sfx}`, "-"); set(`docker-dashboard-${name}-detail${sfx}`, t("dockerWidgetUnavailable")); } + if (base === "docker_host_load") $(`docker-dashboard-load-list${sfx}`)?.replaceChildren(); + series.delete(id); clearChart(id); + } + function loadRow(agent) { + const system = agent.system || {}, row = el("div", undefined, "docker-load-row"), name = el("span", agent.name || agent.id, "docker-load-name"); + name.title = `${agent.name || agent.id}${system.os ? ` · ${system.os}` : ""}${has(system.uptime_seconds) ? ` · ${t("dockerSystemUptime")}: ${uptime(system.uptime_seconds)}` : ""}`; + const bar = (label, pct, title) => { const wrap = el("span", undefined, "docker-load-bar"), meter = el("i"), fill = el("b"); const value = Math.max(0, Math.min(100, Number(pct) || 0)); fill.style.width = `${value}%`; if (value >= 90) meter.className = "is-high"; else if (value >= 75) meter.className = "is-warn"; meter.append(fill); wrap.append(el("small", label), meter); wrap.title = title; return wrap; }; + row.append(name); + if (!agent.ok) { row.append(el("span", t("dockerError"), "docker-load-offline")); return row; } + if (has(system.cpu_percent)) row.append(bar("CPU", system.cpu_percent, `CPU ${Number(system.cpu_percent).toFixed(1)}%`)); + if (has(system.memory_total_bytes) && has(system.memory_available_bytes)) { const total = Number(system.memory_total_bytes), used = Math.max(0, total - Number(system.memory_available_bytes)); row.append(bar("MEM", total ? used / total * 100 : 0, `${t("dockerSystemMemory")}: ${bytes(used)} / ${bytes(total)}`)); } + if (has(system.load1)) row.append(el("span", Number(system.load1).toFixed(2), "docker-load-value")); + if (row.children.length === 1) row.append(el("span", t("dockerWidgetNoSystem"), "docker-load-offline")); + return row; + } + const onlineOf = list => list.filter(agent => agent.ok), systemsOf = list => onlineOf(list).map(agent => agent.system).filter(Boolean); + const RENDERERS = { + docker_agents(id, sfx, agents) { + const online = onlineOf(agents), attention = agents.filter(agent => agent.observed && !agent.ok).length, waiting = agents.filter(agent => !agent.observed).length; + set(`docker-dashboard-agents${sfx}`, `${online.length}/${agents.length}`); + set(`docker-dashboard-agents-detail${sfx}`, [t("dockerWidgetOnline"), attention ? `${attention} ${t("dockerWidgetAttention")}` : "", waiting ? `${waiting} ${t("dockerWaiting").toLowerCase()}` : ""].filter(Boolean).join(" · ")); + }, + docker_apps(id, sfx, agents, status) { + const poolIds = agents.flatMap(agent => agent.published_pool_ids || []), pools = new Map((status.backend_pools || []).map(pool => [pool.id, pool])); + let up = 0, down = 0, other = 0; + for (const poolId of poolIds) { const member = pools.get(poolId)?.members?.[0]; if (!member) other++; else if (member.status === "up") up++; else if (member.status === "down") down++; else other++; } + const missing = agents.reduce((sum, agent) => sum + (Number(agent.missing_services) || 0), 0), discovered = agents.reduce((sum, agent) => sum + (Number(agent.services) || 0), 0); + set(`docker-dashboard-apps${sfx}`, poolIds.length ? `${up}/${poolIds.length}` : "0"); + set(`docker-dashboard-apps-detail${sfx}`, [t("vhUp").toLowerCase(), down ? `${down} ${t("dockerWidgetDown")}` : "", other ? `${other} ${t("dockerWidgetPending")}` : "", missing ? `${missing} ${t("dockerWidgetMissing")}` : ""].filter(Boolean).join(" · ")); + const detail = $(`docker-dashboard-apps-detail${sfx}`); if (detail) detail.title = `${up} ${t("vhUp").toLowerCase()} · ${down} ${t("dockerWidgetDown")} · ${other} ${t("dockerWidgetPending")} · ${missing} ${t("dockerWidgetMissing")} · ${discovered} ${t("dockerWidgetDiscovered")}`; + }, + docker_requests(id, sfx, agents, status, recordSample) { + const requests = chart(id), poolIds = agents.flatMap(agent => agent.published_pool_ids || []), metrics = status.vhost_metrics || {}, views = poolIds.map(poolId => metrics[poolId]).filter(Boolean); + const total = views.reduce((sum, view) => sum + (Number(view.requests) || 0), 0), active = views.reduce((sum, view) => sum + (Number(view.active) || 0), 0), errors = views.reduce((sum, view) => sum + (Number(view.errors) || 0), 0); + if (!views.length) { set(`docker-dashboard-requests${sfx}`, "-"); set(`docker-dashboard-requests-detail${sfx}`, t("dockerWidgetNoTraffic")); return; } + if (!recordSample) return; + const sample = rustProxyRateSampling.difference(requests.last, [total], performance.now(), rustProxyRateSampling.cadence("overview_seconds")); + const paused = requests.last !== null && sample.deltas === null; requests.last = sample.next; + const rate = sample.deltas ? sample.deltas[0] / sample.seconds : 0; + if (!paused) push(requests.points, rate); + set(`docker-dashboard-requests${sfx}`, paused ? "-" : `${rate.toFixed(1)}/s`); + set(`docker-dashboard-requests-detail${sfx}`, `${fmt(active)} ${t("vhActive").toLowerCase()} · ${fmt(errors)} ${t("vhErrors").toLowerCase()}`); + const peak = Math.max(1, ...requests.points); + $(`docker-dashboard-requests-line${sfx}`)?.setAttribute("points", line(requests.points, peak)); + window.rustProxyChartScale.axes(`docker-dashboard-requests-line${sfx}`, peak, "rate", requests.points.length, { top: 5 / 60, bottom: 55 / 60 }); + }, + docker_host_network(id, sfx, agents, status, recordSample) { + const network = chart(id), withRates = systemsOf(agents).filter(system => has(system.network_rx_bytes_per_second)); + if (!withRates.length) { set(`docker-dashboard-network${sfx}`, "-"); set(`docker-dashboard-rx-rate${sfx}`, "-"); set(`docker-dashboard-tx-rate${sfx}`, "-"); return; } + const rx = withRates.reduce((sum, system) => sum + Number(system.network_rx_bytes_per_second), 0), tx = withRates.reduce((sum, system) => sum + Number(system.network_tx_bytes_per_second || 0), 0); + if (recordSample) { push(network.rx, rx); push(network.tx, tx); } + set(`docker-dashboard-network${sfx}`, `${rateBytes(rx + tx)}/s`); set(`docker-dashboard-rx-rate${sfx}`, `${rateBytes(rx)}/s`); set(`docker-dashboard-tx-rate${sfx}`, `${rateBytes(tx)}/s`); + const peak = Math.max(1, ...network.rx, ...network.tx); + $(`docker-dashboard-rx${sfx}`)?.setAttribute("points", line(network.rx, peak)); $(`docker-dashboard-tx${sfx}`)?.setAttribute("points", line(network.tx, peak)); + window.rustProxyChartScale.axes(`docker-dashboard-rx${sfx}`, peak, "bytes/s", network.rx.length, { top: 5 / 60, bottom: 55 / 60 }); + }, + docker_host_load(id, sfx, agents) { + const systems = systemsOf(agents), cpu = systems.filter(system => has(system.cpu_percent)).map(system => Number(system.cpu_percent)), busiest = cpu.length ? Math.max(...cpu) : null; + set(`docker-dashboard-load${sfx}`, busiest === null ? "-" : `${busiest.toFixed(0)}%`); + $(`docker-dashboard-load-list${sfx}`)?.replaceChildren(...agents.map(loadRow)); + const loads = systems.filter(system => has(system.load1) && Number(system.cpu_count) > 0).map(system => Number(system.load1) / Number(system.cpu_count)); + set(`docker-dashboard-load-detail${sfx}`, systems.length ? t("dockerWidgetBusiestCpu") : t("dockerWidgetNoSystem")); + const loadDetail = $(`docker-dashboard-load-detail${sfx}`); if (loadDetail) loadDetail.title = loads.length ? `${t("dockerSystemLoadPerCpu")} ≤ ${Math.max(...loads).toFixed(2)}` : ""; + }, + docker_containers(id, sfx, agents) { + const systems = systemsOf(agents), counted = systems.filter(system => has(system.containers_running)); + if (!counted.length) { set(`docker-dashboard-containers${sfx}`, "-"); set(`docker-dashboard-containers-detail${sfx}`, t("dockerWidgetNoSystem")); return; } + const running = counted.reduce((sum, system) => sum + Number(system.containers_running), 0), total = counted.reduce((sum, system) => sum + Number(system.containers_total || 0), 0), images = counted.reduce((sum, system) => sum + Number(system.images || 0), 0); + const docker = systems.filter(system => system.runtime === "docker").length, podman = systems.filter(system => system.runtime === "podman").length; + set(`docker-dashboard-containers${sfx}`, `${fmt(running)}/${fmt(total)}`); + set(`docker-dashboard-containers-detail${sfx}`, [t("dockerWidgetRunning"), docker ? `Docker ${docker}` : "", podman ? `Podman ${podman}` : ""].filter(Boolean).join(" · ")); + const detail = $(`docker-dashboard-containers-detail${sfx}`); if (detail) detail.title = `${t("dockerSystemImages")}: ${fmt(images)}`; + }, + }; + function render(status, hiddenOverride = null, recordSample = true) { + syncVisibility(hiddenOverride); + if (!status || currentPanel !== "overview" || !ids.some(shown)) return; + syncCardControls(); + const enabledAgents = (status.docker?.agents || []).filter(agent => agent.enabled !== false); + for (const id of ids.filter(shown)) { + if (!enabledAgents.length) { unavailable(id); continue; } + const agent = scopeOf(id), agents = agent ? enabledAgents.filter(item => item.id === agent) : enabledAgents; + RENDERERS[baseOf(id)](id, suffixOf(id), agents, status, recordSample); + } + } + function reset() { clearCharts(); wasVisible = false; } + window.rustProxyOverviewSamples.onChange(() => { + for (const entry of series.values()) for (const list of [entry.points, entry.rx, entry.tx]) window.rustProxyOverviewSamples.trim(list); + if (typeof latestStatus !== "undefined" && latestStatus && currentPanel === "overview") render(latestStatus, null, false); + }); + const ALERT_KEYS = { agent_offline: "dockerAlertAgentOffline", disk_high: "dockerAlertDiskHigh", memory_high: "dockerAlertMemoryHigh", load_high: "dockerAlertLoadHigh", service_missing: "dockerAlertServiceMissingText", container_unhealthy: "dockerAlertContainerUnhealthy", label_invalid: "dockerAlertLabelInvalid" }; + function alertText(alert) { + const key = ALERT_KEYS[alert.kind]; if (!key) return `${alert.agent_name || alert.agent_id}: ${alert.kind}`; + const since = alert.since_unix_ms ? new Date(alert.since_unix_ms).toLocaleTimeString(locale()) : "-"; + return t(key).replace("{agent}", alert.agent_name || alert.agent_id).replace("{service}", alert.service || "-").replace("{value}", alert.value ?? "-").replace("{threshold}", alert.threshold ?? "-").replace("{since}", since).replace("{message}", alert.message || "-"); + } + let seenAlerts = null; + function notify(status) { + const alerts = status?.docker?.alerts; + if (!Array.isArray(alerts)) return; + const keys = new Set(alerts.map(alert => alert.key)); + if (seenAlerts === null) { seenAlerts = keys; if (alerts.length) toast(t("dockerAlertsTitle").replace("{count}", alerts.length), alerts.some(alert => alert.severity === "error")); return; } + for (const alert of alerts) if (!seenAlerts.has(alert.key)) toast(alertText(alert), alert.severity === "error"); + seenAlerts = keys; + } + function healthCheck(status) { + const alerts = status?.docker?.alerts; + if (!status?.docker) return null; + if (!alerts?.length) return { level: "ok", label: t("dockerAlertsHealth"), detail: t("dockerAlertsNone") }; + const detail = alerts.slice(0, 4).map(alertText).join(" · ") + (alerts.length > 4 ? ` · +${alerts.length - 4}` : ""); + return { level: alerts.some(alert => alert.severity === "error") ? "error" : "warning", label: t("dockerAlertsHealth"), detail }; + } + return { syncVisibility, render, reset() { reset(); seenAlerts = null; }, scopeControl, scopeOf, alertText, notify, healthCheck, ids }; +})(); diff --git a/src/admin/web/app/preferences.js b/src/admin/web/app/preferences.js index 87ea1b5..df37952 100644 --- a/src/admin/web/app/preferences.js +++ b/src/admin/web/app/preferences.js @@ -173,17 +173,17 @@ function applyDashboardLayout(order, hidden, sizes = null, heights = undefined) } const currentNodes = [...grid.querySelectorAll("[data-dashboard-widget]")]; if (orderedNodes.some((node, index) => node !== currentNodes[index])) grid.append(...orderedNodes); - window.rustProxyStreamDashboard?.syncVisibility?.([...hiddenSet]); + window.rustProxyStreamDashboard?.syncVisibility?.([...hiddenSet]); window.rustProxyDockerDashboard?.syncVisibility?.([...hiddenSet]); window.rustProxyBackendDashboard?.syncVisibility?.([...hiddenSet]); window.rustProxyMasonry?.refresh?.(); if (heights !== undefined) window.rustProxyOverviewRows?.setHeights?.(normalizeDashboardWidgetHeights(heights)); window.rustProxyOverviewRows?.schedule?.(); - if (typeof latestStatus !== "undefined" && latestStatus && currentPanel === "overview") { window.rustProxyStreamDashboard?.render?.(latestStatus, [...hiddenSet], false); window.rustProxyBackendDashboard?.render?.(latestStatus, [...hiddenSet], false); window.rustProxyExtraOverview?.render?.(latestStatus, false); window.rustProxyWideOverview?.render?.(latestStatus, false); window.rustProxyWebOverview?.render?.(latestStatus, false); } + if (typeof latestStatus !== "undefined" && latestStatus && currentPanel === "overview") { window.rustProxyStreamDashboard?.render?.(latestStatus, [...hiddenSet], false); window.rustProxyDockerDashboard?.render?.(latestStatus, [...hiddenSet], false); window.rustProxyBackendDashboard?.render?.(latestStatus, [...hiddenSet], false); window.rustProxyExtraOverview?.render?.(latestStatus, false); window.rustProxyWideOverview?.render?.(latestStatus, false); window.rustProxyWebOverview?.render?.(latestStatus, false); } return { order: normalizedOrder, hidden: [...hiddenSet], sizes: widths }; } function dashboardWidgetLabel(id) { const widget = ADMIN_DASHBOARD_BY_ID.get(id); - return widget ? t(widget.label_key) : id; + return widget ? `${t(widget.label_key)}${widget.instance > 1 ? ` #${widget.instance}` : ""}` : id; } const DASHBOARD_DISPLAY_TYPE_KEYS = Object.freeze({ value: "overviewBlockTypeValue", value_chart: "overviewBlockTypeValueChart", diff --git a/src/admin/web/css/10-base.css b/src/admin/web/css/10-base.css index 490a7ff..faa9938 100644 --- a/src/admin/web/css/10-base.css +++ b/src/admin/web/css/10-base.css @@ -1093,9 +1093,10 @@ html[data-dashboard-density=compact] #panel-overview .dashboard-overview-grid>.c padding: 8px 0; } -#docker-agent-add { +#docker-agent-add, +#docker-agent-provision { display: inline-flex; - margin-top: 14px; + margin: 0; } #docker-agents-form>.form-actions { diff --git a/src/admin/web/css/30-overview.css b/src/admin/web/css/30-overview.css index a192d9c..463a13e 100644 --- a/src/admin/web/css/30-overview.css +++ b/src/admin/web/css/30-overview.css @@ -2755,6 +2755,7 @@ html[data-table-density=normal] .bo-table td { padding-top: 10px; padding-bottom html[data-table-density=ultra] .bo-table th { padding: 4px 8px; } html[data-table-density=ultra] .bo-table td { padding-left: 8px; padding-right: 8px; } html[data-table-density=ultra] .bo-sub { display: none; } +html[data-table-density=ultra] .bo-identity[data-backend-name] .bo-name { cursor: help; text-decoration: underline dotted color-mix(in srgb, var(--muted) 70%, transparent); text-underline-offset: 3px; } html[data-table-density=ultra] .bo-spark { height: 14px; } html[data-table-density=ultra] .bo-spark-latency { width: 80px; } html[data-table-density=ultra] .bo-spark-traffic { width: 64px; } @@ -2880,3 +2881,24 @@ html[data-table-density=ultra] .bo-ring { width: 14px; height: 14px; } html[data-table-density=ultra] .bo-stack { margin-top: 2px; } html[data-table-density=compact] .bo-ring { width: 18px; height: 18px; } html[data-table-density=compact] .bo-stack { margin-top: 3px; } + +.docker-load-list { display: grid; gap: 4px; margin: 6px 0 4px; min-width: 0; } +.docker-load-row { display: grid; grid-template-columns: minmax(0, 1fr) repeat(2, minmax(34px, 1fr)) auto; align-items: center; gap: 8px; min-width: 0; font-size: 11px; } +.docker-load-name { overflow: hidden; color: var(--text); font-weight: 600; text-overflow: ellipsis; white-space: nowrap; } +.docker-load-bar { display: grid; grid-template-columns: auto 1fr; align-items: center; gap: 4px; min-width: 0; } +.docker-load-bar>small { color: var(--muted); font: 9px var(--mono); } +.docker-load-bar>i { display: block; height: 5px; overflow: hidden; border-radius: 3px; background: var(--line); } +.docker-load-bar>i>b { display: block; height: 100%; border-radius: inherit; background: var(--green); } +.docker-load-bar>i.is-warn>b { background: var(--accent); } +.docker-load-bar>i.is-high>b { background: var(--red); } +.docker-load-value { color: var(--muted); font: 10px var(--mono); text-align: right; } +.docker-load-offline { grid-column: 2 / -1; color: var(--muted); font-size: 10px; } +html[data-dashboard-density=ultra] #panel-overview .docker-load-list { gap: 2px; margin: 3px 0 2px; } +#panel-overview [data-dashboard-widget^="docker_"] strong { white-space: nowrap; } +.docker-load-stat .docker-load-list { grid-column: 1 / -1; width: 100%; } +#panel-overview .stat>.docker-widget-scope { display: block; width: auto; max-width: 100%; min-height: 0; height: 20px; margin: 3px 0 0; padding: 0 4px; border: 1px solid var(--line); background: var(--panel); color: var(--muted); font-size: 10px; line-height: 18px; } +#panel-overview .stats-grid>.stat.stat-chart[data-dashboard-widget^="docker_"]:has(>.docker-widget-scope) { grid-template-rows: auto auto auto 1fr !important; } +#panel-overview .stats-grid>.stat[data-dashboard-widget^="docker_"]>.docker-widget-scope { grid-column: 1 / -1 !important; grid-row: 2 !important; justify-self: start; } +#panel-overview .stats-grid>.stat.stat-chart[data-dashboard-widget^="docker_"]:has(>.docker-widget-scope)>:is(strong, small) { grid-row: 3 !important; } +#panel-overview .stats-grid>.stat.stat-chart[data-dashboard-widget^="docker_"]:has(>.docker-widget-scope)>:is(svg:not(.ui-icon), .rp-chart-axis-host) { grid-row: 4 !important; } +#panel-overview [data-dashboard-widget^="docker_"]>span[data-instance]::after { content: " #" attr(data-instance); color: var(--muted); font-weight: 400; } diff --git a/src/admin/web/css/50-settings.css b/src/admin/web/css/50-settings.css index d0c4e0b..e3d8faa 100644 --- a/src/admin/web/css/50-settings.css +++ b/src/admin/web/css/50-settings.css @@ -1471,3 +1471,72 @@ html[data-dashboard-density=normal] #panel-overview .stat>span, display: block; max-width: 320px; } + +.choice-picker.is-disabled .acl-picker-summary { pointer-events: none; opacity: .55; } +.choice-picker .acl-picker-tag.is-primary { border-color: var(--accent); } +.choice-picker .acl-picker-tag.is-primary>span::before { content: "★ "; color: var(--accent); } +.docker-certificate-field>select { width: 100%; min-height: 38px; box-sizing: border-box; } +.docker-certificate-field>.acl-picker { margin-top: 6px; } +.docker-agent-add-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-top: 14px; } +.docker-target-control { display: flex; gap: 6px; min-width: 0; } +.docker-target-control>select { flex: 1 1 60%; } +.docker-target-control>input { flex: 1 1 40%; } +.docker-target-control>input[hidden] { display: none; } +.docker-provision { margin: 4px 0 10px; border: 1px dashed var(--line); border-radius: var(--rp-radius-control, 8px); padding: 8px 11px; background: var(--panel); } +.docker-provision>summary { display: flex; flex-wrap: wrap; gap: 4px 10px; align-items: baseline; cursor: pointer; font-size: 12px; font-weight: 600; user-select: none; } +.docker-provision>summary small { font-weight: 400; } +.docker-provision-code { display: block; width: 100%; min-height: 54px; margin: 8px 0 4px; box-sizing: border-box; resize: vertical; font-size: 12px; word-break: break-all; } +.docker-provision-status.is-error { color: var(--red); } +.docker-hostname-row, +.docker-alias-row { display: flex; gap: 6px; align-items: stretch; min-width: 0; } +.docker-hostname-row>input { flex: 1 1 auto; min-width: 0; } +.docker-hostname-row>select, +.docker-alias-row>select { flex: 0 1 auto; max-width: 48%; min-width: 0; } +.docker-alias-row>.docker-alias-editor { flex: 1 1 auto; min-width: 0; } +.docker-hostname-field { display: grid; align-content: start; gap: 6px; min-width: 0; } +.docker-service-certificate-bar { flex-wrap: wrap; row-gap: 4px; } +.docker-certificate-hint { display: block; flex: 1 0 100%; margin-top: 2px; line-height: 1.35; } +.docker-agent-diagnostics { margin: 0 0 10px; padding: 9px 11px; border: 1px solid var(--line); border-radius: var(--rp-radius-control, 8px); background: var(--panel2); font-size: 12px; } +.docker-agent-diagnostics[hidden] { display: none; } +.docker-agent-diagnostics-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; } +.docker-agent-diagnostics-error { margin: 6px 0 0; color: var(--red); overflow-wrap: anywhere; } +.docker-agent-diagnostics .docker-system-grid { margin-top: 8px; } +.docker-agent-system { margin-top: 10px; } +.docker-agent-system>.small-label { display: block; margin-bottom: 6px; } +.docker-system-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(170px, 1fr)); gap: 8px; } +.docker-system-grid.is-compact { grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 6px; } +.docker-system-item { display: grid; gap: 2px; min-width: 0; padding: 7px 9px; border: 1px solid var(--line); border-radius: var(--rp-radius-control, 8px); background: var(--panel); } +.docker-system-item>span { color: var(--muted); font-size: 10px; letter-spacing: .04em; text-transform: uppercase; } +.docker-system-item>strong { font: 600 12px var(--mono); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.docker-system-meter { display: block; height: 4px; margin-top: 3px; overflow: hidden; border-radius: 3px; background: var(--line); } +.docker-system-meter>b { display: block; height: 100%; background: var(--green); border-radius: inherit; } +.docker-system-meter.is-warn>b { background: var(--accent); } +.docker-system-meter.is-high>b { background: var(--red); } +.docker-system-item.is-wide { grid-column: span 2; } +.acl-picker-tag .acl-picker-promote { border: 0; background: none; color: var(--muted); padding: 0 2px; min-height: 0; cursor: pointer; font-size: 12px; line-height: 1; } +.acl-picker-tag .acl-picker-promote:hover { color: var(--accent); } +.overview-inline-hidden-item .docker-widget-scope, +.overview-layout-hidden-item .docker-widget-scope { max-width: 160px; min-height: 26px; padding: 2px 6px; font-size: 11px; } +.docker-system-spark { display: block; width: 100%; height: 18px; margin-top: 4px; overflow: visible; } +.docker-system-spark polyline { fill: none; stroke-width: 1.4; vector-effect: non-scaling-stroke; } +.docker-spark-primary { stroke: var(--chart-primary, var(--accent)); } +.docker-spark-secondary { stroke: var(--chart-secondary, var(--green)); } +.docker-agent-system-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; margin-bottom: 6px; } +.docker-agent-system-head>.small-label { margin-bottom: 0; } +.docker-alerts { margin-bottom: 12px; padding: 10px 14px; border-left: 3px solid var(--accent); } +.docker-alerts.is-error { border-left-color: var(--red); } +.docker-alerts>summary { display: flex; flex-wrap: wrap; gap: 4px 12px; align-items: baseline; cursor: pointer; } +.docker-alert-list { margin: 8px 0 0; padding: 0; list-style: none; display: grid; gap: 4px; font-size: 12px; } +.docker-alert-list>li { display: flex; gap: 8px; align-items: baseline; overflow-wrap: anywhere; } +.docker-alert-icon { color: var(--accent); font-size: 10px; } +.docker-alert-list>li.is-error .docker-alert-icon { color: var(--red); } +.docker-alert-settings { margin-top: 14px; } +.docker-alert-editor { border: 1px solid var(--line); border-radius: var(--rp-radius-control, 8px); padding: 9px 12px; background: var(--panel); } +.docker-alert-editor>summary { display: flex; flex-wrap: wrap; gap: 4px 10px; align-items: baseline; cursor: pointer; font-weight: 600; font-size: 13px; } +.docker-alert-editor>summary small { font-weight: 400; } +.docker-alert-grid { margin-top: 10px; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); } +.docker-agent-test-row { display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: center; margin: 0 0 10px; } +.docker-agent-test-result.is-ok { color: var(--green); } +.docker-agent-test-result.is-error { color: var(--red); overflow-wrap: anywhere; } +.docker-label-badge { align-self: center; } +.docker-container-state { display: inline-flex; flex-wrap: wrap; gap: 4px 8px; align-items: center; } diff --git a/src/admin/web/dashboard-defaults.json b/src/admin/web/dashboard-defaults.json index 4b8aa9a..9beb772 100644 --- a/src/admin/web/dashboard-defaults.json +++ b/src/admin/web/dashboard-defaults.json @@ -16,6 +16,30 @@ "stream_traffic", "stream_sessions", "stream_backend_health", + "docker_agents", + "docker_apps", + "docker_requests", + "docker_host_network", + "docker_host_load", + "docker_containers", + "docker_agents_2", + "docker_apps_2", + "docker_requests_2", + "docker_host_network_2", + "docker_host_load_2", + "docker_containers_2", + "docker_agents_3", + "docker_apps_3", + "docker_requests_3", + "docker_host_network_3", + "docker_host_load_3", + "docker_containers_3", + "docker_agents_4", + "docker_apps_4", + "docker_requests_4", + "docker_host_network_4", + "docker_host_load_4", + "docker_containers_4", "backend_health", "backend_activity", "backend_errors", @@ -120,6 +144,30 @@ "extra_cache_hit_rate", "backend_capacity", "stream_traffic", + "docker_agents", + "docker_apps", + "docker_requests", + "docker_host_network", + "docker_host_load", + "docker_containers", + "docker_agents_2", + "docker_apps_2", + "docker_requests_2", + "docker_host_network_2", + "docker_host_load_2", + "docker_containers_2", + "docker_agents_3", + "docker_apps_3", + "docker_requests_3", + "docker_host_network_3", + "docker_host_load_3", + "docker_containers_3", + "docker_agents_4", + "docker_apps_4", + "docker_requests_4", + "docker_host_network_4", + "docker_host_load_4", + "docker_containers_4", "backend_http5xx", "bandwidth", "backend_queue", @@ -150,4 +198,4 @@ ], "dashboard_density": "compact", "overview_samples": 600 -} \ No newline at end of file +} diff --git a/src/admin/web/dashboard-widgets.json b/src/admin/web/dashboard-widgets.json index 40179b1..a76edff 100644 --- a/src/admin/web/dashboard-widgets.json +++ b/src/admin/web/dashboard-widgets.json @@ -186,6 +186,288 @@ "default_hidden": true, "display_type": "value" }, + { + "id": "docker_agents", + "label_key": "dockerWidgetAgents", + "description_key": "dockerWidgetAgentsDescription", + "element_selector": "[data-dashboard-widget=\"docker_agents\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value" + }, + { + "id": "docker_apps", + "label_key": "dockerWidgetApps", + "description_key": "dockerWidgetAppsDescription", + "element_selector": "[data-dashboard-widget=\"docker_apps\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value" + }, + { + "id": "docker_requests", + "label_key": "dockerWidgetRequests", + "description_key": "dockerWidgetRequestsDescription", + "element_selector": "[data-dashboard-widget=\"docker_requests\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value_chart" + }, + { + "id": "docker_host_network", + "label_key": "dockerWidgetNetwork", + "description_key": "dockerWidgetNetworkDescription", + "element_selector": "[data-dashboard-widget=\"docker_host_network\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value_chart" + }, + { + "id": "docker_host_load", + "label_key": "dockerWidgetLoad", + "description_key": "dockerWidgetLoadDescription", + "element_selector": "[data-dashboard-widget=\"docker_host_load\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value" + }, + { + "id": "docker_containers", + "label_key": "dockerWidgetContainers", + "description_key": "dockerWidgetContainersDescription", + "element_selector": "[data-dashboard-widget=\"docker_containers\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value" + }, + { + "id": "docker_agents_2", + "label_key": "dockerWidgetAgents", + "description_key": "dockerWidgetAgentsDescription", + "element_selector": "[data-dashboard-widget=\"docker_agents_2\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value", + "instance": 2 + }, + { + "id": "docker_apps_2", + "label_key": "dockerWidgetApps", + "description_key": "dockerWidgetAppsDescription", + "element_selector": "[data-dashboard-widget=\"docker_apps_2\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value", + "instance": 2 + }, + { + "id": "docker_requests_2", + "label_key": "dockerWidgetRequests", + "description_key": "dockerWidgetRequestsDescription", + "element_selector": "[data-dashboard-widget=\"docker_requests_2\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value_chart", + "instance": 2 + }, + { + "id": "docker_host_network_2", + "label_key": "dockerWidgetNetwork", + "description_key": "dockerWidgetNetworkDescription", + "element_selector": "[data-dashboard-widget=\"docker_host_network_2\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value_chart", + "instance": 2 + }, + { + "id": "docker_host_load_2", + "label_key": "dockerWidgetLoad", + "description_key": "dockerWidgetLoadDescription", + "element_selector": "[data-dashboard-widget=\"docker_host_load_2\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value", + "instance": 2 + }, + { + "id": "docker_containers_2", + "label_key": "dockerWidgetContainers", + "description_key": "dockerWidgetContainersDescription", + "element_selector": "[data-dashboard-widget=\"docker_containers_2\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value", + "instance": 2 + }, + { + "id": "docker_agents_3", + "label_key": "dockerWidgetAgents", + "description_key": "dockerWidgetAgentsDescription", + "element_selector": "[data-dashboard-widget=\"docker_agents_3\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value", + "instance": 3 + }, + { + "id": "docker_apps_3", + "label_key": "dockerWidgetApps", + "description_key": "dockerWidgetAppsDescription", + "element_selector": "[data-dashboard-widget=\"docker_apps_3\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value", + "instance": 3 + }, + { + "id": "docker_requests_3", + "label_key": "dockerWidgetRequests", + "description_key": "dockerWidgetRequestsDescription", + "element_selector": "[data-dashboard-widget=\"docker_requests_3\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value_chart", + "instance": 3 + }, + { + "id": "docker_host_network_3", + "label_key": "dockerWidgetNetwork", + "description_key": "dockerWidgetNetworkDescription", + "element_selector": "[data-dashboard-widget=\"docker_host_network_3\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value_chart", + "instance": 3 + }, + { + "id": "docker_host_load_3", + "label_key": "dockerWidgetLoad", + "description_key": "dockerWidgetLoadDescription", + "element_selector": "[data-dashboard-widget=\"docker_host_load_3\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value", + "instance": 3 + }, + { + "id": "docker_containers_3", + "label_key": "dockerWidgetContainers", + "description_key": "dockerWidgetContainersDescription", + "element_selector": "[data-dashboard-widget=\"docker_containers_3\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value", + "instance": 3 + }, + { + "id": "docker_agents_4", + "label_key": "dockerWidgetAgents", + "description_key": "dockerWidgetAgentsDescription", + "element_selector": "[data-dashboard-widget=\"docker_agents_4\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value", + "instance": 4 + }, + { + "id": "docker_apps_4", + "label_key": "dockerWidgetApps", + "description_key": "dockerWidgetAppsDescription", + "element_selector": "[data-dashboard-widget=\"docker_apps_4\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value", + "instance": 4 + }, + { + "id": "docker_requests_4", + "label_key": "dockerWidgetRequests", + "description_key": "dockerWidgetRequestsDescription", + "element_selector": "[data-dashboard-widget=\"docker_requests_4\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value_chart", + "instance": 4 + }, + { + "id": "docker_host_network_4", + "label_key": "dockerWidgetNetwork", + "description_key": "dockerWidgetNetworkDescription", + "element_selector": "[data-dashboard-widget=\"docker_host_network_4\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value_chart", + "instance": 4 + }, + { + "id": "docker_host_load_4", + "label_key": "dockerWidgetLoad", + "description_key": "dockerWidgetLoadDescription", + "element_selector": "[data-dashboard-widget=\"docker_host_load_4\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value", + "instance": 4 + }, + { + "id": "docker_containers_4", + "label_key": "dockerWidgetContainers", + "description_key": "dockerWidgetContainersDescription", + "element_selector": "[data-dashboard-widget=\"docker_containers_4\"]", + "data_source": "docker_status", + "no_data": "neutral_dash", + "category": "docker", + "default_hidden": true, + "display_type": "value", + "instance": 4 + }, { "id": "backend_health", "label_key": "backendWidgetHealth", @@ -945,4 +1227,4 @@ "default_hidden": true, "display_type": "value_chart" } -] \ No newline at end of file +] diff --git a/src/admin/web/docker.js b/src/admin/web/docker.js index 8f19de8..b51f6c9 100644 --- a/src/admin/web/docker.js +++ b/src/admin/web/docker.js @@ -1,7 +1,7 @@ "use strict"; (() => { const sortColumns = ["service", "hostname", "status", "backend", "scheme", "published"]; - let observations = [], pools = [], poolRoutes = [], poolIndex = new Map(), showHidden = false, listPrefs = { sort: "service", descending: false }; + let observations = [], pools = [], poolRoutes = [], poolIndex = new Map(), dockerAlerts = [], labelIssues = [], systemHistory = new Map(), showHidden = false, listPrefs = { sort: "service", descending: false }; const collapsedMetrics = new Set(), metricHistory = new Map(); function normalizeListPrefs(preferences) { return { sort: sortColumns.includes(preferences?.docker_vhost_sort) ? preferences.docker_vhost_sort : "service", descending: preferences?.docker_vhost_descending === true }; } function syncSortDirection() { const control = $("docker-vhost-sort-direction"); if (!control) return; control.textContent = listPrefs.descending ? "↓" : "↑"; control.setAttribute("aria-label", t(listPrefs.descending ? "backendSortDescending" : "backendSortAscending")); } @@ -10,6 +10,25 @@ const LIVE_KEY = "rustproxy.docker.live-view"; const HIDDEN_KEY = "rustproxy.docker.hidden-vhosts"; const cfg = () => envelope?.config?.docker_agents || { agents: [] }; + const PROVISION_PREFIX = "RPDA1-", CUSTOM_IP = "__custom__", MAX_DOMAINS = 16, MAX_CERTIFICATES = 32; + const cleanDomain = value => String(value || "").trim().replace(/\.$/, "").toLowerCase(); + function agentDomains(agent) { const list = Array.isArray(agent?.domains) && agent.domains.length ? agent.domains : (agent?.base_domain ? [agent.base_domain] : []); return [...new Set(list.map(cleanDomain).filter(Boolean))]; } + function agentCertificates(agent) { return [...new Set([agent?.certificate_id, ...(agent?.certificate_ids || [])].filter(Boolean))]; } + function masterDomain(agent, assignment) { const domains = agentDomains(agent), wanted = cleanDomain(assignment?.domain); return domains.includes(wanted) ? wanted : (domains[0] || ""); } + function hostInDomains(host, domains) { host = cleanDomain(host); return domains.some(domain => host === domain || host.endsWith(`.${domain}`)); } + function validDnsName(value) { return value.length <= 253 && /^[a-z0-9.-]+$/.test(value) && !value.startsWith(".") && !value.endsWith(".") && value.split(".").every(part => part && part.length <= 63 && !part.startsWith("-") && !part.endsWith("-")); } + function certificateNames(cert) { const inventory = typeof certificateInventory !== "undefined" && certificateInventory instanceof Map ? certificateInventory.get(cert.id) : null; const names = inventory?.covered_hosts?.length ? inventory.covered_hosts : (cert.covered_hosts?.length ? cert.covered_hosts : (cert.hosts || [])); return names.map(name => String(name).toLowerCase()); } + function nameCovers(pattern, host) { if (pattern === host) return 2; if (!pattern.startsWith("*.")) return 0; const suffix = pattern.slice(1); return host.length > suffix.length && host.endsWith(suffix) && !host.slice(0, -suffix.length).includes(".") ? 1 : 0; } + function pickCertificate(ids, hosts) { + let best = null; + for (const id of ids) { + const cert = (envelope?.config?.tls?.certificates || []).find(item => item.id === id); if (!cert) continue; + const names = certificateNames(cert); let exact = 0; + if (!hosts.every(host => { const score = Math.max(0, ...names.map(name => nameCovers(name, host))); if (score === 2) exact++; return score > 0; })) continue; + if (!best || exact > best.exact || (exact === best.exact && names.length < best.size)) best = { id, exact, size: names.length }; + } + return best?.id || ""; + } const obs = id => observations.find(item => item.agent_id === id); const hasUnobservedAgent = () => (cfg().agents || []).some(agent => agent.enabled !== false && !obs(agent.id)); const firstListener = () => envelope?.config?.listeners?.endpoints?.find(item => item.enabled !== false)?.id || "http"; @@ -21,13 +40,13 @@ let hiddenVhosts = loadHidden(); const viewKey = (agentId, serviceKey) => `${agentId}|${serviceKey}`; function saveHidden() { try { localStorage.setItem(HIDDEN_KEY, JSON.stringify([...hiddenVhosts].sort())); } catch { } } - function expandedHost(value, baseDomain) { const host = String(value || "").trim().replace(/\.$/, "").toLowerCase(); return host && host.includes(".") ? host : host ? `${host}.${baseDomain}` : ""; } + function expandedHost(value, baseDomain) { const host = String(value || "").trim().replace(/\.$/, "").toLowerCase(); return host && host.includes(".") ? host : host && baseDomain ? `${host}.${baseDomain}` : ""; } function publicListener(agent) { const endpoints = envelope?.config?.listeners?.endpoints || [], wanted = new Set(agent?.listener_ids || []), candidates = endpoints.filter(item => item.enabled !== false && wanted.has(item.id)); return candidates.find(item => item.binding?.tls === true) || candidates[0] || null; } - function proxiedUrl(agent, hostname) { - const host = expandedHost(hostname, agent.base_domain); if (!host) return ""; + function proxiedUrl(agent, hostname, domain = masterDomain(agent)) { + const host = expandedHost(hostname, domain); if (!host) return ""; const listener = publicListener(agent), secure = !!listener?.binding?.tls, scheme = secure ? "https" : "http", address = String(listener?.binding?.address || ""); const match = address.match(/:(\d+)$/), port = match ? Number(match[1]) : (secure ? 443 : 80), suffix = port === (secure ? 443 : 80) ? "" : `:${port}`; return `${scheme}://${host}${suffix}/`; @@ -72,19 +91,24 @@ if (help) wrapper.append(el("small", help, "fine")); return wrapper; } - function aliasEditor(initial = [], onChange = () => { }) { + function aliasEditor(initial = [], onChange = () => { }, scope = { domains: [], master: () => "" }) { const field = el("div", undefined, "docker-field docker-alias-field host-chip-field"), box = el("div", undefined, "host-chip-editor docker-alias-editor"), inputNode = input("", "text", "docker-alias-input"); field.append(el("span", t("dockerAliases"))); inputNode.maxLength = 253; inputNode.placeholder = "alias1 / app.example.com"; inputNode.setAttribute("aria-label", t("dockerAliasAdd")); + const aliasDomain = el("select", undefined, "docker-alias-domain"); aliasDomain.setAttribute("aria-label", t("dockerAliasDomain")); aliasDomain.title = t("dockerAliasDomain"); + const fillAliasDomains = () => { const current = aliasDomain.value; aliasDomain.replaceChildren(); const master = el("option", `.${scope.master() || "…"} (${t("dockerDomainMasterShort")})`); master.value = ""; aliasDomain.append(master); for (const domain of scope.domains) { const option = el("option", `.${domain}`); option.value = domain; aliasDomain.append(option); } aliasDomain.value = [...aliasDomain.options].some(option => option.value === current) ? current : ""; }; + fillAliasDomains(); const values = []; const normalize = raw => { - const value = String(raw || "").trim().toLowerCase().replace(/\.$/, ""); if (!value) return null; - if (value.length > 253 || !/^[a-z0-9.-]+$/.test(value) || value.startsWith(".") || value.endsWith(".") || value.split(".").some(part => !part || part.length > 63 || part.startsWith("-") || part.endsWith("-"))) throw new Error(t("vhHostInvalid")); + let value = String(raw || "").trim().toLowerCase().replace(/\.$/, ""); if (!value) return null; + if (!value.includes(".") && aliasDomain.value) value = `${value}.${aliasDomain.value}`; + if (!validDnsName(value)) throw new Error(t("vhHostInvalid")); + if (value.includes(".") && scope.domains.length && !hostInDomains(value, scope.domains)) throw new Error(t("dockerAliasOutsideDomains").replace("{host}", value).replace("{domains}", scope.domains.join(", "))); return value; }; const sync = () => { box.querySelectorAll(".host-chip").forEach(node => node.remove()); for (const value of values) { - const chip = el("span", undefined, "host-chip"); chip.append(el("span", value)); const remove = el("button", "×"); remove.type = "button"; remove.setAttribute("aria-label", `${t("remove")} ${value}`); + const chip = el("span", undefined, "host-chip"); chip.append(el("span", value)); chip.title = value.includes(".") ? value : `${value}.${scope.master()}`; const remove = el("button", "×"); remove.type = "button"; remove.setAttribute("aria-label", `${t("remove")} ${value}`); remove.addEventListener("click", () => { values.splice(values.indexOf(value), 1); sync(); onChange(); }); chip.append(remove); box.insertBefore(chip, inputNode); } }; @@ -93,8 +117,9 @@ inputNode.addEventListener("keydown", event => { if (event.key === "Enter" || event.key === ",") { event.preventDefault(); try { consume(inputNode.value); } catch (error) { toast(error.message, true); } } }); inputNode.addEventListener("blur", () => { if (!inputNode.value.trim()) return; try { consume(inputNode.value); } catch (error) { toast(error.message, true); } }); inputNode.addEventListener("paste", event => { const value = event.clipboardData?.getData("text") || ""; if (!/[\s,]/.test(value.trim())) return; event.preventDefault(); try { consume(value); } catch (error) { toast(error.message, true); } }); - box.append(inputNode); field.append(box); field.title = t("dockerAliasesHelp"); inputNode.title = t("dockerAliasesHelp"); for (const value of initial) { try { add(value, false); } catch { } } - return { node: field, read() { if (inputNode.value.trim()) consume(inputNode.value); return [...values]; }, count: () => values.length, input: inputNode }; + box.append(inputNode); const editorRow = el("div", undefined, "docker-alias-row"); editorRow.append(box, aliasDomain); field.append(editorRow); field.title = t("dockerAliasesHelp"); inputNode.title = t("dockerAliasesHelp"); + for (const value of initial) { const clean = String(value || "").trim().toLowerCase().replace(/\.$/, ""); if (clean && !values.includes(clean)) values.push(clean); } sync(); + return { node: field, read() { if (inputNode.value.trim()) consume(inputNode.value); return [...values]; }, count: () => values.length, peek: () => [...values], input: inputNode, refresh() { fillAliasDomains(); sync(); } }; } function serviceBindings(service) { if (!service) return []; @@ -148,49 +173,251 @@ const hint = row.querySelector(".docker-agent-security-hint"); if (hint) hint.textContent = info.detail; } - function agentSettingsRow(agent = null) { - const value = agent || { id: "", name: "", enabled: true, endpoint: "https://127.0.0.1:9876", token: "", tls_fingerprint_sha256: null, base_domain: "docker1.lab.local", poll_interval_seconds: 30, certificate_id: null, acl_profile_id: null, default_target_ip: null, listener_ids: [firstListener()], assignments: [] }; + function decodeProvisionCode(raw) { + const code = String(raw || "").replace(/\s+/g, ""); + if (!code.startsWith(PROVISION_PREFIX)) throw new Error(t("dockerProvisionInvalid")); + let payload; + try { + const body = code.slice(PROVISION_PREFIX.length).replace(/-/g, "+").replace(/_/g, "/"), padded = body + "=".repeat((4 - body.length % 4) % 4); + const binary = atob(padded), data = Uint8Array.from(binary, ch => ch.charCodeAt(0)); + payload = JSON.parse(new TextDecoder().decode(data)); + } catch { throw new Error(t("dockerProvisionInvalid")); } + const endpoint = String(payload?.endpoint || ""), fingerprint = String(payload?.fingerprint || "").replace(/[^a-fA-F0-9]/g, "").toLowerCase(); + if (!/^https?:\/\/[^/?#\s]+$/i.test(endpoint) || (fingerprint && fingerprint.length !== 64)) throw new Error(t("dockerProvisionInvalid")); + const base = { name: String(payload.name || "").slice(0, 96), endpoint, fingerprint, agentVersion: String(payload.agent || "") }; + if (payload?.v === 2) { + const enrollment = String(payload.enroll || ""), expires = Number(payload.expires) || 0; + if (enrollment.length < 24 || enrollment.length > 512 || fingerprint.length !== 64 || !endpoint.startsWith("https://")) throw new Error(t("dockerProvisionInvalid")); + if (expires && expires * 1000 < Date.now()) throw new Error(t("dockerProvisionExpired")); + return { ...base, enrollment, expires }; + } + const token = String(payload?.token || ""); + if (payload?.v !== 1 || token.length < 24 || token.length > 512) throw new Error(t("dockerProvisionInvalid")); + return { ...base, token }; + } + function domainOptionsFor(selected) { + const known = new Map(), add = (domain, detail) => { domain = cleanDomain(domain).replace(/^\*\./, ""); if (domain && domain.includes(".") && validDnsName(domain) && !known.has(domain)) known.set(domain, detail); }; + for (const agent of cfg().agents || []) for (const domain of agentDomains(agent)) add(domain, `${t("dockerAgent")}: ${agent.name || agent.id}`); + for (const cert of envelope?.config?.tls?.certificates || []) for (const name of certificateNames(cert)) if (name.startsWith("*.")) add(name, `${t("vhCertificate")}: ${cert.id}`); + for (const domain of selected) add(domain, ""); + return [...known.entries()].map(([id, detail]) => ({ id, title: id, detail })); + } + function domainPicker(selected) { + return window.rustProxyChoicePicker.create({ + className: "docker-agent-domains", selected, items: domainOptionsFor(selected), limit: MAX_DOMAINS, markFirst: "dockerDomainMaster", makeFirst: "dockerDomainMakeMaster", + labels: { choose: "dockerDomainsChoose", selected: "dockerDomainsSelected", none: "dockerDomainsNone", search: "dockerDomainsSearch", addHint: "dockerDomainsAddHint", empty: "dockerDomainsEmpty" }, + custom: raw => { const domain = cleanDomain(raw).replace(/^\*\./, ""); if (!domain) return null; if (!domain.includes(".") || !validDnsName(domain)) throw new Error(`${t("dockerDomainInvalid")}: ${raw}`); return { id: domain, title: domain }; } + }); + } + function certificatePicker(selected) { + const items = (envelope?.config?.tls?.certificates || []).map(cert => { const names = certificateNames(cert); return { id: cert.id, title: cert.id, detail: names.slice(0, 4).join(", ") + (names.length > 4 ? ` +${names.length - 4}` : ""), search: names.join(" "), badge: cert.issuer ? "ACME" : "", badgeClass: "is-allow" }; }); + return window.rustProxyChoicePicker.create({ className: "docker-agent-certificates", selected, items, limit: MAX_CERTIFICATES, unknownDetail: "dockerCertificateUnknown", labels: { choose: "dockerCertificatesChoose", selected: "dockerCertificatesSelected", none: "dockerCertificatesNone", empty: "dockerCertificatesEmpty" } }); + } + function detectedAddresses(agentId) { return (obs(agentId)?.inventory?.addresses || []).map(address => { const details = [address.interface, address.scope, address.source].filter(Boolean).join(" · "); return [address.ip, details ? `${address.ip} (${details})` : address.ip]; }); } + function targetIpControl(agent, current) { + const wrap = el("div", undefined, "docker-target-control"), select = el("select", undefined, "docker-agent-target"), custom = input("", "text", "docker-agent-target-custom mono"); + custom.placeholder = "10.0.0.20 / 2001:db8::20"; custom.maxLength = 45; custom.spellcheck = false; + const auto = el("option", t("dockerTargetAutoDetected")); auto.value = ""; select.append(auto); + const detected = detectedAddresses(agent?.id); + for (const [ip, label] of detected) { const option = el("option", label); option.value = ip; select.append(option); } + const customOption = el("option", t("dockerTargetCustom")); customOption.value = CUSTOM_IP; select.append(customOption); + current = String(current || ""); + if (!current) select.value = ""; else if (detected.some(([ip]) => ip === current)) select.value = current; else { select.value = CUSTOM_IP; custom.value = current; } + const sync = () => { custom.hidden = select.value !== CUSTOM_IP; custom.required = select.value === CUSTOM_IP; }; + select.addEventListener("change", () => { sync(); if (select.value === CUSTOM_IP) custom.focus(); }); sync(); + if (!detected.length) wrap.title = t("dockerTargetNoDetected"); + wrap.append(select, custom); + return { node: wrap, read() { if (select.value !== CUSTOM_IP) return select.value || null; const value = custom.value.trim(); if (!value) throw fieldError(custom, t("dockerTargetCustomRequired")); return value; } }; + } + function percent(part, total) { return total > 0 ? Math.max(0, Math.min(100, part / total * 100)) : 0; } + function meterItem(label, used, total, text) { + const item = el("div", undefined, "docker-system-item docker-system-meter-item"), pct = percent(used, total), meter = el("i", undefined, "docker-system-meter"), fill = el("b"); + fill.style.width = `${pct.toFixed(1)}%`; if (pct >= 90) meter.classList.add("is-high"); else if (pct >= 75) meter.classList.add("is-warn"); + meter.append(fill); item.append(el("span", label), el("strong", text), meter); item.title = `${pct.toFixed(1)}%`; return item; + } + function recordHistory() { + const limit = window.rustProxyOverviewSamples?.getLimit?.() || 120, live = new Set(); + for (const observation of observations) { + live.add(observation.agent_id); + const system = observation.ok ? observation.inventory?.system : null; if (!system) continue; + const samples = systemHistory.get(observation.agent_id) || []; + if (samples.at(-1)?.t === observation.checked_at_unix_ms) continue; + const total = Number(system.memory_total_bytes), available = Number(system.memory_available_bytes); + samples.push({ t: observation.checked_at_unix_ms, cpu: system.cpu_percent, memory: total > 0 && Number.isFinite(available) ? (total - available) / total * 100 : undefined, load1: system.load1, rx: system.network_rx_bytes_per_second, tx: system.network_tx_bytes_per_second }); + while (samples.length > limit) samples.shift(); + systemHistory.set(observation.agent_id, samples); + } + for (const id of [...systemHistory.keys()]) if (!live.has(id)) systemHistory.delete(id); + } + function sparkline(values, max = null, secondary = null) { + const series = values.map(value => Number(value)).filter(Number.isFinite), extra = (secondary || []).map(value => Number(value)).filter(Number.isFinite); + if (series.length < 2) return null; + const peak = max ?? Math.max(1, ...series, ...extra), svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + svg.setAttribute("viewBox", "0 0 100 20"); svg.setAttribute("preserveAspectRatio", "none"); svg.setAttribute("class", "docker-system-spark"); svg.setAttribute("aria-hidden", "true"); + const draw = (list, cls) => { const line = document.createElementNS("http://www.w3.org/2000/svg", "polyline"); line.setAttribute("class", cls); line.setAttribute("points", list.map((value, index) => `${(index * 100 / Math.max(1, list.length - 1)).toFixed(2)},${(19 - Math.min(1, value / peak) * 18).toFixed(2)}`).join(" ")); svg.append(line); }; + draw(series, "docker-spark-primary"); if (extra.length > 1) draw(extra, "docker-spark-secondary"); + return svg; + } + function systemDetails(system, compact = false, history = []) { + if (!system || typeof system !== "object") return null; + const pick = key => (history || []).map(sample => sample[key]).filter(value => value !== undefined && value !== null); + const has = value => value !== undefined && value !== null && value !== ""; + const grid = el("div", undefined, `docker-system-grid${compact ? " is-compact" : ""}`), add = (key, value, title = "") => { if (!has(value)) return; const item = el("div", undefined, "docker-system-item"); item.append(el("span", t(key)), el("strong", String(value))); item.title = title ? `${value}\n${title}` : String(value); grid.append(item); }; + const withSpark = (spark) => { if (spark && !compact) grid.lastElementChild?.append(spark); }; + if (!compact) { add("dockerSystemOs", [system.os, system.arch].filter(Boolean).join(" · "), system.kernel ? `${t("dockerSystemKernel")}: ${system.kernel}` : ""); grid.lastElementChild?.classList.add("is-wide"); } + if (has(system.runtime)) add("dockerSystemRuntime", `${system.runtime === "podman" ? "Podman" : "Docker"}${system.runtime_version ? ` ${system.runtime_version}` : ""}`); + if (has(system.uptime_seconds)) add("dockerSystemUptime", uptime(system.uptime_seconds)); + if (has(system.load1)) { const cpus = Number(system.cpu_count) || 0, load = [system.load1, system.load5, system.load15].filter(has).map(value => Number(value).toFixed(2)).join(" / "); add("dockerSystemLoad", load, cpus ? `${t("dockerSystemCpus")}: ${cpus} · ${t("dockerSystemLoadPerCpu")}: ${(Number(system.load1) / cpus).toFixed(2)}` : ""); withSpark(sparkline(pick("load1"), Math.max(1, Number(system.cpu_count) || 1, ...pick("load1")))); } + if (has(system.cpu_percent)) { grid.append(meterItem(t("dockerSystemCpu"), Number(system.cpu_percent), 100, `${Number(system.cpu_percent).toFixed(1)}%${system.cpu_count ? ` · ${system.cpu_count} ${t("dockerSystemCores")}` : ""}`)); withSpark(sparkline(pick("cpu"), 100)); } + if (has(system.memory_total_bytes) && has(system.memory_available_bytes)) { const total = Number(system.memory_total_bytes), used = Math.max(0, total - Number(system.memory_available_bytes)); grid.append(meterItem(t("dockerSystemMemory"), used, total, `${bytes(used)} / ${bytes(total)}`)); withSpark(sparkline(pick("memory"), 100)); } + if (!compact && Number(system.swap_total_bytes) > 0 && has(system.swap_free_bytes)) { const total = Number(system.swap_total_bytes), used = Math.max(0, total - Number(system.swap_free_bytes)); grid.append(meterItem(t("dockerSystemSwap"), used, total, `${bytes(used)} / ${bytes(total)}`)); } + if (has(system.disk_total_bytes) && has(system.disk_free_bytes)) { const total = Number(system.disk_total_bytes), used = Math.max(0, total - Number(system.disk_free_bytes)); grid.append(meterItem(t("dockerSystemDisk"), used, total, `${bytes(used)} / ${bytes(total)}`)); } + if (has(system.network_rx_bytes_per_second) || has(system.network_rx_bytes)) { + const rate = has(system.network_rx_bytes_per_second) ? `↓ ${rateBytes(system.network_rx_bytes_per_second)}/s · ↑ ${rateBytes(system.network_tx_bytes_per_second)}/s` : t("dockerSystemRatePending"); + add("dockerSystemNetwork", rate, has(system.network_rx_bytes) ? `${t("dockerSystemNetworkTotal")}: ↓ ${bytes(Number(system.network_rx_bytes))} · ↑ ${bytes(Number(system.network_tx_bytes))}` : ""); grid.lastElementChild?.classList.add("is-wide"); withSpark(sparkline(pick("rx"), null, pick("tx"))); + } + if (has(system.containers_running)) add("dockerSystemContainers", `${fmt(system.containers_running)} / ${fmt(system.containers_total)}`, `${t("dockerSystemContainersHelp")}${has(system.images) ? ` · ${t("dockerSystemImages")}: ${fmt(system.images)}` : ""}`); + if (!compact && has(system.images)) add("dockerSystemImages", fmt(system.images)); + return grid.children.length ? grid : null; + } + function renderAgentDiagnostics(holder) { + if (!holder) return; + const agentId = holder.dataset.agentId, state = agentId ? obs(agentId) : null; holder.replaceChildren(); + if (!state) { holder.hidden = true; return; } + holder.hidden = false; + const head = el("div", undefined, "docker-agent-diagnostics-head"), inventory = state.inventory; + head.append(el("span", t("dockerAgentDiagnostics"), "small-label"), el("span", state.ok ? t("dockerConnected") : t("dockerError"), `pill ${state.ok ? "live" : "warn"}`.trim()), el("span", `${t("dockerLastChecked")}: ${checkedAgo(state.checked_at_unix_ms)}`, "fine")); + if (inventory) head.append(el("span", `${t("dockerHost")}: ${inventory.hostname} · ${t("dockerAgentVersion")}: ${inventory.agent_version} · ${t("dockerServices")}: ${(inventory.services || []).length}`, "fine")); + holder.append(head); + if (!state.ok && state.error) holder.append(el("p", state.error, "fine docker-agent-diagnostics-error")); + const system = systemDetails(inventory?.system, true); if (system) holder.append(system); + } + function renderSettingsDiagnostics() { document.querySelectorAll("#docker-agent-settings-list .docker-agent-diagnostics").forEach(renderAgentDiagnostics); } + + function agentSettingsRow(agent = null, options = {}) { + const value = agent || { id: "", name: "", enabled: true, endpoint: "https://127.0.0.1:9876", token: "", tls_fingerprint_sha256: null, domains: [], poll_interval_seconds: 30, certificate_ids: [], acl_profile_id: null, default_target_ip: null, listener_ids: [firstListener()], assignments: [] }; const row = el("div", undefined, "docker-agent-settings entity"); row.dataset.originalId = agent?.id || ""; row._assignments = structuredClone(value.assignments || []); - const head = el("div", undefined, "card-heading"), title = el("div"); title.append(el("span", t("dockerAgent"), "small-label"), el("h3", value.name || value.id || t("dockerAgentNew"))); + const head = el("div", undefined, "card-heading"), title = el("div"), titleText = el("h3", value.name || value.id || t("dockerAgentNew")); title.append(el("span", t("dockerAgent"), "small-label"), titleText); const enabled = input("", "checkbox", "docker-agent-enabled"); enabled.checked = value.enabled !== false; const enabledLabel = el("label", undefined, "check"); enabledLabel.append(enabled, el("span", t("enabled"))); const state = agent ? obs(agent.id) : null, stateBadge = el("span", state?.ok ? t("dockerConnected") : state ? t("dockerError") : t("dockerWaiting"), `pill docker-agent-status-badge ${state?.ok ? "live" : ""}`.trim()); const remove = action(t("remove"), () => { row.remove(); setSettingsDirty("docker-agents-form"); }), actions = el("div", undefined, "entity-actions docker-agent-heading-actions"); actions.append(enabledLabel, stateBadge, remove); head.append(title, actions); const id = input(value.id, "text", "docker-agent-id"); id.maxLength = 64; id.required = true; id.pattern = "[A-Za-z0-9_\\-]{1,64}"; if (agent) id.readOnly = true; const name = input(value.name, "text", "docker-agent-name"); name.maxLength = 96; name.required = true; + name.addEventListener("input", () => { titleText.textContent = name.value.trim() || id.value.trim() || t("dockerAgentNew"); }); const endpoint = input(value.endpoint, "url", "docker-agent-endpoint"); endpoint.required = true; endpoint.placeholder = "https://10.0.0.20:9876"; const token = input(value.token, "password", "docker-agent-token"); token.minLength = 24; token.maxLength = 512; token.required = true; token.autocomplete = "new-password"; const fingerprint = input(value.tls_fingerprint_sha256 || "", "text", "docker-agent-fingerprint mono"); fingerprint.maxLength = 128; fingerprint.placeholder = "SHA-256"; fingerprint.spellcheck = false; - const domain = input(value.base_domain, "text", "docker-agent-domain"); domain.required = true; domain.placeholder = "docker1.lab.local"; const poll = input(value.poll_interval_seconds ?? 30, "number", "docker-agent-poll"); poll.min = 5; poll.max = 3600; poll.required = true; - const target = input(value.default_target_ip || value.target_ip_override || "", "text", "docker-agent-target"); target.placeholder = t("dockerTargetAuto"); - const certificate = el("select", undefined, "docker-agent-certificate"), defaultCertificate = el("option", t("vhCertificateDefault")); defaultCertificate.value = ""; certificate.append(defaultCertificate); - for (const cert of envelope?.config?.tls?.certificates || []) { const item = el("option", cert.id); item.value = cert.id; certificate.append(item); } certificate.value = value.certificate_id || ""; + const target = targetIpControl(agent, value.default_target_ip || value.target_ip_override || ""); row._readTarget = target.read; + const domains = domainPicker(agentDomains(value)); row._domains = domains; + const domainsField = profileField("dockerDomains", domains, t("dockerDomainsHelp")); + const certificateIds = agentCertificates(value), certMode = el("select", undefined, "docker-agent-certificate-mode"); + for (const [mode, key] of [["auto", "dockerCertificateAuto"], ["selected", "dockerCertificateSelected"]]) { const option = el("option", t(key)); option.value = mode; certMode.append(option); } + certMode.value = certificateIds.length ? "selected" : "auto"; + const certificates = certificatePicker(certificateIds); row._certificates = certificates; + const certificateField = el("div", undefined, "docker-field docker-profile-field docker-certificate-field"), certificateHelp = el("small", "", "fine"); + certificateField.append(el("span", t("dockerCertificates")), certMode, certificates, certificateHelp); + const syncCertificateMode = () => { const selected = certMode.value === "selected"; certificates.hidden = !selected; certificateHelp.textContent = t(selected ? "dockerCertificateSelectedHelp" : "dockerCertificateAutoHelp"); }; + certMode.addEventListener("change", syncCertificateMode); syncCertificateMode(); const defaultAcl = profileChoices(selectedProfileIds(value), "docker-agent-acl-profile"); const defaultAclField = profileField("dockerDefaultAcl", defaultAcl, t("dockerDefaultAclHelp")); defaultAclField.append(profileWarning(defaultAcl)); + const provision = el("details", undefined, "docker-provision"), provisionSummary = el("summary"); provisionSummary.append(el("span", t("dockerProvisionTitle")), el("small", t("dockerProvisionSummary"), "fine")); + const provisionInput = document.createElement("textarea"); provisionInput.className = "docker-provision-code mono"; provisionInput.rows = 2; provisionInput.spellcheck = false; provisionInput.autocomplete = "off"; provisionInput.placeholder = "RPDA1-…"; provisionInput.setAttribute("aria-label", t("dockerProvisionTitle")); + const provisionStatus = el("small", t("dockerProvisionHelp"), "fine docker-provision-status"); + provision.append(provisionSummary, provisionInput, provisionStatus); provision.open = !!options.provision; + let provisioning = false; + const applyProvision = async () => { + const raw = provisionInput.value.trim(); if (!raw || provisioning) return; + try { + provisioning = true; + const data = decodeProvisionCode(raw), fire = node => node.dispatchEvent(new Event("input", { bubbles: true })); + if (data.enrollment) { + provisionStatus.classList.remove("is-error"); provisionStatus.textContent = t("dockerProvisionEnrolling"); + const reply = await api("/api/docker/enroll", { method: "POST", body: JSON.stringify({ endpoint: data.endpoint, tls_fingerprint_sha256: data.fingerprint, enrollment_token: data.enrollment }) }); + data.token = reply.token; + } + if (!name.value.trim() && data.name) { name.value = data.name; fire(name); } + endpoint.value = data.endpoint; token.value = data.token; fingerprint.value = data.fingerprint; [endpoint, token, fingerprint].forEach(fire); + provisionInput.value = ""; provisionStatus.textContent = t("dockerProvisionApplied").replace("{endpoint}", data.endpoint); provisionStatus.classList.remove("is-error"); + updateSecurityBadge(row); setSettingsDirty("docker-agents-form"); + } catch (error) { provisionStatus.textContent = error.message; provisionStatus.classList.add("is-error"); } + finally { provisioning = false; } + }; + provisionInput.addEventListener("paste", () => setTimeout(() => void applyProvision(), 0)); + provisionInput.addEventListener("change", () => void applyProvision()); + provisionInput.addEventListener("keydown", event => { if (event.key === "Enter") { event.preventDefault(); void applyProvision(); } }); + row.focusProvision = () => { provision.open = true; provisionInput.focus(); }; + const labelPublish = input("", "checkbox", "docker-agent-label-publish"); labelPublish.checked = value.label_publish === true; + const labelField = checkboxField("dockerLabelPublish", labelPublish); labelField.append(el("small", t("dockerLabelPublishHelp"), "fine")); + const testButton = el("button", t("dockerTestConnection"), "outline docker-agent-test"), testResult = el("small", "", "fine docker-agent-test-result"); testButton.type = "button"; + testButton.addEventListener("click", async () => { + testButton.disabled = true; testResult.className = "fine docker-agent-test-result"; testResult.textContent = t("dockerTestRunning"); + try { + const data = await api("/api/docker/test", { method: "POST", body: JSON.stringify({ endpoint: endpoint.value.trim().replace(/\/$/, ""), token: token.value, tls_fingerprint_sha256: fingerprint.value.trim() || null }) }); + if (data.ok) { testResult.classList.add("is-ok"); testResult.textContent = t("dockerTestOk").replace("{host}", data.hostname || "-").replace("{version}", data.agent_version || "-").replace("{services}", data.services ?? 0).replace("{ms}", data.elapsed_ms ?? "-"); } + else { testResult.classList.add("is-error"); testResult.textContent = `${t("dockerTestFailed")}: ${data.error || "-"}`; } + } catch (error) { testResult.classList.add("is-error"); testResult.textContent = `${t("dockerTestFailed")}: ${error.message}`; } + finally { testButton.disabled = false; } + }); + const testRow = el("div", undefined, "docker-agent-test-row"); testRow.append(testButton, testResult); const grid = el("div", undefined, "field-grid docker-agent-grid"); - grid.append(labeled("dockerAgentId", id), labeled("dockerAgentName", name), labeled("dockerAgentEndpoint", endpoint, t("dockerAgentEndpointHelp")), labeled("dockerAgentToken", token), labeled("dockerTlsFingerprint", fingerprint, t("dockerTlsFingerprintHelp")), labeled("dockerBaseDomain", domain), labeled("dockerPollInterval", poll, t("dockerPollIntervalHelp")), labeled("dockerDefaultTarget", target), labeled("dockerCertificate", certificate, t("dockerCertificateHelp")), defaultAclField); + const idField = labeled("dockerAgentId", id); + grid.append(labeled("dockerAgentName", name), idField, labeled("dockerAgentEndpoint", endpoint, t("dockerAgentEndpointHelp")), labeled("dockerAgentToken", token), labeled("dockerTlsFingerprint", fingerprint, t("dockerTlsFingerprintHelp")), labeled("dockerPollInterval", poll, t("dockerPollIntervalHelp")), domainsField, certificateField, labeled("dockerDefaultTarget", target.node, t("dockerDefaultTargetHelp")), defaultAclField, labelField); const listenerField = el("div", undefined, "docker-agent-listener-field"); listenerField.append(el("span", t("dockerListeners"), "docker-agent-field-label")); const listenerControl = window.rustProxyIntegrations.bindings(listenerField, value.listener_ids || [], !agent); listenerField.querySelector(".listener-choices")?.classList.add("docker-agent-listener-choices"); row._readListeners = listenerControl.read; grid.append(listenerField); const security = el("div", undefined, "docker-agent-security"), secBadge = el("span", "", "pill docker-agent-security-badge"), secHint = el("span", "", "fine docker-agent-security-hint"); security.append(secBadge, secHint); - endpoint.addEventListener("input", () => updateSecurityBadge(row)); fingerprint.addEventListener("input", () => updateSecurityBadge(row)); row.append(head, security, grid); updateSecurityBadge(row); return row; + const diagnostics = el("div", undefined, "docker-agent-diagnostics"); diagnostics.dataset.agentId = agent?.id || ""; renderAgentDiagnostics(diagnostics); + endpoint.addEventListener("input", () => updateSecurityBadge(row)); fingerprint.addEventListener("input", () => updateSecurityBadge(row)); row.append(head, provision, diagnostics, security, testRow, grid); updateSecurityBadge(row); + window.rustProxyAutoId.attach(id, { elements: [name], taken: () => [...(cfg().agents || []).map(item => item.id), ...[...document.querySelectorAll("#docker-agent-settings-list .docker-agent-id")].filter(node => node !== id).map(node => node.value.trim())].filter(Boolean) }); + return row; } function renderSettings() { - const target = $("docker-agent-settings-list"); if (!target || !envelope || settingsDirty.has("docker-agents-form")) return; - target.replaceChildren(...(cfg().agents || []).map(agentSettingsRow)); if (!target.children.length) target.append(el("p", t("dockerNoAgents"), "empty")); + const target = $("docker-agent-settings-list"); if (!target || !envelope) return; + if (settingsDirty.has("docker-agents-form")) { renderSettingsDiagnostics(); return; } + target.replaceChildren(...(cfg().agents || []).map(agent => agentSettingsRow(agent))); if (!target.children.length) target.append(el("p", t("dockerNoAgents"), "empty")); + renderAlertSettings(); + if (!settingsObservationsRequested && authenticated && (cfg().agents || []).length) { settingsObservationsRequested = true; void refresh(false); } + } + let settingsObservationsRequested = false; + const ALERT_DEFAULTS = { enabled: true, disk_percent: 90, memory_percent: 95, load_per_cpu: 2, service_missing: true, container_unhealthy: true }; + function renderAlertSettings() { + const holder = $("docker-alert-settings"); if (!holder || !envelope) return; + const value = { ...ALERT_DEFAULTS, ...(cfg().alerts || {}) }, box = el("details", undefined, "docker-alert-editor"), summary = el("summary"); + summary.append(el("span", t("dockerAlertSettings")), el("small", t("dockerAlertSettingsHelp"), "fine")); box.append(summary); + const grid = el("div", undefined, "field-grid docker-alert-grid"), check = (cls, checked) => { const node = input("", "checkbox", cls); node.checked = checked; return node; }; + const num = (cls, val, min, max, step = 1) => { const node = input(val, "number", cls); node.min = min; node.max = max; node.step = step; node.required = true; return node; }; + grid.append(checkboxField("dockerAlertEnabled", check("docker-alert-enabled", value.enabled !== false)), + labeled("dockerAlertDisk", num("docker-alert-disk", value.disk_percent, 50, 100)), + labeled("dockerAlertMemory", num("docker-alert-memory", value.memory_percent, 50, 100)), + labeled("dockerAlertLoad", num("docker-alert-load", value.load_per_cpu, 0.1, 64, 0.1)), + checkboxField("dockerAlertServiceMissing", check("docker-alert-missing", value.service_missing !== false)), + checkboxField("dockerAlertUnhealthy", check("docker-alert-unhealthy", value.container_unhealthy !== false))); + box.append(grid); holder.replaceChildren(box); + } + function collectAlertSettings() { + const holder = $("docker-alert-settings"); if (!holder?.querySelector(".docker-alert-grid")) return structuredClone(cfg().alerts || ALERT_DEFAULTS); + const n = cls => Number(holder.querySelector(cls).value); + return { enabled: holder.querySelector(".docker-alert-enabled").checked, disk_percent: n(".docker-alert-disk"), memory_percent: n(".docker-alert-memory"), load_per_cpu: n(".docker-alert-load"), service_missing: holder.querySelector(".docker-alert-missing").checked, container_unhealthy: holder.querySelector(".docker-alert-unhealthy").checked }; } function collectSettings() { const rows = [...$("docker-agent-settings-list").querySelectorAll(".docker-agent-settings")]; return { + alerts: collectAlertSettings(), agents: rows.map(row => { const listenerIds = row._readListeners?.() || []; if (!listenerIds.length) throw fieldError(row.querySelector(".docker-agent-listener-choices") || row, t("dockerListenersRequired")); + const domains = row._domains.read(); if (!domains.length) { row._domains.querySelector("details").open = true; throw fieldError(row._domains.querySelector(".acl-picker-search") || row, t("dockerDomainsRequired")); } + const certificateIds = row.querySelector(".docker-agent-certificate-mode").value === "selected" ? row._certificates.read() : []; + if (row.querySelector(".docker-agent-certificate-mode").value === "selected" && !certificateIds.length) throw fieldError(row.querySelector(".docker-agent-certificate-mode"), t("dockerCertificatesRequired")); + const assignments = structuredClone(row._assignments || []); + for (const assignment of assignments) if (assignment.domain && !domains.includes(cleanDomain(assignment.domain))) assignment.domain = domains[0]; return { id: row.querySelector(".docker-agent-id").value.trim(), name: row.querySelector(".docker-agent-name").value.trim(), enabled: row.querySelector(".docker-agent-enabled").checked, endpoint: row.querySelector(".docker-agent-endpoint").value.trim().replace(/\/$/, ""), token: row.querySelector(".docker-agent-token").value, - tls_fingerprint_sha256: row.querySelector(".docker-agent-fingerprint").value.trim() || null, base_domain: row.querySelector(".docker-agent-domain").value.trim().toLowerCase(), - poll_interval_seconds: Number(row.querySelector(".docker-agent-poll").value), certificate_id: row.querySelector(".docker-agent-certificate").value || null, acl_profile_id: null, acl_profile_ids: readProfileChoices(row, ".docker-agent-acl-profile"), default_target_ip: row.querySelector(".docker-agent-target").value.trim() || null, - listener_ids: listenerIds, assignments: structuredClone(row._assignments || []) + tls_fingerprint_sha256: row.querySelector(".docker-agent-fingerprint").value.trim() || null, domains, + poll_interval_seconds: Number(row.querySelector(".docker-agent-poll").value), label_publish: row.querySelector(".docker-agent-label-publish").checked, certificate_ids: certificateIds, acl_profile_id: null, acl_profile_ids: readProfileChoices(row, ".docker-agent-acl-profile"), default_target_ip: row._readTarget(), + listener_ids: listenerIds, assignments }; }) }; @@ -363,7 +590,7 @@ function collectAssignment(row) { const inline = row.querySelector(".docker-acl-inline")?.checked; return { - service_key: row.dataset.key, hostname: row.querySelector(".docker-hostname").value.trim().toLowerCase(), aliases: row._readAliases?.() || [], target_ip: row.querySelector(".docker-target-ip").value || null, + service_key: row.dataset.key, hostname: row.querySelector(".docker-hostname").value.trim().toLowerCase().replace(/\.$/, ""), domain: row.querySelector(".docker-master-domain")?.value || null, aliases: row._readAliases?.() || [], target_ip: row.querySelector(".docker-target-ip").value || null, enabled: true, scheme: row.querySelector(".docker-scheme").value, preserve_host: row.querySelector(".docker-preserve-host").checked, force_ssl: row.querySelector(".docker-force-ssl").checked, websockets: row.querySelector(".docker-websockets").checked, http2_enabled: row.querySelector(".docker-http2-enabled").checked, http3_enabled: row.querySelector(".docker-http3-enabled").checked, cache_enabled: row.querySelector(".docker-cache-enabled").checked, transform_enabled: row.querySelector(".docker-transform-enabled").checked, compression_enabled: row.querySelector(".docker-compression-enabled").checked, compression_zstd: null, compression_br: null, compression_gzip: null, compression_deflate: null, acl_profile_id: null, acl_profile_ids: readProfileChoices(row, ".docker-acl-profile"), @@ -378,17 +605,21 @@ const index = (agent.assignments || []).findIndex(item => item.service_key === row.dataset.key); if (publish) { const assignment = collectAssignment(row); if (!assignment.hostname) throw new Error(t("dockerHostnameRequired")); + const domains = agentDomains(agent); + if (!assignment.domain && !assignment.hostname.includes(".")) throw new Error(t("dockerDomainsRequired")); + if (assignment.hostname.includes(".") && domains.length && !hostInDomains(assignment.hostname, domains)) throw new Error(t("dockerAliasOutsideDomains").replace("{host}", assignment.hostname).replace("{domains}", domains.join(", "))); const previous = index >= 0 ? agent.assignments[index] : null; const consentNames = item => JSON.stringify([item?.hostname || "", ...(item?.aliases || [])].map(v => v.toLowerCase().replace(/\.$/, "")).sort()); if (assignment.allow_certificate_mismatch && (!previous?.allow_certificate_mismatch || consentNames(assignment) !== consentNames(previous)) && !(await appConfirm(t("dockerCertMismatchConfirm"), { danger: true }))) return false; if (index >= 0) agent.assignments[index] = assignment; else agent.assignments.push(assignment); } + else if (row.dataset.fromLabels === "1") { const assignment = { ...collectAssignment(row), enabled: false }; if (index >= 0) agent.assignments[index] = assignment; else agent.assignments.push(assignment); } else if (index >= 0) agent.assignments.splice(index, 1); const saved = await saveSection("docker-agents", current); if (saved) row.classList.remove("is-dirty"); return saved; } function assignmentRow(agent, inventory, service, assignment, stale = false) { - const key = assignment?.service_key || service.key, row = el("article", undefined, "docker-service-row"); row.dataset.key = key; row.dataset.viewKey = viewKey(agent.id, key); + const key = assignment?.service_key || service.key, row = el("article", undefined, "docker-service-row"); row.dataset.key = key; row.dataset.viewKey = viewKey(agent.id, key); if (assignment?.from_labels) row.dataset.fromLabels = "1"; const runtime = runtimeFor(agent.id, key), member = runtime?.members?.[0], technicalName = service?.technical_name || assignment?.service_key || ""; row.dockerSort = { service: technicalName.toLowerCase(), hostname: String(assignment?.hostname || service?.technical_name || "" || technicalName).toLowerCase(), @@ -402,6 +633,22 @@ publishLabel.append(el("span", t("dockerPublish"), "docker-publish-text"), publish); const meta = el("div", undefined, "docker-service-meta"), technical = service?.technical_name || assignment?.service_key || "-", bindings = serviceBindings(service).map(binding => `${binding.bind_ip || "*"}:${binding.public_port}`).join(", "); meta.append(el("b", technical), el("span", stale ? t("dockerServiceMissing") : `${service.container_name} · ${service.image}`), el("span", stale ? assignment.service_key : `${service.private_port}/tcp → ${bindings || "-"}`)); + const fromLabels = assignment?.from_labels === true, issue = labelIssues.find(item => item.agent_id === agent.id && item.service_key === key); + if (fromLabels) { const badge = el("span", t("dockerLabelPublished"), "pill live docker-label-badge"); badge.title = t("dockerLabelPublishedHelp"); meta.append(badge); } + if (issue) { const badge = el("span", t("dockerLabelIssue"), "pill warn docker-label-badge"); badge.title = issue.error; meta.append(badge); } + const container = service?.container; + if (container && (container.state || container.health || container.cpu_percent != null || container.memory_bytes != null)) { + const stateLine = el("span", undefined, "docker-container-state"), healthCls = container.health === "unhealthy" || ["restarting", "exited", "dead"].includes(container.state) ? "danger" : container.health === "healthy" ? "live" : ""; + const healthText = { healthy: t("dockerContainerHealthy"), unhealthy: t("dockerContainerUnhealthy"), starting: t("dockerContainerHealthStarting"), none: t("dockerContainerNoHealthcheck") }[container.health] || container.health; + if (container.state || container.health) { const pill = el("span", [container.state, healthText].filter(Boolean).join(" · "), `pill ${healthCls}`.trim()); if (container.health === "none") pill.title = t("dockerContainerNoHealthcheckHelp"); stateLine.append(pill); } + const parts = []; + if (container.cpu_percent != null) parts.push(`CPU ${Number(container.cpu_percent).toFixed(1)}%`); + if (container.memory_bytes != null) parts.push(`RAM ${bytes(Number(container.memory_bytes))}${container.memory_limit_bytes ? ` / ${bytes(Number(container.memory_limit_bytes))}` : ""}`); + if (container.restart_count != null) parts.push(`${t("dockerContainerRestarts")}: ${fmt(container.restart_count)}`); + if (parts.length) stateLine.append(el("small", parts.join(" · "), "fine")); + if (container.started_at) stateLine.title = `${t("dockerContainerStarted")}: ${container.started_at}`; + meta.append(stateLine); + } const visibility = el("button", "", "quiet docker-view-toggle"); visibility.type = "button"; const syncVisibility = () => { visibility.textContent = t(hiddenVhosts.has(row.dataset.viewKey) ? "dockerUnhideVhost" : "dockerHideVhost"); }; syncVisibility(); visibility.addEventListener("click", () => { const key = row.dataset.viewKey; if (hiddenVhosts.has(key)) hiddenVhosts.delete(key); else hiddenVhosts.add(key); saveHidden(); syncVisibility(); applyViewFilters(); }); const openApp = el("a", t("dockerOpenApp"), "outline docker-open-app"); openApp.target = "_blank"; openApp.rel = "noopener noreferrer"; @@ -412,12 +659,15 @@ if (publish.checked && route?.pool_id) window.rustProxyLogs?.open(route.pool_id); }); const syncOpenActions = hostname => { - const url = proxiedUrl(agent, hostname); + const url = proxiedUrl(agent, hostname, row.querySelector(".docker-master-domain")?.value || masterDomain(agent, assignment)); openApp.href = url || "#"; openApp.hidden = !publish.checked || !url; openApp.title = url || ""; liveLogs.hidden = !publish.checked; liveLogs.disabled = !publish.checked || !poolRoutes.some(item => item.agent_id === agent.id && item.service_key === key && item.pool_id); publish.setAttribute("aria-checked", String(publish.checked)); }; + const domainSelect = el("select", undefined, "docker-master-domain"), domains = agentDomains(agent); domainSelect.setAttribute("aria-label", t("dockerMasterDomain")); + for (const domain of domains) { const option = el("option", `.${domain}`); option.value = domain; domainSelect.append(option); } + domainSelect.value = masterDomain(agent, assignment); domainSelect.disabled = domains.length < 2; syncOpenActions(assignment?.hostname || service?.technical_name || ""); const quickActions = el("div", undefined, "docker-service-quick-actions"); quickActions.append(openApp, liveLogs); const headActions = el("div", undefined, "docker-service-head-actions"); headActions.append(runtimeSummary(runtime, assignment, stale), quickActions, visibility); top.append(publishLabel, meta, headActions); row.append(top); @@ -425,7 +675,11 @@ const editor = el("details", undefined, "docker-service-editor"), editorSummary = el("summary"), editorTitle = el("span", t("dockerConfigureService")), editorHint = el("small", "", "fine docker-config-hint"); editorSummary.append(editorTitle, editorHint); editor.append(editorSummary); const route = el("div", undefined, "docker-route-grid"), host = input(assignment?.hostname || service?.technical_name || "", "text", "docker-hostname"); host.maxLength = 253; host.placeholder = service?.technical_name || "app1"; row.dockerSyncActions = () => syncOpenActions(host.value); - let aliases; const aliasChanged = () => { updateHint?.(); row.dispatchEvent(new Event("input", { bubbles: true })); }; aliases = aliasEditor(assignment?.aliases || [], aliasChanged); row._readAliases = aliases.read; + let aliases; const aliasChanged = () => { updateHint?.(); row.dispatchEvent(new Event("input", { bubbles: true })); }; aliases = aliasEditor(assignment?.aliases || [], aliasChanged, { domains, master: () => domainSelect.value }); row._readAliases = aliases.read; + const hostField = el("label", undefined, "docker-field docker-hostname-field"), hostRow = el("div", undefined, "docker-hostname-row"), hostHelp = el("small", "", "fine"); + hostRow.append(host, domainSelect); hostField.append(el("span", t("dockerHostname")), hostRow, hostHelp); + const syncHostHelp = () => { const full = expandedHost(host.value, domainSelect.value); hostHelp.textContent = `${t("dockerHostnameHelp").replace("{domain}", domainSelect.value || "-")}${full ? ` → ${full}` : ""}`; }; + domainSelect.addEventListener("change", () => { syncHostHelp(); aliases.refresh(); syncOpenActions(host.value); updateHint(); }); host.addEventListener("input", syncHostHelp); const target = el("select", undefined, "docker-target-ip"), auto = el("option", agent.default_target_ip ? `${t("dockerBackendIpAuto")} (${agent.default_target_ip})` : t("dockerBackendIpAuto")); auto.value = ""; target.append(auto); for (const [ip, label] of targetOptions(inventory, service, assignment, agent)) { const option = el("option", label); option.value = ip; target.append(option); } target.value = assignment?.target_ip || ""; const scheme = el("select", undefined, "docker-scheme"); for (const name of ["http", "https"]) { const option = el("option", name.toUpperCase()); option.value = name; scheme.append(option); } scheme.value = assignment?.scheme || "http"; const preserve = input("", "checkbox", "docker-preserve-host"); preserve.checked = assignment?.preserve_host !== false; const preserveLabel = checkboxField("dockerPreserveHost", preserve); preserveLabel.classList.add("docker-preserve-field"); @@ -436,13 +690,19 @@ const compressionEnabled = input("", "checkbox", "docker-compression-enabled"); compressionEnabled.checked = assignment?.compression_enabled !== false; const compressionField = checkboxField("dockerCompression", compressionEnabled); compressionField.title = t("dockerCompressionHelp"); const switches = el("div", undefined, "docker-switch-row"); switches.append(preserveLabel, forceSslField, websocketField, cacheField, compressionField, transformField); const certMismatch = input("", "checkbox", "docker-cert-mismatch"); certMismatch.checked = assignment?.allow_certificate_mismatch === true; - certMismatch.disabled = !agent.certificate_id; + certMismatch.disabled = !agentCertificates(agent).length; if (certMismatch.disabled) certMismatch.checked = false; const mismatchLabel = el("label", undefined, "check"); mismatchLabel.append(certMismatch, el("span", t("dockerCertMismatchForce"))); mismatchLabel.title = t(certMismatch.disabled ? "dockerCertMismatchUnavailable" : "dockerCertMismatchWarning"); const certificateBar = el("div", undefined, "docker-service-certificate-bar"); - certificateBar.append(mismatchLabel); + const certificateHint = el("small", "", "fine docker-certificate-hint"); certificateBar.append(mismatchLabel, certificateHint); + const syncCertificateHint = () => { + const ids = agentCertificates(agent); if (!ids.length) { certificateHint.textContent = t("dockerCertificateHintAuto"); return; } + const hosts = [expandedHost(host.value.trim() || technical, domainSelect.value), ...aliases.peek().map(alias => expandedHost(alias, domainSelect.value))].filter(Boolean); + const picked = pickCertificate(ids, hosts); + certificateHint.textContent = picked ? t("dockerCertificateHintMatched").replace("{id}", picked) : t(certMismatch.checked ? "dockerCertificateHintForced" : "dockerCertificateHintGeneric").replace("{id}", ids[0]); + }; const backendIpSettings = el("div", undefined, "docker-backend-ip-settings"); backendIpSettings.append(labeled("dockerBackendIp", target), certificateBar); @@ -455,13 +715,13 @@ h1.append(el("strong", "HTTP/1.1"), el("small", t("dockerHttp1Always"), "fine")); protocolOptions.append(h1, checkboxField("dockerHttp2Enabled", h2Enabled), checkboxField("dockerHttp3Enabled", h3Enabled)); protocolBox.append(protocolSummary, protocolOptions); - route.append(labeled("dockerHostname", host, t("dockerHostnameHelp").replace("{domain}", agent.base_domain)), aliases.node, backendIpSettings, labeled("dockerBackendScheme", scheme), switches); + route.append(hostField, aliases.node, backendIpSettings, labeled("dockerBackendScheme", scheme), switches); syncHostHelp(); editor.append(route, protocolBox, aclEditor(assignment, agent), timeoutEditor(assignment), healthEditor(assignment), passiveHealthEditor(assignment)); const actions = el("div", undefined, "docker-service-actions"), apply = el("button", t("dockerApplyService"), "outline docker-apply"); apply.type = "button"; apply.disabled = !publish.checked; apply.addEventListener("click", async () => { apply.disabled = true; try { await saveAssignment(agent.id, row, true); } catch (error) { toast(error.message, true); } finally { if (row.isConnected) apply.disabled = !publish.checked; } }); actions.append(apply); editor.append(actions); row.append(editor); if (agent.enabled !== false && assignment && assignment.enabled !== false) row.append(statisticsSection(agent, key)); - function updateHint() { const targetLabel = target.selectedOptions?.[0]?.textContent || t("dockerBackendIpAuto"), aliasCount = aliases.count(); editorHint.textContent = `${host.value.trim() || technical} → ${scheme.value.toUpperCase()} · ${targetLabel} · H1${h2Enabled.checked ? "/H2" : ""}${h3Enabled.checked ? "/H3" : ""}${aliasCount ? ` · +${aliasCount} ${t("dockerAliasesShort")}` : ""}`; } updateHint(); + function updateHint() { syncCertificateHint(); const targetLabel = target.selectedOptions?.[0]?.textContent || t("dockerBackendIpAuto"), aliasCount = aliases.count(); editorHint.textContent = `${expandedHost(host.value.trim() || technical, domainSelect.value) || host.value.trim() || technical} → ${scheme.value.toUpperCase()} · ${targetLabel} · H1${h2Enabled.checked ? "/H2" : ""}${h3Enabled.checked ? "/H3" : ""}${aliasCount ? ` · +${aliasCount} ${t("dockerAliasesShort")}` : ""}`; } updateHint(); for (const control of [host, aliases.input, target, scheme]) { control.addEventListener("input", updateHint); control.addEventListener("change", updateHint); } - for (const control of [h2Enabled, h3Enabled]) control.addEventListener("change", updateHint); + for (const control of [h2Enabled, h3Enabled, certMismatch]) control.addEventListener("change", updateHint); host.addEventListener("input", () => syncOpenActions(host.value)); row.addEventListener("input", event => { if (!event.target.classList.contains("docker-publish")) row.classList.add("is-dirty"); }); row.addEventListener("change", event => { if (!event.target.classList.contains("docker-publish")) row.classList.add("is-dirty"); }); publish.addEventListener("change", async () => { @@ -474,22 +734,39 @@ } function addressSummary(inventory) { const addresses = inventory.addresses || []; if (!addresses.length && inventory.public_ip) return inventory.public_ip; return addresses.map(address => { const details = [address.interface, address.scope, address.source].filter(Boolean).join("/"); return details ? `${address.ip} (${details})` : address.ip; }).join(" · "); } + function renderAlertsBanner(target) { + if (!dockerAlerts.length) return; + const box = el("details", undefined, `card docker-alerts ${dockerAlerts.some(alert => alert.severity === "error") ? "is-error" : "is-warning"}`), summary = el("summary"); + summary.append(el("strong", t("dockerAlertsTitle").replace("{count}", dockerAlerts.length)), el("span", t("dockerAlertsHelp"), "fine")); + const list = el("ul", undefined, "docker-alert-list"); + for (const alert of dockerAlerts) { const item = el("li", undefined, `is-${alert.severity}`); item.append(el("span", alert.severity === "error" ? "●" : "▲", "docker-alert-icon"), el("span", window.rustProxyDockerDashboard?.alertText?.(alert) || alert.kind)); list.append(item); } + box.append(summary, list); box.open = dockerAlerts.length <= 5; target.append(box); + } function renderDiscovery() { const target = $("docker-discovery-list"); if (!target || !envelope) return; target.replaceChildren(); const agents = cfg().agents || []; + renderAlertsBanner(target); if (!agents.length) { target.append(el("p", t("dockerNoAgentsConfigured"), "card empty")); applyViewFilters(); return; } for (const agent of agents) { - const state = obs(agent.id), box = el("article", undefined, "card docker-agent-card"); box.dataset.agentId = agent.id; box.dataset.searchText = `${agent.id} ${agent.name || ""} ${agent.base_domain || ""}`.toLowerCase(); const head = el("div", undefined, "card-heading"), left = el("div"); left.append(el("span", agent.id, "small-label"), el("h2", agent.name)); + const state = obs(agent.id), box = el("article", undefined, "card docker-agent-card"); box.dataset.agentId = agent.id; box.dataset.searchText = `${agent.id} ${agent.name || ""} ${agentDomains(agent).join(" ")}`.toLowerCase(); const head = el("div", undefined, "card-heading"), left = el("div"); left.append(el("span", agent.id, "small-label"), el("h2", agent.name)); const badges = el("div", undefined, "entity-actions"), connection = el("span", state?.ok ? t("dockerConnected") : state ? t("dockerError") : t("dockerWaiting"), `pill ${state?.ok ? "live" : ""}`), sec = securityInfo(agent, state); badges.append(el("span", t(sec.key), `pill ${sec.cls}`.trim()), connection); head.append(left, badges); box.append(head); if (!agent.enabled) { box.append(el("p", t("dockerAgentDisabled"), "fine")); target.append(box); continue; } if (!state) box.append(el("p", t("dockerNoObservation"), "fine")); else if (!state.ok) { const error = el("div", undefined, "docker-agent-error"); error.append(el("b", t("dockerAgentConnectionFailed")), el("p", state.error || t("dockerUnknownPollError"), "fine")); box.append(error); } if (!state?.inventory) { const rows = el("div", undefined, "docker-service-list"); for (const item of agent.assignments || []) rows.append(assignmentRow(agent, null, null, item, true)); if (!rows.children.length) rows.append(el("p", t("dockerNoPublishedPorts"), "empty")); box.append(rows); target.append(box); continue; } const inv = state.inventory, defaultIp = agent.default_target_ip || agent.target_ip_override || t("dockerTargetAuto"), serviceCount = (inv.services || []).length, overview = el("div", undefined, "docker-agent-overview"); box.dataset.searchText += ` ${inv.hostname || ""}`.toLowerCase(); - overview.append(el("span", `${t("dockerHost")}: ${inv.hostname}`), el("span", `${t("dockerServices")}: ${serviceCount}`), el("span", `${t("dockerLastChecked")}: ${checkedAgo(state.checked_at_unix_ms)}`), el("span", `*.${agent.base_domain}`)); box.append(overview); + overview.append(el("span", `${t("dockerHost")}: ${inv.hostname}`), el("span", `${t("dockerServices")}: ${serviceCount}`), el("span", `${t("dockerLastChecked")}: ${checkedAgo(state.checked_at_unix_ms)}`), el("span", agentDomains(agent).map(domain => `*.${domain}`).join(" · ") || t("dockerDomainsNone"))); + const sys = inv.system; if (sys?.runtime) overview.append(el("span", `${sys.runtime === "podman" ? "Podman" : "Docker"}${sys.runtime_version ? ` ${sys.runtime_version}` : ""}`)); + if (sys?.load1 != null) overview.append(el("span", `${t("dockerSystemLoad")}: ${Number(sys.load1).toFixed(2)}`)); + if (sys?.uptime_seconds != null) overview.append(el("span", `${t("dockerSystemUptime")}: ${uptime(sys.uptime_seconds)}`)); + box.append(overview); const agentDetails = el("details", undefined, "docker-agent-details"), detailsSummary = el("summary", t("dockerAgentDetails")), summary = el("div", undefined, "docker-agent-summary"); const defaultAclName = selectedProfileIds(agent).map(id => ((envelope?.config?.acl_profiles || []).find(profile => profile.id === id)?.name || id)).join(", ") || t("dockerDefaultAclNone"); - summary.append(el("span", `${t("dockerAgentVersion")}: ${inv.agent_version}`), el("span", `${t("dockerAgentPollEvery")}: ${agent.poll_interval_seconds ?? 30}s`), el("span", `${t("dockerCertificate")}: ${agent.certificate_id || t("vhCertificateDefault")}`), el("span", `${t("dockerDefaultAcl")}: ${defaultAclName}`), el("span", `${t("dockerDetectedIps")}: ${addressSummary(inv) || t("unavailable")}`), el("span", `${t("dockerDefaultTarget")}: ${defaultIp}`), el("span", `${t("dockerBaseDomain")}: *.${agent.base_domain}`)); if (inv.certificate_sha256) summary.append(el("span", `${t("dockerTlsFingerprint")}: ${prettyFingerprint(inv.certificate_sha256)}`, "mono docker-fingerprint")); agentDetails.append(detailsSummary, summary); box.append(agentDetails); - const rows = el("div", undefined, "docker-service-list"), assignments = new Map((agent.assignments || []).map(item => [item.service_key, item])); for (const service of inv.services || []) rows.append(assignmentRow(agent, inv, service, assignments.get(service.key), false)); for (const item of agent.assignments || []) if (!(inv.services || []).some(service => service.key === item.service_key)) rows.append(assignmentRow(agent, inv, null, item, true)); if (!rows.children.length) rows.append(el("p", t("dockerNoPublishedPorts"), "empty")); box.append(rows); target.append(box); + summary.append(el("span", `${t("dockerAgentVersion")}: ${inv.agent_version}`), el("span", `${t("dockerAgentPollEvery")}: ${agent.poll_interval_seconds ?? 30}s`), el("span", `${t("dockerCertificates")}: ${agentCertificates(agent).join(", ") || t("dockerCertificateAuto")}`), el("span", `${t("dockerDefaultAcl")}: ${defaultAclName}`), el("span", `${t("dockerDetectedIps")}: ${addressSummary(inv) || t("unavailable")}`), el("span", `${t("dockerDefaultTarget")}: ${defaultIp}`), el("span", `${t("dockerDomains")}: ${agentDomains(agent).join(", ") || "-"}`)); if (inv.certificate_sha256) summary.append(el("span", `${t("dockerTlsFingerprint")}: ${prettyFingerprint(inv.certificate_sha256)}`, "mono docker-fingerprint")); agentDetails.append(detailsSummary, summary); + const history = systemHistory.get(agent.id) || [], system = systemDetails(inv.system, false, history); if (system) { const systemBlock = el("div", undefined, "docker-agent-system"), head = el("div", undefined, "docker-agent-system-head"); head.append(el("span", t("dockerAgentSystem"), "small-label")); if (history.length > 1) head.append(el("span", t("dockerSystemHistory").replace("{minutes}", Math.max(1, Math.round((history.at(-1).t - history[0].t) / 60000))), "fine")); systemBlock.append(head, system); agentDetails.append(systemBlock); } + box.append(agentDetails); + const rows = el("div", undefined, "docker-service-list"), assignments = new Map((agent.assignments || []).map(item => [item.service_key, item])); + for (const route of poolRoutes) if (route.agent_id === agent.id && route.source === "labels" && route.assignment && !assignments.has(route.service_key)) assignments.set(route.service_key, { ...route.assignment, from_labels: true }); + for (const service of inv.services || []) rows.append(assignmentRow(agent, inv, service, assignments.get(service.key), false)); for (const item of agent.assignments || []) if (!(inv.services || []).some(service => service.key === item.service_key)) rows.append(assignmentRow(agent, inv, null, item, true)); if (!rows.children.length) rows.append(el("p", t("dockerNoPublishedPorts"), "empty")); box.append(rows); target.append(box); } applyViewFilters(); renderDockerMetrics(); @@ -549,10 +826,10 @@ try { const data = await api(force ? "/api/docker/refresh" : "/api/docker", options); if (!authenticated || epoch !== authEpoch || (context?.isCurrent && !context.isCurrent())) return; - observations = data.observations || []; pools = data.pools || []; poolRoutes = data.pool_routes || []; + observations = data.observations || []; pools = data.pools || []; poolRoutes = data.pool_routes || []; dockerAlerts = data.alerts || []; labelIssues = data.label_issues || []; recordHistory(); poolIndex = new Map(pools.map(pool => [pool.id, pool])); document.querySelectorAll("#docker-discovery-list .docker-service-row").forEach(row => row.dockerSyncActions?.()); - renderSettings(); if (force || canLiveRender()) renderDiscovery(); + renderSettings(); renderSettingsDiagnostics(); if (force || canLiveRender()) renderDiscovery(); else renderDockerMetrics(); } catch (error) { if (force && error?.name !== "AbortError" && authenticated && epoch === authEpoch) toast(error.message, true); @@ -583,6 +860,7 @@ }); $("docker-show-hidden")?.addEventListener("click", () => { showHidden = !showHidden; applyViewFilters(); }); $("docker-agent-add")?.addEventListener("click", () => { const target = $("docker-agent-settings-list"); target.querySelector(".empty")?.remove(); target.append(agentSettingsRow()); setSettingsDirty("docker-agents-form"); }); + $("docker-agent-provision")?.addEventListener("click", () => { const target = $("docker-agent-settings-list"); target.querySelector(".empty")?.remove(); const row = agentSettingsRow(null, { provision: true }); target.append(row); setSettingsDirty("docker-agents-form"); row.scrollIntoView({ block: "nearest" }); row.focusProvision(); }); $("docker-agents-form")?.addEventListener("input", () => setSettingsDirty("docker-agents-form")); $("docker-agents-form")?.addEventListener("change", () => setSettingsDirty("docker-agents-form")); $("docker-agents-form")?.addEventListener("submit", async event => { event.preventDefault(); const form = event.currentTarget; if (!envelope || busy) return; try { @@ -590,7 +868,7 @@ const next = collectSettings(); const changingAcceptedCertificate = next.agents.some(agent => { const previous = (cfg().agents || []).find(old => old.id === agent.id); - return previous && previous.certificate_id !== agent.certificate_id && agent.assignments.some(item => item.allow_certificate_mismatch); + return previous && JSON.stringify(agentCertificates(previous)) !== JSON.stringify(agent.certificate_ids) && agent.assignments.some(item => item.allow_certificate_mismatch); }); if (changingAcceptedCertificate && !(await appConfirm(t("dockerCertMismatchConfirm"), { danger: true }))) return; if (await saveSection("docker-agents", next)) { setSettingsDirty("docker-agents-form", false); await refresh(true); } @@ -602,5 +880,5 @@ active: () => currentPanel === "docker-vhosts" && canLiveRender() && (liveEnabled() || hasUnobservedAgent()), run: async context => refresh(false, context) }); - window.rustProxyDocker = { render() { syncLiveSwitch(); renderSettings(); renderDiscovery(); if (currentPanel === "docker-vhosts" && authenticated) { rustProxyRefresh.sync(); void rustProxyRefresh.manual("docker"); } }, refresh, renderStatus: renderDockerMetrics, applyPreferences, reset() { observations = []; pools = []; poolRoutes = []; poolIndex = new Map(); collapsedMetrics.clear(); metricHistory.clear(); showHidden = false; listPrefs = { sort: "service", descending: false }; hiddenVhosts = loadHidden(); if ($("docker-search")) $("docker-search").value = ""; if ($("docker-vhost-sort")) $("docker-vhost-sort").value = listPrefs.sort; syncSortDirection(); $("docker-discovery-list")?.replaceChildren(); $("docker-agent-settings-list")?.replaceChildren(); syncLiveSwitch(); applyViewFilters(); } }; + window.rustProxyDocker = { observations: () => observations, routes: () => poolRoutes, agentDomains, systemDetails, render() { syncLiveSwitch(); renderSettings(); renderDiscovery(); if (currentPanel === "docker-vhosts" && authenticated) { rustProxyRefresh.sync(); void rustProxyRefresh.manual("docker"); } }, refresh, renderStatus: renderDockerMetrics, applyPreferences, reset() { observations = []; systemHistory = new Map(); settingsObservationsRequested = false; pools = []; poolRoutes = []; poolIndex = new Map(); collapsedMetrics.clear(); metricHistory.clear(); showHidden = false; listPrefs = { sort: "service", descending: false }; hiddenVhosts = loadHidden(); if ($("docker-search")) $("docker-search").value = ""; if ($("docker-vhost-sort")) $("docker-vhost-sort").value = listPrefs.sort; syncSortDirection(); $("docker-discovery-list")?.replaceChildren(); $("docker-agent-settings-list")?.replaceChildren(); syncLiveSwitch(); applyViewFilters(); } }; })(); diff --git a/src/admin/web/index.html b/src/admin/web/index.html index 26c34f8..ce31231 100644 --- a/src/admin/web/index.html +++ b/src/admin/web/index.html @@ -2292,13 +2292,15 @@

Docker agents

LIVE APPLY -

Configure one agent per Docker host. HTTPS - with a persistent self-signed certificate is the default; pin its SHA-256 - fingerprint in RustProxy. Each agent has its own base domain and optional default - backend IP.

+

Configure one agent per Docker or Podman host. + Paste the provisioning code printed by "rustproxy-docker-agent provision-code" to + fill in the endpoint, token and pinned certificate at once. Each agent has its own + domains, certificates and optional default backend IP.

- +
+
diff --git a/src/admin/web/partials/overview-metrics.html b/src/admin/web/partials/overview-metrics.html index 0309450..c4261e4 100644 --- a/src/admin/web/partials/overview-metrics.html +++ b/src/admin/web/partials/overview-metrics.html @@ -124,6 +124,146 @@ No stream data + + + + + + + + + + + + + + + + + + + + + + + +