diff --git a/CHANGELOG.md b/CHANGELOG.md index 231491d..c0e930b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,16 @@ recognisable path forward. ### Added +- **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 +28,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 +285,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/book/src/guide/multi-server.md b/book/src/guide/multi-server.md index ac0c186..7fdb681 100644 --- a/book/src/guide/multi-server.md +++ b/book/src/guide/multi-server.md @@ -21,7 +21,28 @@ What is relayed: - 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. + +## 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 +71,31 @@ 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. + ## 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. +- **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..c5f5b5d 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": { @@ -19626,6 +19972,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 +19994,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": { @@ -19729,13 +20136,90 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PrivacyResponse" + "$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" } } } }, - "default": { - "description": "Error", + "421": { + "description": "The server named by `server_id` has no address", "content": { "application/json": { "schema": { @@ -19743,29 +20227,13 @@ } } } - } - }, - "security": [ - { - "jwt": [] - } - ] - } - }, - "/api/v3/system/restart": { - "post": { - "tags": [ - "System" - ], - "summary": "Perform full system restart.", - "operationId": "system_restart", - "responses": { - "200": { - "description": "System restarted", + }, + "502": { + "description": "The server named by `server_id` did not answer", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DaemonActionResponse" + "$ref": "#/components/schemas/AppResponseError" } } } @@ -19805,6 +20273,17 @@ ], "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" + } + } + ], "responses": { "200": { "description": "System shutdown initiated", @@ -19816,6 +20295,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": { @@ -19931,6 +20460,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 +20482,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 +20566,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 +20600,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 +20648,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 +20670,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 +22460,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 +22997,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 +27887,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 +34736,54 @@ } } }, + "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": { + "type": [ + "object", + "null" + ], + "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/forward.rs b/src/cluster/forward.rs index 87f2a99..6d9b9ff 100644 --- a/src/cluster/forward.rs +++ b/src/cluster/forward.rs @@ -95,36 +95,116 @@ 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, one for a server with no address, and a +/// WebSocket; send 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", + "{what} {}; a WebSocket is not relayed, so connect to {} or use WHEP", peer.label(), peer.base_url ))); } - 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::() @@ -195,7 +275,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..9018f03 100644 --- a/src/cluster/mod.rs +++ b/src/cluster/mod.rs @@ -15,12 +15,13 @@ //! the same JWT key files. pub mod forward; +pub mod system; -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 +53,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 +124,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, @@ -87,6 +151,14 @@ pub struct Cluster { client: reqwest::Client, 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 { @@ -110,6 +182,7 @@ impl Cluster { client: build_client(config), servers: Mutex::new(None), owners: Mutex::new(HashMap::new()), + events: Mutex::new(HashMap::new()), } } @@ -164,6 +237,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 +326,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 { @@ -300,6 +474,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/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..1acaebe 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/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/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..8e6452d 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -542,7 +542,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 +566,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 @@ -670,7 +673,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 +722,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/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..05573e8 --- /dev/null +++ b/tests/common/cluster.rs @@ -0,0 +1,152 @@ +//! 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) +} 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..cf45177 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)"] @@ -596,3 +501,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_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); +}