Skip to content
Open
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
4 changes: 4 additions & 0 deletions docs/architecture.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -631,6 +631,10 @@ PAIR keys the owned local node and authenticated peers by stable host UUID.
That UUID correlates cluster membership, workload attribution, error reports,
scheduling telemetry, and verified proxy routes. Hostnames are display names,
so renaming a host or sharing a hostname does not merge distinct hosts.
PAIR's own host record follows that line: the scanner advertises it under a
synthetic host label, never a name the operating system owns, with the rule
that derives it in the `nvpair-node-scanner` spec §7.1. The computer's
hostname remains only the record's display instance name.

Unverified announcements have independent discovery record IDs. Their claimed
UUIDs cannot select a local or authenticated peer's record. A manual engine
Expand Down
2 changes: 1 addition & 1 deletion services/nvpair-cluster-manager/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,7 @@ The exact `<config-dir>` is the per-user data dir shared by every component: `%L
The Cluster Manager runs no responder or browser of its own. `nvpair-node-scanner` is the single discovery daemon on the node: the Broker registers this service's `cl` service key and listening port with that daemon, the daemon carries the key on this node's one consolidated `_nvpair-node._tcp` record, and the Cluster Manager learns peers by subscribing upward — `discovery:subscribe` filtered to the `cl` service — and consuming the `discovery:nodes` snapshots the Broker relays back.

- **Registered port**: the inter-node listener, **`14321`** (one above `nvpair-workload-manager`'s `14320`; the pairing channel and the mTLS endpoints share it, distinguished by path and by whether the TLS handshake presents a client cert). It reaches the record as the `cl` service key.
- **The record layout is the daemon's contract, not this service's.** Service type, instance name, SRV port, and TXT keys are owned by the discovery daemon and the shared `nvpair-shared/noderec` wire format; this service reads the directory entries it is handed and never parses a record itself. The record's SRV port is a fixed, non-authoritative constant, so a consumer takes each service's port from TXT and never from SRV. The instance name is the OS hostname (the logical `nodeId`), surfaced on a directory entry as its `name` — display only, never trusted.
- **The record layout is the daemon's contract, not this service's.** Service type, instance name, SRV target host label, SRV port, and TXT keys are owned by the discovery daemon and the shared `nvpair-shared/noderec` wire format; this service reads the directory entries it is handed and never parses a record itself. The record's SRV target and A records carry the daemon's own synthetic host label, never a name the operating system owns (`nvpair-node-scanner` spec §7.1). The record's SRV port is a fixed, non-authoritative constant, so a consumer takes each service's port from TXT and never from SRV. The instance name is the OS hostname (the logical `nodeId`), surfaced on a directory entry as its `name` — display only, never trusted.
- **TXT keys this service depends on** (all carried on the one consolidated record, alongside the other services' port keys):

| Key | Value | Why |
Expand Down
126 changes: 115 additions & 11 deletions services/nvpair-node-scanner/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,43 @@ import (
"nvpair-shared/reach"
)

// mdnsResponder and discoveryBrowser are the daemon's two mDNS counterparts:
// the record this node advertises, and the browser watching for everyone
// else's. They are interfaces only so a test can control when each shuts
// down — nothing else supplies them, and production always wires
// mdns.Responder and discovery.Browser, which already satisfy both. Their
// shutdowns matter together: responder.Run returns only once it has sent its
// RFC 6762 §10.1 retraction, while the browser closes its events channel as
// it stops, which is the same instant ctx is cancelled.
type (
// mdnsResponder advertises this node's service record, answering
// queries for it until ctx is cancelled, then sends the retraction that
// withdraws it before returning.
mdnsResponder interface {
Run(ctx context.Context) error

// UpdateTXT swaps the advertised TXT records and re-announces
// immediately, so it is safe before or during Run.
UpdateTXT(txt []string)

// AdvertisedHost is the FQDN this node claims as its own host
// record — the SRV target and the owner of its A records, trailing
// dot included.
AdvertisedHost() string
}

// discoveryBrowser scans the service type and forwards each change on
// events, which it closes when it stops — which is when ctx is
// cancelled. SendFailures reports the interfaces whose multicast sends
// could not leave, the evidence localAddresses ranks this host's own
// addresses on.
discoveryBrowser interface {
Run(ctx context.Context, events chan<- DiscoveryEvent)

SendFailures() map[string]bool
}
)

// daemon owns local registration, candidate discovery, and authenticated peer
// inventory. It publishes discovery:node-* events for the broker relay, which
// delivers directory snapshots to service consumers.
Expand All @@ -39,8 +76,8 @@ type daemon struct {
mesh *clustertrust.Mesh
reg *registry
dir *directory
responder *mdns.Responder
browser *Discovery
responder mdnsResponder
browser discoveryBrowser
// instance is this node's mDNS instance name (the hostname). It names the
// registry-driven self directory entry (publishSelf), which is anchored to
// our own identity rather than to hearing our own multicast.
Expand Down Expand Up @@ -73,6 +110,12 @@ type daemon struct {
// empty selects nodeid's shared default (production's default layout).
baseDir string

// hostLabel is the single DNS label PAIR claims as its mDNS host record —
// the SRV target and A owner name the responder advertises — derived from
// the node UUID by noderec.HostLabel, never the machine's name. Empty when
// HostLabel refused and this node advertises nothing over mDNS.
hostLabel string

// clusterDir is the cluster trust subtree (--cluster-dir) holding this node's
// keypair, pins, and admission record. It gates whether we advertise a
// cluster-uuid=: we advertise only while actually a member
Expand Down Expand Up @@ -298,6 +341,12 @@ func telemetryRetryDelay(consecutiveFailures int) time.Duration {
}

// newDaemon builds the registry publisher and pinned peer discovery daemon.
// hostLabelOf is the source of the advertised mDNS host label. It is a
// variable only so a test can force the no-entropy error the real
// noderec.HostLabel cannot produce in-process (os.Hostname() never fails or
// empties here); production always uses noderec.HostLabel.
var hostLabelOf = noderec.HostLabel

func newDaemon(codec *Codec, mesh *clustertrust.Mesh, clusterDir string) *daemon {
// nodeid reads <base>/cluster/identity.json; --cluster-dir is that cluster
// subdir, so its parent is the base. Empty -> nodeid's shared default.
Expand All @@ -320,11 +369,18 @@ func newDaemon(codec *Codec, mesh *clustertrust.Mesh, clusterDir string) *daemon
reg := newRegistry(hostUUID, cluUUID, netpick.LocalCandidates(netpick.Evidence{}))

instance, _ := os.Hostname()
// The host record advertised over mDNS is PAIR's own label from the node
// UUID, never `instance`: claiming the machine's name is the contention
// that makes macOS append a digit to the computer's Local hostname (issue
// #229). The instance name stays the hostname — it is a display name and is
// legal even when the hostname is not a single DNS label.
hostLabel, labelErr := hostLabelOf(hostUUID, instance)
d := &daemon{
codec: codec,
mesh: mesh,
reg: reg,
instance: instance,
hostLabel: hostLabel,
baseDir: baseDir,
clusterDir: clusterDir,
dir: newDirectory(),
Expand All @@ -342,19 +398,48 @@ func newDaemon(codec *Codec, mesh *clustertrust.Mesh, clusterDir string) *daemon
d.browser = NewDiscovery(noderec.ServiceType, noderec.Domain,
WithKeyFunc(nodeDiscoveryRecordID),
)
if resp, err := mdns.NewResponder(instance, noderec.ServiceType, noderec.Domain, noderec.SRVPort, reg.txt()); err != nil {
slog.Warn("mDNS advertising disabled for _nvpair-node", "err", err)
if labelErr != nil {
// No entropy to name this host with; advertising a fixed placeholder
// would give every host on this path the same record, recreating the
// contention the synthetic label exists to avoid. Advertise nothing.
slog.Error("mDNS advertising disabled for _nvpair-node: no host label to advertise",
"err", labelErr, "baseDir", baseDir)
} else {
d.responder = resp
// HostLabel is pure by design — it cannot log which rule produced the
// label — so ask it the fallback question directly: the same call with
// no node UUID is hostname-derived by definition, and an equal answer
// means the UUID passed in was empty or unusable, so the advertised
// name moves if the hostname moves.
if derived, derivedErr := noderec.HostLabel("", instance); derivedErr == nil && derived == hostLabel {
slog.Warn("advertising a hostname-derived mDNS host label",
"hostLabel", hostLabel, "hostUUID", hostUUID,
"reason", "no usable node identity, so the label follows the hostname and will move with it")
}
if resp, err := mdns.NewResponder(instance, hostLabel, noderec.ServiceType, noderec.Domain,
noderec.SRVPort, reg.txt()); err != nil {
slog.Warn("mDNS advertising disabled for _nvpair-node", "err", err)
} else {
d.responder = resp
slog.Info("advertising _nvpair-node", "instance", instance, "advertisedHost", resp.AdvertisedHost())
}
}
return d
}

// run starts the _nvpair-node responder and browser, folding browse events into
// the directory and emitting discovery:node-* until ctx is cancelled.
func (d *daemon) run(ctx context.Context) {
// responderDone closes when responder.Run returns — including the
// shutdown goodbye it sends after ctx is cancelled (RFC 6762 §10.1),
// which is why Scanner.Run joins this before allowing process exit.
// Nil when the responder is disabled, meaning there is nothing to wait
// for.
var responderDone <-chan struct{}
if d.responder != nil {
done := make(chan struct{})
responderDone = done
go func() {
defer close(done)
if err := d.responder.Run(ctx); err != nil {
slog.Warn("_nvpair-node responder exited", "err", err)
}
Expand All @@ -363,6 +448,28 @@ func (d *daemon) run(ctx context.Context) {
// the responder keeps its A records live (both via netmon).
go d.watchAddress(ctx)
}

// Common cleanup, deferred so it runs whichever way the browse loop
// below ends. Cancelling ctx makes both ctx.Done() and the browser's
// closed events channel ready at the same instant, and select takes
// either: with this wait written into the ctx.Done() branch, a select
// that happened to take the closed channel returned as soon as the
// browser stopped, with responder.Run still inside its shutdown. Only
// the responder is joined — it returns once the RFC 6762 §10.1 goodbye
// has gone out, and Scanner.Run cannot let the process exit before this
// returns. The other background loops are not joined: after
// cancellation they hold nothing the wire still needs, and joining them
// could outlast the responder send for no retraction benefit.
defer func() {
if d.modelsClients != nil {
d.modelsClients.CloseIdle()
}
if d.nodeInfoClients != nil {
d.nodeInfoClients.CloseIdle()
}
waitForShutdown(responderDone, shutdownJoinTimeout, "_nvpair-node mDNS responder")
}()

// Publish our own directory entry from the local registry BEFORE the browse
// loop runs. Self presence is registry-driven, not browse-driven: on Windows
// the host frequently does not loop its own multicast back to the browsing
Expand All @@ -382,15 +489,12 @@ func (d *daemon) run(ctx context.Context) {
for {
select {
case <-ctx.Done():
if d.modelsClients != nil {
d.modelsClients.CloseIdle()
}
if d.nodeInfoClients != nil {
d.nodeInfoClients.CloseIdle()
}
return
case ev, ok := <-events:
if !ok {
// The browser has stopped, which it does as ctx is
// cancelled. The deferred cleanup above still joins the
// responder, whose goodbye may still be going out.
return
}
d.onBrowse(ev)
Expand Down
Loading