diff --git a/CHANGELOG.md b/CHANGELOG.md index 231491d..1228cc7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,27 @@ recognisable path forward. ### Added +- **Streams across servers** (multi-server installs). The WebRTC signalling + WebSocket (`/api/v3/live/{id}/webrtc/ws`) for another server's monitor is + relayed: this server checks the caller, connects to the owning server, then + accepts the upgrade, so a server that is down or refuses gives an HTTP + error. `GET /api/v3/events/stream` now carries every server's `alarm_state` + messages, by following each other server's stream with the client's own + token. `GET /api/v3/monitor-status/{id}` is answered by the server that runs + the monitor. `GET /api/v3/live/sessions` and `/live/sources` take + `?server_id=|all`. On a multi-server install the event stream no longer + reports other servers' monitors as `unknown`. Enables the + `rustls-tls-native-roots` feature of `tokio-tungstenite` for `wss://`. +- **System control across servers** (multi-server installs). The daemon and + system routes (`/api/v3/daemons`, `/api/v3/system/*`) take + `?server_id=` to act on another server, relayed to its zm-api with the + caller's own token, or `?server_id=all` to act on every server and get a 207 + with one result per server. Applying a run state + (`POST /api/v3/system/state`) now also tells every other server to restart + its daemons, and the response gains an optional `servers` list. The request + gains an optional `daemons_only` flag, which restarts daemons and writes + nothing. Without `server_id`, everything behaves as before on a + single-server install. - **Multi-server installs** (#230). Every ZoneMinder server runs a zm-api, and a request for a monitor another server runs is relayed to the zm-api there with the caller's own token: live HLS, WHEP, snapshots, alarms, PTZ, @@ -18,7 +39,14 @@ recognisable path forward. settings name the other servers where the default (this server's scheme and port on `Servers.Hostname`) is wrong. `GET /api/v3/servers` gains `api_url` and `is_this_server`. See the multi-server guide for the limits: WebSocket - signalling, system-wide control and recordings are not relayed yet. + signalling is not relayed. +- **Recordings on per-server storage** (multi-server installs). A storage + area with a `ServerId` holds its files on that server only. A request for + an event's video, frames, thumbnail, synopsis or generated videos, or to + delete the event, is now relayed to the server that holds the files, with + the caller's own token. Storage with no `ServerId` is shared and is never + relayed. Export and the storage list act on what this server can read, and + say so. Media jobs wait for the server that can read the event. - **Live event stream**, `GET /api/v3/events/stream` (Server-Sent Events): `event_start`, `event_end` and `event_updated` (notes changed, where object detection writes) for every monitor the caller may see, and each monitor's @@ -268,6 +296,14 @@ recognisable path forward. ### Fixed +- **The retention reaper and the maintenance audit no longer act on another + server's storage.** On a multi-server install they ran against every + `Storage` row. They could not see a per-server area's files, so the audit + could take every event on it for one with no media and delete the rows, and + the reaper measured the wrong disk. Both now skip a storage whose + `ServerId` is another server, and say so once in the log. The audit's + empty-event sweep and the event audit report also leave those events alone. + - **`POST /events` works.** It never set `Events.StateId`, which is NOT NULL with no default, so every create failed with 500. It now records the active run state, or 0, as zmc does. diff --git a/Cargo.lock b/Cargo.lock index 043095f..bbaae93 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6714,7 +6714,11 @@ checksum = "17a073bfed563fa236697a068031408a93cd9522e08abf9933ead3e73411bd71" dependencies = [ "futures-util", "log", + "rustls", + "rustls-native-certs", + "rustls-pki-types", "tokio", + "tokio-rustls", "tungstenite 0.30.0", ] @@ -7044,6 +7048,8 @@ dependencies = [ "httparse", "log", "rand 0.10.3", + "rustls", + "rustls-pki-types", "sha1 0.11.0", "thiserror 2.0.21", ] diff --git a/Cargo.toml b/Cargo.toml index 93d210c..67356a1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -100,7 +100,7 @@ test-context = "0.5" thiserror = "2" tokio = { version = "1", features = ["full"] } tokio-util = { version = "0.7", features = ["io", "compat"] } -tokio-tungstenite = "0.30" +tokio-tungstenite = { version = "0.30", features = ["rustls-tls-native-roots"] } tracing = { version = "0.1", features = ["attributes"] } tracing-appender = "0.2" tracing-bunyan-formatter = "0.3" diff --git a/book/src/guide/live-events.md b/book/src/guide/live-events.md index dacc095..2d29eab 100644 --- a/book/src/guide/live-events.md +++ b/book/src/guide/live-events.md @@ -46,10 +46,39 @@ The stream ends when your access token expires and when you lose access minute). Reconnect with a fresh token and `Last-Event-ID`. A comment line arrives every 15 seconds, so a silent connection is a dead one. +## Several servers + +On an install with more than one ZoneMinder server, one subscription covers +every server. Events are read from the shared database, so any server has +them all. Alarm states exist only on the server that runs a camera, so the +server you connect to also subscribes to each other server's stream and passes +on its `alarm_state` messages, for that server's own cameras only. Nothing is +sent twice. + +- Each of your streams opens one upstream stream per other server, with your + own token. That server applies your permissions and ends its stream when your + token expires, as it would for you directly. This costs one connection per + client per server. +- A server that is down does not break your stream. Its cameras send no + `alarm_state` updates until it is back. zm-api reconnects with a wait that + grows to 30 seconds and logs one warning per outage. +- On connect you get the current state of each camera as before, from its own + server. After a server returns, only states that changed are sent. +- You see an `alarm_state` only for cameras you may see. +- `Last-Event-ID` and `?since=` replay events from the database, which covers + every server. Alarm states are never replayed. +- A request that carries `X-ZM-Forwarded-By`, which is how one zm-api asks + another, gets only that server's own alarm states and opens no further + streams, so servers never follow each other in a loop. + +A single-server install opens no upstream connections and its output is the same. + ## How it works One watcher in zm-api serves every subscriber and runs only while someone is connected. Alarm states come from each camera's shared memory, four times a second; a camera's new event wakes the watcher at once. Events come from ZoneMinder's `Events` table, so cameras on other ZoneMinder servers appear too, -within a second or so. Nothing is written to the database. +within a second or so. Nothing is written to the database. On a multi-server +install the watcher reads shared memory only for the cameras its own server +runs. diff --git a/book/src/guide/multi-server.md b/book/src/guide/multi-server.md index ac0c186..b1ce4a2 100644 --- a/book/src/guide/multi-server.md +++ b/book/src/guide/multi-server.md @@ -14,14 +14,56 @@ The relayed request carries the caller's own token. The owning server authentica What is relayed: -- live HLS, live start and stop, live stats, WHEP +- live HLS, live start and stop, live stats, WHEP, and the WebRTC signalling WebSocket (see [WebSockets](#websockets)) +- a monitor's status (`GET /api/v3/monitor-status/{id}`), which reads shared memory - snapshots - forcing and cancelling an alarm - PTZ - a monitor's state (start, stop, restart), its pipeline, and edits to and deletion of its row - running a monitor action -What stays on the server the client asked: anything that only reads or writes the database, such as listing monitors, reading a monitor's row, events and users. +- an event's recording and files (see [Recordings](#recordings)) + +What stays on the server the client asked: anything that only reads or writes the database, such as listing monitors, reading a monitor's row, listing events, reading or editing an event's row, tags and users. + +## WebSockets + +`GET /api/v3/live/{monitor_id}/webrtc/ws` carries WebRTC signalling. For another server's monitor, this server checks that you may see the monitor, then opens its own WebSocket to the same path and query on the owning server, with your `Authorization` header and any `Sec-WebSocket-Protocol` you offered. Only then does it accept your upgrade, so the answers are ordinary HTTP errors: + +- the owning server is down: 502 +- the owning server refuses (404, 403, 503, ...): the same status and body come back to you +- the servers have different JWT keys: 502 + +After that, messages are copied one at a time in both directions (text, binary, ping, pong and close, with the close code and reason). When either side closes or fails, the other is closed. A failure on the owning server's side closes your socket with code 1011. The relay sets no idle timeout, since a signalling socket can sit quiet for a long time. + +WebRTC media still travels direct from the owning server to the viewer over UDP. The viewer must be able to reach that server. Only the signalling goes through this one. + +For `wss://` the relay trusts the system's root certificates. If `cluster.tls_ca_file` is set it trusts that file's certificates alone for WebSockets, because the WebSocket client can't add to the system roots the way the HTTP client does. Put every CA the peers need in that file. + +A request that only claims to upgrade, without a valid WebSocket handshake, answers 421. + +## The live event stream + +`GET /api/v3/events/stream` covers every server. Events come from the shared database, so any server has them all. Alarm states come from shared memory, which only the server that runs a monitor has. So the server you connect to also follows each other server's stream for that server's alarm states, and merges them into yours. Each of your own streams opens one stream to each other server, with your own token, so the other server applies your permissions and ends the stream when your token expires. Your server shows you an alarm state only for monitors you may see and only from the server that runs the monitor. If a server is down, its monitors send no alarm states until it is back; the rest of the stream is not affected. See [Live events](live-events.md#several-servers). + +## Recordings + +ZoneMinder gives each storage area an optional `ServerId`: + +- **No `ServerId` (or 0): shared storage.** Every server can read and delete its files, over NFS for example. Requests for these events are answered by whichever server was asked. +- **A `ServerId`: local storage.** Only that server can read its files. A request for one of its events' files goes to that server. + +Relayed for an event on another server's storage: playback and HLS, the event's video, thumbnail and frame images, event info, synopsis, generated videos (list, create, download, delete), and `DELETE /api/v3/events/{id}`, so the server that has the files removes them. This server first checks that the caller may see the event's monitor. + +Not relayed, because the database holds all they need: the event list, an event's row and its edits, tags, notes, and the signed link for playback (the link is valid on every server, and the requests that use it are relayed). + +Background jobs leave another server's storage alone. The retention reaper, the maintenance audit (both its database and its filesystem checks) and the event audit report skip a storage area that names another server, and the log says so once. Each server's own jobs cover its own storage, so run them on every server. A media job for an event whose files are on another server stays queued until that server's worker takes it. The storage list shows no disk figures for another server's area, since the path on this server is not that disk. + +Several events in one request are not split across servers: + +- `POST /api/v3/events/export` packs the files of the events on storage this server can read. For an event on another server's storage it adds the details (`event.json`, `frames.json`) and a `files-unavailable.txt` naming the server. Ask that server for the files. + +An event with no storage id is treated as shared. ## Setup @@ -50,12 +92,36 @@ If the servers use certificates from a private CA, point `cluster.tls_ca_file` a | 421 `belongs to server 2, which has no address` | The `Servers` row has no hostname and `cluster.peers` names none. | | 421 `the servers disagree` | Two servers each think the other runs the monitor. Check `ZM_SERVER_ID` on both. | +## Daemons and system control + +`/api/v3/daemons` and `/api/v3/system/*` act on one server's daemons. Add `?server_id=` to say which: + +| `server_id` | What happens | +| --- | --- | +| absent | This server, as before. | +| a number | That server. A request for another server is relayed to its zm-api with your own token, and its answer comes back unchanged. An unknown number answers 404, and a server with no address answers 421. | +| `all` | Every server, at once. The answer is 207 with one entry per server: `server_id`, `name`, `ok`, `status`, and either `result` (what that server answered) or `error`. One server being down does not fail the request, so check each entry. This server is first. | + +The permission check happens here before anything is relayed, and the other server checks it again. A request that another server relayed is always handled where it lands, whatever `server_id` says. + +On an install with one server, `all` answers with a single entry whose `server_id` is `null`, and any number answers 404. + +### Applying a run state + +`POST /api/v3/system/state` changes monitor rows for every server in the shared database, so it reaches every server's daemons without a `server_id`. This server writes the rows once, then tells each other server to restart the daemons of its own monitors that the state names. It sends `{"state_name": ..., "daemons_only": true}`, which restarts daemons and writes nothing, so sending it twice is harmless. The response keeps its usual fields for this server and adds `servers`, one entry per other server in the same shape as above. A server that cannot be reached does not undo the change: its entry says `ok: false`, and its daemons pick up the new state at their next restart. + +Run states are not aimed at one server. `server_id=all` is the same as leaving it out, and a server's number answers 400. + +## Live sessions and sources + +`GET /api/v3/live/sessions` and `GET /api/v3/live/sources` list one server's live sessions and sources. They take `?server_id=|all` exactly as the daemon routes do (see above): a number is relayed, and `all` answers 207 with one entry per server. + ## Limits -- **WebRTC media goes direct.** WHEP signalling is relayed, but the video itself travels over UDP from the server that runs the camera. The viewer must be able to reach that server. -- **WebSocket signalling is not relayed.** A WebSocket for another server's monitor answers 421 with that server's address. Use WHEP, or connect to that server. -- **System-wide control is per server.** `/api/v3/daemons` and `/api/v3/system/*` act on the server that receives them. -- **Recordings are served by the server asked.** Event video and frame images are read from that server's filesystem, so they need storage every server can reach. +- **WebRTC media goes direct.** WHEP and WebSocket signalling are relayed, but the video itself travels over UDP from the server that runs the camera. The viewer must be able to reach that server. +- **The monitor status list has no live fields for other servers' monitors.** `GET /api/v3/monitor-status` fills `alarm_state` and the other shared-memory fields only for this server's monitors. Ask for one monitor (`/monitor-status/{id}`) to have it answered by its server, or use the [live event stream](live-events.md#several-servers). +- **The event stream follows the servers it sees when it opens.** A server added later is picked up by the next connection. +- **Whole-database views are not relayed.** The media job list (`/api/v3/jobs`) shows the queue this server sees: all jobs when the database holds the queue, only this server's when a file does. The range synopsis (`/api/v3/events/synopsis`) names no single event, so this server answers it. - **A logout takes up to ten seconds to reach the other servers.** Each server re-reads the token floors from the database on that interval. - **Rate limits see the relaying server.** A relayed request arrives from another server's address, with the client's own appended to `X-Forwarded-For`. The global limiter is off by default. If you turn it on, set `trust_proxy_headers = true` and list the other servers in `trusted_proxies`, so each client is counted on its own. diff --git a/openapi.json b/openapi.json index 7836932..b944b6f 100644 --- a/openapi.json +++ b/openapi.json @@ -1807,6 +1807,17 @@ ], "summary": "List all daemons.", "operationId": "list_daemons", + "parameters": [ + { + "name": "server_id", + "in": "query", + "description": "Absent: this server. A server's number: that server, relayed to its\nzm-api when it is not this one. `all`: every server, answered with 207\nand one entry per server (see `AllServersResponse`). A request that\nanother server already relayed is always handled here.", + "required": false, + "schema": { + "type": "string" + } + } + ], "responses": { "200": { "description": "List of all daemons", @@ -1818,6 +1829,56 @@ } } }, + "207": { + "description": "With `server_id=all`: one entry per server; the status is 207 even when every server failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllServersResponse" + } + } + } + }, + "400": { + "description": "`server_id` is neither a server number nor `all`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "404": { + "description": "No server has the number given in `server_id`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "421": { + "description": "The server named by `server_id` has no address", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "502": { + "description": "The server named by `server_id` did not answer", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, "503": { "description": "Daemon manager not available", "content": { @@ -1854,6 +1915,15 @@ "summary": "Get a specific daemon's status.", "operationId": "get_daemon", "parameters": [ + { + "name": "server_id", + "in": "query", + "description": "Absent: this server. A server's number: that server, relayed to its\nzm-api when it is not this one. `all`: every server, answered with 207\nand one entry per server (see `AllServersResponse`). A request that\nanother server already relayed is always handled here.", + "required": false, + "schema": { + "type": "string" + } + }, { "name": "id", "in": "path", @@ -1875,6 +1945,26 @@ } } }, + "207": { + "description": "With `server_id=all`: one entry per server; the status is 207 even when every server failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllServersResponse" + } + } + } + }, + "400": { + "description": "`server_id` is neither a server number nor `all`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, "404": { "description": "Daemon not found", "content": { @@ -1885,6 +1975,26 @@ } } }, + "421": { + "description": "The server named by `server_id` has no address", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "502": { + "description": "The server named by `server_id` did not answer", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, "503": { "description": "Daemon manager not available", "content": { @@ -1921,6 +2031,15 @@ "summary": "Reload a daemon's configuration (SIGHUP).", "operationId": "reload_daemon", "parameters": [ + { + "name": "server_id", + "in": "query", + "description": "Absent: this server. A server's number: that server, relayed to its\nzm-api when it is not this one. `all`: every server, answered with 207\nand one entry per server (see `AllServersResponse`). A request that\nanother server already relayed is always handled here.", + "required": false, + "schema": { + "type": "string" + } + }, { "name": "id", "in": "path", @@ -1942,6 +2061,56 @@ } } }, + "207": { + "description": "With `server_id=all`: one entry per server; the status is 207 even when every server failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllServersResponse" + } + } + } + }, + "400": { + "description": "`server_id` is neither a server number nor `all`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "404": { + "description": "No server has the number given in `server_id`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "421": { + "description": "The server named by `server_id` has no address", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "502": { + "description": "The server named by `server_id` did not answer", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, "503": { "description": "Daemon manager not available", "content": { @@ -1978,6 +2147,15 @@ "summary": "Restart a daemon.", "operationId": "restart_daemon", "parameters": [ + { + "name": "server_id", + "in": "query", + "description": "Absent: this server. A server's number: that server, relayed to its\nzm-api when it is not this one. `all`: every server, answered with 207\nand one entry per server (see `AllServersResponse`). A request that\nanother server already relayed is always handled here.", + "required": false, + "schema": { + "type": "string" + } + }, { "name": "id", "in": "path", @@ -1999,6 +2177,56 @@ } } }, + "207": { + "description": "With `server_id=all`: one entry per server; the status is 207 even when every server failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllServersResponse" + } + } + } + }, + "400": { + "description": "`server_id` is neither a server number nor `all`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "404": { + "description": "No server has the number given in `server_id`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "421": { + "description": "The server named by `server_id` has no address", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "502": { + "description": "The server named by `server_id` did not answer", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, "503": { "description": "Daemon manager not available", "content": { @@ -2035,6 +2263,15 @@ "summary": "Start a daemon.", "operationId": "start_daemon", "parameters": [ + { + "name": "server_id", + "in": "query", + "description": "Absent: this server. A server's number: that server, relayed to its\nzm-api when it is not this one. `all`: every server, answered with 207\nand one entry per server (see `AllServersResponse`). A request that\nanother server already relayed is always handled here.", + "required": false, + "schema": { + "type": "string" + } + }, { "name": "id", "in": "path", @@ -2073,6 +2310,56 @@ } } }, + "207": { + "description": "With `server_id=all`: one entry per server; the status is 207 even when every server failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllServersResponse" + } + } + } + }, + "400": { + "description": "`server_id` is neither a server number nor `all`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "404": { + "description": "No server has the number given in `server_id`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "421": { + "description": "The server named by `server_id` has no address", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "502": { + "description": "The server named by `server_id` did not answer", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, "503": { "description": "Daemon manager not available", "content": { @@ -2109,6 +2396,15 @@ "summary": "Stop a daemon.", "operationId": "stop_daemon", "parameters": [ + { + "name": "server_id", + "in": "query", + "description": "Absent: this server. A server's number: that server, relayed to its\nzm-api when it is not this one. `all`: every server, answered with 207\nand one entry per server (see `AllServersResponse`). A request that\nanother server already relayed is always handled here.", + "required": false, + "schema": { + "type": "string" + } + }, { "name": "id", "in": "path", @@ -2130,6 +2426,56 @@ } } }, + "207": { + "description": "With `server_id=all`: one entry per server; the status is 207 even when every server failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllServersResponse" + } + } + } + }, + "400": { + "description": "`server_id` is neither a server number nor `all`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "404": { + "description": "No server has the number given in `server_id`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "421": { + "description": "The server named by `server_id` has no address", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "502": { + "description": "The server named by `server_id` did not answer", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, "503": { "description": "Daemon manager not available", "content": { @@ -7202,24 +7548,150 @@ ], "summary": "List all active live streams", "operationId": "listLiveSessions", + "parameters": [ + { + "name": "server_id", + "in": "query", + "description": "Absent: this server. A server's number: that server, relayed to its\nzm-api when it is not this one. `all`: every server, answered with 207\nand one entry per server (see `AllServersResponse`). A request that\nanother server already relayed is always handled here.", + "required": false, + "schema": { + "type": "string" + } + } + ], "responses": { "200": { "description": "List of active live sessions", "content": { "application/json": { "schema": { - "type": "array", - "items": { - "type": "integer", - "format": "int32", - "minimum": 0 - } + "type": "array", + "items": { + "type": "integer", + "format": "int32", + "minimum": 0 + } + } + } + } + }, + "207": { + "description": "With `server_id=all`: one entry per server; the status is 207 even when every server failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllServersResponse" + } + } + } + }, + "400": { + "description": "`server_id` is neither a server number nor `all`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "404": { + "description": "No server has the number given in `server_id`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "421": { + "description": "The server named by `server_id` has no address", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "502": { + "description": "The server named by `server_id` did not answer", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "503": { + "description": "Service unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "default": { + "description": "Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + } + }, + "security": [ + { + "jwt": [] + } + ] + } + }, + "/api/v3/live/sources": { + "get": { + "tags": [ + "Live Streaming" + ], + "summary": "Get source router statistics", + "operationId": "getLiveSources", + "parameters": [ + { + "name": "server_id", + "in": "query", + "description": "Absent: this server. A server's number: that server, relayed to its\nzm-api when it is not this one. `all`: every server, answered with 207\nand one entry per server (see `AllServersResponse`). A request that\nanother server already relayed is always handled here.", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Source statistics: `active_sources` and `sources`", + "content": { + "application/json": { + "schema": {} + } + } + }, + "207": { + "description": "With `server_id=all`: one entry per server; the status is 207 even when every server failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllServersResponse" } } } }, - "503": { - "description": "Service unavailable", + "400": { + "description": "`server_id` is neither a server number nor `all`", "content": { "application/json": { "schema": { @@ -7228,8 +7700,28 @@ } } }, - "default": { - "description": "Error", + "404": { + "description": "No server has the number given in `server_id`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "421": { + "description": "The server named by `server_id` has no address", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "502": { + "description": "The server named by `server_id` did not answer", "content": { "application/json": { "schema": { @@ -7237,25 +7729,6 @@ } } } - } - }, - "security": [ - { - "jwt": [] - } - ] - } - }, - "/api/v3/live/sources": { - "get": { - "tags": [ - "Live Streaming" - ], - "summary": "Get source router statistics", - "operationId": "getLiveSources", - "responses": { - "200": { - "description": "Source statistics" }, "503": { "description": "Service unavailable", @@ -9634,7 +10107,7 @@ ], "responses": { "200": { - "description": "Monitor status detail", + "description": "Monitor status detail. For a monitor another server runs, the request is relayed to that server, which reads its shared memory", "content": { "application/json": { "schema": { @@ -9643,6 +10116,26 @@ } } }, + "421": { + "description": "The server that runs the monitor has no address", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "502": { + "description": "The server that runs the monitor did not answer", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, "default": { "description": "Error", "content": { @@ -19626,6 +20119,17 @@ ], "summary": "Trigger log rotation for all daemons.", "operationId": "system_logrot", + "parameters": [ + { + "name": "server_id", + "in": "query", + "description": "Absent: this server. A server's number: that server, relayed to its\nzm-api when it is not this one. `all`: every server, answered with 207\nand one entry per server (see `AllServersResponse`). A request that\nanother server already relayed is always handled here.", + "required": false, + "schema": { + "type": "string" + } + } + ], "responses": { "200": { "description": "Log rotation triggered", @@ -19637,6 +20141,56 @@ } } }, + "207": { + "description": "With `server_id=all`: one entry per server; the status is 207 even when every server failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllServersResponse" + } + } + } + }, + "400": { + "description": "`server_id` is neither a server number nor `all`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "404": { + "description": "No server has the number given in `server_id`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "421": { + "description": "The server named by `server_id` has no address", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "502": { + "description": "The server named by `server_id` did not answer", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, "503": { "description": "Daemon manager not available", "content": { @@ -19705,73 +20259,211 @@ ] } }, - "/api/v3/system/privacy": { + "/api/v3/system/privacy": { + "post": { + "tags": [ + "System" + ], + "summary": "Record the answer to the privacy statement", + "description": "- What ZoneMinder's privacy page does: the statement stops being shown,\n and telemetry (`ZM_TELEMETRY_DATA`) follows the answer.\n- Requires System edit.", + "operationId": "record_privacy", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PrivacyRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Privacy settings now", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PrivacyResponse" + } + } + } + }, + "default": { + "description": "Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + } + }, + "security": [ + { + "jwt": [] + } + ] + } + }, + "/api/v3/system/restart": { + "post": { + "tags": [ + "System" + ], + "summary": "Perform full system restart.", + "operationId": "system_restart", + "parameters": [ + { + "name": "server_id", + "in": "query", + "description": "Absent: this server. A server's number: that server, relayed to its\nzm-api when it is not this one. `all`: every server, answered with 207\nand one entry per server (see `AllServersResponse`). A request that\nanother server already relayed is always handled here.", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "System restarted", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DaemonActionResponse" + } + } + } + }, + "207": { + "description": "With `server_id=all`: one entry per server; the status is 207 even when every server failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllServersResponse" + } + } + } + }, + "400": { + "description": "`server_id` is neither a server number nor `all`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "404": { + "description": "No server has the number given in `server_id`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "421": { + "description": "The server named by `server_id` has no address", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "502": { + "description": "The server named by `server_id` did not answer", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "503": { + "description": "Daemon manager not available", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "default": { + "description": "Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + } + }, + "security": [ + { + "jwt": [] + } + ] + } + }, + "/api/v3/system/shutdown": { "post": { "tags": [ "System" ], - "summary": "Record the answer to the privacy statement", - "description": "- What ZoneMinder's privacy page does: the statement stops being shown,\n and telemetry (`ZM_TELEMETRY_DATA`) follows the answer.\n- Requires System edit.", - "operationId": "record_privacy", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PrivacyRequest" - } + "summary": "Perform full system shutdown.", + "operationId": "system_shutdown", + "parameters": [ + { + "name": "server_id", + "in": "query", + "description": "Absent: this server. A server's number: that server, relayed to its\nzm-api when it is not this one. `all`: every server, answered with 207\nand one entry per server (see `AllServersResponse`). A request that\nanother server already relayed is always handled here.", + "required": false, + "schema": { + "type": "string" } - }, - "required": true - }, + } + ], "responses": { "200": { - "description": "Privacy settings now", + "description": "System shutdown initiated", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PrivacyResponse" + "$ref": "#/components/schemas/DaemonActionResponse" } } } }, - "default": { - "description": "Error", + "207": { + "description": "With `server_id=all`: one entry per server; the status is 207 even when every server failed", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AppResponseError" + "$ref": "#/components/schemas/AllServersResponse" } } } - } - }, - "security": [ - { - "jwt": [] - } - ] - } - }, - "/api/v3/system/restart": { - "post": { - "tags": [ - "System" - ], - "summary": "Perform full system restart.", - "operationId": "system_restart", - "responses": { - "200": { - "description": "System restarted", + }, + "400": { + "description": "`server_id` is neither a server number nor `all`", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DaemonActionResponse" + "$ref": "#/components/schemas/AppResponseError" } } } }, - "503": { - "description": "Daemon manager not available", + "404": { + "description": "No server has the number given in `server_id`", "content": { "application/json": { "schema": { @@ -19780,8 +20472,8 @@ } } }, - "default": { - "description": "Error", + "421": { + "description": "The server named by `server_id` has no address", "content": { "application/json": { "schema": { @@ -19789,29 +20481,13 @@ } } } - } - }, - "security": [ - { - "jwt": [] - } - ] - } - }, - "/api/v3/system/shutdown": { - "post": { - "tags": [ - "System" - ], - "summary": "Perform full system shutdown.", - "operationId": "system_shutdown", - "responses": { - "200": { - "description": "System shutdown initiated", + }, + "502": { + "description": "The server named by `server_id` did not answer", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DaemonActionResponse" + "$ref": "#/components/schemas/AppResponseError" } } } @@ -19931,6 +20607,17 @@ ], "summary": "Perform full system startup.", "operationId": "system_startup", + "parameters": [ + { + "name": "server_id", + "in": "query", + "description": "Absent: this server. A server's number: that server, relayed to its\nzm-api when it is not this one. `all`: every server, answered with 207\nand one entry per server (see `AllServersResponse`). A request that\nanother server already relayed is always handled here.", + "required": false, + "schema": { + "type": "string" + } + } + ], "responses": { "200": { "description": "System started", @@ -19942,6 +20629,56 @@ } } }, + "207": { + "description": "With `server_id=all`: one entry per server; the status is 207 even when every server failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllServersResponse" + } + } + } + }, + "400": { + "description": "`server_id` is neither a server number nor `all`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "404": { + "description": "No server has the number given in `server_id`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "421": { + "description": "The server named by `server_id` has no address", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "502": { + "description": "The server named by `server_id` did not answer", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, "503": { "description": "Daemon manager not available", "content": { @@ -19976,8 +20713,19 @@ "System" ], "summary": "Apply a system state.", - "description": "States are predefined monitor configurations stored in the database.\nApplying a state updates monitor Function/Enabled settings and restarts affected daemons.", + "description": "States are predefined monitor configurations stored in the database.\nApplying a state updates monitor Function/Enabled settings and restarts affected daemons.\n\nOn a multi-server install the database change is made once, here, and then\nevery other server is told to restart its daemons for the monitors the\nstate names. What each of them answered is in `servers`; a server that\ncould not be reached does not undo the change. `server_id` may be absent or\n`all` (the same); a server's number is refused with 400, because the\nmonitors of every server change together. A request that another server\nrelayed is handled here only.", "operationId": "apply_state", + "parameters": [ + { + "name": "server_id", + "in": "query", + "description": "Absent: this server. A server's number: that server, relayed to its\nzm-api when it is not this one. `all`: every server, answered with 207\nand one entry per server (see `AllServersResponse`). A request that\nanother server already relayed is always handled here.", + "required": false, + "schema": { + "type": "string" + } + } + ], "requestBody": { "content": { "application/json": { @@ -19999,6 +20747,16 @@ } } }, + "400": { + "description": "`server_id` is neither absent nor `all`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, "404": { "description": "State not found" }, @@ -20037,6 +20795,17 @@ ], "summary": "Get system status.", "operationId": "get_system_status", + "parameters": [ + { + "name": "server_id", + "in": "query", + "description": "Absent: this server. A server's number: that server, relayed to its\nzm-api when it is not this one. `all`: every server, answered with 207\nand one entry per server (see `AllServersResponse`). A request that\nanother server already relayed is always handled here.", + "required": false, + "schema": { + "type": "string" + } + } + ], "responses": { "200": { "description": "System status", @@ -20048,6 +20817,56 @@ } } }, + "207": { + "description": "With `server_id=all`: one entry per server; the status is 207 even when every server failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AllServersResponse" + } + } + } + }, + "400": { + "description": "`server_id` is neither a server number nor `all`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "404": { + "description": "No server has the number given in `server_id`", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "421": { + "description": "The server named by `server_id` has no address", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, + "502": { + "description": "The server named by `server_id` did not answer", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppResponseError" + } + } + } + }, "503": { "description": "Daemon manager not available", "content": { @@ -21788,6 +22607,21 @@ } } }, + "AllServersResponse": { + "type": "object", + "description": "The answer to a request sent with `server_id=all`: one entry per server,\nthis server first, then the others by id. The HTTP status is 207 whenever\nthe request ran, even if every server failed; each entry says how it went.", + "required": [ + "servers" + ], + "properties": { + "servers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ServerResult" + } + } + } + }, "Analysing": { "type": "string", "enum": [ @@ -22310,6 +23144,10 @@ "state_name" ], "properties": { + "daemons_only": { + "type": "boolean", + "description": "Leave the database alone and only restart this server's daemons for\nthe monitors the state names. This is what a server sends the other\nservers after it has applied the state, so the change is written once.\nIt is handled on this server and never passed on." + }, "state_name": { "type": "string", "description": "Name of the state to apply" @@ -27196,6 +28034,16 @@ "type": "string", "description": "Human-readable message" }, + "servers": { + "type": [ + "array", + "null" + ], + "items": { + "$ref": "#/components/schemas/ServerResult" + }, + "description": "What the other servers of a multi-server install did, when the action\nreaches them too (applying a run state does). `success` and `message`\ndescribe this server only. Absent on a single-server install and for\nactions that stay on one server." + }, "success": { "type": "boolean", "description": "Whether the action succeeded" @@ -34035,6 +34883,50 @@ } } }, + "ServerResult": { + "type": "object", + "description": "What one server of a multi-server install answered to a request that went\nto several of them.", + "required": [ + "name", + "ok", + "status" + ], + "properties": { + "error": { + "type": [ + "string", + "null" + ], + "description": "Why the request failed on this server." + }, + "name": { + "type": "string", + "description": "The server's name." + }, + "ok": { + "type": "boolean", + "description": "Whether the server answered with a success status." + }, + "result": { + "description": "The JSON the server answered, as it would for the same request sent to\nit alone." + }, + "server_id": { + "type": [ + "integer", + "null" + ], + "format": "int32", + "description": "The server's `Servers.Id`. Null for the one server of an install whose\nhost has no server id.", + "minimum": 0 + }, + "status": { + "type": "integer", + "format": "int32", + "description": "The HTTP status the server answered with, or the one this server\ngives for not reaching it (502 no answer, 421 no address).", + "minimum": 0 + } + } + }, "ServerStatResponse": { "type": "object", "required": [ diff --git a/src/cluster/events.rs b/src/cluster/events.rs new file mode 100644 index 0000000..4da3cd7 --- /dev/null +++ b/src/cluster/events.rs @@ -0,0 +1,396 @@ +//! The live event stream across servers. +//! +//! `GET /api/v3/events/stream` carries two kinds of message. Events come from +//! the `Events` table, which every server shares, so any server has them all. +//! Alarm states come from shared memory, which only the server that runs a +//! monitor has. So a stream served here follows each other server's stream +//! for the one thing it cannot produce itself: that server's alarm states. +//! +//! Each client stream opens its own upstream stream to each other server, +//! with that client's own token. The peer applies the client's permissions +//! and ends the stream when the token expires, exactly as for a direct +//! connection, and no server holds a credential that can act as anyone. The +//! price is one connection per client per server, which the small client +//! counts of a camera system can bear. +//! +//! The upstream request carries [`FORWARDED_BY`]. A server that sees it +//! serves its own alarm states and nothing else, so servers never follow +//! each other in a loop and no event arrives twice. + +use std::collections::HashMap; +use std::time::Duration; + +use axum::http::{header, HeaderMap}; +use tokio::sync::mpsc; +use tokio::task::JoinHandle; +use tracing::{debug, warn}; + +use super::forward::FORWARDED_BY; +use super::Peer; +use crate::error::AppResult; +use crate::server::state::AppState; +use crate::service::event_stream::AlarmInfo; + +/// The wait before the first retry of a stream that failed, doubled after +/// each failure. +const FIRST_RETRY: Duration = Duration::from_secs(1); +/// The longest wait between retries. +const LONGEST_RETRY: Duration = Duration::from_secs(30); +/// The most one unfinished SSE message may hold. A peer that sends more is +/// not speaking the stream protocol. +const MAX_MESSAGE: usize = 256 * 1024; + +/// An alarm state a peer sent. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PeerAlarm { + pub server_id: u32, + pub alarm: AlarmInfo, +} + +/// The upstream streams of one client stream. Dropping it closes them. +pub struct PeerStreams { + rx: mpsc::Receiver, + tasks: Vec>, +} + +impl PeerStreams { + /// The next alarm state from any peer. `None` when every upstream has + /// ended for good (the peers refused the client's credentials). + pub async fn next(&mut self) -> Option { + self.rx.recv().await + } +} + +impl Drop for PeerStreams { + fn drop(&mut self) { + for task in &self.tasks { + task.abort(); + } + } +} + +/// Open the upstream streams for a client stream, or `None` when there is +/// nothing to follow: a single-server install, a request another server +/// relayed, or no other server with an address. +pub async fn follow_peers( + state: &AppState, + caller: &HeaderMap, + monitor: Option, +) -> AppResult> { + if !state.cluster.relays() || caller.contains_key(&FORWARDED_BY) { + return Ok(None); + } + let (Some(this_server), Some(auth)) = ( + state.cluster.this_server(), + caller.get(header::AUTHORIZATION).cloned(), + ) else { + return Ok(None); + }; + let peers: Vec = state + .cluster + .other_servers(state.db()) + .await? + .into_iter() + .filter_map(|member| member.peer) + .collect(); + if peers.is_empty() { + return Ok(None); + } + + let (tx, rx) = mpsc::channel(256); + let tasks = peers + .into_iter() + .map(|peer| { + let mut headers = HeaderMap::new(); + headers.insert(header::AUTHORIZATION, auth.clone()); + headers.insert(header::ACCEPT, "text/event-stream".parse().expect("static")); + headers.insert(FORWARDED_BY, this_server.into()); + let url = stream_url(&peer, monitor); + tokio::spawn(follow( + state.cluster.client().clone(), + peer, + url, + headers, + tx.clone(), + )) + }) + .collect(); + Ok(Some(PeerStreams { rx, tasks })) +} + +fn stream_url(peer: &Peer, monitor: Option) -> String { + let mut url = format!("{}/api/v3/events/stream", peer.base_url); + if let Some(monitor) = monitor { + url.push_str(&format!("?monitor_id={monitor}")); + } + url +} + +/// How a stream to a peer ended. +enum Ended { + /// Retrying would not help: the peer refused the credentials, or nobody + /// is listening any more. + Stop, + /// Try again. `connected` is whether the peer had accepted the stream. + Retry { connected: bool, why: String }, +} + +/// Keep one upstream stream open, reconnecting with a growing wait. Logs at +/// warn once per outage, not once per attempt. +async fn follow( + client: reqwest::Client, + peer: Peer, + url: String, + headers: HeaderMap, + tx: mpsc::Sender, +) { + // Across reconnects, so the snapshot a peer sends again on each + // connection only passes on what changed while the stream was down. + let mut last: HashMap = HashMap::new(); + let mut delay = FIRST_RETRY; + let mut warned = false; + loop { + match read_once(&client, &peer, &url, &headers, &tx, &mut last).await { + Ended::Stop => return, + Ended::Retry { connected, why } => { + if connected { + warned = false; + delay = FIRST_RETRY; + } + if !warned { + warn!( + "{} is not sending alarm states ({why}); retrying until it does", + peer.label() + ); + warned = true; + } else { + debug!("{} still not sending alarm states ({why})", peer.label()); + } + tokio::time::sleep(delay).await; + delay = next_delay(delay); + } + } + } +} + +fn next_delay(delay: Duration) -> Duration { + (delay * 2).min(LONGEST_RETRY) +} + +async fn read_once( + client: &reqwest::Client, + peer: &Peer, + url: &str, + headers: &HeaderMap, + tx: &mpsc::Sender, + last: &mut HashMap, +) -> Ended { + let answer = match client.get(url).headers(headers.clone()).send().await { + Ok(answer) => answer, + // The URL can carry a monitor filter, not a token, but is left out + // as it is everywhere else. + Err(e) => { + return Ended::Retry { + connected: false, + why: e.without_url().to_string(), + } + } + }; + let status = answer.status(); + if status == reqwest::StatusCode::UNAUTHORIZED { + warn!( + "{} refused credentials this server accepted: every server must use the same JWT \ + key files", + peer.label() + ); + return Ended::Stop; + } + if status == reqwest::StatusCode::FORBIDDEN { + debug!("{} gives this caller no Events access", peer.label()); + return Ended::Stop; + } + if !status.is_success() { + return Ended::Retry { + connected: false, + why: format!("answered {status}"), + }; + } + + let mut parser = SseParser::default(); + let mut body = answer; + loop { + match body.chunk().await { + Ok(Some(chunk)) => { + let messages = match parser.push(&chunk) { + Ok(messages) => messages, + Err(why) => { + return Ended::Retry { + connected: true, + why: why.to_string(), + } + } + }; + for message in messages { + let Some(alarm) = alarm_state(&message) else { + continue; + }; + if last.get(&alarm.monitor_id) == Some(&alarm) { + continue; + } + last.insert(alarm.monitor_id, alarm.clone()); + let sent = tx + .send(PeerAlarm { + server_id: peer.id, + alarm, + }) + .await; + if sent.is_err() { + return Ended::Stop; + } + } + } + // The peer ended the stream: its client's token expired, or it + // restarted. A reconnect with an expired token is refused, which + // stops this task. + Ok(None) => { + return Ended::Retry { + connected: true, + why: "the stream ended".to_string(), + } + } + Err(e) => { + return Ended::Retry { + connected: true, + why: e.without_url().to_string(), + } + } + } + } +} + +/// One Server-Sent Event: its `event` name and its `data`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SseMessage { + pub event: String, + pub data: String, +} + +/// The alarm state in a message, if it is one. +fn alarm_state(message: &SseMessage) -> Option { + if message.event != "alarm_state" { + return None; + } + serde_json::from_str(&message.data).ok() +} + +/// Splits a Server-Sent Events byte stream into messages. Comments (the +/// heartbeat) and fields it doesn't use are dropped. +#[derive(Default)] +pub struct SseParser { + buffer: Vec, +} + +impl SseParser { + /// Add bytes; return the messages they completed. An error when one + /// message grows past [`MAX_MESSAGE`]. + pub fn push(&mut self, bytes: &[u8]) -> Result, &'static str> { + // Line ends are LF, CR LF or CR; only the first two are sent here. + self.buffer.extend(bytes.iter().filter(|b| **b != b'\r')); + let mut out = Vec::new(); + while let Some(end) = self.buffer.windows(2).position(|w| w == b"\n\n") { + let block: Vec = self.buffer.drain(..end + 2).collect(); + if let Some(message) = parse_block(&String::from_utf8_lossy(&block)) { + out.push(message); + } + } + if self.buffer.len() > MAX_MESSAGE { + return Err("a message was too large"); + } + Ok(out) + } +} + +fn parse_block(block: &str) -> Option { + let mut event = None; + let mut data: Vec<&str> = Vec::new(); + for line in block.lines() { + let Some((field, value)) = line.split_once(':') else { + continue; + }; + let value = value.strip_prefix(' ').unwrap_or(value); + match field { + "event" => event = Some(value.to_string()), + "data" => data.push(value), + // An empty field name is a comment. + _ => {} + } + } + Some(SseMessage { + event: event?, + data: data.join("\n"), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn messages_are_split_across_chunks_and_comments_are_dropped() { + let mut parser = SseParser::default(); + assert!(parser + .push(b": keep-alive\n\nevent: alarm_st") + .unwrap() + .is_empty()); + let out = parser + .push(b"ate\ndata: {\"monitor_id\":3,\"state\":\"alarm\",\"score\":9}\n\nevent: x\n") + .unwrap(); + assert_eq!(out.len(), 1); + assert_eq!(out[0].event, "alarm_state"); + let alarm = alarm_state(&out[0]).unwrap(); + assert_eq!( + alarm, + AlarmInfo { + monitor_id: 3, + state: "alarm".into(), + score: 9 + } + ); + // The unfinished one completes later; CR LF line ends work. + let out = parser.push(b"id: 4\r\ndata: 1\r\n\r\n").unwrap(); + assert_eq!(out[0].event, "x"); + assert!(alarm_state(&out[0]).is_none()); + } + + #[test] + fn only_alarm_states_are_taken() { + let event = SseMessage { + event: "event_start".into(), + data: r#"{"monitor_id":3,"state":"alarm","score":9}"#.into(), + }; + assert!(alarm_state(&event).is_none()); + let broken = SseMessage { + event: "alarm_state".into(), + data: "not json".into(), + }; + assert!(alarm_state(&broken).is_none()); + } + + #[test] + fn a_runaway_message_is_an_error() { + let mut parser = SseParser::default(); + let big = vec![b'a'; MAX_MESSAGE + 1]; + assert!(parser.push(&big).is_err()); + } + + #[test] + fn retries_back_off_to_a_cap() { + let mut delay = FIRST_RETRY; + let mut seen = Vec::new(); + for _ in 0..8 { + seen.push(delay.as_secs()); + delay = next_delay(delay); + } + assert_eq!(seen, [1, 2, 4, 8, 16, 30, 30, 30]); + } +} diff --git a/src/cluster/forward.rs b/src/cluster/forward.rs index 87f2a99..4d99b8e 100644 --- a/src/cluster/forward.rs +++ b/src/cluster/forward.rs @@ -95,36 +95,112 @@ pub async fn forward_to_owner( })); } + relay_to_server( + &state, + server_id, + &format!("monitor {monitor_id} belongs to"), + &path_and_query, + request, + ) + .await +} + +/// The middleware for routes that read or change an event's files. Apply +/// with `route_layer`, inside the guards, on the routes that touch the +/// event's directory and on no others: a route that only reads or writes the +/// event's row is answered here, as any server can. +/// +/// Files live on one server when their storage area has a `ServerId`, so a +/// request for them goes there. Shared storage (no `ServerId`) is reachable +/// from everywhere and is never relayed. +pub async fn forward_to_storage_owner( + State(state): State, + params: RawPathParams, + request: Request, + next: Next, +) -> Result { + if !state.cluster.relays() { + return Ok(next.run(request).await); + } + let Some(event_id) = path_event_id(¶ms) else { + return Ok(next.run(request).await); + }; + let Some(home) = state.cluster.event_home(state.db(), event_id).await? else { + return Ok(next.run(request).await); + }; + let Owner::Peer(server_id) = home.owner else { + return Ok(next.run(request).await); + }; + + // As for a monitor: the caller must be able to see the event's monitor + // before anything leaves this server, and the owner checks again. + let sight = sight(&request, home.monitor_id); + if !caller_sees(&state, sight, home.monitor_id).await? { + return Err(AppError::NotFoundError(Resource { + details: vec![("id".to_string(), event_id.to_string())], + resource_type: ResourceType::Event, + })); + } + let path_and_query = original_path_and_query(&request); + relay_to_server( + &state, + server_id, + &format!("the files of event {event_id} are on"), + &path_and_query, + request, + ) + .await +} + +/// The event a route names: `{id}` on the event routes, `{event_id}` on +/// the frame routes. +fn path_event_id(params: &RawPathParams) -> Option { + params + .iter() + .find(|(name, _)| *name == "event_id" || *name == "id") + .and_then(|(_, value)| value.parse().ok()) +} + +/// The steps both relays share once the owner is known: refuse a request +/// another server already relayed and one for a server with no address; send +/// a WebSocket upgrade to [`super::websocket`] and anything else on. `what` finishes with "belongs to" or +/// "are on", and reads as the start of every refusal. +pub(crate) async fn relay_to_server( + state: &AppState, + server_id: u32, + what: &str, + path_and_query: &str, + request: Request, +) -> Result { let peer = state.cluster.peer(state.db(), server_id).await?; if let Some(by) = request.headers().get(&FORWARDED_BY) { return Err(AppError::MisdirectedError(format!( - "monitor {monitor_id} belongs to server {server_id}, and server {} already relayed \ - this request here; the servers disagree about which one this is", + "{what} server {server_id}, and server {} already relayed this request here; the \ + servers disagree about which one this is", by.to_str().unwrap_or("?") ))); } let Some(peer) = peer else { return Err(AppError::MisdirectedError(format!( - "monitor {monitor_id} belongs to server {server_id}, which has no address: give its \ - Servers row a hostname, or set cluster.peers.{server_id}" + "{what} server {server_id}, which has no address: give its Servers row a hostname, \ + or set cluster.peers.{server_id}" ))); }; if request.headers().contains_key(header::UPGRADE) { - return Err(AppError::MisdirectedError(format!( - "monitor {monitor_id} belongs to {}; a WebSocket is not relayed, so connect to {} \ - or use WHEP", - peer.label(), - peer.base_url - ))); + return super::websocket::relay(state, &peer, what, path_and_query, request).await; } - debug!("relaying monitor {monitor_id} request to {}", peer.label()); - relay(&state, &peer, &path_and_query, request).await + debug!( + "relaying request ({what} {}) to {}", + server_id, + peer.label() + ); + relay(state, &peer, path_and_query, request).await } /// The path and query the client sent. A nested router strips its prefix /// from the request's own URI, so the original is read from the extension /// axum keeps. -fn original_path_and_query(request: &Request) -> String { +pub(crate) fn original_path_and_query(request: &Request) -> String { let uri = request .extensions() .get::() @@ -169,7 +245,7 @@ async fn caller_sees(state: &AppState, sight: Sight, monitor_id: u32) -> AppResu /// The headers the owning server gets: the caller's own, minus the ones /// that belong to this connection, plus who relayed it and for whom. -fn relayed_headers( +pub(super) fn relayed_headers( from_caller: &HeaderMap, client: Option, this_server: Option, @@ -195,7 +271,7 @@ fn end_to_end(headers: &HeaderMap) -> HeaderMap { } /// Send `request` to `peer` and stream its answer back. -async fn relay( +pub(crate) async fn relay( state: &AppState, peer: &Peer, path_and_query: &str, diff --git a/src/cluster/mod.rs b/src/cluster/mod.rs index d34248a..e7a617e 100644 --- a/src/cluster/mod.rs +++ b/src/cluster/mod.rs @@ -14,13 +14,16 @@ //! credential that can act as anyone. That requires every server to share //! the same JWT key files. +pub mod events; pub mod forward; +pub mod system; +pub mod websocket; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; -use sea_orm::DatabaseConnection; +use sea_orm::{DatabaseConnection, EntityTrait}; use crate::configure::cluster::ClusterConfig; use crate::error::AppResult; @@ -52,6 +55,61 @@ pub fn owner(this_server: Option, monitor_server: Option) -> Owner { } } +/// Which server can read and delete the files on a storage area. +/// +/// ZoneMinder's rule: a `Storage.ServerId` of NULL or 0 means shared storage +/// (NFS, say) that every server reaches. Any other value is local to that +/// server, and the others can neither read nor delete its files. A host with +/// no server id is a single-server install, where everything is local. +pub fn storage_owner(this_server: Option, storage_server: Option) -> Owner { + owner(this_server, storage_server) +} + +/// Where an event's files are, and which monitor it belongs to (so a caller's +/// right to see the monitor can be checked before anything is relayed). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct EventHome { + pub monitor_id: u32, + pub owner: Owner, +} + +/// Remembers which storage areas a background job has already said it skips, +/// so a pass that repeats every few minutes logs it once. +#[derive(Debug, Default)] +pub struct SkipLog(Mutex>); + +impl SkipLog { + fn first_time(&self, storage_id: u16) -> bool { + self.0.lock().unwrap().insert(storage_id) + } +} + +/// Whether a background job must leave `storage` alone because another +/// server holds its files. Says so once, at info level. +/// +/// Such a job can't see the files, so every event on the storage would look +/// as if its media were gone, and the free space it measured would belong to +/// the wrong disk. The right answer is to touch neither the files nor the +/// rows: the owning server's own job covers them. +pub fn skips_peer_storage( + log: &SkipLog, + job: &str, + this_server: Option, + storage: &crate::entity::storage::Model, +) -> bool { + let Owner::Peer(server) = storage_owner(this_server, storage.server_id) else { + return false; + }; + if log.first_time(storage.id) { + tracing::info!( + "{job}: storage {} ({}) belongs to server {server}; leaving it to that server", + storage.id, + storage.path + ); + } + true +} + /// Another server's zm-api. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Peer { @@ -68,6 +126,14 @@ impl Peer { } } +/// Another server of the install, with its address if it has one. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Member { + pub id: u32, + pub name: String, + pub peer: Option, +} + #[derive(Debug, Clone)] struct ServerRow { name: String, @@ -85,8 +151,20 @@ pub struct Cluster { port: u16, overrides: HashMap, client: reqwest::Client, + connect_timeout: Duration, + /// What a WebSocket to another server trusts, when `cluster.tls_ca_file` + /// is set. `None` means the system roots. + ws_tls: Option>, servers: Cached>>, owners: Mutex)>>, + /// An event's monitor and its storage's `ServerId`, by event id. + events: Mutex>, +} + +#[derive(Debug, Clone, Copy)] +struct EventPlace { + monitor_id: u32, + storage_server: Option, } impl std::fmt::Debug for Cluster { @@ -108,8 +186,11 @@ impl Cluster { port: config.peer_port.unwrap_or(own_port), overrides: config.peer_overrides(), client: build_client(config), + connect_timeout: Duration::from_secs(config.connect_timeout_secs.max(1)), + ws_tls: build_ws_tls(config), servers: Mutex::new(None), owners: Mutex::new(HashMap::new()), + events: Mutex::new(HashMap::new()), } } @@ -132,6 +213,14 @@ impl Cluster { &self.client } + pub(crate) fn connect_timeout(&self) -> Duration { + self.connect_timeout + } + + pub(crate) fn ws_tls(&self) -> Option> { + self.ws_tls.clone() + } + /// The server that owns a monitor. `Here` for a monitor that doesn't /// exist, so the local handler answers 404 as it always did. pub async fn monitor_owner( @@ -164,6 +253,76 @@ impl Cluster { Ok(owner(self.this_server, monitor_server)) } + /// Which server holds a storage area's files, for a `Storage.ServerId`. + /// Unlike the relay, this does not depend on `cluster.enabled`: a server + /// can't read another's files whatever the setting. + pub fn owner_of_storage(&self, storage_server: Option) -> Owner { + storage_owner(self.this_server, storage_server) + } + + /// An event's monitor and the server that holds its files. `None` for an + /// event that doesn't exist, so the local handler answers 404 as it + /// always did. An event with no storage id (or the default-storage 0), + /// or whose storage row is missing, is handled here. + pub async fn event_home( + &self, + db: &DatabaseConnection, + event_id: u64, + ) -> AppResult> { + let cached = self + .events + .lock() + .unwrap() + .get(&event_id) + .filter(|(at, _)| at.elapsed() < CACHE_TTL) + .map(|(_, place)| *place); + let place = match cached { + Some(place) => place, + None => { + let Some(event) = crate::entity::events::Entity::find_by_id(event_id) + .one(db) + .await? + else { + return Ok(None); + }; + let storage_server = match event.storage_id.filter(|id| *id != 0) { + Some(id) => crate::repo::storage::find_by_id(db, id) + .await? + .and_then(|s| s.server_id), + None => None, + }; + let place = EventPlace { + monitor_id: event.monitor_id, + storage_server, + }; + let mut events = self.events.lock().unwrap(); + events.retain(|_, (at, _)| at.elapsed() < CACHE_TTL); + events.insert(event_id, (Instant::now(), place)); + place + } + }; + Ok(Some(EventHome { + monitor_id: place.monitor_id, + owner: storage_owner(self.this_server, place.storage_server), + })) + } + + /// The server that holds an event's files, when requests can be relayed + /// at all. `Here` otherwise, and for an event that doesn't exist. + pub async fn event_storage_owner( + &self, + db: &DatabaseConnection, + event_id: u64, + ) -> AppResult { + if !self.relays() { + return Ok(Owner::Here); + } + Ok(self + .event_home(db, event_id) + .await? + .map_or(Owner::Here, |home| home.owner)) + } + /// Drop what is remembered about a monitor, after its row changed here. pub fn forget_monitor(&self, monitor_id: u32) { self.owners.lock().unwrap().remove(&monitor_id); @@ -183,6 +342,37 @@ impl Cluster { })) } + /// Every `Servers` row except this server's own, by id, each with its + /// address or the fact that it has none. + pub async fn other_servers(&self, db: &DatabaseConnection) -> AppResult> { + let servers = self.servers(db).await?; + let mut members: Vec = servers + .iter() + .filter(|(id, _)| Some(**id) != self.this_server) + .map(|(id, row)| Member { + id: *id, + name: row.name.clone(), + peer: self + .base_url(*id, row.hostname.as_deref()) + .map(|base_url| Peer { + id: *id, + name: row.name.clone(), + base_url, + }), + }) + .collect(); + members.sort_by_key(|m| m.id); + Ok(members) + } + + /// This server's name from its `Servers` row, if it has one. + pub async fn this_name(&self, db: &DatabaseConnection) -> AppResult> { + let Some(id) = self.this_server else { + return Ok(None); + }; + Ok(self.servers(db).await?.get(&id).map(|row| row.name.clone())) + } + /// The v3 address of a server: the settings override, else this server's /// scheme and the peer port on the row's hostname. pub fn base_url(&self, server_id: u32, hostname: Option<&str>) -> Option { @@ -273,6 +463,42 @@ fn build_client(config: &ClusterConfig) -> reqwest::Client { builder.build().unwrap_or_default() } +/// The TLS settings for a WebSocket to another server. Only built when +/// `cluster.tls_ca_file` is set: the file's certificates are then the only +/// roots, because the WebSocket connector can't add to the system roots the +/// way the HTTP client does. Without the setting the connector uses the +/// system roots. +fn build_ws_tls(config: &ClusterConfig) -> Option> { + use rustls_pki_types::pem::PemObject; + let path = config.tls_ca_file.as_ref()?; + let certs = match rustls_pki_types::CertificateDer::pem_file_iter(path) + .and_then(|certs| certs.collect::, _>>()) + { + Ok(certs) => certs, + Err(e) => { + tracing::warn!("cluster.tls_ca_file {}: {e}", path.display()); + return None; + } + }; + let mut roots = rustls::RootCertStore::empty(); + let (added, _) = roots.add_parsable_certificates(certs); + if added == 0 { + tracing::warn!( + "cluster.tls_ca_file {}: no usable certificate", + path.display() + ); + return None; + } + let config = rustls::ClientConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions() + .ok()? + .with_root_certificates(roots) + .with_no_client_auth(); + Some(Arc::new(config)) +} + #[cfg(test)] mod tests { use super::*; @@ -300,6 +526,53 @@ mod tests { assert_eq!(owner(Some(1), Some(0)), Owner::Here); } + #[test] + fn storage_with_no_server_is_shared() { + assert_eq!(storage_owner(Some(1), None), Owner::Here); + assert_eq!(storage_owner(Some(1), Some(0)), Owner::Here); + } + + #[test] + fn storage_belongs_to_the_server_its_row_names() { + assert_eq!(storage_owner(Some(1), Some(1)), Owner::Here); + assert_eq!(storage_owner(Some(1), Some(2)), Owner::Peer(2)); + } + + #[test] + fn a_single_server_install_reaches_all_storage() { + assert_eq!(storage_owner(None, Some(2)), Owner::Here); + assert_eq!(storage_owner(None, None), Owner::Here); + } + + #[test] + fn a_job_skips_a_peers_storage_and_says_so_once() { + let log = SkipLog::default(); + let mut st = crate::entity::storage::Model { + id: 3, + path: "/srv/zm2".into(), + name: "zm2 events".into(), + r#type: crate::entity::sea_orm_active_enums::StorageType::Local, + url: None, + disk_space: None, + scheme: crate::entity::sea_orm_active_enums::Scheme::Medium, + server_id: Some(2), + do_delete: 1, + enabled: 1, + }; + assert!(skips_peer_storage(&log, "test", Some(1), &st)); + assert!(log.first_time(4), "another storage is new"); + assert!(!log.first_time(3), "this one was already announced"); + // Still skipped the second time, only not announced again. + assert!(skips_peer_storage(&log, "test", Some(1), &st)); + // Shared, or this server's own, or a single-server install: not skipped. + st.server_id = None; + assert!(!skips_peer_storage(&log, "test", Some(1), &st)); + st.server_id = Some(1); + assert!(!skips_peer_storage(&log, "test", Some(1), &st)); + st.server_id = Some(2); + assert!(!skips_peer_storage(&log, "test", None, &st)); + } + #[test] fn a_peer_is_at_this_servers_scheme_and_port_on_its_hostname() { let c = cluster(Some(1), &ClusterConfig::default()); diff --git a/src/cluster/system.rs b/src/cluster/system.rs new file mode 100644 index 0000000..1340d1f --- /dev/null +++ b/src/cluster/system.rs @@ -0,0 +1,335 @@ +//! System-wide control across servers: `?server_id=` on the daemon and +//! system routes. +//! +//! Daemons and the run state belong to one server each, but a client talks to +//! whichever zm-api it knows. `server_id` says which server a request is for: +//! absent means this one, a number means that server (relayed to its zm-api +//! with the caller's own credentials, as for a monitor), and `all` means every +//! server, with one entry per server in the answer. +//! +//! [`target_server`] sits behind authentication and the route's permission +//! check, so nothing leaves this server for a caller who could not do the +//! same here. + +use std::net::SocketAddr; + +use axum::body::{Body, Bytes}; +use axum::extract::{ConnectInfo, Request, State}; +use axum::http::{header, HeaderMap, Method, StatusCode}; +use axum::middleware::Next; +use axum::response::{IntoResponse, Response}; +use axum::Json; +use futures_util::future::join_all; + +use super::forward::{original_path_and_query, relay, relay_to_server, FORWARDED_BY}; +use super::Member; +use crate::dto::response::daemon::{AllServersResponse, ServerResult}; +use crate::error::{AppError, AppResult, Resource, ResourceType}; +use crate::server::state::AppState; + +const QUERY_KEY: &str = "server_id"; + +/// The largest body read back from a server in a fan-out. A daemon list or a +/// system status is a few kilobytes. +const MAX_ANSWER: usize = 4 * 1024 * 1024; + +/// The largest request body held while it is sent to several servers. +const MAX_REQUEST: usize = 2 * 1024 * 1024; + +/// Which server a request is for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Target { + /// This server. + Here, + /// The server with this `Servers.Id`, which may be this one. + Server(u32), + /// Every server. + All, +} + +/// Read `server_id` from a raw query string. A value that is neither a +/// number nor `all` is an error, so a typo never acts on this server by +/// accident. +pub fn parse_target(query: Option<&str>) -> AppResult { + let value = query + .unwrap_or_default() + .split('&') + .filter_map(|pair| pair.split_once('=').or(Some((pair, "")))) + .find(|(key, _)| *key == QUERY_KEY) + .map(|(_, value)| value); + match value { + None => Ok(Target::Here), + Some(v) if v.eq_ignore_ascii_case("all") => Ok(Target::All), + Some(v) => v.parse().map(Target::Server).map_err(|_| { + AppError::BadRequestError("server_id must be a server's number or \"all\"".to_string()) + }), + } +} + +/// `path_and_query` with `server_id` set to `id`, so the server that gets it +/// handles it as its own. +pub fn with_server_id(path_and_query: &str, id: u32) -> String { + let (path, query) = path_and_query + .split_once('?') + .unwrap_or((path_and_query, "")); + let mut pairs: Vec<&str> = query + .split('&') + .filter(|pair| !pair.is_empty() && pair.split('=').next() != Some(QUERY_KEY)) + .collect(); + let id = format!("{QUERY_KEY}={id}"); + pairs.push(&id); + format!("{path}?{}", pairs.join("&")) +} + +fn unknown_server(id: u32) -> AppError { + AppError::NotFoundError(Resource { + details: vec![("server_id".to_string(), id.to_string())], + resource_type: ResourceType::Config, + }) +} + +/// The status and text a failure is reported with in a per-server entry. +fn describe(error: AppError) -> (u16, String) { + let text = match &error { + AppError::BadGatewayError(m) | AppError::MisdirectedError(m) => m.clone(), + other => other.to_string(), + }; + (error.into_response().status().as_u16(), text) +} + +/// The middleware. Apply with `route_layer`, inside the guards. +/// +/// A request that already carries [`FORWARDED_BY`] is handled here whatever +/// `server_id` says: that is what stops two servers passing a request back +/// and forth. +pub async fn target_server( + State(state): State, + request: Request, + next: Next, +) -> Result { + if request.headers().contains_key(&FORWARDED_BY) { + return Ok(next.run(request).await); + } + match parse_target(request.uri().query())? { + Target::Here => Ok(next.run(request).await), + Target::Server(id) if Some(id) == state.cluster.this_server() => { + Ok(next.run(request).await) + } + Target::Server(id) => { + if !state.cluster.relays() { + return Err(unknown_server(id)); + } + let others = state.cluster.other_servers(state.db()).await?; + if !others.iter().any(|m| m.id == id) { + return Err(unknown_server(id)); + } + let path_and_query = with_server_id(&original_path_and_query(&request), id); + relay_to_server(&state, id, "this request is for", &path_and_query, request).await + } + Target::All => all_servers(&state, request, next).await, + } +} + +async fn all_servers(state: &AppState, request: Request, next: Next) -> Result { + let path_and_query = original_path_and_query(&request); + let (parts, body) = request.into_parts(); + let body = axum::body::to_bytes(body, MAX_REQUEST) + .await + .map_err(|_| AppError::BadRequestError("the request body is too large".to_string()))?; + let connect = parts.extensions.get::>().copied(); + let (method, headers) = (parts.method.clone(), parts.headers.clone()); + let local = Request::from_parts(parts, Body::from(body.clone())); + + let here = async { + let name = state.cluster.this_name(state.db()).await.ok().flatten(); + let response = next.run(local).await; + let status = response.status().as_u16(); + let answer = axum::body::to_bytes(response.into_body(), MAX_ANSWER).await; + let id = state.cluster.this_server(); + let name = name.unwrap_or_else(|| "local".to_string()); + match answer { + Ok(bytes) => ServerResult::answered(id, name, status, &bytes), + Err(e) => { + ServerResult::failed(id, name, 500, format!("reading the answer failed: {e}")) + } + } + }; + let others = fan_out(state, &method, &path_and_query, &headers, connect, &body); + let (here, others) = tokio::join!(here, others); + + let mut servers = vec![here]; + servers.extend(others?); + Ok(( + StatusCode::MULTI_STATUS, + Json(AllServersResponse { servers }), + ) + .into_response()) +} + +/// Send the same request to every other server at once and collect what each +/// answers. One server failing never fails the others: it becomes an entry +/// with `ok: false`. Empty when this install does not relay. +/// +/// Each server gets `server_id` set to its own id, and the caller's +/// credentials, so it authenticates and authorises the caller itself. +pub async fn fan_out( + state: &AppState, + method: &Method, + path_and_query: &str, + caller: &HeaderMap, + connect: Option>, + body: &Bytes, +) -> AppResult> { + if !state.cluster.relays() { + return Ok(Vec::new()); + } + let members = state.cluster.other_servers(state.db()).await?; + Ok(join_all( + members + .iter() + .map(|m| ask(state, m, method, path_and_query, caller, connect, body)), + ) + .await) +} + +async fn ask( + state: &AppState, + member: &Member, + method: &Method, + path_and_query: &str, + caller: &HeaderMap, + connect: Option>, + body: &Bytes, +) -> ServerResult { + let id = Some(member.id); + let name = member.name.clone(); + let Some(peer) = &member.peer else { + return ServerResult::failed( + id, + name, + 421, + format!( + "server {} ({}) has no address: give its Servers row a hostname, or set \ + cluster.peers.{}", + member.id, member.name, member.id + ), + ); + }; + let mut request = Request::new(Body::from(body.clone())); + *request.method_mut() = method.clone(); + *request.headers_mut() = caller.clone(); + request.headers_mut().remove(header::CONTENT_LENGTH); + // The answer is read here as JSON, so it must not come back compressed. + request.headers_mut().remove(header::ACCEPT_ENCODING); + if let Some(connect) = connect { + request.extensions_mut().insert(connect); + } + let path_and_query = with_server_id(path_and_query, member.id); + match relay(state, peer, &path_and_query, request).await { + Ok(response) => { + let status = response.status().as_u16(); + match axum::body::to_bytes(response.into_body(), MAX_ANSWER).await { + Ok(bytes) => ServerResult::answered(id, name, status, &bytes), + Err(_) => ServerResult::failed( + id, + name, + 502, + format!("{} did not finish its answer", peer.label()), + ), + } + } + Err(e) => { + let (status, error) = describe(e); + ServerResult::failed(id, name, status, error) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn no_server_id_means_this_server() { + assert_eq!(parse_target(None).unwrap(), Target::Here); + assert_eq!(parse_target(Some("")).unwrap(), Target::Here); + assert_eq!(parse_target(Some("other=1")).unwrap(), Target::Here); + } + + #[test] + fn a_number_names_a_server_and_all_names_every_one() { + assert_eq!( + parse_target(Some("server_id=2")).unwrap(), + Target::Server(2) + ); + assert_eq!( + parse_target(Some("a=b&server_id=7&c=d")).unwrap(), + Target::Server(7) + ); + assert_eq!(parse_target(Some("server_id=all")).unwrap(), Target::All); + assert_eq!(parse_target(Some("server_id=ALL")).unwrap(), Target::All); + } + + #[test] + fn anything_else_is_refused_rather_than_run_here() { + for bad in [ + "server_id=", + "server_id", + "server_id=two", + "server_id=-1", + "server_id=2,3", + ] { + assert!( + matches!(parse_target(Some(bad)), Err(AppError::BadRequestError(_))), + "{bad}" + ); + } + } + + #[test] + fn a_relayed_request_names_the_server_it_goes_to() { + assert_eq!( + with_server_id("/api/v3/daemons", 2), + "/api/v3/daemons?server_id=2" + ); + assert_eq!( + with_server_id("/api/v3/daemons?server_id=all", 2), + "/api/v3/daemons?server_id=2" + ); + assert_eq!( + with_server_id("/api/v3/x?a=1&server_id=all&b=2", 3), + "/api/v3/x?a=1&b=2&server_id=3" + ); + } + + #[test] + fn a_success_keeps_the_servers_json() { + let r = ServerResult::answered(Some(2), "zm2".into(), 200, br#"{"daemons":[]}"#); + assert!(r.ok); + assert_eq!(r.status, 200); + assert_eq!(r.result.unwrap()["daemons"], serde_json::json!([])); + assert!(r.error.is_none()); + } + + #[test] + fn a_refusal_carries_the_servers_message() { + let body = br#"{"kind":"X","error_message":"no such daemon","details":[]}"#; + let r = ServerResult::answered(Some(2), "zm2".into(), 404, body); + assert!(!r.ok); + assert_eq!(r.error.as_deref(), Some("no such daemon")); + assert!(r.result.is_none()); + let bare = ServerResult::answered(Some(2), "zm2".into(), 500, b"oops"); + assert_eq!(bare.error.as_deref(), Some("answered 500")); + } + + #[test] + fn a_server_that_did_not_answer_is_named_and_marked_failed() { + let (status, text) = describe(AppError::BadGatewayError( + "server 2 (zm2) did not answer".into(), + )); + assert_eq!(status, 502); + assert_eq!(text, "server 2 (zm2) did not answer"); + let (status, _) = describe(AppError::MisdirectedError("no address".into())); + assert_eq!(status, 421); + } +} diff --git a/src/cluster/websocket.rs b/src/cluster/websocket.rs new file mode 100644 index 0000000..9d78c89 --- /dev/null +++ b/src/cluster/websocket.rs @@ -0,0 +1,383 @@ +//! Relay a WebSocket to the zm-api on the server that owns the monitor. +//! +//! The relay layer ([`super::forward`]) sees any upgrade request for a +//! monitor another server runs. This server checks the caller first, then +//! opens its own WebSocket to the same path on the owner, and only then +//! accepts the client's upgrade. A server that is down or refuses the +//! connection therefore gives the client an ordinary HTTP error instead of a +//! socket that closes at once. +//! +//! Messages are copied one at a time in both directions, so a slow side slows +//! the other and nothing queues without bound. A socket that carries +//! signalling can sit idle for minutes, so there is no read timeout; the +//! connect timeout covers the connection and the handshake. + +use std::time::Duration; + +use axum::extract::ws::{CloseFrame, Message, WebSocket, WebSocketUpgrade}; +use axum::extract::{FromRequestParts, Request}; +use axum::http::{header, HeaderMap, HeaderName, HeaderValue, StatusCode}; +use axum::response::{IntoResponse, Response}; +use futures_util::{SinkExt, StreamExt}; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode; +use tokio_tungstenite::tungstenite::protocol::CloseFrame as PeerCloseFrame; +use tokio_tungstenite::tungstenite::{Error as PeerError, Message as PeerMessage}; +use tokio_tungstenite::Connector; +use tracing::{debug, warn}; + +use super::forward::{relayed_headers, FORWARDED_BY}; +use super::Peer; +use crate::error::AppError; +use crate::server::state::AppState; + +/// How long one side may take to answer a close after the other closed. +const CLOSE_GRACE: Duration = Duration::from_secs(5); + +/// The only headers the owner gets besides the ones the WebSocket client +/// makes itself (key, version, host): the caller's credentials and +/// subprotocols, and who relayed it. +const PASSED_ON: [HeaderName; 4] = [ + header::AUTHORIZATION, + header::SEC_WEBSOCKET_PROTOCOL, + FORWARDED_BY, + HeaderName::from_static("x-forwarded-for"), +]; + +/// The WebSocket URL for a peer's HTTP base URL and a path with query. +/// `None` when the base URL is neither `http` nor `https`. +fn socket_url(base_url: &str, path_and_query: &str) -> Option { + let rest = match base_url.split_once("://")? { + ("https", rest) => format!("wss://{rest}"), + ("http", rest) => format!("ws://{rest}"), + _ => return None, + }; + Some(format!("{rest}{path_and_query}")) +} + +/// What goes on the handshake to the owner. +fn handshake_headers(relayed: &HeaderMap) -> HeaderMap { + relayed + .iter() + .filter(|(name, _)| PASSED_ON.contains(name)) + .map(|(name, value)| (name.clone(), value.clone())) + .collect() +} + +/// Relay an upgrade request to `peer`. `what` is the start of a refusal, as +/// for the HTTP relay. +pub(crate) async fn relay( + state: &AppState, + peer: &Peer, + what: &str, + path_and_query: &str, + request: Request, +) -> Result { + let (mut parts, _) = request.into_parts(); + // Something that asks to upgrade but isn't a WebSocket handshake is not + // something this relay can carry. + let Ok(upgrade) = WebSocketUpgrade::from_request_parts(&mut parts, &()).await else { + return Err(AppError::MisdirectedError(format!( + "{what} {}; this upgrade request is not a WebSocket handshake, so it can't be relayed", + peer.label() + ))); + }; + + let client = parts + .extensions + .get::>() + .map(|info| info.0.ip()); + let headers = handshake_headers(&relayed_headers( + &parts.headers, + client, + state.cluster.this_server(), + )); + let url = socket_url(&peer.base_url, path_and_query).ok_or_else(|| { + AppError::MisdirectedError(format!( + "{} has an address that is not http(s)", + peer.label() + )) + })?; + let mut handshake = url + .as_str() + .into_client_request() + .map_err(|e| AppError::InternalServerError(format!("building the handshake: {e}")))?; + handshake.headers_mut().extend(headers); + + let connector = state.cluster.ws_tls().map(Connector::Rustls); + let connected = tokio::time::timeout( + state.cluster.connect_timeout(), + tokio_tungstenite::connect_async_tls_with_config(handshake, None, false, connector), + ) + .await; + let (socket, answer) = match connected { + Ok(Ok(connected)) => connected, + Ok(Err(PeerError::Http(answer))) => return refusal(peer, *answer), + // The URL can carry a token in its query, and the error text of some + // failures names it, so only the kind is logged. + Ok(Err(e)) => { + warn!("{} did not accept a WebSocket: {}", peer.label(), kind(&e)); + return Err(unreachable(peer)); + } + Err(_) => { + warn!("{} did not answer a WebSocket in time", peer.label()); + return Err(unreachable(peer)); + } + }; + + // Echo the subprotocol the owner chose. The client offered it, or the + // owner would not have picked it. + let chosen = answer + .headers() + .get(header::SEC_WEBSOCKET_PROTOCOL) + .and_then(|v| v.to_str().ok()) + .map(str::to_string); + let upgrade = match chosen { + Some(protocol) => upgrade.protocols([protocol]), + None => upgrade, + }; + let label = peer.label(); + debug!("relaying a WebSocket to {label}"); + Ok(upgrade.on_upgrade(move |client| pump(client, socket, label))) +} + +fn unreachable(peer: &Peer) -> AppError { + AppError::BadGatewayError(format!("{} did not answer", peer.label())) +} + +/// The owner answered the handshake with something other than an upgrade. +fn refusal( + peer: &Peer, + answer: tokio_tungstenite::tungstenite::http::Response>>, +) -> Result { + let status = answer.status(); + // This server accepted the credentials a moment ago, so only different + // signing keys explain a refusal. + if status == StatusCode::UNAUTHORIZED { + warn!( + "{} refused credentials this server accepted: every server must use the same JWT \ + key files", + peer.label() + ); + return Err(AppError::BadGatewayError(format!( + "{} refused credentials this server accepted; the servers' JWT keys differ", + peer.label() + ))); + } + Ok(RelayedAnswer::new(status, answer).into_response()) +} + +/// The variant name of a connection error, without its text. +fn kind(e: &PeerError) -> &'static str { + match e { + PeerError::Io(_) => "connection failed", + PeerError::Tls(_) => "TLS failed", + PeerError::Url(_) => "bad address", + PeerError::Protocol(_) => "handshake failed", + _ => "connection failed", + } +} + +fn to_peer(message: Message) -> PeerMessage { + match message { + Message::Text(text) => PeerMessage::text(text.as_str()), + Message::Binary(bytes) => PeerMessage::Binary(bytes), + Message::Ping(bytes) => PeerMessage::Ping(bytes), + Message::Pong(bytes) => PeerMessage::Pong(bytes), + Message::Close(frame) => PeerMessage::Close(frame.map(|f| PeerCloseFrame { + code: CloseCode::from(f.code), + reason: f.reason.as_str().into(), + })), + } +} + +/// `None` for a raw frame, which a reader never yields. +fn to_client(message: PeerMessage) -> Option { + Some(match message { + PeerMessage::Text(text) => Message::text(text.as_str()), + PeerMessage::Binary(bytes) => Message::Binary(bytes), + PeerMessage::Ping(bytes) => Message::Ping(bytes), + PeerMessage::Pong(bytes) => Message::Pong(bytes), + PeerMessage::Close(frame) => Message::Close(frame.map(|f| CloseFrame { + code: u16::from(f.code), + reason: f.reason.as_str().into(), + })), + PeerMessage::Frame(_) => return None, + }) +} + +/// 1011: the relay itself failed, so the client can tell it from a close +/// the owner chose. +fn relay_failed(reason: &'static str) -> CloseFrame { + CloseFrame { + code: 1011, + reason: reason.into(), + } +} + +/// Copy messages both ways until one side closes or fails, then close the +/// other. +async fn pump(client: WebSocket, peer: tokio_tungstenite::WebSocketStream, label: String) +where + S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send, +{ + let (mut to_client_sink, mut from_client) = client.split(); + let (mut to_peer_sink, mut from_peer) = peer.split(); + + let upstream = async { + while let Some(message) = from_client.next().await { + let Ok(message) = message else { break }; + let closing = matches!(message, Message::Close(_)); + if to_peer_sink.send(to_peer(message)).await.is_err() || closing { + break; + } + } + // The client left or failed: tell the owner, if it has not heard. + let _ = to_peer_sink.send(PeerMessage::Close(None)).await; + }; + let downstream = async { + loop { + match from_peer.next().await { + Some(Ok(message)) => { + let Some(message) = to_client(message) else { + continue; + }; + let closing = matches!(message, Message::Close(_)); + if to_client_sink.send(message).await.is_err() || closing { + break; + } + } + Some(Err(e)) => { + debug!("{label}: WebSocket failed: {}", kind(&e)); + let _ = to_client_sink + .send(Message::Close(Some(relay_failed( + "the owning server's connection failed", + )))) + .await; + break; + } + None => { + // The owner went without a close frame. + let _ = to_client_sink + .send(Message::Close(Some(relay_failed( + "the owning server closed the connection", + )))) + .await; + break; + } + } + } + }; + tokio::pin!(upstream, downstream); + // Once one direction ends the other gets a short time to finish its + // close handshake. + tokio::select! { + () = &mut upstream => { let _ = tokio::time::timeout(CLOSE_GRACE, &mut downstream).await; } + () = &mut downstream => { let _ = tokio::time::timeout(CLOSE_GRACE, &mut upstream).await; } + } + debug!("{label}: WebSocket relay ended"); +} + +/// A refusal from the owner, passed on as it came: its status, its body and +/// its content type. +#[derive(Debug)] +pub struct RelayedAnswer { + status: StatusCode, + content_type: Option, + body: Vec, +} + +impl RelayedAnswer { + fn new( + status: StatusCode, + answer: tokio_tungstenite::tungstenite::http::Response>>, + ) -> Self { + Self { + status, + content_type: answer.headers().get(header::CONTENT_TYPE).cloned(), + body: answer.into_body().unwrap_or_default(), + } + } +} + +impl IntoResponse for RelayedAnswer { + fn into_response(self) -> Response { + let mut response = (self.status, self.body).into_response(); + if let Some(content_type) = self.content_type { + response + .headers_mut() + .insert(header::CONTENT_TYPE, content_type); + } + response + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_peers_http_address_becomes_a_websocket_address() { + assert_eq!( + socket_url("http://zm2:8080", "/api/v3/live/7/webrtc/ws?token=t").unwrap(), + "ws://zm2:8080/api/v3/live/7/webrtc/ws?token=t" + ); + assert_eq!( + socket_url("https://zm2:8443", "/x").unwrap(), + "wss://zm2:8443/x" + ); + assert!(socket_url("ftp://zm2", "/x").is_none()); + } + + #[test] + fn the_handshake_carries_credentials_and_nothing_of_the_clients_own_handshake() { + let mut from_caller = HeaderMap::new(); + from_caller.insert(header::AUTHORIZATION, HeaderValue::from_static("Bearer t")); + from_caller.insert( + header::SEC_WEBSOCKET_PROTOCOL, + HeaderValue::from_static("zm"), + ); + from_caller.insert( + header::SEC_WEBSOCKET_KEY, + HeaderValue::from_static("client-key"), + ); + from_caller.insert(header::COOKIE, HeaderValue::from_static("a=b")); + from_caller.insert(FORWARDED_BY, HeaderValue::from_static("9")); + let out = handshake_headers(&relayed_headers(&from_caller, None, Some(1))); + assert_eq!(out.get(header::AUTHORIZATION).unwrap(), "Bearer t"); + assert_eq!(out.get(header::SEC_WEBSOCKET_PROTOCOL).unwrap(), "zm"); + assert_eq!(out.get(FORWARDED_BY).unwrap(), "1"); + assert!(!out.contains_key(header::SEC_WEBSOCKET_KEY)); + assert!(!out.contains_key(header::COOKIE)); + } + + #[test] + fn close_frames_keep_their_code_and_reason_both_ways() { + let closed = Message::Close(Some(CloseFrame { + code: 4001, + reason: "bye".into(), + })); + let PeerMessage::Close(Some(frame)) = to_peer(closed) else { + panic!("a close frame") + }; + assert_eq!(u16::from(frame.code), 4001); + assert_eq!(frame.reason.as_str(), "bye"); + let Some(Message::Close(Some(back))) = to_client(PeerMessage::Close(Some(frame))) else { + panic!("a close frame") + }; + assert_eq!((back.code, back.reason.as_str()), (4001, "bye")); + } + + #[test] + fn text_and_binary_cross_unchanged() { + let PeerMessage::Text(text) = to_peer(Message::text("hello")) else { + panic!("text") + }; + assert_eq!(text.as_str(), "hello"); + let Some(Message::Binary(bytes)) = to_client(PeerMessage::Binary(vec![1u8, 2, 3].into())) + else { + panic!("binary") + }; + assert_eq!(&bytes[..], [1, 2, 3]); + } +} diff --git a/src/dto/request/daemon.rs b/src/dto/request/daemon.rs index da9735c..c5991c3 100644 --- a/src/dto/request/daemon.rs +++ b/src/dto/request/daemon.rs @@ -18,4 +18,11 @@ pub struct ApplyStateRequest { /// Name of the state to apply #[garde(length(chars, max = 64))] pub state_name: String, + /// Leave the database alone and only restart this server's daemons for + /// the monitors the state names. This is what a server sends the other + /// servers after it has applied the state, so the change is written once. + /// It is handled on this server and never passed on. + #[serde(default)] + #[garde(skip)] + pub daemons_only: bool, } diff --git a/src/dto/response/daemon.rs b/src/dto/response/daemon.rs index b5ac26b..1810cc3 100644 --- a/src/dto/response/daemon.rs +++ b/src/dto/response/daemon.rs @@ -138,6 +138,12 @@ pub struct DaemonActionResponse { pub success: bool, /// Human-readable message pub message: String, + /// What the other servers of a multi-server install did, when the action + /// reaches them too (applying a run state does). `success` and `message` + /// describe this server only. Absent on a single-server install and for + /// actions that stay on one server. + #[serde(skip_serializing_if = "Option::is_none")] + pub servers: Option>, } impl DaemonActionResponse { @@ -146,6 +152,7 @@ impl DaemonActionResponse { Self { success: true, message: message.into(), + servers: None, } } @@ -154,6 +161,85 @@ impl DaemonActionResponse { Self { success: false, message: message.into(), + servers: None, } } } + +/// What one server of a multi-server install answered to a request that went +/// to several of them. +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct ServerResult { + /// The server's `Servers.Id`. Null for the one server of an install whose + /// host has no server id. + pub server_id: Option, + /// The server's name. + pub name: String, + /// Whether the server answered with a success status. + pub ok: bool, + /// The HTTP status the server answered with, or the one this server + /// gives for not reaching it (502 no answer, 421 no address). + pub status: u16, + /// The JSON the server answered, as it would for the same request sent to + /// it alone. + #[serde(skip_serializing_if = "Option::is_none")] + #[schema(value_type = Option)] + pub result: Option, + /// Why the request failed on this server. + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +impl ServerResult { + /// A server answered with `status` and `body`. + pub fn answered(server_id: Option, name: String, status: u16, body: &[u8]) -> Self { + let ok = (200..300).contains(&status); + let json: Option = serde_json::from_slice(body).ok(); + let error = (!ok).then(|| { + json.as_ref() + .and_then(|v| v.get("error_message").or_else(|| v.get("message"))) + .and_then(|m| m.as_str()) + .map_or_else(|| format!("answered {status}"), str::to_string) + }); + Self { + server_id, + name, + ok, + status, + result: if ok { json } else { None }, + error, + } + } + + /// The request never got an answer from the server. + pub fn failed(server_id: Option, name: String, status: u16, error: String) -> Self { + Self { + server_id, + name, + ok: false, + status, + result: None, + error: Some(error), + } + } +} + +/// The answer to a request sent with `server_id=all`: one entry per server, +/// this server first, then the others by id. The HTTP status is 207 whenever +/// the request ran, even if every server failed; each entry says how it went. +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct AllServersResponse { + pub servers: Vec, +} + +/// Which server a request is for. +#[derive(Debug, Clone, utoipa::IntoParams)] +#[allow(dead_code)] +#[into_params(parameter_in = Query)] +pub struct ServerTargetQuery { + /// Absent: this server. A server's number: that server, relayed to its + /// zm-api when it is not this one. `all`: every server, answered with 207 + /// and one entry per server (see `AllServersResponse`). A request that + /// another server already relayed is always handled here. + pub server_id: Option, +} diff --git a/src/handlers/daemon.rs b/src/handlers/daemon.rs index 20f8ebd..5dbf9e5 100644 --- a/src/handlers/daemon.rs +++ b/src/handlers/daemon.rs @@ -1,12 +1,18 @@ //! HTTP handlers for daemon controller API. -use axum::extract::{Path, State}; +use axum::extract::{ConnectInfo, Path, State}; +use axum::http::request::Parts; +use axum::http::Method; use axum::Json; -use tracing::info; +use tracing::{info, warn}; + +use crate::cluster::forward::FORWARDED_BY; +use crate::cluster::system::{fan_out, parse_target, Target}; use crate::dto::request::daemon::{ApplyStateRequest, StartDaemonRequest}; use crate::dto::response::daemon::{ - DaemonActionResponse, DaemonListResponse, DaemonStatusResponse, SystemStatusResponse, + AllServersResponse, DaemonActionResponse, DaemonListResponse, DaemonStatusResponse, + ServerTargetQuery, SystemStatusResponse, }; use crate::error::{AppError, AppResult}; use crate::server::state::AppState; @@ -18,8 +24,14 @@ use garde::Validate; security(("jwt" = [])), get, path = "/api/v3/daemons", + params(ServerTargetQuery), responses( (status = 200, description = "List of all daemons", body = DaemonListResponse), + (status = 207, description = "With `server_id=all`: one entry per server; the status is 207 even when every server failed", body = AllServersResponse), + (status = 400, description = "`server_id` is neither a server number nor `all`", body = crate::error::AppResponseError), + (status = 404, description = "No server has the number given in `server_id`", body = crate::error::AppResponseError), + (status = 421, description = "The server named by `server_id` has no address", body = crate::error::AppResponseError), + (status = 502, description = "The server named by `server_id` did not answer", body = crate::error::AppResponseError), (status = 503, description = "Daemon manager not available", body = crate::error::AppResponseError) ), tag = "Daemons" @@ -36,10 +48,15 @@ pub async fn list_daemons(State(state): State) -> AppResult, description = "Optional arguments"), responses( (status = 200, description = "Daemon started", body = DaemonActionResponse), + (status = 207, description = "With `server_id=all`: one entry per server; the status is 207 even when every server failed", body = AllServersResponse), + (status = 400, description = "`server_id` is neither a server number nor `all`", body = crate::error::AppResponseError), + (status = 404, description = "No server has the number given in `server_id`", body = crate::error::AppResponseError), + (status = 421, description = "The server named by `server_id` has no address", body = crate::error::AppResponseError), + (status = 502, description = "The server named by `server_id` did not answer", body = crate::error::AppResponseError), (status = 503, description = "Daemon manager not available", body = crate::error::AppResponseError) ), tag = "Daemons", @@ -85,10 +108,16 @@ pub async fn start_daemon( post, path = "/api/v3/daemons/{id}/stop", params( + ServerTargetQuery, ("id" = String, Path, description = "Daemon identifier") ), responses( (status = 200, description = "Daemon stopped", body = DaemonActionResponse), + (status = 207, description = "With `server_id=all`: one entry per server; the status is 207 even when every server failed", body = AllServersResponse), + (status = 400, description = "`server_id` is neither a server number nor `all`", body = crate::error::AppResponseError), + (status = 404, description = "No server has the number given in `server_id`", body = crate::error::AppResponseError), + (status = 421, description = "The server named by `server_id` has no address", body = crate::error::AppResponseError), + (status = 502, description = "The server named by `server_id` did not answer", body = crate::error::AppResponseError), (status = 503, description = "Daemon manager not available", body = crate::error::AppResponseError) ), tag = "Daemons", @@ -108,10 +137,16 @@ pub async fn stop_daemon( post, path = "/api/v3/daemons/{id}/restart", params( + ServerTargetQuery, ("id" = String, Path, description = "Daemon identifier") ), responses( (status = 200, description = "Daemon restarted", body = DaemonActionResponse), + (status = 207, description = "With `server_id=all`: one entry per server; the status is 207 even when every server failed", body = AllServersResponse), + (status = 400, description = "`server_id` is neither a server number nor `all`", body = crate::error::AppResponseError), + (status = 404, description = "No server has the number given in `server_id`", body = crate::error::AppResponseError), + (status = 421, description = "The server named by `server_id` has no address", body = crate::error::AppResponseError), + (status = 502, description = "The server named by `server_id` did not answer", body = crate::error::AppResponseError), (status = 503, description = "Daemon manager not available", body = crate::error::AppResponseError) ), tag = "Daemons", @@ -131,10 +166,16 @@ pub async fn restart_daemon( post, path = "/api/v3/daemons/{id}/reload", params( + ServerTargetQuery, ("id" = String, Path, description = "Daemon identifier") ), responses( (status = 200, description = "Reload signal sent", body = DaemonActionResponse), + (status = 207, description = "With `server_id=all`: one entry per server; the status is 207 even when every server failed", body = AllServersResponse), + (status = 400, description = "`server_id` is neither a server number nor `all`", body = crate::error::AppResponseError), + (status = 404, description = "No server has the number given in `server_id`", body = crate::error::AppResponseError), + (status = 421, description = "The server named by `server_id` has no address", body = crate::error::AppResponseError), + (status = 502, description = "The server named by `server_id` did not answer", body = crate::error::AppResponseError), (status = 503, description = "Daemon manager not available", body = crate::error::AppResponseError) ), tag = "Daemons", @@ -154,8 +195,14 @@ pub async fn reload_daemon( security(("jwt" = [])), get, path = "/api/v3/system/status", + params(ServerTargetQuery), responses( (status = 200, description = "System status", body = SystemStatusResponse), + (status = 207, description = "With `server_id=all`: one entry per server; the status is 207 even when every server failed", body = AllServersResponse), + (status = 400, description = "`server_id` is neither a server number nor `all`", body = crate::error::AppResponseError), + (status = 404, description = "No server has the number given in `server_id`", body = crate::error::AppResponseError), + (status = 421, description = "The server named by `server_id` has no address", body = crate::error::AppResponseError), + (status = 502, description = "The server named by `server_id` did not answer", body = crate::error::AppResponseError), (status = 503, description = "Daemon manager not available", body = crate::error::AppResponseError) ), tag = "System" @@ -172,8 +219,14 @@ pub async fn get_system_status( #[utoipa::path( post, path = "/api/v3/system/startup", + params(ServerTargetQuery), responses( (status = 200, description = "System started", body = DaemonActionResponse), + (status = 207, description = "With `server_id=all`: one entry per server; the status is 207 even when every server failed", body = AllServersResponse), + (status = 400, description = "`server_id` is neither a server number nor `all`", body = crate::error::AppResponseError), + (status = 404, description = "No server has the number given in `server_id`", body = crate::error::AppResponseError), + (status = 421, description = "The server named by `server_id` has no address", body = crate::error::AppResponseError), + (status = 502, description = "The server named by `server_id` did not answer", body = crate::error::AppResponseError), (status = 503, description = "Daemon manager not available", body = crate::error::AppResponseError) ), tag = "System", @@ -191,8 +244,14 @@ pub async fn system_startup( #[utoipa::path( post, path = "/api/v3/system/shutdown", + params(ServerTargetQuery), responses( (status = 200, description = "System shutdown initiated", body = DaemonActionResponse), + (status = 207, description = "With `server_id=all`: one entry per server; the status is 207 even when every server failed", body = AllServersResponse), + (status = 400, description = "`server_id` is neither a server number nor `all`", body = crate::error::AppResponseError), + (status = 404, description = "No server has the number given in `server_id`", body = crate::error::AppResponseError), + (status = 421, description = "The server named by `server_id` has no address", body = crate::error::AppResponseError), + (status = 502, description = "The server named by `server_id` did not answer", body = crate::error::AppResponseError), (status = 503, description = "Daemon manager not available", body = crate::error::AppResponseError) ), tag = "System", @@ -210,8 +269,14 @@ pub async fn system_shutdown( #[utoipa::path( post, path = "/api/v3/system/restart", + params(ServerTargetQuery), responses( (status = 200, description = "System restarted", body = DaemonActionResponse), + (status = 207, description = "With `server_id=all`: one entry per server; the status is 207 even when every server failed", body = AllServersResponse), + (status = 400, description = "`server_id` is neither a server number nor `all`", body = crate::error::AppResponseError), + (status = 404, description = "No server has the number given in `server_id`", body = crate::error::AppResponseError), + (status = 421, description = "The server named by `server_id` has no address", body = crate::error::AppResponseError), + (status = 502, description = "The server named by `server_id` did not answer", body = crate::error::AppResponseError), (status = 503, description = "Daemon manager not available", body = crate::error::AppResponseError) ), tag = "System", @@ -229,8 +294,14 @@ pub async fn system_restart( #[utoipa::path( post, path = "/api/v3/system/logrot", + params(ServerTargetQuery), responses( (status = 200, description = "Log rotation triggered", body = DaemonActionResponse), + (status = 207, description = "With `server_id=all`: one entry per server; the status is 207 even when every server failed", body = AllServersResponse), + (status = 400, description = "`server_id` is neither a server number nor `all`", body = crate::error::AppResponseError), + (status = 404, description = "No server has the number given in `server_id`", body = crate::error::AppResponseError), + (status = 421, description = "The server named by `server_id` has no address", body = crate::error::AppResponseError), + (status = 502, description = "The server named by `server_id` did not answer", body = crate::error::AppResponseError), (status = 503, description = "Daemon manager not available", body = crate::error::AppResponseError) ), tag = "System", @@ -246,12 +317,22 @@ pub async fn system_logrot(State(state): State) -> AppResult) -> AppResult, + parts: Parts, Json(request): Json, ) -> AppResult> { request.validate().map_err(AppError::InvalidInputError)?; + let forwarded = parts.headers.contains_key(&FORWARDED_BY); + if !forwarded && matches!(parse_target(parts.uri.query())?, Target::Server(_)) { + return Err(AppError::BadRequestError( + "a run state applies to every server's monitors at once: leave out server_id, or \ + use server_id=all" + .to_string(), + )); + } + if request.daemons_only { + info!("Restarting daemons for state: {}", request.state_name); + let response = + service::daemon::restart_daemons_for_state(&state, &request.state_name).await?; + return Ok(Json(response)); + } info!("Applying state: {}", request.state_name); - let response = service::daemon::apply_state(&state, &request.state_name).await?; + let mut response = service::daemon::apply_state(&state, &request.state_name).await?; + + // The rows are written; the other servers' daemons don't watch them. + if !forwarded && state.cluster.relays() { + let body = serde_json::json!({ "state_name": request.state_name, "daemons_only": true }); + let connect = parts.extensions.get::>(); + match fan_out( + &state, + &Method::POST, + parts.uri.path(), + &parts.headers, + connect.copied(), + &body.to_string().into(), + ) + .await + { + Ok(others) if !others.is_empty() => response.servers = Some(others), + Ok(_) => {} + // The state is committed either way, as with a failed restart. + Err(e) => warn!( + "state '{}' applied here, but listing the other servers failed: {e}", + request.state_name + ), + } + } Ok(Json(response)) } diff --git a/src/handlers/event_stream.rs b/src/handlers/event_stream.rs index 98a562b..668c5f8 100644 --- a/src/handlers/event_stream.rs +++ b/src/handlers/event_stream.rs @@ -14,6 +14,9 @@ use serde::Deserialize; use tokio::sync::broadcast; use utoipa::IntoParams; +use crate::cluster::events::{follow_peers, PeerAlarm, PeerStreams}; +use crate::cluster::forward::FORWARDED_BY; +use crate::cluster::Owner; use crate::error::{AppResponseError, AppResult}; use crate::server::state::AppState; use crate::service::event_stream::{self, StreamMessage}; @@ -41,6 +44,12 @@ struct Subscriber { claims: UserClaims, scope: MonitorScope, monitor: Option, + /// Another server asked for this stream on behalf of a client: only this + /// server's alarm states are wanted, because the client's own server has + /// the events already. + alarms_only: bool, + /// The alarm states of the monitors other servers run. + peers: Option, queue: VecDeque, rx: broadcast::Receiver, recheck: tokio::time::Interval, @@ -51,11 +60,29 @@ struct Subscriber { impl Subscriber { fn shows(&self, msg: &StreamMessage) -> bool { + if self.alarms_only && !matches!(msg, StreamMessage::AlarmState(_)) { + return false; + } let m = msg.monitor_id(); self.monitor.is_none_or(|f| f == m) && self.scope.allows(m, Level::View) } } +impl Subscriber { + /// An alarm state a peer sent, if that peer runs the monitor (it can't + /// speak for any other) and this caller may see the monitor. + async fn peer_alarm(&self, from: PeerAlarm) -> Option { + let owner = self + .state + .cluster + .monitor_owner(self.state.db(), from.alarm.monitor_id) + .await + .ok()?; + let msg = StreamMessage::AlarmState(from.alarm); + (owner == Owner::Peer(from.server_id) && self.shows(&msg)).then_some(msg) + } +} + fn sse(msg: &StreamMessage) -> Event { let event = Event::default() .event(msg.kind()) @@ -128,14 +155,19 @@ pub async fn stream_events( Query(q): Query, headers: HeaderMap, ) -> AppResult>>> { + // Another server's request on behalf of a client: this server's own + // alarm states only, no replay, and nobody else to follow. + let alarms_only = headers.contains_key(&FORWARDED_BY); let since = q.since.or_else(|| { headers .get("last-event-id") .and_then(|v| v.to_str().ok()) .and_then(|v| v.trim().parse().ok()) }); + let since = since.filter(|_| !alarms_only); // Subscribe before the snapshot and replay, so nothing falls between. let rx = state.event_hub.subscribe(&state); + let peers = follow_peers(&state, &headers, q.monitor_id).await?; let mut sub = Subscriber { expires: tokio::time::Instant::now() @@ -144,6 +176,8 @@ pub async fn stream_events( claims, scope, monitor: q.monitor_id, + alarms_only, + peers, queue: VecDeque::new(), rx, recheck: tokio::time::interval(RECHECK), @@ -183,6 +217,20 @@ pub async fn stream_events( } Err(broadcast::error::RecvError::Closed) => return None, }, + alarm = async { + match sub.peers.as_mut() { + Some(peers) => peers.next().await, + None => std::future::pending().await, + } + } => match alarm { + Some(alarm) => match sub.peer_alarm(alarm).await { + Some(msg) => return Some((Ok(sse(&msg)), sub)), + None => continue, + }, + // Every peer refused this caller's token: nothing more + // will come, and the local stream goes on. + None => sub.peers = None, + }, _ = sub.recheck.tick() => match still_allowed(&sub.state, &sub.claims).await { Some(scope) => sub.scope = scope, None => return None, diff --git a/src/handlers/live.rs b/src/handlers/live.rs index eb17769..a3d0c38 100644 --- a/src/handlers/live.rs +++ b/src/handlers/live.rs @@ -322,8 +322,14 @@ pub async fn get_live_stats( path = "/api/v3/live/sessions", operation_id = "listLiveSessions", tag = "Live Streaming", + params(crate::dto::response::daemon::ServerTargetQuery), responses( (status = 200, description = "List of active live sessions", body = Vec), + (status = 207, description = "With `server_id=all`: one entry per server; the status is 207 even when every server failed", body = crate::dto::response::daemon::AllServersResponse), + (status = 400, description = "`server_id` is neither a server number nor `all`", body = AppResponseError), + (status = 404, description = "No server has the number given in `server_id`", body = AppResponseError), + (status = 421, description = "The server named by `server_id` has no address", body = AppResponseError), + (status = 502, description = "The server named by `server_id` did not answer", body = AppResponseError), (status = 503, description = "Service unavailable", body = AppResponseError) ), security( @@ -1646,8 +1652,14 @@ fn status_changes( path = "/api/v3/live/sources", operation_id = "getLiveSources", tag = "Live Streaming", + params(crate::dto::response::daemon::ServerTargetQuery), responses( - (status = 200, description = "Source statistics"), + (status = 200, description = "Source statistics: `active_sources` and `sources`", body = serde_json::Value), + (status = 207, description = "With `server_id=all`: one entry per server; the status is 207 even when every server failed", body = crate::dto::response::daemon::AllServersResponse), + (status = 400, description = "`server_id` is neither a server number nor `all`", body = AppResponseError), + (status = 404, description = "No server has the number given in `server_id`", body = AppResponseError), + (status = 421, description = "The server named by `server_id` has no address", body = AppResponseError), + (status = 502, description = "The server named by `server_id` did not answer", body = AppResponseError), (status = 503, description = "Service unavailable", body = AppResponseError) ), security( diff --git a/src/handlers/monitor_status.rs b/src/handlers/monitor_status.rs index 6c557ec..9cfd443 100644 --- a/src/handlers/monitor_status.rs +++ b/src/handlers/monitor_status.rs @@ -36,7 +36,11 @@ pub async fn list_monitor_statuses( get, path = "/api/v3/monitor-status/{monitor_id}", params(("monitor_id" = u32, Path, description = "Monitor ID")), - responses((status = 200, description = "Monitor status detail", body = MonitorStatusResponse)), + responses( + (status = 200, description = "Monitor status detail. For a monitor another server runs, the request is relayed to that server, which reads its shared memory", body = MonitorStatusResponse), + (status = 421, description = "The server that runs the monitor has no address", body = crate::error::AppResponseError), + (status = 502, description = "The server that runs the monitor did not answer", body = crate::error::AppResponseError) + ), tag = "Monitor Status", security(("jwt" = [])) )] diff --git a/src/handlers/openapi.rs b/src/handlers/openapi.rs index 024a2aa..4941e4c 100644 --- a/src/handlers/openapi.rs +++ b/src/handlers/openapi.rs @@ -497,7 +497,9 @@ use crate::util::claim::UserClaims; // daemons crate::dto::request::daemon::ApplyStateRequest, crate::dto::request::daemon::StartDaemonRequest, + crate::dto::response::daemon::AllServersResponse, crate::dto::response::daemon::DaemonActionResponse, + crate::dto::response::daemon::ServerResult, crate::dto::response::daemon::DaemonListResponse, crate::dto::response::daemon::DaemonStatusResponse, crate::dto::response::daemon::SystemStatusResponse, diff --git a/src/routes/daemon.rs b/src/routes/daemon.rs index f18fb75..bd1c4c6 100644 --- a/src/routes/daemon.rs +++ b/src/routes/daemon.rs @@ -14,8 +14,10 @@ use crate::util::middleware::auth_middleware; /// /// These endpoints control ZoneMinder process and system lifecycle, so the /// whole group is gated behind JWT auth via [`auth_middleware`]. -pub fn add_daemon_routes(router: Router) -> Router { - let protected_routes = Router::new() +pub fn add_daemon_routes(router: Router, state: AppState) -> Router { + // Every route but the run state takes `?server_id=`; the state route + // fans out by itself, because it changes the database first. + let targeted = Router::new() // Daemon management .route("/api/v3/daemons", get(daemon::list_daemons)) .route("/api/v3/daemons/{id}", get(daemon::get_daemon)) @@ -29,6 +31,11 @@ pub fn add_daemon_routes(router: Router) -> Router { .route("/api/v3/system/shutdown", post(daemon::system_shutdown)) .route("/api/v3/system/restart", post(daemon::system_restart)) .route("/api/v3/system/logrot", post(daemon::system_logrot)) + .route_layer(middleware::from_fn_with_state( + state, + crate::cluster::system::target_server, + )); + let protected_routes = targeted .route("/api/v3/system/state", post(daemon::apply_state)) .layer(middleware::from_fn(auth_middleware)); diff --git a/src/routes/events.rs b/src/routes/events.rs index eb862e9..8142d84 100644 --- a/src/routes/events.rs +++ b/src/routes/events.rs @@ -1,17 +1,21 @@ -use axum::{middleware, routing::get, Router}; +use axum::{ + middleware, + routing::{delete, get}, + Router, +}; use crate::util::middleware::auth_middleware; use crate::{handlers, server::state::AppState}; /// Create events router using JWT middleware -pub fn add_event_routes(router: Router) -> Router { +pub fn add_event_routes(router: Router, state: AppState) -> Router { router.nest( "/api/v3/events", - routes().layer(middleware::from_fn(auth_middleware)), + routes(state).layer(middleware::from_fn(auth_middleware)), ) } -pub fn routes() -> Router { +pub fn routes(state: AppState) -> Router { Router::new() // Use fully qualified handler paths .route( @@ -20,10 +24,16 @@ pub fn routes() -> Router { ) .route( "/{id}", - // Use fully qualified handler paths - get(handlers::events::get_event) - .patch(handlers::events::update_event) - .delete(handlers::events::delete_event), + get(handlers::events::get_event).patch(handlers::events::update_event), + ) + // Deleting removes the files too, and only the server that holds + // them can. Reading or editing the row works on any server. + .route( + "/{id}", + delete(handlers::events::delete_event).route_layer(middleware::from_fn_with_state( + state, + crate::cluster::forward::forward_to_storage_owner, + )), ) // Live events and alarm states (Server-Sent Events) .route("/stream", get(handlers::event_stream::stream_events)) diff --git a/src/routes/events_playback.rs b/src/routes/events_playback.rs index ae80cd9..a5ea2ed 100644 --- a/src/routes/events_playback.rs +++ b/src/routes/events_playback.rs @@ -40,18 +40,32 @@ use crate::handlers::{events_playback, frame_images, synopsis}; use crate::server::state::AppState; use crate::util::middleware::media_auth_middleware; -/// Add event playback routes to the router -pub fn add_events_playback_routes(router: Router) -> Router { +/// Add event playback routes to the router. +/// +/// Every route that names an event reads its files, so each is relayed to +/// the server that holds them (multi-server, see `cluster::forward`). The +/// relay sits inside the media authentication: this server checks who is +/// asking, and that they may see the monitor, before anything is sent on. The +/// range montage names no event and spans many, so it stays on this server. +pub fn add_events_playback_routes(router: Router, state: AppState) -> Router { + let to_storage_owner = || { + axum::middleware::from_fn_with_state( + state.clone(), + crate::cluster::forward::forward_to_storage_owner, + ) + }; router // HLS streaming endpoints .route( "/api/v3/events/{id}/stream/playlist.m3u8", get(events_playback::get_event_playlist) + .route_layer(to_storage_owner()) .route_layer(axum::middleware::from_fn(media_auth_middleware)), ) .route( "/api/v3/events/{id}/stream/video.mp4", get(events_playback::get_event_stream_video) + .route_layer(to_storage_owner()) .route_layer(axum::middleware::from_fn(media_auth_middleware)), ) // Range-served media for the in-progress (EVENT) playlist's byte-range @@ -59,65 +73,76 @@ pub fn add_events_playback_routes(router: Router) -> Router .route( "/api/v3/events/{id}/stream/media.mp4", get(events_playback::get_event_stream_media) + .route_layer(to_storage_owner()) .route_layer(axum::middleware::from_fn(media_auth_middleware)), ) // HLS-VOD init + media segments .route( "/api/v3/events/{id}/stream/init.mp4", get(events_playback::get_event_init) + .route_layer(to_storage_owner()) .route_layer(axum::middleware::from_fn(media_auth_middleware)), ) .route( "/api/v3/events/{id}/stream/segment/{seq}", get(events_playback::get_event_segment) + .route_layer(to_storage_owner()) .route_layer(axum::middleware::from_fn(media_auth_middleware)), ) // Direct video access .route( "/api/v3/events/{id}/video", get(events_playback::get_event_video) + .route_layer(to_storage_owner()) .route_layer(axum::middleware::from_fn(media_auth_middleware)), ) // Thumbnail .route( "/api/v3/events/{id}/thumbnail", get(events_playback::get_event_thumbnail) + .route_layer(to_storage_owner()) .route_layer(axum::middleware::from_fn(media_auth_middleware)), ) // One frame of an event as a JPEG (GH #26) .route( "/api/v3/events/{id}/frames/{fid}/image", get(frame_images::get_event_frame_image) + .route_layer(to_storage_owner()) .route_layer(axum::middleware::from_fn(media_auth_middleware)), ) // Codec / dimensions / duration metadata .route( "/api/v3/events/{id}/info", get(events_playback::get_event_info) + .route_layer(to_storage_owner()) .route_layer(axum::middleware::from_fn(media_auth_middleware)), ) // Motion synopsis — glanceable composite still (P1). .route( "/api/v3/events/{id}/synopsis/review", get(synopsis::get_event_synopsis_review) + .route_layer(to_storage_owner()) .route_layer(axum::middleware::from_fn(media_auth_middleware)), ) // Motion synopsis — temporal layout preview (P2). .route( "/api/v3/events/{id}/synopsis/layout", get(synopsis::get_event_synopsis_layout) + .route_layer(to_storage_owner()) .route_layer(axum::middleware::from_fn(media_auth_middleware)), ) // Motion synopsis — request/poll the rendered mp4 (P3). .route( "/api/v3/events/{id}/synopsis", get(synopsis::get_event_synopsis) + .route_layer(to_storage_owner()) .route_layer(axum::middleware::from_fn(media_auth_middleware)), ) // Motion synopsis — stream the rendered mp4 (P3). .route( "/api/v3/events/{id}/synopsis/mp4", get(synopsis::get_event_synopsis_mp4) + .route_layer(to_storage_owner()) .route_layer(axum::middleware::from_fn(media_auth_middleware)), ) // Motion synopsis — range/overview montage across events (P4). The static diff --git a/src/routes/live.rs b/src/routes/live.rs index d9a7a09..8ff5494 100644 --- a/src/routes/live.rs +++ b/src/routes/live.rs @@ -52,18 +52,32 @@ pub fn routes() -> Router { } /// Add live streaming routes to the router -pub fn add_live_routes(router: Router) -> Router { +pub fn add_live_routes(router: Router, state: AppState) -> Router { router // Per-monitor live streaming endpoints .nest("/api/v3/live/{monitor_id}", routes()) // Global live streaming endpoints .route( "/api/v3/live/sessions", - get(live::list_live_sessions).route_layer(axum::middleware::from_fn(auth_middleware)), + get(live::list_live_sessions) + // `server_id=|all`, as on the daemon routes. Inside the + // login check, so nothing leaves this server unauthenticated. + .route_layer(axum::middleware::from_fn_with_state( + state.clone(), + crate::cluster::system::target_server, + )) + .route_layer(axum::middleware::from_fn(auth_middleware)), ) .route( "/api/v3/live/sources", - get(live::get_live_sources).route_layer(axum::middleware::from_fn(auth_middleware)), + get(live::get_live_sources) + // `server_id=|all`, as on the daemon routes. Inside the + // login check, so nothing leaves this server unauthenticated. + .route_layer(axum::middleware::from_fn_with_state( + state.clone(), + crate::cluster::system::target_server, + )) + .route_layer(axum::middleware::from_fn(auth_middleware)), ) // Monitor snapshot (supports token query param for tags) // `POST` takes a fresh snapshot through a zm-next worker. Header auth diff --git a/src/routes/media_jobs.rs b/src/routes/media_jobs.rs index aa5f4fd..dbb63ad 100644 --- a/src/routes/media_jobs.rs +++ b/src/routes/media_jobs.rs @@ -5,15 +5,29 @@ use axum::{middleware, routing::get, Router}; /// An event's video files: with the streaming routes, outside compression. /// Events-gated by the caller (View to read, Edit to generate or delete). -pub fn add_event_video_routes(router: Router) -> Router { +/// +/// The videos sit in the event's directory, so every route is relayed to the +/// server that holds it (multi-server, see `cluster::forward`). The relay is +/// inside the authentication, as the monitor relays are. +pub fn add_event_video_routes(router: Router, state: AppState) -> Router { + let to_storage_owner = || { + middleware::from_fn_with_state( + state.clone(), + crate::cluster::forward::forward_to_storage_owner, + ) + }; let protected = Router::new() .route( "/api/v3/events/{id}/videos", - get(h::list_videos).post(h::generate_video), + get(h::list_videos) + .post(h::generate_video) + .route_layer(to_storage_owner()), ) .route( "/api/v3/events/{id}/videos/{name}", - get(h::download_video).delete(h::delete_video), + get(h::download_video) + .delete(h::delete_video) + .route_layer(to_storage_owner()), ) .layer(middleware::from_fn(auth_middleware)); router.merge(protected) diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 995ccb4..5e16814 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -522,8 +522,9 @@ pub fn create_router_app(state: AppState) -> Router { monitor_presets::add_monitor_preset_routes(Router::new()), Feature::Monitors, ); - let monitor_status_routes = - monitor_gate(monitor_status::add_monitor_status_routes(Router::new())); + let monitor_status_routes = monitor_gate(to_owner(monitor_status::add_monitor_status_routes( + Router::new(), + ))); // Permission CRUD is administrative: a Groups:Edit / Monitors:Edit user // would otherwise be able to grant themselves or others elevated row-level // access via this endpoint. Require System (admin-tier) instead. @@ -542,7 +543,10 @@ pub fn create_router_app(state: AppState) -> Router { Feature::Monitors, ); - let events_routes = protect(events::add_event_routes(Router::new()), Feature::Events); + let events_routes = protect( + events::add_event_routes(Router::new(), state.clone()), + Feature::Events, + ); let event_data_routes = protect( event_data::add_event_data_routes(Router::new()), Feature::Events, @@ -563,7 +567,7 @@ pub fn create_router_app(state: AppState) -> Router { Feature::Events, ); let events_playback_routes = protect( - events_playback::add_events_playback_routes(Router::new()), + events_playback::add_events_playback_routes(Router::new(), state.clone()), Feature::Events, ); // Natural-language / semantic event search. JSON (compressible), so it lives @@ -632,7 +636,7 @@ pub fn create_router_app(state: AppState) -> Router { // feature-level RBAC check runs first and the guard's DB query is only // reached after the caller has at least `Stream:View`. let live_routes = protect( - to_owner(live::add_live_routes(Router::new())).route_layer( + to_owner(live::add_live_routes(Router::new(), state.clone())).route_layer( axum::middleware::from_fn_with_state( state.clone(), crate::service::monitor_acl::monitor_stream_guard, @@ -670,7 +674,10 @@ pub fn create_router_app(state: AppState) -> Router { // `[daemon].enable_rest_api = false` leaves daemon/system control to the // legacy socket only; the routes are not registered at all (#88). let daemon_routes = if config.daemon.enable_rest_api { - protect(daemon::add_daemon_routes(Router::new()), Feature::System) + protect( + daemon::add_daemon_routes(Router::new(), state.clone()), + Feature::System, + ) } else { Router::new() }; @@ -716,7 +723,7 @@ pub fn create_router_app(state: AppState) -> Router { .merge(snapshot_routes) .merge(snapshot_event_routes) .merge(protect( - media_jobs::add_event_video_routes(Router::new()), + media_jobs::add_event_video_routes(Router::new(), state.clone()), Feature::Events, )) .merge(crate::util::authz::protect_at( diff --git a/src/server/state.rs b/src/server/state.rs index 248b959..100e137 100644 --- a/src/server/state.rs +++ b/src/server/state.rs @@ -175,6 +175,10 @@ impl AppState { // own daemons do it, from zm.conf and the Servers table. let this_server = crate::daemon::server_id::resolve_this_server(db.as_ref()).await; let server_id = this_server.id; + // Which server's storage this host can read. The widest answer, so a + // host that only matched by hostname still leaves other servers' + // files alone. + let storage_server = this_server.id.or(this_server.zoneminder_id); // On a multi-server host zmdc.pl listens on zmdc.sock // (#229). A socket name set in the config is left alone. if config.daemon.socket_name == "zmdc.sock" { @@ -205,10 +209,13 @@ impl AppState { ); } if m.audit.enabled { - Arc::new(crate::service::maintenance::audit::AuditService::new( - db.clone(), - m.audit.clone(), - )) + Arc::new( + crate::service::maintenance::audit::AuditService::new( + db.clone(), + m.audit.clone(), + ) + .with_server_id(storage_server), + ) .spawn(); tracing::info!( "audit maintenance enabled (every {}s, min_age {}s, dry_run {}) \ @@ -239,10 +246,13 @@ impl AppState { // free-space floor / age / quota so the disk can't silently fill. Off // by default; never stored on AppState (no handlers need it). if config.retention.enabled { - let svc = Arc::new(crate::service::retention::RetentionService::new( - db.clone(), - config.retention.clone(), - )); + let svc = Arc::new( + crate::service::retention::RetentionService::new( + db.clone(), + config.retention.clone(), + ) + .with_server_id(storage_server), + ); Arc::clone(&svc).spawn(); tracing::info!( "event retention enabled (every {}s, min_free {}%, max_age {}d, max_bytes {}, dry_run {})", diff --git a/src/service/daemon.rs b/src/service/daemon.rs index fe4e6c0..ba63f3b 100644 --- a/src/service/daemon.rs +++ b/src/service/daemon.rs @@ -574,6 +574,73 @@ pub async fn apply_state(state: &AppState, state_name: &str) -> AppResult AppResult { + use crate::entity::states; + let zm_state = states::Entity::find() + .filter(states::Column::Name.eq(state_name)) + .one(state.db.as_ref()) + .await? + .ok_or_else(|| { + AppError::NotFoundError(crate::error::Resource { + resource_type: crate::error::ResourceType::Config, + details: vec![("state_name".to_string(), state_name.to_string())], + }) + })?; + + if state.daemon_manager.is_some() { + return Ok(match system_restart(state).await { + Ok(restart) => { + DaemonActionResponse::success(format!("State '{state_name}': {}", restart.message)) + } + Err(e) => { + warn!("state '{state_name}': the daemon restart failed: {e}"); + DaemonActionResponse::error(format!( + "State '{state_name}': the daemon restart failed: {e}" + )) + } + }); + } + + let named = state_monitor_ids(&zm_state.definition); + let mine: Vec = monitors::Entity::find() + .filter(monitors::Column::Id.is_in(named)) + .all(state.db.as_ref()) + .await? + .into_iter() + .filter(|m| crate::service::monitor_daemons::runs_here(state.server_id, m.server_id)) + .collect(); + let count = mine.len(); + let bg = state.clone(); + tokio::spawn(async move { + for m in &mine { + crate::service::monitor_daemons::updated(&bg, m, m).await; + } + }); + info!("State '{state_name}': restarting the daemons of {count} monitors through zmdc.pl"); + Ok(DaemonActionResponse::success(format!( + "State '{state_name}': {count} monitors on this server with daemons restarting" + ))) +} + +/// The monitor ids a state definition names, in either format. +fn state_monitor_ids(definition: &str) -> Vec { + definition + .split(',') + .filter_map(|entry| entry.trim().split(':').next()?.parse().ok()) + .collect() +} + /// The monitors whose Capturing, Analysing or Recording differ between two /// reads, as (before, after). fn changed_modes<'a>( @@ -778,6 +845,15 @@ mod tests { assert_eq!(action.message, "Failed"); } + #[test] + fn a_state_names_its_monitors_in_either_format() { + assert_eq!( + state_monitor_ids("1:Always:Always:OnMotion, 2:Modect:1,x:None:0,,3"), + vec![1, 2, 3] + ); + assert!(state_monitor_ids("").is_empty()); + } + #[test] fn test_parse_function() { assert_eq!(parse_function("None"), Some(Function::None)); diff --git a/src/service/event_audit.rs b/src/service/event_audit.rs index 2b77161..07afd1f 100644 --- a/src/service/event_audit.rs +++ b/src/service/event_audit.rs @@ -119,6 +119,21 @@ pub async fn event_audit( .all(state.db()) .await?; + // Events on another server's storage can't be checked from here: their + // files are not visible, so every one would be reported as missing. They + // are counted, and their media left to the server that holds it. + let elsewhere: std::collections::HashSet = crate::repo::storage::find_all(state.db()) + .await? + .into_iter() + .filter(|st| { + matches!( + state.cluster.owner_of_storage(st.server_id), + crate::cluster::Owner::Peer(_) + ) + }) + .map(|st| st.id) + .collect(); + // Storage roots resolve once per storage, not once per event. let mut roots: HashMap, Option> = HashMap::new(); let mut by_monitor: BTreeMap = BTreeMap::new(); @@ -130,6 +145,9 @@ pub async fn event_audit( e.end_date_time.map(time::civil), ); + if e.storage_id.is_some_and(|id| elsewhere.contains(&id)) { + continue; + } let root = match roots.get(&e.storage_id) { Some(root) => root.clone(), None => { diff --git a/src/service/event_export.rs b/src/service/event_export.rs index 7da245a..cd48859 100644 --- a/src/service/event_export.rs +++ b/src/service/event_export.rs @@ -30,6 +30,9 @@ pub struct Export { event: EventModel, response: EventResponse, dir: PathBuf, + /// The server that holds the event's files, when that is not this one. + /// The export lists no files for it: it can't read them. + files_on: Option, } /// Which part an event-directory file belongs to. @@ -67,6 +70,16 @@ pub async fn prepare( return Err(not_found()); } let dir = crate::service::event_storage::event_directory(state, &event).await?; + let files_on = match state.cluster.event_storage_owner(state.db(), id).await? { + crate::cluster::Owner::Peer(server) => { + warn!( + "event {id} export: its files are on server {server}; \ + exporting its details only" + ); + Some(server) + } + crate::cluster::Owner::Here => None, + }; let summaries = tags .iter() .map(crate::dto::response::events_tags::TagSummary::from) @@ -77,6 +90,7 @@ pub async fn prepare( event, response, dir, + files_on, }); } Ok(out) @@ -128,6 +142,20 @@ async fn write_zip( if !file_parts.iter().any(|p| parts.contains(p)) { continue; } + if let Some(server) = ex.files_on { + let note = format!( + "The files of event {} are on server {server}, which this server can't read. \ + Ask that server for them.\n", + ex.event.id + ); + let entry = ZipEntryBuilder::new( + format!("{folder}/files-unavailable.txt").into(), + Compression::Deflate, + ) + .last_modification_date(now); + zip.write_entry_whole(entry, note.as_bytes()).await?; + continue; + } let mut dir = match tokio::fs::read_dir(&ex.dir).await { Ok(d) => d, Err(e) => { diff --git a/src/service/event_stream.rs b/src/service/event_stream.rs index be91445..0700ccf 100644 --- a/src/service/event_stream.rs +++ b/src/service/event_stream.rs @@ -21,7 +21,7 @@ use std::sync::RwLock; use std::time::{Duration, Instant}; use sea_orm::{ColumnTrait, EntityTrait, QueryFilter, QueryOrder, QuerySelect}; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use tokio::sync::{broadcast, Notify}; use tracing::{debug, warn}; use utoipa::ToSchema; @@ -82,7 +82,7 @@ impl From<&events::Model> for EventInfo { } /// A monitor's alarm state. -#[derive(Debug, Clone, Serialize, ToSchema, PartialEq, Eq)] +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)] pub struct AlarmInfo { pub monitor_id: u32, /// `idle`, `prealarm`, `alarm`, `alert`, or `unknown` (zmc not running). @@ -310,16 +310,22 @@ impl EventTracker { } } +/// The monitors whose shared memory this server holds. On a multi-server +/// install that is the ones whose `ServerId` is this server's: reading the +/// others' would report them `unknown` forever, and their real state comes +/// from the server that runs them (see `crate::cluster::events`). async fn local_monitors(state: &AppState) -> Vec { + use crate::entity::monitors::Column; match crate::entity::monitors::Entity::find() .select_only() - .column(crate::entity::monitors::Column::Id) - .filter(crate::entity::monitors::Column::Deleted.eq(0)) - .into_tuple::() + .column(Column::Id) + .column(Column::ServerId) + .filter(Column::Deleted.eq(0)) + .into_tuple::<(u32, Option)>() .all(state.db()) .await { - Ok(ids) => ids, + Ok(rows) => owned_here(state.cluster.relays(), state.cluster.this_server(), rows), Err(e) => { warn!("event stream: listing monitors: {e}"); Vec::new() @@ -327,6 +333,22 @@ async fn local_monitors(state: &AppState) -> Vec { } } +/// The ids of the monitors, as `(id, ServerId)`, that this server runs. +/// Every monitor when the install does not relay. +fn owned_here( + relays: bool, + this_server: Option, + monitors: Vec<(u32, Option)>, +) -> Vec { + monitors + .into_iter() + .filter(|(_, server)| { + !relays || crate::cluster::owner(this_server, *server) == crate::cluster::Owner::Here + }) + .map(|(id, _)| id) + .collect() +} + async fn poll_events(state: &AppState, events: &mut EventTracker, hub: &EventHub) { let db = state.db(); let now = Instant::now(); @@ -538,6 +560,15 @@ mod tests { } } + #[test] + fn only_this_servers_monitors_are_read_from_shared_memory() { + let rows = vec![(1, Some(1)), (2, Some(2)), (3, None), (4, Some(0))]; + assert_eq!(owned_here(true, Some(1), rows.clone()), [1, 3, 4]); + // Without relaying (or without a server id) every monitor is read, as before. + assert_eq!(owned_here(false, Some(1), rows.clone()), [1, 2, 3, 4]); + assert_eq!(owned_here(true, None, rows), [1, 2, 3, 4]); + } + #[test] fn messages_serialize_with_their_type() { let msg = StreamMessage::EventStart(EventInfo::from(&event(7, 3, false, None))); diff --git a/src/service/maintenance/audit/mod.rs b/src/service/maintenance/audit/mod.rs index c031859..6cf0913 100644 --- a/src/service/maintenance/audit/mod.rs +++ b/src/service/maintenance/audit/mod.rs @@ -43,6 +43,10 @@ use crate::configure::maintenance::AuditConfig; pub struct AuditService { db: Arc, config: AuditConfig, + /// Which `Servers` row this host is. A storage area that names another + /// server holds files this host can't see, so it is left alone. + this_server: Option, + announced: crate::cluster::SkipLog, /// Orphans seen on previous passes, and how many times. /// /// Nothing is acted on until it has been seen `confirmations_required` @@ -155,10 +159,33 @@ impl AuditService { Self { db, config, + this_server: None, + announced: Default::default(), seen_orphans: tokio::sync::Mutex::new(OrphanTracker::default()), } } + /// Record which `Servers` row is this host (`None` = single-server). + pub fn with_server_id(mut self, server_id: Option) -> Self { + self.this_server = server_id; + self + } + + /// The storage rows whose files this host can see. Walking another + /// server's storage would find nothing, call every event on it + /// media-less, and delete their rows. + async fn local_storages(&self) -> Result, DbErr> { + use sea_orm::EntityTrait; + Ok(crate::entity::storage::Entity::find() + .all(self.db.as_ref()) + .await? + .into_iter() + .filter(|st| { + !crate::cluster::skips_peer_storage(&self.announced, "audit", self.this_server, st) + }) + .collect()) + } + pub fn spawn(self: Arc) { let interval = self.config.interval(); tokio::spawn(async move { @@ -231,11 +258,8 @@ impl AuditService { /// stop the others — a single unmounted volume should not disable the /// audit for the whole install. async fn reconcile_filesystem(&self, report: &mut AuditReport) -> Result<(), DbErr> { - use crate::entity::storage; - use sea_orm::EntityTrait; - let fs = &self.config.filesystem; - let storages = storage::Entity::find().all(self.db.as_ref()).await?; + let storages = self.local_storages().await?; // Candidates gathered across all storages, so the confirmation tracker // sees one coherent view per pass rather than one per storage. @@ -654,7 +678,28 @@ impl AuditService { /// deleted live recordings (#124). Archived events are excluded — see the /// module note. async fn remove_empty_events(&self) -> Result { - let predicate = empty_event_predicate(self.config.min_age_seconds); + use sea_orm::EntityTrait; + let mut predicate = empty_event_predicate(self.config.min_age_seconds); + // An event on another server's storage is that server's to judge: its + // row goes only with its files. + let elsewhere: Vec = crate::entity::storage::Entity::find() + .all(self.db.as_ref()) + .await? + .into_iter() + .filter(|st| { + matches!( + crate::cluster::storage_owner(self.this_server, st.server_id), + crate::cluster::Owner::Peer(_) + ) + }) + .map(|st| st.id.to_string()) + .collect(); + if !elsewhere.is_empty() { + predicate.push_str(&format!( + " AND (StorageId IS NULL OR StorageId NOT IN ({}))", + elsewhere.join(",") + )); + } self.delete_where("Events", &predicate).await } diff --git a/src/service/media_job_store.rs b/src/service/media_job_store.rs index 6d05993..17a8d21 100644 --- a/src/service/media_job_store.rs +++ b/src/service/media_job_store.rs @@ -204,15 +204,21 @@ impl JobStore { } } - /// The oldest queued job. - pub async fn next_queued(&self, db: &DatabaseConnection) -> AppResult> { + /// The oldest queued job, leaving out the ids in `skip`: jobs this server + /// has seen and can't run (their event's files are on another server). + pub async fn next_queued( + &self, + db: &DatabaseConnection, + skip: &[u32], + ) -> AppResult> { match self { JobStore::Table => Ok(media_jobs::Entity::find() .filter(media_jobs::Column::Status.eq(QUEUED)) + .filter(media_jobs::Column::Id.is_not_in(skip.iter().copied())) .order_by_asc(media_jobs::Column::Id) .one(db) .await?), - JobStore::File(f) => Ok(f.next_queued().await), + JobStore::File(f) => Ok(f.next_queued(skip).await), } } @@ -502,12 +508,12 @@ impl FileJobs { self.save(&jobs).await } - async fn next_queued(&self) -> Option { + async fn next_queued(&self, skip: &[u32]) -> Option { self.jobs .lock() .await .iter() - .find(|j| j.status == QUEUED) + .find(|j| j.status == QUEUED && !skip.contains(&j.id)) .cloned() } @@ -565,13 +571,29 @@ mod tests { // A restart: the running job goes back in the queue, ids continue. let store = JobStore::File(FileJobs::load(path).await); store.requeue_running(&db).await.unwrap(); - let next = store.next_queued(&db).await.unwrap().unwrap(); + let next = store.next_queued(&db, &[]).await.unwrap().unwrap(); assert_eq!(next.id, a.id); assert_eq!(next.created_at, from_ms(1_760_000_000_123)); let c = store.insert(&db, new_job(12, 1)).await.unwrap(); assert_eq!(c.id, 3); } + #[tokio::test] + async fn the_next_job_can_pass_over_ones_this_server_cannot_run() { + let dir = tempfile::tempdir().unwrap(); + let store = JobStore::File(FileJobs::load(dir.path().join("j.json")).await); + let db = db(); + let a = store.insert(&db, new_job(10, 1)).await.unwrap(); + let b = store.insert(&db, new_job(11, 1)).await.unwrap(); + let next = store.next_queued(&db, &[a.id]).await.unwrap().unwrap(); + assert_eq!(next.id, b.id); + assert!(store + .next_queued(&db, &[a.id, b.id]) + .await + .unwrap() + .is_none()); + } + #[tokio::test] async fn listing_filters_newest_first() { let dir = tempfile::tempdir().unwrap(); @@ -614,7 +636,7 @@ mod tests { assert_eq!(got.output.as_deref(), Some("Event-2.mp4")); store.delete(&db, a.id).await.unwrap(); assert!(store.get(&db, a.id).await.unwrap().is_none()); - assert!(store.next_queued(&db).await.unwrap().is_none()); + assert!(store.next_queued(&db, &[]).await.unwrap().is_none()); } #[tokio::test] diff --git a/src/service/media_jobs.rs b/src/service/media_jobs.rs index 8cb4683..4a34774 100644 --- a/src/service/media_jobs.rs +++ b/src/service/media_jobs.rs @@ -14,7 +14,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::time::Duration; -use tracing::{info, warn}; +use tracing::{debug, info, warn}; use crate::dto::request::media_jobs::{GenerateVideoRequest, JobListQuery, VideoTransform}; use crate::dto::response::media_jobs::{EventVideoResponse, MediaJobResponse}; @@ -546,8 +546,12 @@ async fn jobs(state: &AppState) -> &JobStore { pub async fn run_pending(state: &AppState) -> usize { let store = jobs(state).await; let mut ran = 0; + // Jobs for events whose files another server holds. They stay queued for + // that server's worker (the table is shared) and are not looked at again + // this round. + let mut elsewhere: Vec = Vec::new(); loop { - let job = match store.next_queued(state.db()).await { + let job = match store.next_queued(state.db(), &elsewhere).await { Ok(Some(j)) => j, Ok(None) => return ran, Err(e) => { @@ -555,6 +559,25 @@ pub async fn run_pending(state: &AppState) -> usize { return ran; } }; + match state + .cluster + .event_storage_owner(state.db(), job.event_id) + .await + { + Ok(crate::cluster::Owner::Peer(server)) => { + debug!( + "media job {}: event {} is on server {server}; leaving it to that server", + job.id, job.event_id + ); + elsewhere.push(job.id); + continue; + } + Ok(crate::cluster::Owner::Here) => {} + Err(e) => { + warn!("media jobs: {e}"); + return ran; + } + } // Claim it; another instance may have. if !store .claim(state.db(), job.id, now()) diff --git a/src/service/retention/mod.rs b/src/service/retention/mod.rs index 1e56848..7689031 100644 --- a/src/service/retention/mod.rs +++ b/src/service/retention/mod.rs @@ -52,6 +52,10 @@ const RESYNC_EVERY: usize = 25; pub struct RetentionService { db: Arc, config: RetentionConfig, + /// Which `Servers` row this host is. A storage area that names another + /// server holds files this host can't see, so it is left alone. + this_server: Option, + announced: crate::cluster::SkipLog, } /// Outcome of reaping a single storage, for logging. @@ -91,7 +95,18 @@ pub(crate) trait ReapIo: Send + Sync { impl RetentionService { pub fn new(db: Arc, config: RetentionConfig) -> Self { - Self { db, config } + Self { + db, + config, + this_server: None, + announced: Default::default(), + } + } + + /// Record which `Servers` row is this host (`None` = single-server). + pub fn with_server_id(mut self, server_id: Option) -> Self { + self.this_server = server_id; + self } /// Spawn the periodic reaper loop. Returns immediately. @@ -169,6 +184,12 @@ impl RetentionService { st: &storage::Model, is_default: bool, ) -> Result { + // Another server's storage: its files and its free space are not + // visible from here, so neither its events nor its rows are touched. + // The server that owns it runs its own reaper. + if crate::cluster::skips_peer_storage(&self.announced, "retention", self.this_server, st) { + return Ok(ReapStats::default()); + } // Candidate set: events on this storage that are safe to delete. let mut storage_match = Condition::any().add(events::Column::StorageId.eq(st.id)); if is_default { diff --git a/tests/common/cluster.rs b/tests/common/cluster.rs new file mode 100644 index 0000000..a74fc5a --- /dev/null +++ b/tests/common/cluster.rs @@ -0,0 +1,332 @@ +//! A stub second server for the multi-server tests. +//! +//! The app under test is server 1. Server 2 is a stub on a real socket that +//! records what reaches it and answers with a fixed status and body. +#![allow(dead_code)] + +use std::sync::{Arc, Mutex}; + +use axum::body::Bytes; +use axum::extract::{Request, State}; +use axum::http::{header, HeaderMap, Method, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::Router; +use sea_orm::{ActiveModelTrait, DatabaseConnection, EntityTrait, Set}; +use zm_api::cluster::Cluster; +use zm_api::configure::cluster::ClusterConfig; +use zm_api::entity::monitors::{ActiveModel as MonitorActiveModel, Model as MonitorModel}; + +use super::fixtures::{insert_monitor, RowGuard}; +use super::harness::TestApp; + +pub const HERE: u32 = 1; +pub const THERE: u32 = 2; + +/// One request the stub received. +#[derive(Clone)] +pub struct Seen { + pub method: Method, + pub path_and_query: String, + pub headers: HeaderMap, + pub body: Bytes, +} + +#[derive(Clone)] +struct Stub { + status: StatusCode, + content_type: &'static str, + body: String, + seen: Arc>>, +} + +pub struct Peer { + pub url: String, + seen: Arc>>, +} + +impl Peer { + pub fn seen(&self) -> Vec { + self.seen.lock().unwrap().clone() + } +} + +async fn record(State(stub): State, request: Request) -> Response { + let (parts, body) = request.into_parts(); + let body = axum::body::to_bytes(body, usize::MAX).await.unwrap(); + stub.seen.lock().unwrap().push(Seen { + method: parts.method, + path_and_query: parts + .uri + .path_and_query() + .map(|pq| pq.as_str().to_string()) + .unwrap_or_default(), + headers: parts.headers, + body, + }); + ( + stub.status, + [ + (header::CONTENT_TYPE, stub.content_type), + (header::HeaderName::from_static("x-answered-by"), "2"), + ], + stub.body, + ) + .into_response() +} + +/// Server 2: answers every request with `status` and a plain-text body. +pub async fn peer(status: StatusCode) -> Peer { + peer_with(status, "text/plain", "from server 2".to_string()).await +} + +/// Server 2: answers every request with `status` and this JSON. +pub async fn peer_json(status: StatusCode, json: serde_json::Value) -> Peer { + peer_with(status, "application/json", json.to_string()).await +} + +async fn peer_with(status: StatusCode, content_type: &'static str, body: String) -> Peer { + let seen = Arc::new(Mutex::new(Vec::new())); + let router = Router::new().fallback(record).with_state(Stub { + status, + content_type, + body, + seen: seen.clone(), + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { + axum::serve(listener, router).await.unwrap(); + }); + Peer { url, seen } +} + +/// The app as server 1, with server 2 at `peer_url` (if any). +pub async fn server_one(peer_url: Option<&str>) -> TestApp { + server_as(HERE, THERE, peer_url).await +} + +/// The app as server `here`, with server `there` at `peer_url` (if any). +pub async fn server_as(here: u32, there: u32, peer_url: Option<&str>) -> TestApp { + let mut config = ClusterConfig { + connect_timeout_secs: 1, + ..Default::default() + }; + if let Some(url) = peer_url { + config.peers.insert(there.to_string(), url.to_string()); + } + TestApp::spawn_with(move |state| { + state.server_id = Some(here); + state.cluster = Arc::new(Cluster::new(Some(here), &config, 0, false)); + }) + .await +} + +/// A monitor that `server` runs. +pub async fn monitor_on(db: &DatabaseConnection, label: &str, server: u32) -> MonitorModel { + let monitor = insert_monitor(db, label).await.expect("monitor"); + let mut row: MonitorActiveModel = monitor.into(); + row.server_id = Set(Some(server)); + row.update(db).await.expect("set server") +} + +/// A `Servers` row, so the server is known to the cluster. The guard removes it. +pub async fn server_row(db: &DatabaseConnection, id: u32, name: &str) -> RowGuard { + use zm_api::entity::sea_orm_active_enums::Status; + let _ = zm_api::entity::servers::Entity::delete_by_id(id) + .exec(db) + .await; + zm_api::entity::servers::ActiveModel { + id: Set(id), + name: Set(name.to_string()), + status: Set(Status::Unknown), + zmstats: Set(0), + zmaudit: Set(0), + zmtrigger: Set(0), + zmeventnotification: Set(0), + ..Default::default() + } + .insert(db) + .await + .expect("insert server row"); + RowGuard::server(id) +} + +// ---- Streams: a WebSocket peer, an event-stream peer, a real listener ------ + +use axum::extract::ws::{CloseFrame, Message, WebSocketUpgrade}; +use axum::extract::FromRequestParts; +use axum::response::sse::{Event, Sse}; +use futures_util::{stream, StreamExt}; + +#[derive(Clone)] +struct WsStub { + seen: Arc>>, + log: Arc>>, +} + +/// Server 2 as a WebSocket peer. It selects the subprotocol `zm.v1` when the +/// client offers it, and answers text `t` with `peer:t`, a binary message +/// with its bytes reversed, and the text `close-me` with a close frame +/// (4002, "from peer"). +pub struct WsPeer { + pub url: String, + seen: Arc>>, + log: Arc>>, +} + +impl WsPeer { + pub fn seen(&self) -> Vec { + self.seen.lock().unwrap().clone() + } + + /// What the peer observed on its socket, in order: `close::` + /// for a close frame, `gone` for a socket that ended without one. + pub fn log(&self) -> Vec { + self.log.lock().unwrap().clone() + } +} + +async fn ws_record(State(stub): State, request: Request) -> Response { + let (mut parts, _) = request.into_parts(); + stub.seen.lock().unwrap().push(Seen { + method: parts.method.clone(), + path_and_query: parts + .uri + .path_and_query() + .map(|pq| pq.as_str().to_string()) + .unwrap_or_default(), + headers: parts.headers.clone(), + body: Bytes::new(), + }); + let Ok(ws) = WebSocketUpgrade::from_request_parts(&mut parts, &()).await else { + return StatusCode::BAD_REQUEST.into_response(); + }; + let log = stub.log.clone(); + ws.protocols(["zm.v1"]) + .on_upgrade(move |mut socket| async move { + while let Some(message) = socket.next().await { + let reply = match message { + Ok(Message::Text(text)) if text.as_str() == "close-me" => { + let _ = socket + .send(Message::Close(Some(CloseFrame { + code: 4002, + reason: "from peer".into(), + }))) + .await; + return; + } + Ok(Message::Text(text)) => Message::text(format!("peer:{}", text.as_str())), + Ok(Message::Binary(bytes)) => { + Message::Binary(bytes.iter().rev().copied().collect::>().into()) + } + Ok(Message::Close(frame)) => { + let (code, reason) = frame + .map(|f| (f.code, f.reason.as_str().to_string())) + .unwrap_or((1005, String::new())); + log.lock().unwrap().push(format!("close:{code}:{reason}")); + return; + } + Ok(_) => continue, + Err(_) => break, + }; + if socket.send(reply).await.is_err() { + break; + } + } + log.lock().unwrap().push("gone".to_string()); + }) +} + +pub async fn ws_peer() -> WsPeer { + let seen = Arc::new(Mutex::new(Vec::new())); + let log = Arc::new(Mutex::new(Vec::new())); + let router = Router::new().fallback(ws_record).with_state(WsStub { + seen: seen.clone(), + log: log.clone(), + }); + WsPeer { + url: serve_router(router).await, + seen, + log, + } +} + +#[derive(Clone)] +struct SseStub { + events: Arc>, + seen: Arc>>, +} + +/// Server 2 as an event-stream peer: sends `events` to each subscriber, then +/// holds the stream open. +pub struct SsePeer { + pub url: String, + seen: Arc>>, +} + +impl SsePeer { + pub fn seen(&self) -> Vec { + self.seen.lock().unwrap().clone() + } +} + +async fn sse_record(State(stub): State, request: Request) -> Response { + let (parts, _) = request.into_parts(); + stub.seen.lock().unwrap().push(Seen { + method: parts.method, + path_and_query: parts + .uri + .path_and_query() + .map(|pq| pq.as_str().to_string()) + .unwrap_or_default(), + headers: parts.headers, + body: Bytes::new(), + }); + let sent: Vec> = stub + .events + .iter() + .map(|(name, data)| Ok(Event::default().event(name).data(data.to_string()))) + .collect(); + Sse::new(stream::iter(sent).chain(stream::pending())).into_response() +} + +pub async fn sse_peer(events: Vec<(&str, serde_json::Value)>) -> SsePeer { + let seen = Arc::new(Mutex::new(Vec::new())); + let events = events + .into_iter() + .map(|(name, data)| (name.to_string(), data)) + .collect(); + let router = Router::new().fallback(sse_record).with_state(SseStub { + events: Arc::new(events), + seen: seen.clone(), + }); + SsePeer { + url: serve_router(router).await, + seen, + } +} + +/// Serve `router` on a free port; its base URL. +pub async fn serve_router(router: Router) -> String { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { + axum::serve(listener, router).await.unwrap(); + }); + url +} + +/// Serve the app on a real socket, for clients that need one (WebSockets); +/// its `host:port`. +pub async fn serve_app(app: &TestApp) -> String { + serve_router(app.router()) + .await + .trim_start_matches("http://") + .to_string() +} + +/// A base URL where nothing listens, for a server that is down. +pub async fn down_url() -> String { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + format!("http://{}", listener.local_addr().unwrap()) +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 33a60f3..e401b79 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -1,5 +1,6 @@ // Common test helpers for integration tests pub mod assertions; +pub mod cluster; pub mod fake_zmc; pub mod fixtures; pub mod harness; diff --git a/tests/it_cluster.rs b/tests/it_cluster.rs index 90b0f33..4fbd16b 100644 --- a/tests/it_cluster.rs +++ b/tests/it_cluster.rs @@ -9,113 +9,18 @@ mod common; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; -use axum::body::Bytes; -use axum::extract::{Request, State}; -use axum::http::{header, HeaderMap, Method, StatusCode}; -use axum::response::{IntoResponse, Response}; -use axum::Router; +use axum::http::{header, Method, StatusCode}; use common::assertions::{assert_error, assert_status}; -use common::fixtures::{insert_monitor, RowGuard}; +use common::fixtures::RowGuard; use common::harness::{superuser_token, TestApp}; -use sea_orm::{ActiveModelTrait, DatabaseConnection, Set}; +use sea_orm::{ActiveModelTrait, DatabaseConnection, EntityTrait, Set}; use serde_json::json; use zm_api::cluster::Cluster; use zm_api::configure::cluster::ClusterConfig; -use zm_api::entity::monitors::{ActiveModel as MonitorActiveModel, Model as MonitorModel}; - -const HERE: u32 = 1; -const THERE: u32 = 2; - -/// One request the stub received. -#[derive(Clone)] -struct Seen { - method: Method, - path_and_query: String, - headers: HeaderMap, - body: Bytes, -} - -#[derive(Clone)] -struct Stub { - status: StatusCode, - seen: Arc>>, -} - -struct Peer { - url: String, - seen: Arc>>, -} - -impl Peer { - fn seen(&self) -> Vec { - self.seen.lock().unwrap().clone() - } -} - -async fn record(State(stub): State, request: Request) -> Response { - let (parts, body) = request.into_parts(); - let body = axum::body::to_bytes(body, usize::MAX).await.unwrap(); - stub.seen.lock().unwrap().push(Seen { - method: parts.method, - path_and_query: parts - .uri - .path_and_query() - .map(|pq| pq.as_str().to_string()) - .unwrap_or_default(), - headers: parts.headers, - body, - }); - ( - stub.status, - [ - (header::CONTENT_TYPE, "text/plain"), - (header::HeaderName::from_static("x-answered-by"), "2"), - ], - "from server 2", - ) - .into_response() -} - -/// Server 2: answers every request with `status`. -async fn peer(status: StatusCode) -> Peer { - let seen = Arc::new(Mutex::new(Vec::new())); - let router = Router::new().fallback(record).with_state(Stub { - status, - seen: seen.clone(), - }); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let url = format!("http://{}", listener.local_addr().unwrap()); - tokio::spawn(async move { - axum::serve(listener, router).await.unwrap(); - }); - Peer { url, seen } -} - -/// The app as server 1, with server 2 at `peer_url` (if any). -async fn server_one(peer_url: Option<&str>) -> TestApp { - let mut config = ClusterConfig { - connect_timeout_secs: 1, - ..Default::default() - }; - if let Some(url) = peer_url { - config.peers.insert(THERE.to_string(), url.to_string()); - } - TestApp::spawn_with(move |state| { - state.server_id = Some(HERE); - state.cluster = Arc::new(Cluster::new(Some(HERE), &config, 0, false)); - }) - .await -} -/// A monitor that `server` runs. -async fn monitor_on(db: &DatabaseConnection, label: &str, server: u32) -> MonitorModel { - let monitor = insert_monitor(db, label).await.expect("monitor"); - let mut row: MonitorActiveModel = monitor.into(); - row.server_id = Set(Some(server)); - row.update(db).await.expect("set server") -} +use common::cluster::{monitor_on, peer, server_one, HERE, THERE}; #[tokio::test] #[ignore = "requires the test database (APP_PROFILE=test-db)"] @@ -399,7 +304,7 @@ async fn the_owners_error_status_passes_through() { #[tokio::test] #[ignore = "requires the test database (APP_PROFILE=test-db)"] -async fn a_websocket_for_another_servers_monitor_is_refused_with_its_address() { +async fn an_upgrade_that_is_not_a_websocket_handshake_is_refused() { let peer = peer(StatusCode::OK).await; let app = server_one(Some(&peer.url)).await; let monitor = monitor_on(&app.db, "ClusterWs", THERE).await; @@ -422,7 +327,8 @@ async fn a_websocket_for_another_servers_monitor_is_refused_with_its_address() { StatusCode::MISDIRECTED_REQUEST, "MISDIRECTED_REQUEST_ERROR", ); - assert!(r.text().contains(&peer.url), "{}", r.text()); + // The relay carries WebSockets (see it_cluster_streams); a request that + // only claims to upgrade has no handshake to relay. assert!(peer.seen().is_empty()); } @@ -596,3 +502,285 @@ async fn two_real_servers_share_one_token() { .await; assert_status(&r, StatusCode::FORBIDDEN); } + +// ---- Recordings: a storage area that belongs to one server ----------------- + +/// A storage area that `server` holds (`None`: shared by every server). +async fn storage_on( + db: &DatabaseConnection, + label: &str, + server: Option, +) -> (zm_api::entity::storage::Model, RowGuard) { + use zm_api::entity::sea_orm_active_enums::Scheme; + let storage = + common::fixtures::insert_storage(db, label, "/nonexistent/zm-cluster", Scheme::Medium) + .await + .expect("storage"); + let guard = RowGuard::storage(storage.id); + let mut row: zm_api::entity::storage::ActiveModel = storage.into(); + row.server_id = Set(server); + (row.update(db).await.expect("set server"), guard) +} + +/// An event of `monitor_id` recorded on `storage_id`. +async fn event_on(db: &DatabaseConnection, monitor_id: u32, storage_id: u16) -> (u64, RowGuard) { + let start = zm_api::util::time::db_datetime(zm_api::util::time::utc_now()); + let id = zm_api::entity::events::ActiveModel { + monitor_id: Set(monitor_id), + storage_id: Set(Some(storage_id)), + state_id: Set(1), + name: Set(common::fixtures::unique_name("ClusterEvent")), + scheme: Set(zm_api::entity::sea_orm_active_enums::Scheme::Medium), + start_date_time: Set(Some(start)), + end_date_time: Set(Some(start)), + ..Default::default() + } + .insert(db) + .await + .expect("event") + .id; + let guard = RowGuard::new(format!("Events#{id}"), move |db| async move { + let _ = zm_api::entity::events::Entity::delete_by_id(id) + .exec(&db) + .await; + }); + (id, guard) +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_file_request_for_another_servers_storage_is_relayed_there() { + let peer = peer(StatusCode::OK).await; + let app = server_one(Some(&peer.url)).await; + let monitor = monitor_on(&app.db, "StorageRelay", HERE).await; + let _m = RowGuard::monitor(monitor.id); + let (storage, _s) = storage_on(&app.db, "StorageRelay", Some(THERE)).await; + let (event, _e) = event_on(&app.db, monitor.id, storage.id).await; + let token = superuser_token(); + + // Playback routes are nested and take a query: the owner gets all of it. + for path in [ + format!("/api/v3/events/{event}/thumbnail?width=120"), + format!("/api/v3/events/{event}/stream/playlist.m3u8"), + format!("/api/v3/events/{event}/frames/1/image"), + format!("/api/v3/events/{event}/videos"), + format!("/api/v3/events/{event}/info"), + ] { + let r = app.get(&path, &token).await; + assert_status(&r, StatusCode::OK); + assert_eq!(r.text(), "from server 2", "{path}"); + } + let seen = peer.seen(); + assert_eq!(seen.len(), 5); + assert_eq!( + seen[0].path_and_query, + format!("/api/v3/events/{event}/thumbnail?width=120") + ); + assert_eq!( + seen[0].headers[header::AUTHORIZATION], + format!("Bearer {token}") + ); + assert_eq!(seen[0].headers["x-zm-forwarded-by"], "1"); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn shared_storage_is_not_relayed() { + let peer = peer(StatusCode::OK).await; + let app = server_one(Some(&peer.url)).await; + let monitor = monitor_on(&app.db, "StorageShared", THERE).await; + let _m = RowGuard::monitor(monitor.id); + let (none, _a) = storage_on(&app.db, "SharedNull", None).await; + let (zero, _b) = storage_on(&app.db, "SharedZero", Some(0)).await; + for storage in [none, zero] { + let (event, _e) = event_on(&app.db, monitor.id, storage.id).await; + let r = app + .get( + &format!("/api/v3/events/{event}/thumbnail"), + &superuser_token(), + ) + .await; + assert_ne!(r.text(), "from server 2"); + } + assert!(peer.seen().is_empty()); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn this_servers_own_storage_is_not_relayed() { + let peer = peer(StatusCode::OK).await; + let app = server_one(Some(&peer.url)).await; + // The monitor runs on server 2, but its recordings are on this server. + let monitor = monitor_on(&app.db, "StorageLocal", THERE).await; + let _m = RowGuard::monitor(monitor.id); + let (storage, _s) = storage_on(&app.db, "StorageLocal", Some(HERE)).await; + let (event, _e) = event_on(&app.db, monitor.id, storage.id).await; + + let r = app + .get( + &format!("/api/v3/events/{event}/thumbnail"), + &superuser_token(), + ) + .await; + + assert_ne!(r.text(), "from server 2"); + assert!(peer.seen().is_empty()); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_single_server_install_relays_no_recordings() { + let peer = peer(StatusCode::OK).await; + let app = TestApp::spawn().await; + let monitor = monitor_on(&app.db, "StorageSingle", HERE).await; + let _m = RowGuard::monitor(monitor.id); + let (storage, _s) = storage_on(&app.db, "StorageSingle", Some(THERE)).await; + let (event, _e) = event_on(&app.db, monitor.id, storage.id).await; + + let r = app + .get( + &format!("/api/v3/events/{event}/thumbnail"), + &superuser_token(), + ) + .await; + + assert_ne!(r.text(), "from server 2"); + assert!(peer.seen().is_empty()); +} + +/// Reading or editing an event's row works on any server. +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn an_events_row_is_answered_here_whatever_its_storage() { + let peer = peer(StatusCode::OK).await; + let app = server_one(Some(&peer.url)).await; + let monitor = monitor_on(&app.db, "StorageRow", HERE).await; + let _m = RowGuard::monitor(monitor.id); + let (storage, _s) = storage_on(&app.db, "StorageRow", Some(THERE)).await; + let (event, _e) = event_on(&app.db, monitor.id, storage.id).await; + + let r = app + .get(&format!("/api/v3/events/{event}"), &superuser_token()) + .await; + + assert_status(&r, StatusCode::OK); + assert_eq!(r.json::()["id"], event); + assert!(peer.seen().is_empty()); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_caller_who_cannot_see_the_events_monitor_is_not_relayed() { + use common::fixtures::{grant_monitor_permission, insert_user_with_id}; + use common::harness::token_for; + use zm_api::entity::sea_orm_active_enums::Permission; + use zm_api::util::authz::UserPermissions; + + let peer = peer(StatusCode::OK).await; + let app = server_one(Some(&peer.url)).await; + let hidden = monitor_on(&app.db, "StorageHidden", HERE).await; + let _h = RowGuard::monitor(hidden.id); + let (storage, _s) = storage_on(&app.db, "StorageHidden", Some(THERE)).await; + let (event, _e) = event_on(&app.db, hidden.id, storage.id).await; + + const UID: u32 = 990_231; + insert_user_with_id(&app.db, UID, "StorageAcl") + .await + .expect("user"); + let _u = RowGuard::user(UID); + grant_monitor_permission(&app.db, hidden.id, UID, Permission::None) + .await + .expect("grant"); + let token = token_for(UID, UserPermissions::superuser()); + + for method in [Method::GET, Method::DELETE] { + let path = if method == Method::GET { + format!("/api/v3/events/{event}/thumbnail") + } else { + format!("/api/v3/events/{event}") + }; + let r = app.request(method, &path).bearer(&token).send().await; + assert_status(&r, StatusCode::NOT_FOUND); + } + assert!(peer.seen().is_empty()); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn deleting_an_event_on_another_servers_storage_is_relayed() { + let peer = peer(StatusCode::NO_CONTENT).await; + let app = server_one(Some(&peer.url)).await; + let monitor = monitor_on(&app.db, "StorageDelete", HERE).await; + let _m = RowGuard::monitor(monitor.id); + let (storage, _s) = storage_on(&app.db, "StorageDelete", Some(THERE)).await; + let (event, _e) = event_on(&app.db, monitor.id, storage.id).await; + + let r = app + .request(Method::DELETE, &format!("/api/v3/events/{event}")) + .bearer(&superuser_token()) + .send() + .await; + + assert_status(&r, StatusCode::NO_CONTENT); + let seen = peer.seen(); + assert_eq!(seen.len(), 1); + assert_eq!(seen[0].method, Method::DELETE); + assert_eq!(seen[0].path_and_query, format!("/api/v3/events/{event}")); + // This server left the row for the owner to remove along with the files. + let rows = zm_api::entity::events::Entity::find_by_id(event) + .one(&app.db) + .await + .unwrap(); + assert!(rows.is_some()); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_file_request_that_was_already_relayed_is_not_relayed_again() { + let peer = peer(StatusCode::OK).await; + let app = server_one(Some(&peer.url)).await; + let monitor = monitor_on(&app.db, "StorageLoop", HERE).await; + let _m = RowGuard::monitor(monitor.id); + let (storage, _s) = storage_on(&app.db, "StorageLoop", Some(THERE)).await; + let (event, _e) = event_on(&app.db, monitor.id, storage.id).await; + + let r = app + .request(Method::GET, &format!("/api/v3/events/{event}/thumbnail")) + .bearer(&superuser_token()) + .header("x-zm-forwarded-by", "2") + .send() + .await; + + assert_error( + &r, + StatusCode::MISDIRECTED_REQUEST, + "MISDIRECTED_REQUEST_ERROR", + ); + assert!(peer.seen().is_empty()); +} + +/// The storage list shows another server's area without a disk reading: the +/// path on this server is not that disk. +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn another_servers_storage_shows_no_disk_figures() { + let app = server_one(None).await; + let (peers, _p) = storage_on(&app.db, "ListPeer", Some(THERE)).await; + let tmp = tempfile::tempdir().unwrap(); + let (here, _h) = storage_on(&app.db, "ListHere", Some(HERE)).await; + let mut row: zm_api::entity::storage::ActiveModel = here.clone().into(); + row.path = Set(tmp.path().to_str().unwrap().to_string()); + row.update(&app.db).await.unwrap(); + + let token = superuser_token(); + let theirs = app + .get(&format!("/api/v3/storage/{}", peers.id), &token) + .await + .json::(); + assert!(theirs["filesystem"].is_null(), "{theirs}"); + let ours = app + .get(&format!("/api/v3/storage/{}", here.id), &token) + .await + .json::(); + assert!(ours["filesystem"].is_object(), "{ours}"); +} diff --git a/tests/it_cluster_streams.rs b/tests/it_cluster_streams.rs new file mode 100644 index 0000000..09b5b31 --- /dev/null +++ b/tests/it_cluster_streams.rs @@ -0,0 +1,594 @@ +//! Multi-server installs: the long-lived and aggregate requests. The WebRTC +//! signalling WebSocket is relayed to the server that runs the monitor, the +//! live event stream carries every server's alarm states, and the status and +//! live lists reach other servers. +//! +//! The app under test is server 1; server 2 is a stub. Tests that touch the +//! `Servers` table use their own pair of ids. +//! +//! Requires the test database. Run with: +//! APP_PROFILE=test-db cargo test --test it_cluster_streams -- --include-ignored + +mod common; + +use std::time::Duration; + +use axum::http::{header, StatusCode}; +use common::assertions::assert_status; +use common::cluster::{ + down_url, monitor_on, peer, peer_json, serve_app, server_as, server_one, server_row, sse_peer, + ws_peer, HERE, THERE, +}; +use common::fixtures::{grant_monitor_permission, insert_user_with_id, RowGuard}; +use common::harness::{superuser_token, token_for, TestApp}; +use futures_util::{SinkExt, StreamExt}; +use serde_json::{json, Value}; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode; +use tokio_tungstenite::tungstenite::protocol::CloseFrame; +use tokio_tungstenite::tungstenite::{Error as WsError, Message}; +use tower::ServiceExt; +use zm_api::entity::sea_orm_active_enums::Permission; +use zm_api::util::authz::UserPermissions; + +// ---- The signalling WebSocket ---------------------------------------------- + +type Client = + tokio_tungstenite::WebSocketStream>; + +fn ws_path(monitor_id: u32) -> String { + format!("/api/v3/live/{monitor_id}/webrtc/ws?room=a") +} + +/// Connect as a client of the app served at `addr`, offering `zm.v1`. +async fn connect( + addr: &str, + path: &str, + token: &str, + extra: &[(&str, &str)], +) -> Result< + ( + Client, + tokio_tungstenite::tungstenite::handshake::client::Response, + ), + WsError, +> { + let mut request = format!("ws://{addr}{path}").into_client_request().unwrap(); + let headers = request.headers_mut(); + headers.insert( + header::AUTHORIZATION, + format!("Bearer {token}").parse().unwrap(), + ); + headers.insert(header::SEC_WEBSOCKET_PROTOCOL, "zm.v1".parse().unwrap()); + for (name, value) in extra { + headers.insert( + header::HeaderName::from_bytes(name.as_bytes()).unwrap(), + value.parse().unwrap(), + ); + } + tokio::time::timeout( + Duration::from_secs(10), + tokio_tungstenite::connect_async(request), + ) + .await + .expect("connect within 10 s") +} + +fn refused_with(result: Result<(Client, impl Sized), WsError>) -> StatusCode { + match result { + Err(WsError::Http(response)) => response.status(), + Err(other) => panic!("expected an HTTP refusal, got {other}"), + Ok(_) => panic!("expected an HTTP refusal, the socket opened"), + } +} + +async fn next_message(client: &mut Client) -> Message { + tokio::time::timeout(Duration::from_secs(10), client.next()) + .await + .expect("a message within 10 s") + .expect("the socket is open") + .expect("no error") +} + +async fn wait_for(what: &str, mut ready: impl FnMut() -> bool) { + for _ in 0..100 { + if ready() { + return; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + panic!("{what} did not happen within 5 s"); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_websocket_is_relayed_both_ways() { + let stub = ws_peer().await; + let app = server_one(Some(&stub.url)).await; + let monitor = monitor_on(&app.db, "StreamsWs", THERE).await; + let _m = RowGuard::monitor(monitor.id); + let addr = serve_app(&app).await; + let token = superuser_token(); + + let (mut client, answer) = connect(&addr, &ws_path(monitor.id), &token, &[]) + .await + .expect("the relay opens"); + + // The owner's choice of subprotocol reaches the client. + assert_eq!(answer.headers()[header::SEC_WEBSOCKET_PROTOCOL], "zm.v1"); + + client.send(Message::text("hello")).await.unwrap(); + assert_eq!(next_message(&mut client).await, Message::text("peer:hello")); + client + .send(Message::Binary(vec![1u8, 2, 3].into())) + .await + .unwrap(); + assert_eq!( + next_message(&mut client).await, + Message::Binary(vec![3u8, 2, 1].into()) + ); + + // The owner saw the same path and query, the caller's token and who + // relayed it. + let seen = stub.seen(); + assert_eq!(seen.len(), 1); + assert_eq!(seen[0].path_and_query, ws_path(monitor.id)); + assert_eq!( + seen[0].headers[header::AUTHORIZATION], + format!("Bearer {token}") + ); + assert_eq!(seen[0].headers["x-zm-forwarded-by"], "1"); + assert_eq!(seen[0].headers[header::SEC_WEBSOCKET_PROTOCOL], "zm.v1"); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_close_from_the_client_closes_the_owners_socket() { + let stub = ws_peer().await; + let app = server_one(Some(&stub.url)).await; + let monitor = monitor_on(&app.db, "StreamsWsClientClose", THERE).await; + let _m = RowGuard::monitor(monitor.id); + let addr = serve_app(&app).await; + + let (mut client, _) = connect(&addr, &ws_path(monitor.id), &superuser_token(), &[]) + .await + .unwrap(); + client + .send(Message::Close(Some(CloseFrame { + code: CloseCode::Library(4001), + reason: "bye".into(), + }))) + .await + .unwrap(); + + wait_for("the owner seeing the close", || { + stub.log() == ["close:4001:bye"] + }) + .await; +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_close_from_the_owner_closes_the_clients_socket() { + let stub = ws_peer().await; + let app = server_one(Some(&stub.url)).await; + let monitor = monitor_on(&app.db, "StreamsWsPeerClose", THERE).await; + let _m = RowGuard::monitor(monitor.id); + let addr = serve_app(&app).await; + + let (mut client, _) = connect(&addr, &ws_path(monitor.id), &superuser_token(), &[]) + .await + .unwrap(); + client.send(Message::text("close-me")).await.unwrap(); + + match next_message(&mut client).await { + Message::Close(Some(frame)) => { + assert_eq!(u16::from(frame.code), 4002); + assert_eq!(frame.reason.as_str(), "from peer"); + } + other => panic!("expected the owner's close frame, got {other:?}"), + } +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_dropped_client_closes_the_owners_socket() { + let stub = ws_peer().await; + let app = server_one(Some(&stub.url)).await; + let monitor = monitor_on(&app.db, "StreamsWsDrop", THERE).await; + let _m = RowGuard::monitor(monitor.id); + let addr = serve_app(&app).await; + + let (client, _) = connect(&addr, &ws_path(monitor.id), &superuser_token(), &[]) + .await + .unwrap(); + drop(client); + + wait_for("the owner losing its socket", || !stub.log().is_empty()).await; +} + +/// The owner is connected to before the client's upgrade is accepted, so a +/// server that is down is an HTTP error the client can read. +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_server_that_is_down_is_a_bad_gateway() { + let app = server_one(Some(&down_url().await)).await; + let monitor = monitor_on(&app.db, "StreamsWsDown", THERE).await; + let _m = RowGuard::monitor(monitor.id); + let addr = serve_app(&app).await; + + let result = connect(&addr, &ws_path(monitor.id), &superuser_token(), &[]).await; + + assert_eq!(refused_with(result), StatusCode::BAD_GATEWAY); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_refusal_from_the_owner_is_passed_on() { + // The stub answers the upgrade with a plain 403. + let forbidden = peer(StatusCode::FORBIDDEN).await; + let app = server_one(Some(&forbidden.url)).await; + let monitor = monitor_on(&app.db, "StreamsWsRefused", THERE).await; + let _m = RowGuard::monitor(monitor.id); + let addr = serve_app(&app).await; + let result = connect(&addr, &ws_path(monitor.id), &superuser_token(), &[]).await; + assert_eq!(refused_with(result), StatusCode::FORBIDDEN); + + // A 401 means the servers sign tokens with different keys. + let unauthorized = peer(StatusCode::UNAUTHORIZED).await; + let app = server_one(Some(&unauthorized.url)).await; + let addr = serve_app(&app).await; + let result = connect(&addr, &ws_path(monitor.id), &superuser_token(), &[]).await; + assert_eq!(refused_with(result), StatusCode::BAD_GATEWAY); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_caller_who_cannot_see_the_monitor_never_reaches_the_owner() { + let stub = ws_peer().await; + let app = server_one(Some(&stub.url)).await; + let hidden = monitor_on(&app.db, "StreamsWsHidden", THERE).await; + let _h = RowGuard::monitor(hidden.id); + + const UID: u32 = 990_231; + insert_user_with_id(&app.db, UID, "StreamsWsAcl") + .await + .expect("user"); + let _u = RowGuard::user(UID); + grant_monitor_permission(&app.db, hidden.id, UID, Permission::None) + .await + .expect("grant"); + let token = token_for(UID, UserPermissions::superuser()); + let addr = serve_app(&app).await; + + let result = connect(&addr, &ws_path(hidden.id), &token, &[]).await; + + assert_eq!(refused_with(result), StatusCode::NOT_FOUND); + assert!(stub.seen().is_empty()); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_request_another_server_relayed_is_not_relayed_again() { + let stub = ws_peer().await; + let app = server_one(Some(&stub.url)).await; + let monitor = monitor_on(&app.db, "StreamsWsLoop", THERE).await; + let _m = RowGuard::monitor(monitor.id); + let addr = serve_app(&app).await; + + let result = connect( + &addr, + &ws_path(monitor.id), + &superuser_token(), + &[("x-zm-forwarded-by", "2")], + ) + .await; + + assert_eq!(refused_with(result), StatusCode::MISDIRECTED_REQUEST); + assert!(stub.seen().is_empty()); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn this_servers_own_monitor_is_not_relayed() { + let stub = ws_peer().await; + let app = server_one(Some(&stub.url)).await; + let monitor = monitor_on(&app.db, "StreamsWsOwn", HERE).await; + let _m = RowGuard::monitor(monitor.id); + let addr = serve_app(&app).await; + + let result = connect(&addr, &ws_path(monitor.id), &superuser_token(), &[]).await; + + // The local handler answers: the test app has no live streaming. + assert_eq!(refused_with(result), StatusCode::SERVICE_UNAVAILABLE); + assert!(stub.seen().is_empty()); +} + +/// An `Upgrade` header without a WebSocket handshake is not something the +/// relay can carry. +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn an_upgrade_that_is_not_a_websocket_is_refused() { + let stub = ws_peer().await; + let app = server_one(Some(&stub.url)).await; + let monitor = monitor_on(&app.db, "StreamsWsNot", THERE).await; + let _m = RowGuard::monitor(monitor.id); + + let r = app + .request(axum::http::Method::GET, &ws_path(monitor.id)) + .bearer(&superuser_token()) + .header("connection", "upgrade") + .header("upgrade", "websocket") + .send() + .await; + + assert_status(&r, StatusCode::MISDIRECTED_REQUEST); + assert!(stub.seen().is_empty()); +} + +// ---- The live event stream ------------------------------------------------- + +/// Open `/events/stream` as `token`, with these extra headers. The response +/// head only: the body is read with [`read_until`]. +async fn open_stream( + app: &TestApp, + token: &str, + extra: &[(&str, &str)], +) -> axum::response::Response { + let mut request = axum::http::Request::builder() + .uri("/api/v3/events/stream") + .header(header::AUTHORIZATION, format!("Bearer {token}")) + .extension(axum::extract::ConnectInfo(std::net::SocketAddr::from(( + [127, 0, 0, 1], + 50000, + )))); + for (name, value) in extra { + request = request.header(*name, *value); + } + tokio::time::timeout( + Duration::from_secs(10), + app.router() + .oneshot(request.body(axum::body::Body::empty()).unwrap()), + ) + .await + .expect("the head within 10 s") + .unwrap() +} + +/// Read the body until `done` accepts what has arrived, or `within` passes. +/// Returns everything read. +async fn read_until( + response: axum::response::Response, + within: Duration, + done: impl Fn(&str) -> bool, +) -> String { + let mut body = response.into_body().into_data_stream(); + let mut text = String::new(); + let _ = tokio::time::timeout(within, async { + while let Some(Ok(chunk)) = body.next().await { + text.push_str(&String::from_utf8_lossy(&chunk)); + if done(&text) { + return; + } + } + }) + .await; + text +} + +fn alarm(monitor_id: u32, state: &str) -> Value { + json!({ "type": "alarm_state", "monitor_id": monitor_id, "state": state, "score": 5 }) +} + +fn has_alarm(text: &str, monitor_id: u32, state: &str) -> bool { + text.contains(&format!(r#""monitor_id":{monitor_id},"state":"{state}""#)) +} + +/// Server ids for the stream tests, one pair each: the `Servers` rows are +/// shared database state. +fn ids(n: u32) -> (u32, u32) { + (7600 + 2 * n, 7601 + 2 * n) +} + +const SECONDS: Duration = Duration::from_secs(1); + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_peers_alarm_state_reaches_the_client() { + let (here, there) = ids(0); + let app_db = common::test_db::get_test_db().await.unwrap(); + let theirs = monitor_on(&app_db, "StreamsSseTheirs", there).await; + let _t = RowGuard::monitor(theirs.id); + let ours = monitor_on(&app_db, "StreamsSseOurs", here).await; + let _o = RowGuard::monitor(ours.id); + let stub = sse_peer(vec![ + // A monitor the peer does not run: dropped. + ("alarm_state", alarm(ours.id, "alarm")), + // A table-backed event: this server reads those itself. + ( + "event_start", + json!({ "type": "event_start", "event_id": 987654321u64, "monitor_id": theirs.id }), + ), + ("alarm_state", alarm(theirs.id, "alert")), + ]) + .await; + let app = server_as(here, there, Some(&stub.url)).await; + let _a = server_row(&app.db, here, "streams-a").await; + let _b = server_row(&app.db, there, "streams-b").await; + let token = superuser_token(); + + let response = open_stream(&app, &token, &[]).await; + assert_eq!(response.status(), StatusCode::OK); + let text = read_until(response, 10 * SECONDS, |t| has_alarm(t, theirs.id, "alert")).await; + + assert!(has_alarm(&text, theirs.id, "alert"), "{text}"); + assert!( + !has_alarm(&text, ours.id, "alarm"), + "a peer can't speak for our monitor: {text}" + ); + assert!(!text.contains("987654321"), "no duplicated event: {text}"); + + let seen = stub.seen(); + assert_eq!(seen.len(), 1); + assert_eq!(seen[0].path_and_query, "/api/v3/events/stream"); + assert_eq!( + seen[0].headers[header::AUTHORIZATION], + format!("Bearer {token}") + ); + assert_eq!(seen[0].headers["x-zm-forwarded-by"], here.to_string()); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_client_does_not_get_alarm_states_for_monitors_it_cannot_see() { + let (here, there) = ids(1); + let db = common::test_db::get_test_db().await.unwrap(); + let hidden = monitor_on(&db, "StreamsSseHidden", there).await; + let _h = RowGuard::monitor(hidden.id); + let visible = monitor_on(&db, "StreamsSseVisible", there).await; + let _v = RowGuard::monitor(visible.id); + let stub = sse_peer(vec![ + ("alarm_state", alarm(hidden.id, "alarm")), + ("alarm_state", alarm(visible.id, "alarm")), + ]) + .await; + let app = server_as(here, there, Some(&stub.url)).await; + let _a = server_row(&app.db, here, "streams-a").await; + let _b = server_row(&app.db, there, "streams-b").await; + + const UID: u32 = 990_232; + insert_user_with_id(&app.db, UID, "StreamsSseAcl") + .await + .expect("user"); + let _u = RowGuard::user(UID); + grant_monitor_permission(&app.db, hidden.id, UID, Permission::None) + .await + .expect("grant"); + let token = token_for(UID, UserPermissions::superuser()); + + let response = open_stream(&app, &token, &[]).await; + let text = read_until(response, 10 * SECONDS, |t| { + has_alarm(t, visible.id, "alarm") + }) + .await; + + assert!(has_alarm(&text, visible.id, "alarm"), "{text}"); + assert!(!has_alarm(&text, hidden.id, "alarm"), "{text}"); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_relayed_stream_request_follows_nobody() { + let (here, there) = ids(2); + let stub = sse_peer(vec![]).await; + let app = server_as(here, there, Some(&stub.url)).await; + let _a = server_row(&app.db, here, "streams-a").await; + let _b = server_row(&app.db, there, "streams-b").await; + + let response = open_stream(&app, &superuser_token(), &[("x-zm-forwarded-by", "9")]).await; + assert_eq!(response.status(), StatusCode::OK); + let _ = read_until(response, 2 * SECONDS, |_| false).await; + + assert!(stub.seen().is_empty()); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn the_stream_works_while_a_peer_is_down() { + let (here, there) = ids(3); + let db = common::test_db::get_test_db().await.unwrap(); + let ours = monitor_on(&db, "StreamsSseDown", here).await; + let _o = RowGuard::monitor(ours.id); + let app = server_as(here, there, Some(&down_url().await)).await; + let _a = server_row(&app.db, here, "streams-a").await; + let _b = server_row(&app.db, there, "streams-b").await; + + let response = open_stream(&app, &superuser_token(), &[]).await; + assert_eq!(response.status(), StatusCode::OK); + // This server's own monitors still report. + let needle = format!(r#""monitor_id":{}"#, ours.id); + let text = read_until(response, 10 * SECONDS, |t| t.contains(&needle)).await; + + assert!(text.contains(&needle), "{text}"); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_single_server_install_follows_nobody() { + let stub = sse_peer(vec![("alarm_state", alarm(1, "alarm"))]).await; + // An address for a peer, but no server id here: nothing relays. + let mut config = zm_api::configure::cluster::ClusterConfig::default(); + config.peers.insert(THERE.to_string(), stub.url.clone()); + let app = TestApp::spawn_with(move |state| { + state.cluster = std::sync::Arc::new(zm_api::cluster::Cluster::new(None, &config, 0, false)); + }) + .await; + let _b = server_row(&app.db, 7699, "streams-lone").await; + + let response = open_stream(&app, &superuser_token(), &[]).await; + assert_eq!(response.status(), StatusCode::OK); + let _ = read_until(response, 2 * SECONDS, |_| false).await; + + assert!(stub.seen().is_empty()); +} + +// ---- Monitor status and the live lists --------------------------------------- + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_peers_monitor_status_is_relayed() { + let stub = peer(StatusCode::OK).await; + let app = server_one(Some(&stub.url)).await; + let monitor = monitor_on(&app.db, "StreamsStatus", THERE).await; + let _m = RowGuard::monitor(monitor.id); + + let path = format!("/api/v3/monitor-status/{}", monitor.id); + let r = app.get(&path, &superuser_token()).await; + + assert_status(&r, StatusCode::OK); + assert_eq!(r.text(), "from server 2"); + let seen = stub.seen(); + assert_eq!(seen.len(), 1); + assert_eq!(seen[0].path_and_query, path); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn the_live_lists_answer_for_every_server() { + let sources = json!({ "active_sources": 0, "sources": [] }); + for (n, path, answer) in [ + (4, "/api/v3/live/sessions", json!([7])), + (5, "/api/v3/live/sources", sources), + ] { + let (here, there) = ids(n); + let stub = peer_json(StatusCode::OK, answer.clone()).await; + let app = server_as(here, there, Some(&stub.url)).await; + let _a = server_row(&app.db, here, "streams-a").await; + let _b = server_row(&app.db, there, "streams-b").await; + + let r = app + .get(&format!("{path}?server_id=all"), &superuser_token()) + .await; + + assert_status(&r, StatusCode::MULTI_STATUS); + let body = r.json::(); + let servers = body["servers"].as_array().unwrap(); + // Other tests' `Servers` rows may be there too: each of ours once. + let entries = |id: u32| servers.iter().filter(|e| e["server_id"] == id).count(); + assert_eq!((entries(here), entries(there)), (1, 1), "{body}"); + assert_eq!(servers[0]["server_id"], here, "this server first"); + let remote = servers.iter().find(|e| e["server_id"] == there).unwrap(); + assert_eq!(remote["ok"], true); + assert_eq!(remote["result"], answer); + let seen = stub.seen(); + assert_eq!(seen.len(), 1); + assert_eq!(seen[0].path_and_query, format!("{path}?server_id={there}")); + + // One server by number is relayed as that server's own answer. + let r = app + .get(&format!("{path}?server_id={there}"), &superuser_token()) + .await; + assert_status(&r, StatusCode::OK); + assert_eq!(r.json::(), answer); + } +} diff --git a/tests/it_cluster_system.rs b/tests/it_cluster_system.rs new file mode 100644 index 0000000..c1336a7 --- /dev/null +++ b/tests/it_cluster_system.rs @@ -0,0 +1,587 @@ +//! System-wide control across servers: `?server_id=` on the daemon and system +//! routes, and the run state reaching every server. +//! +//! The app under test is server `here`. Server `there` is a stub that records +//! what reaches it. Each test uses its own pair of server ids, because the +//! `Servers` rows are shared database state. +//! +//! Requires the test database. Run with: +//! APP_PROFILE=test-db cargo test --test it_cluster_system -- --include-ignored + +mod common; + +use axum::http::{Method, StatusCode}; +use common::assertions::{assert_error, assert_status}; +use common::cluster::{peer, peer_json, server_as, server_row}; +use common::fixtures::{insert_monitor, unique_name, RowGuard}; +use common::harness::{superuser_token, token_with, TestApp}; +use sea_orm::{ActiveModelTrait, EntityTrait, Set}; +use serde_json::{json, Value}; +use zm_api::util::authz::{Level, UserPermissions}; + +/// The server ids test number `n` uses. +fn ids(n: u32) -> (u32, u32) { + (7200 + 2 * n, 7201 + 2 * n) +} + +fn entry(body: &Value, server_id: u32) -> &Value { + body["servers"] + .as_array() + .expect("servers array") + .iter() + .find(|e| e["server_id"] == server_id) + .unwrap_or_else(|| panic!("no entry for server {server_id} in {body}")) +} + +const DAEMONS: &str = "/api/v3/daemons"; +const STATUS: &str = "/api/v3/system/status"; + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_request_for_another_server_is_relayed_with_the_callers_token() { + let (here, there) = ids(0); + let stub = peer_json(StatusCode::OK, json!({ "daemons": [] })).await; + let app = server_as(here, there, Some(&stub.url)).await; + let _a = server_row(&app.db, here, "zm-a").await; + let _b = server_row(&app.db, there, "zm-b").await; + let token = superuser_token(); + + let r = app + .get(&format!("{DAEMONS}?server_id={there}"), &token) + .await; + + assert_status(&r, StatusCode::OK); + assert_eq!(r.json::(), json!({ "daemons": [] })); + let seen = stub.seen(); + assert_eq!(seen.len(), 1); + assert_eq!(seen[0].method, Method::GET); + assert_eq!( + seen[0].path_and_query, + format!("{DAEMONS}?server_id={there}") + ); + assert_eq!(seen[0].headers["authorization"], format!("Bearer {token}")); + assert_eq!(seen[0].headers["x-zm-forwarded-by"], here.to_string()); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_write_for_another_server_keeps_its_method_path_and_body() { + let (here, there) = ids(1); + let stub = peer_json( + StatusCode::OK, + json!({ "success": true, "message": "restarted" }), + ) + .await; + let app = server_as(here, there, Some(&stub.url)).await; + let _a = server_row(&app.db, here, "zm-a").await; + let _b = server_row(&app.db, there, "zm-b").await; + + let r = app + .post_json( + &format!("/api/v3/daemons/zmc%20-m%201/start?server_id={there}"), + &superuser_token(), + &json!({ "args": ["x"] }), + ) + .await; + + assert_status(&r, StatusCode::OK); + let seen = stub.seen(); + assert_eq!(seen.len(), 1); + assert_eq!(seen[0].method, Method::POST); + assert_eq!( + seen[0].path_and_query, + format!("/api/v3/daemons/zmc%20-m%201/start?server_id={there}") + ); + assert_eq!( + serde_json::from_slice::(&seen[0].body).unwrap(), + json!({ "args": ["x"] }) + ); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn no_server_id_acts_here_and_contacts_nobody() { + let (here, there) = ids(2); + let stub = peer(StatusCode::OK).await; + let app = server_as(here, there, Some(&stub.url)).await; + let _a = server_row(&app.db, here, "zm-a").await; + let _b = server_row(&app.db, there, "zm-b").await; + + // Passive mode with no zmdc.sock: this server's own answer is a 503. + let r = app.get(DAEMONS, &superuser_token()).await; + + assert_status(&r, StatusCode::SERVICE_UNAVAILABLE); + assert!(stub.seen().is_empty()); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn naming_this_server_is_handled_here() { + let (here, there) = ids(3); + let stub = peer(StatusCode::OK).await; + let app = server_as(here, there, Some(&stub.url)).await; + let _a = server_row(&app.db, here, "zm-a").await; + let _b = server_row(&app.db, there, "zm-b").await; + + let r = app + .get(&format!("{STATUS}?server_id={here}"), &superuser_token()) + .await; + + assert_status(&r, StatusCode::OK); + assert!(r.json::().get("running").is_some()); + assert!(stub.seen().is_empty()); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn an_unknown_server_is_404_and_a_bad_value_is_400() { + let (here, there) = ids(4); + let stub = peer(StatusCode::OK).await; + let app = server_as(here, there, Some(&stub.url)).await; + let _a = server_row(&app.db, here, "zm-a").await; + let _b = server_row(&app.db, there, "zm-b").await; + let token = superuser_token(); + + let r = app.get(&format!("{STATUS}?server_id=7999"), &token).await; + assert_status(&r, StatusCode::NOT_FOUND); + + for bad in ["two", "", "-1"] { + let r = app.get(&format!("{STATUS}?server_id={bad}"), &token).await; + assert_status(&r, StatusCode::BAD_REQUEST); + } + assert!(stub.seen().is_empty()); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_server_with_no_address_is_misdirected() { + let (here, there) = ids(5); + let app = server_as(here, there, None).await; + let _a = server_row(&app.db, here, "zm-a").await; + let _b = server_row(&app.db, there, "zm-b").await; + + let r = app + .get(&format!("{STATUS}?server_id={there}"), &superuser_token()) + .await; + + assert_error( + &r, + StatusCode::MISDIRECTED_REQUEST, + "MISDIRECTED_REQUEST_ERROR", + ); + assert!( + r.text().contains(&format!("server {there}")), + "{}", + r.text() + ); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn all_returns_one_entry_per_server() { + let (here, there) = ids(6); + let stub = peer_json( + StatusCode::OK, + json!({ "running": true, "daemons": [], "marker": "from the stub" }), + ) + .await; + let app = server_as(here, there, Some(&stub.url)).await; + let _a = server_row(&app.db, here, "zm-a").await; + let _b = server_row(&app.db, there, "zm-b").await; + + let r = app + .get(&format!("{STATUS}?server_id=all"), &superuser_token()) + .await; + + assert_status(&r, StatusCode::MULTI_STATUS); + let body = r.json::(); + let servers = body["servers"].as_array().unwrap(); + assert_eq!(servers[0]["server_id"], here, "this server comes first"); + + let local = entry(&body, here); + assert_eq!(local["ok"], true); + assert_eq!(local["name"], "zm-a"); + assert!(local["result"].get("running").is_some()); + + let remote = entry(&body, there); + assert_eq!(remote["ok"], true); + assert_eq!(remote["status"], 200); + assert_eq!(remote["name"], "zm-b"); + assert_eq!(remote["result"]["marker"], "from the stub"); + + // The stub is asked as itself, once. + let seen = stub.seen(); + assert_eq!(seen.len(), 1); + assert_eq!( + seen[0].path_and_query, + format!("{STATUS}?server_id={there}") + ); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_server_that_is_down_does_not_fail_the_rest() { + let (here, there) = ids(7); + // Nothing listens on port 1. + let app = server_as(here, there, Some("http://127.0.0.1:1")).await; + let _a = server_row(&app.db, here, "zm-a").await; + let _b = server_row(&app.db, there, "zm-b").await; + + let r = app + .get(&format!("{STATUS}?server_id=all"), &superuser_token()) + .await; + + assert_status(&r, StatusCode::MULTI_STATUS); + let body = r.json::(); + assert_eq!(entry(&body, here)["ok"], true); + let down = entry(&body, there); + assert_eq!(down["ok"], false); + assert_eq!(down["status"], 502); + let error = down["error"].as_str().unwrap(); + assert!(error.contains(&format!("server {there} (zm-b)")), "{error}"); + assert!(down.get("result").is_none()); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_relayed_request_is_never_relayed_again() { + let (here, there) = ids(8); + let stub = peer(StatusCode::OK).await; + let app = server_as(here, there, Some(&stub.url)).await; + let _a = server_row(&app.db, here, "zm-a").await; + let _b = server_row(&app.db, there, "zm-b").await; + let token = superuser_token(); + + for value in ["all", &there.to_string(), "nonsense"] { + let r = app + .request(Method::GET, &format!("{STATUS}?server_id={value}")) + .bearer(&token) + .header("x-zm-forwarded-by", "9") + .send() + .await; + assert_status(&r, StatusCode::OK); + let body = r.json::(); + assert!(body.get("servers").is_none(), "{value}: {body}"); + assert!(body.get("running").is_some(), "{value}: {body}"); + } + assert!(stub.seen().is_empty()); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn someone_without_the_permission_is_refused_before_anything_is_relayed() { + let (here, there) = ids(9); + let stub = peer(StatusCode::OK).await; + let app = server_as(here, there, Some(&stub.url)).await; + let _a = server_row(&app.db, here, "zm-a").await; + let _b = server_row(&app.db, there, "zm-b").await; + let token = token_with(UserPermissions { + system: Level::None, + ..UserPermissions::superuser() + }); + + for suffix in [there.to_string(), "all".to_string()] { + let r = app + .get(&format!("{DAEMONS}?server_id={suffix}"), &token) + .await; + assert_status(&r, StatusCode::FORBIDDEN); + let r = app + .post_json( + &format!("/api/v3/system/restart?server_id={suffix}"), + &token, + &json!({}), + ) + .await; + assert_status(&r, StatusCode::FORBIDDEN); + } + assert!(stub.seen().is_empty()); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_single_server_install_answers_all_with_its_one_server() { + // The harness default: no server id, nothing relayed. + let app = TestApp::spawn().await; + let token = superuser_token(); + + let r = app.get(&format!("{STATUS}?server_id=all"), &token).await; + + assert_status(&r, StatusCode::MULTI_STATUS); + let body = r.json::(); + let servers = body["servers"].as_array().unwrap(); + assert_eq!(servers.len(), 1); + assert_eq!(servers[0]["server_id"], Value::Null); + assert_eq!(servers[0]["ok"], true); + assert!(servers[0]["result"].get("running").is_some()); + + // Any number is some other host, which this install does not know. + let r = app.get(&format!("{STATUS}?server_id=2"), &token).await; + assert_status(&r, StatusCode::NOT_FOUND); + let r = app.get(STATUS, &token).await; + assert_status(&r, StatusCode::OK); +} + +/// Applying a state deactivates every other state, so the tests that apply or +/// check one take turns. +static STATES: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +/// A run state naming one monitor, and guards for both rows. +async fn state_with_monitor( + db: &sea_orm::DatabaseConnection, + label: &str, +) -> (String, u32, u32, RowGuard, RowGuard) { + let monitor = insert_monitor(db, "SysState").await.expect("monitor"); + let name = unique_name(label); + let state = zm_api::entity::states::ActiveModel { + name: Set(name.clone()), + definition: Set(format!("{}:Always:Always:OnMotion", monitor.id)), + is_active: Set(0), + ..Default::default() + } + .insert(db) + .await + .expect("state"); + ( + name, + state.id, + monitor.id, + RowGuard::state(state.id), + RowGuard::monitor(monitor.id), + ) +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn applying_a_state_tells_each_other_server_once() { + let (here, there) = ids(10); + let _turn = STATES.lock().await; + let stub = peer_json( + StatusCode::OK, + json!({ "success": true, "message": "2 monitors with daemons restarting" }), + ) + .await; + let app = server_as(here, there, Some(&stub.url)).await; + let _a = server_row(&app.db, here, "zm-a").await; + let _b = server_row(&app.db, there, "zm-b").await; + let (name, state_id, monitor_id, _s, _m) = state_with_monitor(&app.db, "SysTold").await; + let token = superuser_token(); + + let r = app + .post_json( + "/api/v3/system/state", + &token, + &json!({ "state_name": name }), + ) + .await; + + assert_status(&r, StatusCode::OK); + let body = r.json::(); + // The fields clients already read describe this server. + assert_eq!(body["success"], true); + assert!(body["message"].as_str().unwrap().contains(&name)); + let other = entry(&body, there); + assert_eq!(other["ok"], true); + assert_eq!( + other["result"]["message"], + "2 monitors with daemons restarting" + ); + + // The rows changed here, once. + let row = zm_api::entity::monitors::Entity::find_by_id(monitor_id) + .one(&app.db) + .await + .unwrap() + .unwrap(); + assert_eq!( + row.recording, + zm_api::entity::sea_orm_active_enums::Recording::OnMotion + ); + let active = zm_api::entity::states::Entity::find_by_id(state_id) + .one(&app.db) + .await + .unwrap() + .unwrap(); + assert_eq!(active.is_active, 1); + + // The other server was told once, to restart daemons and not to write. + let seen = stub.seen(); + assert_eq!(seen.len(), 1); + assert_eq!(seen[0].method, Method::POST); + assert_eq!(seen[0].headers["authorization"], format!("Bearer {token}")); + assert_eq!(seen[0].headers["x-zm-forwarded-by"], here.to_string()); + assert_eq!( + serde_json::from_slice::(&seen[0].body).unwrap(), + json!({ "state_name": name, "daemons_only": true }) + ); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_relayed_state_is_applied_here_and_goes_no_further() { + let (here, there) = ids(11); + let _turn = STATES.lock().await; + let stub = peer(StatusCode::OK).await; + let app = server_as(here, there, Some(&stub.url)).await; + let _a = server_row(&app.db, here, "zm-a").await; + let _b = server_row(&app.db, there, "zm-b").await; + let (name, _sid, _mid, _s, _m) = state_with_monitor(&app.db, "SysRelayed").await; + + let r = app + .request(Method::POST, "/api/v3/system/state?server_id=all") + .bearer(&superuser_token()) + .header("x-zm-forwarded-by", "9") + .json(&json!({ "state_name": name })) + .send() + .await; + + assert_status(&r, StatusCode::OK); + assert!(r.json::().get("servers").is_none()); + assert!(stub.seen().is_empty()); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn daemons_only_leaves_the_database_alone() { + let (here, there) = ids(12); + let _turn = STATES.lock().await; + let stub = peer(StatusCode::OK).await; + let app = server_as(here, there, Some(&stub.url)).await; + let _a = server_row(&app.db, here, "zm-a").await; + let _b = server_row(&app.db, there, "zm-b").await; + let (name, state_id, monitor_id, _s, _m) = state_with_monitor(&app.db, "SysDaemons").await; + let before = zm_api::entity::monitors::Entity::find_by_id(monitor_id) + .one(&app.db) + .await + .unwrap() + .unwrap(); + + let r = app + .post_json( + "/api/v3/system/state", + &superuser_token(), + &json!({ "state_name": name, "daemons_only": true }), + ) + .await; + + assert_status(&r, StatusCode::OK); + assert!(r.json::().get("servers").is_none()); + let after = zm_api::entity::monitors::Entity::find_by_id(monitor_id) + .one(&app.db) + .await + .unwrap() + .unwrap(); + assert_eq!(before.recording, after.recording); + let state = zm_api::entity::states::Entity::find_by_id(state_id) + .one(&app.db) + .await + .unwrap() + .unwrap(); + assert_eq!(state.is_active, 0, "a daemons-only request writes nothing"); + assert!(stub.seen().is_empty(), "and is not passed on"); +} + +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_state_cannot_be_aimed_at_one_server() { + let (here, there) = ids(13); + let _turn = STATES.lock().await; + let stub = peer(StatusCode::OK).await; + let app = server_as(here, there, Some(&stub.url)).await; + let _a = server_row(&app.db, here, "zm-a").await; + let _b = server_row(&app.db, there, "zm-b").await; + let (name, state_id, _mid, _s, _m) = state_with_monitor(&app.db, "SysOne").await; + + let r = app + .post_json( + &format!("/api/v3/system/state?server_id={there}"), + &superuser_token(), + &json!({ "state_name": name }), + ) + .await; + + assert_status(&r, StatusCode::BAD_REQUEST); + let state = zm_api::entity::states::Entity::find_by_id(state_id) + .one(&app.db) + .await + .unwrap() + .unwrap(); + assert_eq!(state.is_active, 0); + assert!(stub.seen().is_empty()); +} + +/// What the server that did not apply the state does: restart the daemons of +/// its own monitors that the state names, through its zmdc.pl. +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn daemons_only_restarts_this_servers_monitors_through_zmdc() { + use std::sync::{Arc, Mutex}; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let (here, there) = ids(14); + let _turn = STATES.lock().await; + let tmp = tempfile::tempdir().unwrap(); + let listener = tokio::net::UnixListener::bind(tmp.path().join("zmdc.sock")).unwrap(); + let got = Arc::new(Mutex::new(Vec::::new())); + let log = Arc::clone(&got); + tokio::spawn(async move { + while let Ok((mut s, _)) = listener.accept().await { + let mut msg = String::new(); + let _ = s.read_to_string(&mut msg).await; + log.lock().unwrap().push(msg); + let _ = s.write_all(b"").await; + } + }); + let dir = tmp.path().to_path_buf(); + let app = TestApp::spawn_with(move |state| { + state.server_id = Some(here); + state.cluster = Arc::new(zm_api::cluster::Cluster::new( + Some(here), + &zm_api::configure::cluster::ClusterConfig::default(), + 0, + false, + )); + let mut config = (*state.config).clone(); + config.daemon.socket_path = dir; + config.daemon.socket_name = "zmdc.sock".to_string(); + state.config = Arc::new(config); + }) + .await; + let _a = server_row(&app.db, here, "zm-a").await; + let _b = server_row(&app.db, there, "zm-b").await; + let (name, _sid, monitor_id, _s, _m) = state_with_monitor(&app.db, "SysZmdc").await; + let mut row: zm_api::entity::monitors::ActiveModel = + zm_api::entity::monitors::Entity::find_by_id(monitor_id) + .one(&app.db) + .await + .unwrap() + .unwrap() + .into(); + row.server_id = Set(Some(here)); + row.capturing = Set(zm_api::entity::sea_orm_active_enums::Capturing::Always); + row.update(&app.db).await.unwrap(); + + let r = app + .post_json( + "/api/v3/system/state", + &superuser_token(), + &json!({ "state_name": name, "daemons_only": true }), + ) + .await; + assert_status(&r, StatusCode::OK); + assert!(r.json::()["message"] + .as_str() + .unwrap() + .contains("1 monitors")); + + let stop = format!("stop;zmc;-m;{monitor_id}"); + let start = format!("start;zmc;-m;{monitor_id}"); + for _ in 0..40 { + if got.lock().unwrap().contains(&start) { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + let got = got.lock().unwrap(); + assert!(got.contains(&stop), "zmdc got {got:?}"); + assert!(got.contains(&start), "zmdc got {got:?}"); +} diff --git a/tests/it_maintenance.rs b/tests/it_maintenance.rs index f34db22..67933a4 100644 --- a/tests/it_maintenance.rs +++ b/tests/it_maintenance.rs @@ -28,6 +28,7 @@ const MON_UNCLOSED: u32 = 99_313; const MON_COUNTERS: u32 = 99_314; const MON_LIVE: u32 = 99_315; const MON_SUPERSEDED: u32 = 99_316; +const MON_PEER: u32 = 99_317; /// Every audit pass sweeps the whole database, not just the calling test's /// monitor, so two tests running passes at once can delete or close each @@ -788,3 +789,83 @@ fn walkdir_files(dir: &std::path::Path) -> Vec { } out } + +/// An event on another server's storage is that server's to judge. This host +/// can't see the files, so the audit neither walks the storage (which would +/// refuse, or worse, find nothing) nor deletes the event as empty. +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn the_audit_leaves_another_servers_storage_alone() { + use common::fixtures::{insert_storage, RowGuard}; + use sea_orm::{ActiveModelTrait, Set}; + use zm_api::configure::maintenance::FilesystemAuditConfig; + use zm_api::entity::sea_orm_active_enums::Scheme; + + let iso = common::isolated::IsolatedDb::create().await; + let _serial = SERIAL.lock().await; + const MON: u32 = MON_PEER; + let db = Arc::new(iso.connect().await); + cleanup(&db, MON, 9_930_070, 9_930_071).await; + + let mut ids = Vec::new(); + let mut guards = Vec::new(); + for (label, server) in [("AuditPeer", Some(2u32)), ("AuditShared", None)] { + let st = insert_storage(&db, label, "/nonexistent/zm-audit-peer", Scheme::Medium) + .await + .expect("storage"); + guards.push(RowGuard::storage(st.id)); + let mut row: zm_api::entity::storage::ActiveModel = st.clone().into(); + row.server_id = Set(server); + row.update(&*db).await.expect("server"); + ids.push(st.id); + } + // Both events are old, frameless and unarchived: empty by the database's + // own evidence. Only the one on shared storage is this host's to delete. + for (event, storage) in [(9_930_070u64, ids[0]), (9_930_071, ids[1])] { + exec( + &db, + format!( + "INSERT INTO Events (Id, MonitorId, StorageId, StateId, StartDateTime, Scheme) \ + VALUES ({event}, {MON}, {storage}, 1, DATE_SUB(NOW(), INTERVAL 2 HOUR), 'Medium')" + ), + ) + .await; + } + + let config = AuditConfig { + filesystem: FilesystemAuditConfig { + enabled: true, + remove_rows_without_media: true, + ..Default::default() + }, + ..audit_config(false) + }; + let report = AuditService::new(Arc::clone(&db), config) + .with_server_id(Some(1)) + .run_once() + .await + .expect("pass"); + + let present = |id: u64| { + let db = Arc::clone(&db); + async move { + scalar( + &db, + &format!("SELECT COUNT(*) AS n FROM Events WHERE Id = {id}"), + ) + .await + } + }; + assert_eq!(present(9_930_070).await, 1, "another server's event stays"); + assert_eq!(present(9_930_071).await, 0, "shared storage is this host's"); + assert!( + report + .refusals + .iter() + .all(|r| !r.contains(&format!("storage {} ", ids[0]))), + "the peer's storage was never walked: {:?}", + report.refusals + ); + + cleanup(&db, MON, 9_930_070, 9_930_071).await; +} diff --git a/tests/it_media_jobs.rs b/tests/it_media_jobs.rs index 0a3211b..0f93502 100644 --- a/tests/it_media_jobs.rs +++ b/tests/it_media_jobs.rs @@ -249,3 +249,97 @@ async fn a_generated_video_never_replaces_the_recording() { .await; assert_eq!(r.status(), StatusCode::BAD_REQUEST, "{}", r.text()); } + +/// A server that can't read an event's files leaves its job queued, for the +/// server that can. The queue is one table in the shared database, so the +/// other server's worker finds it there. +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn a_job_for_another_servers_storage_is_left_queued() { + use std::sync::Arc; + use zm_api::cluster::Cluster; + use zm_api::configure::cluster::ClusterConfig; + + let iso = common::isolated::IsolatedDb::create().await; + let app = TestApp::spawn_on(&iso).await; + common::test_db::migrate_test_db(&app.db).await; + let token = superuser_token(); + let tmp = tempfile::tempdir().unwrap(); + let monitor = insert_monitor(&app.db, "VideoPeer").await.unwrap(); + let storage = insert_storage( + &app.db, + "VideoPeer", + tmp.path().to_str().unwrap(), + Scheme::Shallow, + ) + .await + .unwrap(); + let event = zm_api::entity::events::ActiveModel { + monitor_id: Set(monitor.id), + storage_id: Set(Some(storage.id)), + scheme: Set(Scheme::Shallow), + state_id: Set(1), + name: Set(format!("Event {}", unique_name("p"))), + frames: Set(Some(10)), + length: Set(Decimal::new(100, 2)), + width: Set(64), + height: Set(48), + default_video: Set(String::new()), + ..Default::default() + } + .insert(&app.db) + .await + .unwrap(); + let id = event.id; + let _g = ( + RowGuard::new(format!("Events#{id}"), move |db| async move { + use zm_api::entity::{events, media_jobs}; + let _ = media_jobs::Entity::delete_many() + .filter(media_jobs::Column::EventId.eq(id)) + .exec(&db) + .await; + let _ = events::Entity::delete_by_id(id).exec(&db).await; + }), + RowGuard::storage(storage.id), + RowGuard::monitor(monitor.id), + ); + + let r = app + .post_json(&format!("/api/v3/events/{id}/videos"), &token, &json!({})) + .await; + assert_eq!(r.status(), StatusCode::ACCEPTED, "{}", r.text()); + let job_id = r.json::()["id"].as_u64().unwrap(); + let status = || async { + let job: serde_json::Value = app + .get(&format!("/api/v3/jobs/{job_id}"), &token) + .await + .json(); + job["status"].as_str().unwrap().to_string() + }; + let as_server_one = || { + let mut state = zm_api::server::state::AppState::for_test_with_db(app.db.clone()); + state.cluster = Arc::new(Cluster::new(Some(1), &ClusterConfig::default(), 0, false)); + state + }; + + // The storage is server 2's: server 1's worker takes nothing. + let mut row: zm_api::entity::storage::ActiveModel = storage.into(); + row.server_id = Set(Some(2)); + let storage = row.update(&app.db).await.unwrap(); + assert_eq!( + zm_api::service::media_jobs::run_pending(&as_server_one()).await, + 0 + ); + assert_eq!(status().await, "queued"); + + // Once it is shared, server 1 may run the job (it fails here: no frames, + // and that is all this test needs to see). + let mut row: zm_api::entity::storage::ActiveModel = storage.into(); + row.server_id = Set(None); + row.update(&app.db).await.unwrap(); + assert_eq!( + zm_api::service::media_jobs::run_pending(&as_server_one()).await, + 1 + ); + assert_ne!(status().await, "queued"); +} diff --git a/tests/it_retention.rs b/tests/it_retention.rs index fefd151..9554214 100644 --- a/tests/it_retention.rs +++ b/tests/it_retention.rs @@ -351,3 +351,62 @@ async fn reap_dry_run_reports_but_deletes_nothing() { assert!(event_exists(&db, e2).await, "dry-run must not delete e2"); assert!(event_exists(&db, e3).await, "dry-run must not delete e3"); } + +/// A storage that belongs to another server holds files this host can't see +/// or measure. The reaper leaves its events and rows alone, however far over +/// quota the rows say it is, and still reaps a storage every server shares. +#[tokio::test] +#[ignore = "requires the test database (APP_PROFILE=test-db)"] +async fn reap_leaves_another_servers_storage_alone() { + let iso = common::isolated::IsolatedDb::create().await; + let db = iso.connect().await; + let monitor = insert_monitor(&db, "ReapPeerMon").await.expect("monitor"); + let _mg = RowGuard::monitor(monitor.id); + + let mut results = Vec::new(); + // Held to the end: dropping a guard deletes its row. + let (mut guards, mut dirs) = (Vec::new(), Vec::new()); + for (label, server) in [("ReapPeer", Some(2u32)), ("ReapShared", None)] { + let tmp = tempfile::tempdir().unwrap(); + let (storage, guard) = dedicated_storage(&db, &tmp, label).await; + let mut row: zm_api::entity::storage::ActiveModel = storage.into(); + row.server_id = Set(server); + let storage = row.update(&db).await.expect("server"); + + let base = zm_api::util::time::utc_now(); + let mut events = Vec::new(); + for (hours, name) in [(3, "old"), (1, "new")] { + let id = insert_event( + &db, + monitor.id, + storage.id, + base - jiff::SignedDuration::from_hours(hours), + true, + 0, + 100 * MIB, + name, + ) + .await; + make_event_dir(tmp.path(), monitor.id, id); + events.push((id, guard_event(id))); + } + // Over quota by a wide margin: the oldest would go on a storage this + // host owns. + let deleted = service(quota_config(50 * MIB, false), &iso) + .await + .with_server_id(Some(1)) + .reap_storage_once(&storage, false) + .await + .expect("reap"); + results.push((deleted, events.first().map(|(id, _)| *id))); + guards.push((events, guard)); + dirs.push(tmp); + } + + let (peer_deleted, peer_old) = &results[0]; + assert_eq!(*peer_deleted, 0, "another server's storage is not reaped"); + assert!(event_exists(&db, peer_old.unwrap()).await); + let (shared_deleted, shared_old) = &results[1]; + assert_eq!(*shared_deleted, 1, "shared storage still is"); + assert!(!event_exists(&db, shared_old.unwrap()).await); +}