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 |
openwrt/plane |
The device side of the Perch config plane, for any daemon: redacted reads, change watching with an author, applies with base hashes, a confirm window, rollback, a boot guard, signing, pairing and sealed secrets (below) |
update |
Self-update of a daemon from its controller: the signed release manifest and its signify/usign signature, version order, preflight, resumable downloads, the watchdog and boot guard script (agent-updates design) |
cmd/perch-release |
The release tool: builds a release's manifest from its files, verifies a manifest, its signature and the files, compares published artefacts with a rebuild, builds the files bundle, uploads a signed release to a controller (below) |
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. With
PortOptions.Counters a port with a link also carries rxBytes / txBytes and
counterScope: a DSA user port's netdev only counts what reaches the CPU (frames the
switch forwards between two of its ports never do), so its counters come from the
switch's own statistics (the ethtool ioctl: names once per facts, then one read per
port) and are "port" scoped; a switch whose byte counters are not known falls back to
the netdev with "cpu". Every other port reads its netdev ("port"). 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. Names in
uci.NotSecret (public_key: a WireGuard peer's key is its public identity) match
a suffix rule but stay readable; a caller's extras still win. An unbound
redactor (Redactor{Key: fleetKey, Unbound: true}) puts * in place of the section
name, so one value fingerprints alike in every section and on every device that
shares the key: a Wi-Fi passphrase used by one network on several access points.
Vector: key 32 × 0x44, wireless.*.key=correct horse battery →
hmac:ac349a3eb980336c; the list ["a","b"] → hmac:afe901da1eba8775.
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.
Config plane (openwrt/plane)
The device side of the Perch config plane (docs/gateway/config-plane.md in
perch-controller), shared by the daemons: perch-collector on the gateway
(gateway.*) and perch-apd on the access points (wifi.*). Cut from the
collector's internal/gwconfig (1.1.0-pre.3); the collector keeps its copy until it
switches, so a fix to the shared logic goes to both.
p, err := plane.New(plane.Options{
Name: "perch-apd", Prefix: "wifi", // wifi.config.apply, wifi.pair.begin, ...
StateDir: "/etc/perch-apd/plane", RunDir: "/var/run/perch-apd",
Access: "write", Allow: []string{"wireless", "network"},
ForeignStaged: []string{"network", "wireless"},
Redactor: uci.Redactor{Unbound: true}, // the key comes with agent.configure
TransportOK: tlsVerified, ServerURL: controllerURL,
Health: checkBSSes, Lock: writeLock, WirelessRadios: uplinkRadios,
})
p.Start() // resume or restore a pending apply
p.SetHooks(plane.Hooks{Reconnect: redial, Result: notifyResult, PairState: notifyPair})
go p.Run(ctx, notifyChanged) // change watching; p.Trigger() on SIGHUP
// per session: p.Hello(ctx, challenge), p.Configure(block), p.EndSession()
// requests: p.Serve(ctx, method, params, sessionRef) for p.Served(), errors via plane.RPCError
What it does, and what a device plugs in:
- Reads and watching.
Read returns the committed files of the allowlist and
the ledger (perch-managed) with secrets fingerprinted by the session's redactor
(Configure's fingerprintKey replaces the base key; EndSession keeps it).
Run/Step poll and hash, Trigger is procd's reload trigger; changes are
reported after a debounce with an author (the single logged-in LuCI user, cli,
unknown), the plane's own writes as origin: perch (RecordOwn, also for the
device's other writers). Options.Owner marks sections another writer owns.
- Applies. Ops
put | adopt | delete | order on owned sections (the ledger),
{"$keep": true} and {"$secret": ref} values, base hashes (stale_base),
simulated first (Options.Validators see the result), then snapshot to
StateDir/rollback/<id>/, a tmpfs marker, a private rpcd session (Go-rendered
files without rpcd), commit in apply order, read-back check, reload
(Options.Reload, Settle), the reply pending_confirm, and the session dropped.
The controller confirms on a later session, or the snapshot comes back at the
deadline, on rollback, or on a failure after the first commit. A job on the
management path (ip route get, the interface, its bridge and VLANs, the firewall
zone, the radios of a wireless uplink, Options.Protected) gets at least
MinProtectedSeconds. Discarded device edits of the window come back redacted.
- Health. With
Options.Health a change is kept only when the device's check
passed (every HealthInterval, up to the configured wait, longer while the check
asks with Extend, never past the deadline minus 5 s) and the controller confirmed;
a failed check rolls back at once (health_failed), a confirm before the check
passes is health_pending. HealthBefore records what was broken already.
- Restarts and reboots.
Start re-arms a pending apply or restores it (no
marker = rebooted, not committed, past the deadline); plane.Guard(opts, now) is
the boot guard (<daemon> config-guard before network), which restores without
reloading. PendingApply(opts) reads the pending job from disk.
- One writer at a time.
Options.Lock (perch-apd's applylock) is taken for
an apply's whole life; another writer's hold is busy with its reason.
- Plain HTTP. Writes need verified TLS, or the device's opt-in and a signature
(
Sign, SignatureMessage: the envelope and vector of the controller's
rpc_signing.ts) with a key agreed in a pairing (<prefix>.pair.*, X25519 +
commitment + 6-digit code confirmed on the device through the root-only socket
RunDir/pair.sock; the transcript's Subject is "7" for gateway 7 or "ap:4"
for AP 4). Secret values travel only over verified TLS, or sealed with the
pairing's key (Seal/OpenSealed: HKDF-SHA256 + AES-256-GCM, AAD
perch-seal-v1\n<method>\n<applyId>\n<ref>).
- A device's own jobs.
Reserve → StartJob → Job.Commit | Job.Fail share the
slot, snapshot and window; Options.Jobs[kind].Undo reverts the job on a rollback
and in the boot guard (the collector's package installs). Options.ExtraWrites
serves more write methods behind the same gate.
No regexp, no new module: crypto/ecdh, AES-GCM and HMAC are the standard library.
Releases (cmd/perch-release)
Every self-updating release of perch-apd and perch-collector carries a
perch-manifest.json (product, version, channel, the version floor and every
artefact's SHA-256, size and target) and a detached Ed25519 signature in
signify/usign format made by the owner's key. Devices install only what a key
they pin signed (update/keys.go, plus root's UCI list update_key).
go run github.com/capthndsme/perch-agentkit/cmd/perch-release <command>
manifest -product perch-apd -version 1.2.0 [-channel …] [-commit …] [-min-version …]
[-sdk-env openwrt/sdk.env] [-files-spec openwrt/perch-apd/files.json] DIR
verify [-key K.pub]… [-sig S | -unsigned] [-dir DIR] perch-manifest.json
compare -manifest M -published DIR -rebuilt DIR
bundle -spec openwrt/perch-apd/files.json -root . -o dist/
contents PACKAGE… # what an .ipk / .apk (apk-tools 3 adb) installs
key KEY.pub… # key id and the lines that pin it
info perch-manifest.json
upload -controller URL -dir DIR # token in PERCH_API_TOKEN
manifest reads kinds, arches and variants from the file names, package
names, versions, architectures and the daemon's payload hash from inside the
packages (both formats, no external tools), series from openwrt/sdk.env, and
the bundle's members from its spec; the result passes the kit's own parser.
compare is what the owner's scripts/sign-release.sh (in each daemon
repository) runs before it signs: binaries must match the owner's rebuild byte
for byte, packages must install the same files, modes and hashes and carry the
same maintainer scripts and dependencies (archive metadata may differ), the
bundle the same members. The tool never signs: signify-openbsd does, with a
passphrase-protected key that stays on the owner's workstation.
scripts/release-keygen.sh makes the two keys (workstation and cold) and
prints the lines that pin them here and in the controller.
License
MIT; see LICENSE.