Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,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 and system-wide control are 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
Expand Down Expand Up @@ -268,6 +275,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.
Expand Down
25 changes: 23 additions & 2 deletions book/src/guide/multi-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -55,7 +76,7 @@ If the servers use certificates from a private CA, point `cluster.tls_ca_file` a
- **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.

Expand Down
96 changes: 88 additions & 8 deletions src/cluster/forward.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,30 +95,110 @@ 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<AppState>,
params: RawPathParams,
request: Request,
next: Next,
) -> Result<Response, AppError> {
if !state.cluster.relays() {
return Ok(next.run(request).await);
}
let Some(event_id) = path_event_id(&params) 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<u64> {
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.
async fn relay_to_server(
state: &AppState,
server_id: u32,
what: &str,
path_and_query: &str,
request: Request,
) -> Result<Response, AppError> {
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
Expand Down
Loading
Loading