Architecture
How the code is cut up and which crate owns what.
Crates
| Crate | Owns | Depends on | I/O |
|---|---|---|---|
probeward-model | Shared domain types: ids, health, freshness, poll outcome, limits, credentials. | — | none |
probeward-engine | The state, scheduling and alert engine. Pure and deterministic. | model | none |
probeward-sensors | Sensor implementations, sensor and device templates, discovery fingerprinting. | model | network, behind traits |
probeward-librenms | Converts the device definitions of a LibreNMS checkout into device templates, with a report of what could not be converted. Ships no LibreNMS files. See LibreNMS import. | sensors | reads files only |
probeward-store | PostgreSQL schema, migrations, repositories, metrics storage and retention, credential vault. | model | PostgreSQL |
probeward-server | The probeward binary: HTTP API, auth, audit, live push, runtime (drives engine and sensors), notification delivery, heartbeat, discovery jobs, embedded UI. | all of the above | everything |
ui/ | Vue 3 + TypeScript + Vite + Pinia + ECharts single-page app, embedded into the binary. | the HTTP API only | — |
Rules:
modelis the contract. It changes rarely and deliberately.enginenever touches a socket, a file, the database or the system clock. Every entry point takesnowas an argument. This is how "time is injectable" is met.sensorsnever touches the database. A sensor is given a target, parameters and a credential and returns aPollOutcome.storeknows nothing about HTTP.serveris the only place where these meet.
The engine
The engine holds the runtime state of every sensor and decides what happens next. It is a synchronous state machine:
Engine::handle(now, Input) -> Vec<Effect>
Engine::next_wakeup() -> Option<Timestamp>- Inputs: a configuration snapshot (the resolved tree: sensors with effective interval, timeout, failure count, limits per channel, pause, device, master check, explicit dependencies, notification rules with their schedules, monitoring schedule, per-device concurrency; plus the schedules and maintenance windows themselves), a clock tick, a finished poll, and the control actions (scan now, acknowledge, timed pause and resume, simulate error and clear), plus probe connected/disconnected.
- Effects: start a poll, record a sample, a sensor state change, an incident opened / repeated / recovered, a notification event to deliver, a timeline entry (state change, suppression with its reason, control action).
- The engine also owns poll scheduling: the stable per-sensor offset, timeouts, the per-device concurrency limit, never starting a poll twice, and counting missed intervals.
- State is serialisable so the runtime can persist it and restore it after a restart without re-paging for incidents that are already open.
The runtime in server is a thin loop: sleep until next_wakeup, feed inputs, carry out effects. Scenario tests drive the same engine with a simulated clock and scripted poll results.
Inheritance resolution (credentials, interval, notification rules, pause, concurrency limit, flowing Probe → Group → Device → Sensor, with the source of each effective value) is a pure function in the engine crate, used by both the runtime and the API.
Schedules and maintenance windows
The engine evaluates calendars itself (probeward-engine/src/calendar.rs): the configuration carries each schedule and window as defined (zone, ranges, exception dates, timing), and the engine turns them into instants, keeps per calendar whether it is in force and when that next changes, and arms a wake there, so next_wakeup covers every transition. The rules, including the daylight saving rule, are in schedules and maintenance.
The alternative was for the server to resolve calendars into a list of transitions and feed them to the engine as inputs. It was not chosen because:
- The behaviour that matters (no page during a window, a burst-free page after it, a delayed page when a schedule opens, nothing lost across a restart) is alerting behaviour. With the calendars inside the engine, the scenario tests drive it with the simulated clock like every other rule; resolved transitions would split it between a server component and the engine, with the join tested only against the database.
- A restart needs no stored transition list and no catching up: the engine recomputes every calendar from the configuration and the clock, and only per-sensor consequences (halted, in maintenance, destinations still waiting) live in the snapshot. Snapshots from before this change load with those fields empty.
- Ending a window early or extending it is a configuration change like any other, applied at once.
The cost is a time zone database in the engine. It uses jiff 1.0 with its bundled copy of the IANA database (jiff-tzdb), so results do not depend on the host's /usr/share/zoneinfo and every installation of one version agrees. Both crates are Unlicense OR MIT. Measured on a minimal release binary that resolves one local time in one zone: 330,800 bytes with no zone support, 886,776 bytes with jiff and its bundled database, and 2,237,008 bytes with the chrono-tz alternative, which was therefore not used. The rest of the code keeps chrono for instants; jiff is used only inside the calendar module.
The server only presents calendars: the API computes open_now, next_change and upcoming occurrences with the same engine functions, so what the UI says and what the engine does cannot drift apart.
Observation model
Three aspects, kept apart:
- Health —
Up,Warning,Down, from the last successful poll: the worst of the per-channel limit evaluations and the sensor's own verdict. - Freshness —
Fresh,CollectionFailure(the last poll failed),Unknown(never sampled, stale, or the probe is not reporting), with a reason. The last good sample stays visible. - Handling — acknowledged, paused, suppressed by dependency, simulated. Never changes health.
A sensor is failing when its last poll failed or its health is Down. Consecutive failing polls up to the configured count open an incident. Warning is visible but does not page unless a notification rule opts in.
Sensors
#[async_trait]
pub trait Sensor: Send + Sync {
async fn poll(&self, ctx: &PollContext, previous: Option<serde_json::Value>) -> PollOutput;
}
pub struct PollOutput { pub outcome: PollOutcome, pub state: Option<serde_json::Value> }PollContextcarries the target, the credential, the timeout and the protocol clients (traits), so tests can script responses.previous/stateis an opaque per-sensor blob the runtime hands back on the next poll. Counter sensors use it to compute rates; a counter reset or a first sample yields an unknown rate.- A sensor is identified by a
kindstring (ping,snmp_interface,win_cpu,proxmox_backupand so on; the full list is the sensor reference) plus a JSON parameter object. The registry validates parameters and builds the sensor. A kind can need an SNMP, SSH, Windows or genericsecretcredential, required or optional, and can be marked admin-only (the kinds that run programs). - Besides the network clients,
Clientsholds a DNS client, an HTTP client that returns headers and a bounded body, and the one place that starts local programs (proto/exec.rs), which only runs files from the directory named byPROBEWARD_SCRIPT_DIR. See scripts. - Each kind has a sensor template (YAML, embedded in the binary): display name, description of what failure means, suggested interval, and channels with stable key, name, unit and default limits. Device templates say which sensors attach when a fingerprint matches.
- Discovery fingerprinting (ICMP, TCP banners, SNMP
sysObjectID) lives here too, behind the same protocol traits.
Derived sensors
The combined and business_process kinds take their result from other sensors. They are never polled and never leave the core: no probe is involved, and nothing is sent over the network. The combined and business process pages describe what an operator sees; this section says how the engine does it.
Where evaluation happens. In the engine. A derived sensor carries a DerivedConfig in its SensorConfig (the way a push sensor carries a PushConfig): the sources it reads and the rules or functions to apply. The engine evaluates it and feeds the result through the same path as a finished poll (apply_result), so the sample, the limits, the failure count, suppression by dependencies, maintenance windows, incidents and notifications all behave as for any sensor. Evaluating in the server instead and injecting the result as a push would have split the alerting behaviour between two components, and the scenario tests could not have driven it with the simulated clock.
Inputs. Only what the engine already holds: for each source its current status (health, freshness, handling, failure streak against its failure count) and the channel values of its last good sample. The evaluation is a pure function from those readings and the configured rules to a PollOutcome (derived.rs); it reads no clock and no store. A source is read as one of:
Up,Warning,Down: fresh and healthy, fresh with limits crossed, or fresh with aDownhealth. A source whose last poll failed counts asDownonce it has reached its own failure count (it is confirmed failing, the same test dependencies use) and asWarningbefore that, so one lost poll does not turn a process red.Unknown, with a reason: the source no longer exists, is paused, outside its monitoring schedule or in a window that stops polling, has never been sampled, is stale, or its probe is not reporting. An unknown source has no value either: values are taken only from a fresh sample, never from the last good sample of a failing or silent source.
Maintenance windows that keep polling, acknowledgements, suppression and simulation do not change how a source is read: they are handling, not health.
Unknown, paused, stale and deleted sources. The sensor's unknown_as setting says how an unreadable source counts towards a rule: as warning (the default, so it is visible and pages nobody unless a notify rule opts in), as down, or not at all (ignore). A source that is only settling (not sampled yet, or being polled again after a pause or a reconnect) is always left out, so a new sensor or a restart cannot turn a process red while its sources report in. A deleted source is an unknown source with the reason "no longer exists"; the sensor keeps working on the rest and says so in its message. A combined channel with an unavailable input is an unknown value by default (missing: unknown) or is calculated from the inputs that are there (missing: skip). When nothing can be read (every source is unknown, whatever unknown_as says) the sensor becomes Unknown with the reason SourcesUnknown: it does not invent a failure, does not count towards its failure count, and neither opens nor recovers an incident. That is also what happens after a restart, when every source is briefly stale at once: a gap in monitoring is not a verdict. It evaluates again as soon as a source is readable.
Cycles. A derived sensor may read another derived sensor, so the sources form a graph. validate_config rejects a cycle among derived sensors (ConfigError::DerivedCycle, a sensor naming itself included), and the API runs the same validation when a derived sensor is created or changed, before it is saved. A derived sensor cannot be a master check or a dependency (ConfigError::DerivedNotPollable): nothing can ask it to confirm its state. The engine evaluates in source order and a pass over the sensors is bounded by their number, so a configuration that somehow slipped through cannot spin.
Time. Evaluation takes now like every engine entry point. A derived sensor is evaluated on its own interval grid, which counts as a poll towards its failure count, and once more straight away whenever the reading of one of its sources changes class (up, warning, down, unknown), so a business process does not wait a whole interval to learn that a source went down. Value-only changes of a source wait for the next slot: the sensor does not write a sample for every sample of every source. Scan now evaluates at once; a pause, a closed monitoring schedule or a stop-polling window halts it as it halts a poll. The last class of each source is kept in memory only: after a restart or a configuration change that alters the sources the sensor evaluates once, and otherwise nothing is recomputed that did not change.
Access. The source ids are parameters of the sensor. The API refuses a source the caller cannot read, so a branch operator cannot make a sensor in their branch report the state or the values of sensors outside it.
Storage
- Plain PostgreSQL 18+, no required extensions, native range partitioning by day for scan rows.
- One row per sensor scan; channel values keyed by
ChannelKey. - Raw retention is enforced by dropping whole partitions. Default 30 days.
- 5-minute and hourly rollups (min, max, sum, count per channel, and poll counts by health) are computed incrementally by the housekeeping task, with a watermark per level and a mark for late scans, and have their own partitions and retention (90 days and 730 days). See storage.
- The credential vault uses envelope encryption: a data key per credential, wrapped by a master key that is read from a file outside PostgreSQL.
- Metrics storage is behind a trait so another backend can be added.
Server
- REST API under
/api/v1, described by an OpenAPI document served at/api/v1/openapi.json. The UI uses only this API. - Session-cookie authentication for the UI (local users with Argon2id and optional TOTP, or OpenID Connect). State-changing requests need the
X-Probeward-CSRFheader. One authorisation layer (authz/) decides every request from tree-scoped grants; see access control. - Every configuration change and control action writes an audit record: actor, action, object. Scripts authenticate with personal API tokens (
Authorization: Bearer), which need no CSRF header and set no cookie; the audit record of a change made with one names the token and its owner. See API. - Push sensors take their results from an inbound HTTP request (
POST /api/v1/push/{token}). The engine treats the report as the poll result of a sensor that is never polled (Input::Pushed), and silence as staleness. See HTTP push. - Receiver sensors (
snmp_trap,syslog) are polled like any sensor, but what they count is what a device sent to the probe. One receiver per probe process (probeward-sensors/src/proto/receiver/) opens UDP 162 and UDP and TCP 514 when the first such sensor is polled and keeps a bounded in-memory store of the messages of the devices the sensors watch, with a token bucket per source. A poll counts the matches in a sliding window and hands the newest matches to the core asSensorEvents in its result; the journal writes them tosensor_events, which the sensor's page reads. The engine is unchanged and never sees a message. The design, the limits and what a probe needs are in receivers. NetFlow, IPFIX and sFlow collectors (proto/flow/) follow the same life cycle and keep only per-interval top lists; see flow collectors. - The tree can be exported as files and imported from files (
configfiles/). The pieces are separate on purpose:yaml(a strict reader and a deterministic writer),docandlayout(the document model and its two file layouts),export(tree to document, reading settings generically so a new setting is exported without changes there),import(document to tree, with the API's own validation, and the comparison that becomes the plan),service(loading and applying) andcli. The writes are one transaction inprobeward-store::config_apply, which compares the configuration revision under its lock. See export and import. - Live updates are pushed to the UI over Server-Sent Events at
/api/v1/events. - Notification delivery is its own pipeline with an injectable clock and a transport trait: per-destination delivery records, retries that reuse the event id, and a visible final state.
- The heartbeat is sent only while scheduler, database and notification pipeline are healthy.
- The local probe is the in-process executor that carries out the engine's "start poll" effects. The tree always contains one probe node for it.
- Remote probes (
probeward probe) dial out to a dedicated mutual-TLS listener and carry out the polls of their sensors that the engine starts, through the probe hub (runtime/probes.rs). While disconnected they poll on the engine's schedule and buffer; replayed samples go to history only, so the engine stays the single decider. See probes and the protocol. - Self-observability (
telemetry/) is optional and off unless an OTLP endpoint is configured. Atracinglayer turns the spans this crate creates with the targetprobeward_otel(theotel_span!macro) and the events the log filter lets through into OTLP messages and pushes them on bounded queues, dropping the oldest when full; exporter tasks, one per signal, post them over HTTP and back off when the collector fails; a metrics task reads the runtime's health counters, the live sensor statuses, the database pool and the probes' stored status at each interval, plus the few histograms the poller, the HTTP middleware, the delivery worker and the loop feed. Nothing touches the engine: it stays pure and takes no trace context, which is why a delivery is linked to its incident by ids and not as a child span. When it is off, no layer is installed, so the exported spans are disabled at their callsites. See telemetry.
Flow collectors
NetFlow (v5, v9), IPFIX and sFlow (v5) exporters send a description of the traffic that crossed a router or switch. Probeward collects it with two more receivers (next to the trap and syslog ones: same life cycle, same idea of limits) and shows it as the netflow and sflow sensors. These decisions were taken before the code and the code follows them; the operator's side is in the NetFlow and IPFIX sensor and the sFlow sensor.
Principle: store aggregates, never flows. A flow record is read, added to a few bounded counters and forgotten. No flow, no packet and no raw datagram is kept, in memory or in the database. Everything below is a limit on a count.
exporter ──UDP 2055 (NetFlow, IPFIX), UDP 6343 (sFlow)──▶ collector (one per probe process)
watched exporters only, token bucket per exporter, template cache per exporter
│ decode (pure functions of the bytes and the time)
▼
interval being filled: bounded tables by host, conversation and service
│ at the end of the interval: keep the top entries, drop the tables
▼
finished intervals (memory, bounded, retention) ◀── sensor poll: "the last N seconds of this exporter"
│ channels (limits apply), one summary event
▼ core: channel history, sensor_eventsListener. One collector per probe process, like the trap and syslog receivers: the first poll of a flow sensor opens the port its kind needs (UDP 2055 for netflow, which reads NetFlow v5, v9 and IPFIX from the same port by the version in the header; UDP 6343 for sflow) and it stays open. A probe with no flow sensor listens on nothing. Both ports are above 1023, so the defaults need no capability. The addresses come from PROBEWARD_FLOW_LISTEN and PROBEWARD_SFLOW_LISTEN. The code has the receivers' shape: ingest is a function of (exporter address, bytes, time), the socket loops only read and hand over, and sensors reach the collector through a trait (FlowClient) that tests script. A remote probe collects on its own sockets and sends only the sensor's result to the core.
Who an exporter is. The source address of the datagram, as for traps and syslog. A sensor watches its device's address and the extra_sources it names. A datagram from any other address is counted and dropped before it is decoded. The agent address inside an sFlow datagram is not used: it is not the source of the datagram when the router sends from another interface, and it can be forged.
Aggregation. Per exporter, per interval of PROBEWARD_FLOW_INTERVAL_SECS (60 s, aligned to the clock, by the time the datagram was received and never the exporter's clock), a flow adds its bytes, packets and one flow to:
- the totals and four classes (TCP, UDP, ICMP, other);
- a table of source hosts, a table of destination hosts, a table of conversations (source, destination, IP protocol, service port, one direction) and a table of services (IP protocol and service port, such as
tcp/443).
The service port is the lower of the two ports when it is at most 49151, else 0 (an ephemeral pair): the server side of a conversation, without knowing which side it is. A table holds at most PROBEWARD_FLOW_KEYS keys (1,024; 512 for services). When a table is full, a new key replaces the smallest of eight keys sampled from it and the replaced key's counts go to an "other" entry, so the totals stay exact, a scan with millions of source addresses costs a fixed amount of memory, and a heavy talker is not pushed out by it. The interval is marked approximate when that happened. Counts are multiplied by the exporter's sampling rate before they are added (below).
Interfaces. A sensor can ask for one interface and a direction (in, out or either), which is how limits apply "per exporter and interface". Interfaces are not tabulated for every flow: a sensor that names one asks the collector to keep a second set of tables, a scope, for it, and the collector keeps one only for the interfaces some sensor asked for. An exporter has at most 16 scopes besides the whole exporter.
Storage. At the end of an interval each table is cut to its PROBEWARD_FLOW_TOP biggest entries (20), with the rest summed, and the interval joins the scope's ring of finished intervals. The rings keep PROBEWARD_FLOW_RETENTION_SECS (1 hour, at most one day) and all together at most PROBEWARD_FLOW_BYTES (64 MiB); a scope that would go over gives up its own oldest intervals first. That memory is the whole store: the sensor reads from it, and a restart of the probe is a gap, not a page. What reaches the database is only what a sensor reports:
- the channel values of every poll, in the ordinary history and its rollups;
- at most one summary event per poll, for the intervals finished since the last poll: the totals and the top sources, destinations, conversations and services with their shares. They are kept as
sensor_eventsfor the timeline's retention, at most 1,000 per sensor, so a sensor's page can show who talked yesterday.
Sensors and channels. The sensor's poll sums the finished intervals of the last window_secs and reports bits, packets and flows per second, the biggest source, destination and conversation (rate and share of all traffic), the rate of TCP, UDP, ICMP and other, the busiest service, the number of active sources, the time since the exporter last sent, and what was dropped, lost or unreadable. Every channel can have limits. The poll's message names the top few. A window longer than what the ring holds, or an interval that was approximate, is reported as a minimum in the message. Intervals that have not finished are not counted, and a sensor whose exporter has been watched for less than one interval reports no rates yet.
NetFlow v9 and IPFIX templates. A data set can be read only with the template the exporter sent earlier, so each exporter has a template cache, keyed by observation domain and template id. A template is kept for PROBEWARD_FLOW_TEMPLATE_SECS (30 minutes) after it was last seen, replaced when it is sent again, and withdrawn when the exporter says so (IPFIX). Data for an unknown template is counted as undecoded and shown by the sensor, because that is what a restarted collector shows until the exporter's next refresh. Options templates are read for one thing: the exporter's sampling interval. A template may have at most 256 fields, an exporter at most 8 domains and 64 templates in all.
Sampling. A sampled exporter reports one packet in N. The collector scales bytes, packets and flows by N: the rate in the NetFlow v5 header, the sampling interval of a v9 or IPFIX options record, and the rate of each sFlow sample. A sensor can set the rate for an exporter that samples without saying so. Scaled counts are estimates, and the sensor's message says that the traffic is sampled and at what rate.
Limits. Every count has a limit; a value that does not parse or is out of range is ignored, so a typo cannot switch a protection off.
| Limit | Default | Variable |
|---|---|---|
| Datagrams per second one exporter may send, sustained | 2,000 | PROBEWARD_FLOW_RATE |
| Datagrams one exporter may send at once | 4,000 | PROBEWARD_FLOW_BURST |
| Exporters watched at once on one probe | 256 | PROBEWARD_FLOW_EXPORTERS |
| Interval length | 60 s | PROBEWARD_FLOW_INTERVAL_SECS |
| Keys per table in the interval being filled | 1,024 | PROBEWARD_FLOW_KEYS |
| Entries kept per table in a finished interval | 20 | PROBEWARD_FLOW_TOP |
| How long finished intervals are kept | 3,600 s | PROBEWARD_FLOW_RETENTION_SECS |
| Bytes kept in finished intervals, all exporters | 64 MiB | PROBEWARD_FLOW_BYTES |
| How long an exporter stays watched after its sensor last asked | 6 h | PROBEWARD_FLOW_WATCH_SECS |
| How long a template is kept without being seen | 30 min | PROBEWARD_FLOW_TEMPLATE_SECS |
| Flow records read from one datagram | 4,096 | fixed |
| Fields in a template; templates and domains per exporter | 256; 64 and 8 | fixed |
| Interface scopes per exporter | 16 | fixed |
| Interfaces whose sFlow counters are followed per exporter | 256 | fixed |
| Largest sampling rate accepted | 1,000,000 | fixed |
| Top entries a sensor's summary event carries | 10 | fixed (top_n, at most 10) |
Capacity: the interval being filled costs at most about 300 KiB per watched scope (three tables of 1,024 keys and one of 512, with the hash tables' spare room) and a finished interval at most about 6 KiB (counted generously), so 256 exporters with one scope each use at most about 80 MiB in the tables being filled, plus the ring's 64 MiB; a typical probe with a few exporters uses a few MiB. CPU is bounded by the datagram rate limit; the measured cost of a record is on the sensor page. What a probe cannot keep up with is dropped by the kernel's receive buffer (4 MiB requested), which the collector cannot see; the sequence numbers of NetFlow v5, v9 and sFlow datagrams are read for exactly that (IPFIX counts records, which cannot be known for data that has no template yet), and the sensor reports datagrams missing in the sequence as lost.
Hostile input. Every length in a datagram is checked against the bytes that are there before it is used, nothing is allocated from a number in the datagram, loops are bounded by the bytes left or by a fixed count, and a datagram that fails a check is counted as unreadable and dropped whole. The decoders are tested with hand-made packets and with truncated, mutated and random input, which must never panic.
Alternatives not taken. Storing flows in PostgreSQL: the volume (thousands per second) is the very thing the design refuses to carry, and nothing a sensor needs requires one flow. Aggregating in the core: every datagram would have to cross the probe protocol, where today only a poll result does. One sensor kind for both protocols: the ports, the template handling and the documentation differ, and a router sends one or the other.
Configuration
Environment variables, prefixed PROBEWARD_ except the standard OTEL_* ones of telemetry export. The main ones are below; configuration lists every one.
| Variable | Meaning | Default |
|---|---|---|
PROBEWARD_DATABASE_URL | PostgreSQL connection string | required |
PROBEWARD_LISTEN | HTTP listen address | 127.0.0.1:8080 |
PROBEWARD_VAULT_KEY_FILE | Path to the vault master key (created on first start if absent) | ./data/vault.key |
PROBEWARD_PUBLIC_URL | Base URL used for links in notifications | http://localhost:8080 |
PROBEWARD_LOG | Log level / filter | info,sqlx::postgres::notice=warn |
PROBEWARD_SCRIPT_DIR | Directory of programs the script and nagios_plugin sensors may run | unset (no programs run) |
OTEL_EXPORTER_OTLP_ENDPOINT and the other telemetry variables | Where to send Probeward's own logs, metrics and traces | unset (nothing is sent) |
Development
just lists the recipes. just dev-up starts PostgreSQL (port 54329) and Mailpit (SMTP 54325, web 54326). just test runs everything except the capacity test.