perch-agentkit

module
v0.3.0-pre.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 23, 2026 License: MIT

README

perch-agentkit

Shared Go code of the Perch device daemons: the Perch Network Collector and the Perch AP Daemon. Both dial the Perch Network Controller over a WebSocket, speak JSON-RPC 2.0 on it and push on a schedule the controller sets, so that part lives here once.

Package What
rpc JSON-RPC 2.0, one object per WebSocket message: codec, dispatcher, requests, notifications
link One session to the controller: dial (TLS options, subprotocol, optional permessage-deflate), pings, serving the controller's requests, routing its notifications, calls of our own, the push scheduler driven by agent.configure, reconnect backoff, the controller's HTTP error bodies
hoststat Typed readers for /proc: load, memory, interface counters, conntrack fill, SNMP counters, default-route interfaces; and the host's Ethernet ports from /sys/class/net and /etc/board.json. All over a root that tests can point at a fixture tree
openwrt/ubus OpenWrt's ubus through its command-line client, one fork per call: Call, CallRaw, List, HasObject; exit codes mapped to ubus statuses (ErrNotFound, ErrPermissionDenied, ErrMethodNotFound, *Error)
openwrt/uci UCI configs (/etc/config/*): a typed model (sections incl. anonymous ones and @type[n], string and list options), a pure parser and renderer of the file format that matches libuci, file and content hashes, redaction of secrets, reads from the file or rpcd, staging and commit in a private rpcd session (uci CLI fallback), uncommitted/LuCI-pending detection
openwrt/pkgdb Installed packages from the opkg or apk database (never by exec), which manager is in use, /proc/mounts, free space of the overlay

Reconnect policy is the daemon's: link.Run is one session and returns why it ended (a *link.StatusError for a refused upgrade, the close code otherwise).

Ports

hoststat.PortReader lists the host's Ethernet ports with their live link state, for the controller's infrastructure view: the JSON array both daemons send (docs/infrastructure-view.md §2.1 and §4 in perch-controller). It tells a port from everything else in /sys/class/net: DSA user ports count and the DSA conduit does not; per-port netdevs and a second MAC used as WAN count; an LTE modem in 802.3 mode (DEVTYPE=wwan) counts with medium wireless; bridges, bonds, teams, VLANs on a local device, Wi-Fi interfaces, tunnels, ifb, dummy and tun/tap devices do not. A veth, macvlan or VLAN whose other end or parent is in another network namespace counts as a virtual port, by default only on a host that has no wired hardware port (a router in a container; an LTE modem next to its veths does not hide them). role comes from board.json (OpenWrt; hardware ports only, since a container sees its host's file) plus the WAN interfaces the caller names, and the result is in display order: WAN first, then the board's LAN order, then the rest in natural order.

r := &hoststat.PortReader{Options: hoststat.PortOptions{WAN: []string{"wan0"}}}
ports := r.Read() // nil: /sys/class/net unreadable; []: looked, found none

A reader keeps what does not change (classification, label, medium, MAC) per name + ifindex for five minutes and board.json as long, so a read in steady state is one directory listing plus an open/read/close of about seven small attributes per port. Link state (adminUp, carrier, operstate, speedMbps, duplex, carrierChanges) is read fresh every time; what the kernel does not answer (carrier of a port that is administratively down, speed -1 without a link) is left out. FS.Ports is the one-shot form. The fixture trees in hoststat/testdata/ports/ are named after the port layouts they model (DSA with a conduit, per-port netdevs, a second MAC as WAN, a container with only veths, a VM, and a tree of everything that is not a port).

Go 1.22 or newer (the OpenWrt SDK floor); one dependency, github.com/coder/websocket. No cgo.

go test ./...
GOTOOLCHAIN=go1.22.12 go test ./...

OpenWrt

The openwrt/* packages are what the Perch config plane needs on a router (docs/gateway/ in perch-controller): read UCI, hash it, notice changes, stage and commit changes safely, and know what is installed. None of them links libuci or speaks the ubus protocol; rpcd and the uci CLI are reached through their command-line clients, and the file format is parsed in Go.

Parser. uci.Parse(name, data) reads the file format the way libuci does in its default strict mode, quirks included: option x '' is ignored, a ; right after a bare word drops the rest of its line, a second config with an earlier name continues that section. Anonymous sections get libuci's names (cfg + 1-based position in two hex digits + a 16-bit hash of the type, e.g. cfg080f15; uci.AnonymousName), the names rpcd, LuCI and uci -X show use. uci.Render writes what uci commit writes, byte for byte, and uci.Export what uci export prints. The fixtures in openwrt/uci/testdata/openwrt-24.10 are real configs with, for each, rpcd's reply and uci export's output for that exact file on an OpenWrt 24.10.8 router; the tests require the parser to agree with both, and parse → render → parse to be the identity.

Hashes. uci.FileHash is the SHA-256 of a file's bytes (what the config plane compares); Config.ContentHash ignores comments and formatting; uci.SectionHash / uci.Canonical hash a section's content only (type plus options sorted by name, list order kept), ["<type>",{"opt":"v","list":["a","b"]}] as compact JSON without HTML escaping, so the controller can compute the same.

Secrets. uci.Redactor{Key: apiKey}.Section(config, s) removes secret options (uci.SecretOptions, the suffixes in uci.SecretSuffixes, key1..key4, plus a domain's extras) and returns "hmac:" + 16 hex fingerprints of HMAC-SHA256(key, config.section.option=value) in their place.

Reads. uci.Files{} reads committed configs from /etc/config (hash and content from the same bytes). uci.Ubus{Client, Session} reads through rpcd. Without a session rpcd reads with the save directory /tmp/.uci, so its answer includes changes staged with the uci CLI and not committed; with a private session it does not.

Staging. uci.NewSession(ctx, ubus, configs, write) creates an rpcd session granted only those configs; its Add/Set/DeleteOptions/ DeleteSection/Rename/Order/Changes/Revert/Commit stage in /var/run/rpcd/uci-<id>/ and commit only that, and rpcd's commit emits config.change so procd reloads the services, as after a LuCI save. uci.CLI{SaveDir} is the fallback without rpcd (uci -t <dir>, argv only; run uci.ReloadConfig after a commit). libuci always includes /tmp/.uci in what the CLI changes and commits, so the CLI stager refuses a config that has foreign staged changes there (uci.ErrForeignChanges). Values with control characters or over 4 KiB and names outside [A-Za-z0-9_]{1,64} are refused before anything runs. uci.PendingState(root) lists configs someone has staged but not committed and whether a LuCI apply-with-rollback is pending.

Packages. pkgdb.DB{}.Manager() is apk or opkg by database file; Installed() and Watched(extra...) read /lib/apk/db/installed or /usr/lib/opkg/status; pkgdb.FreeFlash() is the free space of /overlay (or / without one); pkgdb.Mounts / MountFor resolve which mount holds a path.

License

MIT; see LICENSE.

Directories

Path Synopsis
Package hoststat reads the kernel's view of the host from /proc: load, memory, interface counters, connection tracking, SNMP counters and the default routes.
Package hoststat reads the kernel's view of the host from /proc: load, memory, interface counters, connection tracking, SNMP counters and the default routes.
Package link keeps an agent's WebSocket session to the Perch controller: dial with the agent's credentials, keep the connection alive with pings, serve the controller's JSON-RPC requests, route its notifications, make calls of the agent's own and push on the schedule the controller sets.
Package link keeps an agent's WebSocket session to the Perch controller: dial with the agent's credentials, keep the connection alive with pings, serve the controller's JSON-RPC requests, route its notifications, make calls of the agent's own and push on the schedule the controller sets.
openwrt
pkgdb
Package pkgdb reads what is installed on an OpenWrt system and how much room is left: the package manager in use (opkg up to 24.10, apk from 25.12), the installed packages with their versions straight from the package database (never by running the package manager), and the free space of the writable overlay.
Package pkgdb reads what is installed on an OpenWrt system and how much room is left: the package manager in use (opkg up to 24.10, apk from 25.12), the installed packages with their versions straight from the package database (never by running the package manager), and the free space of the writable overlay.
ubus
Package ubus calls OpenWrt's ubus through its command-line client, one fork per call.
Package ubus calls OpenWrt's ubus through its command-line client, one fork per call.
uci
Package uci reads and writes OpenWrt's UCI configuration (/etc/config/*) for the Perch config plane: a typed model of configs, sections and options; a pure parser and renderer of the file format that behaves like libuci (including the names libuci gives anonymous sections); content hashes; redaction of secrets; reads through rpcd's `uci` ubus object or the file; and staging plus commit of changes in a private rpcd session, with the `uci` command line as the fallback.
Package uci reads and writes OpenWrt's UCI configuration (/etc/config/*) for the Perch config plane: a typed model of configs, sections and options; a pure parser and renderer of the file format that behaves like libuci (including the names libuci gives anonymous sections); content hashes; redaction of secrets; reads through rpcd's `uci` ubus object or the file; and staging plus commit of changes in a private rpcd session, with the `uci` command line as the fallback.
Package rpc is JSON-RPC 2.0 over whole WebSocket messages: one object per frame, no batches.
Package rpc is JSON-RPC 2.0 over whole WebSocket messages: one object per frame, no batches.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL