LabwereldHomeInstallationConnectorsWorld modelDownloadNederlands

Connectors

Nederlands

A connector links one existing service to Labwereld. It reads the service (read-only) and translates what it sees into observations. The composer merges the observations of all connectors into the world model (world-model.html); frontends cannot tell which source delivered what.

service ──► connector.poll() ──► Batch ──┐
service ──► connector.poll() ──► Batch ──┼─► Composer.build() ──► world ──► SSE
service ──► connector.poll() ──► Batch ──┘        (runtime.py schedules the rounds)

Status of all connectors: /status/ in the browser, or GET /api/connectors (per connector the interval, last successful round, error, what it delivers as counts, and the minimal right; no contents).

Existing connectors

NameFileIntervalDelivers
zabbix (or demo)collector/connectors/zabbix.pycollector.interval (30 s)nodes, measurements, status, backups (PBS/Borg), tunnels, Plex via Zabbix items
zabbix-alarmencollector/connectors/zabbix.pyzabbix.problems_interval (10 s)open problems; fetched separately and more often because that call is light
prometheus (configurable name)collector/connectors/prometheus.pycollector.interval (30 s)machines with node_exporter: cpu, memory, load, disk, network, uptime, disk temperature (smartctl_exporter, hwmon), up as status; matched on host name
docker (configurable name)collector/connectors/docker.pycollector.interval (30 s)containers of one Docker host (state, health, restarts, cpu over two rounds, memory, image, start)
opnsense-<site>collector/connectors/opnsense.pycollector.interval (30 s)WAN traffic and gateway of a site, WireGuard tunnels as links (handshake → status, counters → traffic), WAN on the firewall node
proxmox-<site>collector/connectors/proxmox.pycollector.interval (30 s)hypervisor and guests (state, cpu, memory, network, also without an agent), unknown running guests, tasks
pbs-<site>collector/connectors/pbs.pycollector.interval, at least 60 sbackups per guest straight from Proxmox Backup Server
backup-status (configurable name)collector/connectors/backupstatus.pycollector.interval, at least 60 sbackups from any tool via JSON records the script writes itself (open backup status)
unificollector/connectors/unifi.pyunifi.interval (30 s)network devices, client counts, WAN traffic; unifi.timeout (20 s) per call, at most two at a time; three missed rounds in a row before the source counts as gone
plex-relaycollector/connectors/plex_relay.pyimmediate (push), fallback 30 sPlex sessions with artwork within seconds, via the bundled relay on the Plex host
tautulli (or tautulli-<service>)collector/connectors/media.pycollector.interval, at most 15 sPlex sessions with artwork via Tautulli, without Zabbix
jellyfin (or jellyfin-<service>)collector/connectors/media.pycollector.interval, at most 15 sJellyfin sessions with artwork, without Zabbix
paperless (or paperless-<service>)collector/connectors/paperless.pycollector.interval, at most 15 sincoming documents, queue and failed processing from Paperless-ngx; the Zabbix connector delivers the copy elsewhere

The order of the connectors is their precedence: for a measurement the first source with a value wins. For status, a source that can prove up or down wins over a source that only knows unknown.

Writing a connector

from collector.connectors.base import Connector, ConnectorError
from collector.observations import Batch, NodeObs, NodeSpec

class ExampleConnector(Connector):
    name = "example"        # shows up in world.sources
    interval = 30           # seconds between two rounds
    grace = 300             # how long the previous batch still counts after a failure (None = forever)
    provides_metrics = True # delivers cpu/memory/network of nodes

    def poll(self) -> Batch:
        try:
            data = ...      # read-only call to the service
        except OSError as exc:
            raise ConnectorError(str(exc)) from None
        return Batch(
            source=self.name, taken_at=time.time(),
            specs=[NodeSpec("nas", "NAS", "home", "nas", "nas", auto=True)],  # new nodes
            nodes=[NodeObs("nas", {"cpu_pct": 12.5}, "up", "API reports running")],
        )

Rules:

  • Read-only. No write calls; document the minimal right.
  • Only what is proven. Leave a measurement out (or None) if you do not have it. A status always comes with a reason.
  • Privacy. No names of network clients or viewers, no IP or MAC addresses in a Batch (except in clients, which is internal for events only and never published).
  • Secrets via *_FILE environment variables; never log them.
  • Push sources keep a connection open themselves (a thread) and announce new data with ready() and the wake event; the scheduler then runs them immediately (see the Plex relay connector).
  • Tests with a fake source: keeping observe() separate from fetch() makes that easy (see the Zabbix and UniFi connectors).

Identity across sources

Every NodeSpec can carry recognition hints (hints): normalised host names (names), IP addresses (ips) and site + VMID (site_vmid). When a connector discovers a node that does not exist yet, the composer first looks for an existing node with the same site and VMID, then the same IP, then the same host name on the same site. On a match they become one node, and problems, tasks and backups refer to that single id. This way a host discovered by Zabbix and the guest Proxmox sees become one machine.

[[node]] blocks in the configuration are optional: they fix names, roles, sites and links (Zabbix host name, hypervisor + VMID). Without blocks the world is built entirely from discovery; see config/voorbeeld.toml.

A discovered node you do not want to see in the world (a test machine, an old guest) is hidden with:

[discovery]
ignore = ["ubuntu-test", "home-old-vm"]   # ids as /beheer/ shows them

The composer leaves those nodes out; alarms stay visible, but without a reference to the hidden node. An id that is also described as a [[node]] is an error. In /beheer/ (tab Nodes) this is one click, just like adopting a discovered node as a [[node]].

Zabbix items Labwereld recognises

Ordinary measurements come from the standard Zabbix agent items (system.cpu.util, vm.memory.utilization, net.if.in[…], vfs.fs.dependent.size[…,pused], the Docker by Zabbix agent 2 template, …); change them per node with metrics. There is no standard for backups, disk temperatures and media, so Labwereld recognises the items below. The names are a Labwereld convention and configurable per installation, so existing scripts can keep working.

Disk temperature (°C), the highest value counts:

[zabbix]
temperature_keys = ["smart.disk.temperature"]   # default: Zabbix's SMART template

Without Zabbix the disk temperature comes from Prometheus (see Setting up Prometheus). If both have a value, the first source in connector order wins.

Backups per guest (Proxmox Backup Server shape), on the backup server's host:

<prefix>last_backup["<store>/<namespace>/<vm|ct|host>/<id>"]   unix time of the last successful backup
<prefix>max_age[…]                                             maximum age in seconds
<prefix>error[…]                                               error message, empty = fine
[backups.pbs]
item_prefix = "labwereld.backup.group."          # default
namespaces = { home = "home" }                   # namespace → site; together with the id this finds the guest

Backups per repository (such as Borg), on the host that makes the backup:

<prefix>last_success[<repo>]   unix time
<prefix>max_age[<repo>]        seconds
<prefix>error[<repo>]          empty = fine
[backups.borg]
item_prefix = "labwereld.backup.repo."           # default
repos = { photos = "nas" }                       # repository → node being backed up

Media: an item with JSON {"ok": 1, "count": 1, "sessions": [{"key", "type", "title", "show", "state", "progress", "transcode"}]} and optionally an item with pixel art {"ok": 1, "art": {"<key>": {"w", "h", "px"}}} (see world-model.html):

[media.plex]
host = "mediaserver"                             # Zabbix host
node = "mediaserver"
key = "labwereld.media.sessions"
art_key = "labwereld.media.sessions.art"

Media also works without Zabbix: via the bundled Plex relay, Tautulli or Jellyfin (see Setting up media). Backups can also come straight from Proxmox Backup Server (see below).

Setting up media (Plex relay, Tautulli, Jellyfin)

What is playing ends up in media.<service> and in Station's cinema. There are four ways; you may fill in more than one per [media.<service>], and then the first one with data wins, in this order: relay, Tautulli, Jellyfin, Zabbix items. The service name is free; plex and jellyfin are the obvious ones. Without node the cinema does not know where it is (/status/ says so).

[media.plex]
node = "mediaserver"                             # node where Plex runs
relay = "http://mediaserver.example.lan:32500"   # the Plex relay (live, see below)
# tautulli = "http://tautulli.example.lan:8181"  # or: Tautulli
# tautulli_key_file = "/config/tautulli-key"

[media.jellyfin]
node = "mediaserver"
jellyfin = "http://jellyfin.example.lan:8096"
jellyfin_key_file = "/config/jellyfin-key"
# art = false                                    # do not fetch pictures
# interval = 15                                  # seconds (default: collector.interval, at most 15)

A note on rights. Plex has no read-only tokens, and the API keys of Tautulli and Jellyfin give full access. That Labwereld only reads is therefore a promise made by Labwereld, not a limit enforced by the source. Labwereld only makes these calls, all GET:

SourceCallsKey
Plex relay/events, on the relay; the relay itself: /:/eventsource/notifications, /status/sessions, /photo/:/transcodenone in Labwereld; the Plex token stays on the Plex host
Tautulli/api/v2?cmd=get_activity, /api/v2?cmd=pms_image_proxyTautulli → Settings → Web Interface → API
Jellyfin/Sessions, /Items/<id>/Images/<type>Jellyfin → Dashboard → API Keys, sent in the Authorization header

That is why the Plex relay is preferred: the token never leaves the Plex host and Labwereld only receives cleaned-up sessions. All three pass on only type, title, series, state, progress, transcode and a picture of at most 64×64 pixels; never users, devices or addresses. If a picture fails, the session plays without one (/status/ reports it).

Plex relay

The relay lives in contrib/plex-relay/: one Python file (standard library only) and a systemd unit. It runs on the Plex host, listens to Plex's notifications and passes on cleaned-up sessions within a second (GET /sessions and GET /events), only to addresses in PLEX_RELAY_ALLOW.

sudo install -d -m 0755 /opt/plex-relay /etc/plex-relay
sudo install -m 0755 contrib/plex-relay/plex_relay.py /opt/plex-relay/
# the Plex token (PlexOnlineToken from Preferences.xml), root only:
sudo install -m 0600 /dev/stdin /etc/plex-relay/token    # paste the token, Ctrl-D
sudo install -m 0644 contrib/plex-relay/plex-relay.service /etc/systemd/system/
sudo systemctl edit plex-relay   # Environment=PLEX_RELAY_ALLOW=127.0.0.1,<address of Labwereld>
sudo systemctl daemon-reload && sudo systemctl enable --now plex-relay
curl -s http://127.0.0.1:32500/sessions

The unit runs as DynamicUser with systemd hardening; the token arrives via LoadCredential. To remove: systemctl disable --now plex-relay and delete the unit, /opt/plex-relay and /etc/plex-relay.

Setting up documents (Paperless-ngx)

Station shows scans flying from the scanner to the archive, and from there to a copy elsewhere (e.g. Nextcloud), if you have one.

[documents.paperless]
url = "https://paperless.example.lan"
token_file = "/config/paperless-token"
node = "docker1"                  # node id where Paperless runs (where the archive is)
# interval = 15                   # seconds (default: collector.interval, at most 15)

# Optional: your own copy job to elsewhere, measured with Zabbix items.
# [documents.paperless.copy]
# target = "nextcloud"            # node id of the copy (or leave out: sheets fly into space)
# label = "Nextcloud"
# host = "docker1"                # Zabbix host with the items below
# last_run = "copy.last_run"              # unix time of the last run
# last_success = "copy.last_success"      # unix time of the last successful run
# result = "copy.result"                  # 0 = good, otherwise failed
# copied = "copy.copied"                  # files in the last run
# copied_total = "copy.copied_total"      # counter; counts better than `copied`
# max_age_min = 60                # no successful copy for longer = failed

Token: create a Paperless user labwereld without admin rights, with only View on Documents (and on Tasks for the queue and failed processing), and create an API token in its profile. Put that token in token_file. Labwereld only does GET on /api/documents/ (fields id and added) and /api/tasks/; titles, content and correspondents are never read. Without rights on tasks the connector still works, but without the queue (shown in notes on /status/).

Paperless itself has no copy elsewhere. If you run your own copy job, let it fill the items above; all items are optional, but host and at least one item are required. Without copy only the scans fly.

Setting up Prometheus

[[prometheus]]
name = "prometheus"                       # name in world.sources
url = "https://prometheus.example.lan"    # without /api/v1
site = "home"                             # optional; otherwise by IP (cidrs)
# token_file = "/config/prometheus-token" # optional: bearer token
# verify_tls = false                      # for a self-signed certificate

Every instance with node_uname_info (node_exporter) becomes a node with the nodename as host name; other targets (Prometheus itself, exporters) are ignored. Minimal right: read access to /api/v1/query.

Disk temperature (disk_temp_max_c, the highest value per machine) comes from two optional sources; whatever is present counts:

  • smartctl_exporter (SMART, all disks). A series belongs to the node_exporter with the same instance, or otherwise with the same host (host name or IP address without port), so the usual setup with a separate port per exporter works;
  • node_exporter itself: the hwmon sensors node_hwmon_temp_celsius of chips whose node_hwmon_chip_names matches nvme|drivetemp (NVMe drives, and SATA drives with the drivetemp kernel module). CPU and motherboard sensors do not count.
[[prometheus]]
# disk_temperature = false                                                 # do not fetch
# smart_temperature = 'smartctl_device_temperature{temperature_type="current"}'  # default; "" = do not use
# hwmon_disk_chips = "nvme|drivetemp"                                      # default; "" = do not use

A value of 0 °C counts as no measurement. If a metric is missing or a query fails, the value stays null, the other measurements carry on and /status/ reports what was skipped. /beheer/ has the same options for the Prometheus source.

Setting up OPNsense

[[opnsense]]
site = "office"
url = "https://firewall.example.lan"
node = "opnsense"                          # optional: node that receives the WAN traffic
key_file = "/config/opnsense-key"          # the file downloaded from OPNsense (key=…, secret=…)
peers = { "peer-name" = "link-id" }        # WireGuard peer → [[link]]
# wan = "wan"                              # interface id of the WAN

Minimal right: a dedicated user with only Status: Interfaces, Reporting: Traffic, System: Gateways, VPN: WireGuard: Status and System: Deny config write, plus an API key. Other parts (firewall rules, system status) then return 403. A link is up with a handshake no older than 180 s; rx/tx are seen from site a of the link. Only traffic is required: without the WireGuard plugin, or without the rights for gateways or WireGuard, the connector still works and /status/ shows what was skipped.

Setting up Docker

[[docker]]
name = "docker-media"
url = "http://docker-proxy.example.lan:2375"   # or unix:///var/run/docker.sock (mounted read-only)
node = "media"          # optional: topology id; otherwise by host name from /info
site = "home"           # for a discovered node
# stats = false         # without cpu/memory (fewer calls)

Preferably use a docker socket proxy (e.g. tecnativa/docker-socket-proxy) with only CONTAINERS=1 and INFO=1; never expose the Docker socket directly on the network. Per round: one list, one inspect per container and (with stats) one one-shot statistic.

Setting up Proxmox Backup Server

Backups per guest, straight from PBS; no scripts or Zabbix items needed.

[[pbs]]
site = "home"                     # site of the PBS; also the default site of the guests
url = "https://pbs.example.lan:8007"
token_file = "/config/pbs-token"  # contents: <user>@<realm>!<tokenid>:<secret>
# node = "backup"                 # optional: topology id; without it the PBS is discovered (<site>-<host>)
# max_age_h = 30                  # older than this = too old
# datastores = ["data"]           # optional: only these datastores
# verify_tls = true               # with a valid certificate

A group vm/101 or ct/101 belongs to the guest with VMID 101 at the site of the namespace ([backups.pbs] namespaces, with root for the root namespace), otherwise at the site of the PBS. This works with described guests and with guests discovered by Proxmox. Groups of type host count without a guest.

Minimal right: role DatastoreAudit on /datastore, for both the user and the token:

proxmox-backup-manager user create labwereld@pbs --comment "Labwereld (read-only)"
proxmox-backup-manager acl update /datastore DatastoreAudit --auth-id labwereld@pbs
proxmox-backup-manager user generate-token labwereld@pbs labwereld
proxmox-backup-manager acl update /datastore DatastoreAudit --auth-id 'labwereld@pbs!labwereld'

Open backup status

For any backup tool without a connector of its own (restic, Borg, rsync, Duplicati, a cron job): the script writes a small JSON record when it is done and Labwereld reads it. No Zabbix, no agent and no rights on the backup tool needed.

[[backup_status]]
path = "/config/backupstatus"     # directory (all *.json and *.jsonl), file or glob; also a list
# url = "https://nas.example.lan/labwereld/backups.jsonl"   # and/or: GET on an address; also a list
# site = "home"                   # site for host names and VMIDs in the records
# max_age_h = 30                  # default norm: older than this = too old
# token_file = "/config/backupstatus-token"   # optional: bearer token for the addresses
# verify_tls = false              # for a self-signed certificate
# name = "backup-status"          # with several blocks: each its own name

A file (or response) holds one JSON object, an array of objects, or JSON Lines: one object per line; empty lines and lines starting with # do not count. One record per backup:

{"id": "nas-documents", "tool": "restic", "source": "nas", "target": "b2", "last_success": "2026-10-10T03:12:00+02:00"}
FieldMeaning
idrequiredunique name within this source; in the world <name>:<id>
last_successrecommendedend of the last successful backup: Unix time (seconds or milliseconds) or ISO 8601 with a time zone
erroroptionaltext if the last attempt failed; empty or null = no error
tooloptionalrestic, borg, rsync, …; becomes system in the world (default backup)
labeloptionalreadable name (default the id)
sourceoptionalwhat is backed up: node id, host name or IP address
targetoptionalwhere the backup goes: node id, host name or IP address
vmid, siteoptionala guest by site + VMID (site defaults to that of the block)
max_age_soptionalown norm in seconds (default max_age_h of the block)

Other fields are ignored, so the format can grow later.

Labwereld does the maths: ok is false with an error or when last_success is older than the norm, true within the norm and null without last_success (unknown). If a script stops writing, last_success ages by itself and the backup becomes too old. A source or target that does not point to a known node stays null; nothing is guessed. A record without id, a broken line or an unreadable time is skipped and reported under Skipped on /status/. The connector only fails when none of the given places can be read; an empty directory is not an error.

How the status reaches Labwereld. A directory in ./labwereld/ is already visible in the container as /config/…; backups on the same machine write straight into it. From other machines, copy the file there (rsync, scp, a shared folder) or put it behind a web server that Labwereld reads with GET. Always write to a temporary file first and rename it (mv), so Labwereld never reads half a file; files starting with a dot are skipped.

Example script (POSIX sh) that wraps any backup command, for example labwereld-backup.sh nas-documents restic restic backup /srv/documents or labwereld-backup.sh nas-borg borg borg create ::{now} /srv:

#!/bin/sh
# labwereld-backup.sh <id> <tool> <command…>
# Runs the backup and then writes the status for Labwereld.
set -u
id=$1 tool=$2
shift 2
dir=${LABWERELD_STATUS_DIR:-/var/lib/labwereld-backup}
mkdir -p "$dir"
rc=0
if "$@"; then
  date +%s > "$dir/.$id.last"     # time of the last successful backup
  err=null
else
  rc=$?
  err="\"$tool: exit $rc\""
fi
last=$(cat "$dir/.$id.last" 2>/dev/null || echo null)
printf '{"id":"%s","tool":"%s","source":"%s","last_success":%s,"error":%s}\n' \
  "$id" "$tool" "$(hostname -s)" "$last" "$err" > "$dir/.$id.tmp" &&
  mv "$dir/.$id.tmp" "$dir/$id.json"
exit "$rc"                          # cron and systemd see the outcome of the backup

Borg exits with 1 when there are only warnings; to count that as a success, wrap sh -c 'borg create ::{now} /srv || [ $? -eq 1 ]'.

Setting up Proxmox

One block per Proxmox host (or cluster) in the configuration:

[[proxmox]]
site = "home"               # site in the world
hypervisor = "pve1"         # optional: topology id; without it the node is discovered (<site>-<node>)
url = "https://pve.example.lan:8006"
token_file = "/config/proxmox-token"   # contents: <user>@<realm>!<tokenid>=<secret>
# verify_tls = true         # with a valid certificate

Minimal right: a user with role PVEAuditor on / and an API token with privilege separation and the same role:

pveum user add labwereld@pve --comment "Labwereld (read-only)"
pveum aclmod / --users labwereld@pve --roles PVEAuditor
pveum user token add labwereld@pve labwereld --privsep 1
pveum aclmod / --tokens 'labwereld@pve!labwereld' --roles PVEAuditor

EUPL-1.2 · made with Claude · questions: labwereld@wiehie.nl