meshdns

package
v0.29.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package meshdns answers the mesh DNS names of a node's Domain and forwards the names its forwarding setting sends elsewhere. Both come from the dns block of the state pull, which the "Mesh DNS names" section of plexsphere's agent contract describes: the hosts of the Domain and the DNS records its Domain and Projects define, and the forwarding member, whose forward zones go to the resolvers listed with them and whose catch-all resolvers take every other name. The package validates the block into immutable Records and a Forwarding table, answers queries for the mesh names on the node's own mesh IP, relays the forwarded ones to their resolvers without caching them, and registers the mesh zones and forward zones with the operating system's resolver. The host asks plexd for those zones only and resolves every other name as before, unless a catch-all makes plexd the host's default DNS route.

Index

Constants

View Source
const DefaultListenPort = 5354

DefaultListenPort is the port the resolver listens on when listen_port is not set. It is unprivileged, so plexd.service needs no CAP_NET_BIND_SERVICE, and systemd-resolved 246 and newer accept a port beside the server address of a link.

Variables

View Source
var ErrUnavailable = errors.New("meshdns: no usable system resolver")

ErrUnavailable reports that the host has no system resolver plexd can register with, such as a Linux host without systemd-resolved or with one older than 246. The resolver still answers on its listen address, and the manager logs that once instead of warning on every pull.

Functions

This section is empty.

Types

type Answer

type Answer struct {
	// Result is the kind of answer.
	Result Result
	// Zone is the accepted zone or reverse zone with the longest label-wise
	// suffix match of the name the lookup ended at, set for every result but
	// ResultRefused. It owns the SOA the server synthesizes for a negative
	// answer. After a CNAME into another zone it is the target's zone.
	Zone string
	// RRs are the records of the answer section in order: the CNAME records
	// a lookup followed, then the records of the asked type. A negative
	// answer carries the CNAME records that led to it, and none otherwise.
	// The records share their Text with the Records they came from, which
	// nothing changes.
	RRs []RR
}

Answer is what Lookup found for a name and a type.

type Config

type Config struct {
	// Enabled controls whether the resolver runs. A pointer, so an unset key
	// stays distinguishable from an explicit false: an existing deployment
	// sets nothing and gets the resolver, and `enabled: false` is the Node
	// operator's only way out, so it must survive ApplyDefaults exactly as
	// written.
	// Default: true (nil reads as enabled).
	Enabled *bool `yaml:"enabled"`

	// ListenPort is the UDP and TCP port the resolver listens on, on the
	// node's own mesh IP.
	// Default: 5354.
	ListenPort int `yaml:"listen_port"`
}

Config holds the configuration of the mesh DNS resolver.

func (*Config) ApplyDefaults

func (c *Config) ApplyDefaults()

ApplyDefaults sets default values for zero-valued fields. Enabled is left untouched, because nil already means enabled, and writing a value into it would erase the difference between an omitted key and an operator's `false`.

func (*Config) IsEnabled

func (c *Config) IsEnabled() bool

IsEnabled returns the effective Enabled setting: true unless explicitly set to false.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks that configuration values are within acceptable ranges. A disabled resolver binds nothing, so its port is not checked.

type Forwarding

type Forwarding struct {
	// contains filtered or unexported fields
}

Forwarding is the validated forwarding member of one dns block: the forward zones plexd accepted, each with the resolvers that answer the names under it, and the catch-all resolvers that answer every name outside the mesh zones, the reverse zones and the forward zones. Nothing changes it after BuildForwarding returns, so the server reads it from any number of goroutines and a pull replaces it whole. A nil *Forwarding forwards nothing, which is what the server holds while the manager keeps no forwarding member.

func BuildForwarding

func BuildForwarding(setting api.NodeStateDNSForwarding, records *Records, self netip.Addr) (*Forwarding, []string)

BuildForwarding validates setting and builds the table the server forwards with. records supplies the accepted mesh zones and reverse zones, which answer every name under them, so a forward zone that equals one of them or lies under one is skipped; a nil records has none. self is the address the resolver listens on, which no query is forwarded to. The second result names each entry that was skipped, one sentence per entry, for the manager to log.

A forward zone is folded to lower case and checked in this order, and the first check it fails skips it: the name, the reserved names, a mesh zone above it, an accepted forward zone of the same name, and at least one accepted resolver. A resolver is checked in this order, and a skipped one costs only itself: it parses as an IP address, it is an address a query can be sent to, it is not self, and the same owner did not list it before. The checks guard the host, not the limits the control plane sets on the number of zones and resolvers, so a change of those limits needs no new plexd.

func (*Forwarding) CatchAllCount

func (f *Forwarding) CatchAllCount() int

CatchAllCount returns the number of accepted catch-all resolvers.

func (*Forwarding) Equal

func (f *Forwarding) Equal(o *Forwarding) bool

Equal reports whether f and o forward every query alike: the same zones with the same resolvers in the same order, and the same catch-all in the same order. A nil *Forwarding equals one without zones and without a catch-all, so a node that never forwards logs no change.

func (*Forwarding) Route

func (f *Forwarding) Route(name string) (resolvers []netip.Addr, zone string, ok bool)

Route returns where a query for name goes: the resolvers of the longest accepted forward zone that is name itself or lies above it, label by label, with that zone; otherwise the catch-all resolvers with the zone ".", when there are any; otherwise ok is false. The name may carry one trailing dot, as a parsed question does, and is compared in ASCII lower case. The resolvers are shared with the table, which nothing changes.

func (*Forwarding) ZoneCount

func (f *Forwarding) ZoneCount() int

ZoneCount returns the number of accepted forward zones.

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager follows the dns block of the state pull: it builds the records and the forwarding table of each block, swaps them into its server, and keeps the registration with the system resolver in step with them. A mutex guards the state Handle and Shutdown share, so a pull racing the drain either finishes before the revert or does nothing at all. The manager never touches health or readiness: a node whose resolver cannot register still serves its mesh, and the log lines are the operator's view of it.

func NewManager

func NewManager(cfg Config, iface string, meshIP netip.Addr, registrar Registrar, logger *slog.Logger) *Manager

NewManager returns a manager whose resolver listens on meshIP and cfg.ListenPort and registers with registrar for the interface iface. It binds nothing until Start, so the caller learns about an occupied port from Start's error. cfg must have passed Validate; Enabled is not consulted, because the caller decides whether to build a manager at all. A ListenPort of 0 lets the kernel pick the port, which tests use. Every line the manager and its server log carries "component" "meshdns".

func (*Manager) Addr

func (m *Manager) Addr() netip.AddrPort

Addr returns the address the resolver is bound to, with the port the kernel picked when the configured port was 0. It is the server of every registration, so it is what the log lines name as the listen address. Before Start, and after a Start that failed, it is the configured address, so a caller can name it in a bind error.

func (*Manager) Handle

func (m *Manager) Handle(ctx context.Context, desired *api.NodeStateSnapshot)

Handle takes the dns block of one state pull. It has the signature of reconcile.DispatchHandler and runs on every successful pull, drift or not: the block is not desired state the differ tracks, and a pull that changed no name must still retry a registration that failed. A snapshot without a block keeps the names, the forwarding and the registration held, because the block is missing when the control plane predates it or said nothing this time, not when the Domain lost its names.

A block without a forwarding member keeps the member held for the same reason, while two empty lists end the forwarding. The kept member is built into a table against the records of each block, so a forward zone that a new mesh zone shadows goes with the pull that brings the mesh zone, and comes back with the pull that removes it.

func (*Manager) Run

func (m *Manager) Run(ctx context.Context) error

Run answers queries until ctx ends and returns nil then. An error means the resolver stopped while ctx was live, and no mesh name is answered after it.

func (*Manager) Shutdown

func (m *Manager) Shutdown(ctx context.Context) error

Shutdown reverts the registration of the interface and stops every later Handle. It reverts on every run, registered or not, so a registration that a killed predecessor left behind goes too; otherwise the system resolver would keep sending the mesh zones to an address nothing answers. It does not stop the server, which Run's context does. A registrar error is returned wrapped.

func (*Manager) Start

func (m *Manager) Start() error

Start binds the resolver's UDP and TCP sockets. It returns the server's Listen error, which wraps the error of the bind that failed.

type RR

type RR struct {
	Name     string
	Type     dnsmessage.Type
	Addr     netip.Addr
	Target   string
	Priority uint16
	Weight   uint16
	Port     uint16
	Text     []string
}

RR is one resource record of an answer. Name and Target are folded to lower case and carry no trailing dot. Only the members of Type are set: Addr for A and AAAA, Target for PTR and CNAME, Priority and Target for MX, whose preference Priority holds, Priority, Weight, Port and Target for SRV, and Text for TXT. An SOA record carries Name alone, because the server synthesizes its data.

type Records

type Records struct {
	// contains filtered or unexported fields
}

Records is the validated set of mesh names of one dns block. Nothing changes it after BuildRecords returns, so the server reads it from any number of goroutines and a pull replaces it whole. A nil *Records answers ResultRefused for every name, which is what the server holds before the first block.

func BuildRecords

func BuildRecords(block api.NodeStateDNS) (*Records, []string)

BuildRecords validates block and builds the records the server answers from. The control plane is trusted, but a bug there must not hand the node a zone that swallows the host's own resolution, so every entry is checked where it enters. The second result names each entry that was skipped, one sentence per entry, for the manager to log. A zone or reverse zone listed twice is kept once without a sentence. Records are checked against what a DNS message needs, not against the limits the control plane sets on them, so a change of those limits needs no new plexd.

func (*Records) Equal

func (r *Records) Equal(o *Records) bool

Equal reports whether r and o answer every query alike, so the manager logs a change only when a pull changed a name or a record. Node IDs are not answered and are not compared. The records of a name are compared in order, because they are answered in that order. A nil *Records equals only another nil one, so the first block counts as a change even when it is empty.

func (*Records) HostCount

func (r *Records) HostCount() int

HostCount returns the number of accepted hosts.

func (*Records) Lookup

func (r *Records) Lookup(name string, qtype dnsmessage.Type) Answer

Lookup answers name for the type qtype. The name may carry one trailing dot, as a parsed question does, and is compared in ASCII lower case, so the answer does not depend on the spelling of the query.

At each name it tries, in this order: a host of the asked address family; a PTR for a reverse name that maps to a host; a CNAME, which answers every type and is followed, unless the query asks for CNAME or for any type, while its target lies under a zone or reverse zone plexd answers; the records of the asked type; the SOA of a zone itself. A name that exists without any of them answers ResultNoData, and any other name ResultNXDomain, both with the CNAME records that led there. The response code is that of the last name, as RFC 6604 has it.

func (*Records) RecordCount

func (r *Records) RecordCount() int

RecordCount returns the number of accepted records.

func (*Records) Registration

func (r *Records) Registration(iface string, server netip.AddrPort, fwd *Forwarding) Registration

Registration returns what the system resolver should send to server through the interface iface. Routing a domain routes every name under it, so a zone below another accepted zone is left out, which keeps the list short when every Project has a zone under the Domain's default domain. The search domain is a routing domain too, so it is left out as well. Reverse zones are never merged: a wider zone would make plexd deny the addresses outside the mesh. The accepted forward zones of fwd follow, every one of them, so the link lists each zone the node forwards. Each group is in ascending byte order, so equal records and tables give equal registrations. DefaultRoute is set when fwd has a catch-all resolver. A nil r adds no zone and no search domain, and a nil fwd no forward zone and no default route.

func (*Records) ReverseZoneCount

func (r *Records) ReverseZoneCount() int

ReverseZoneCount returns the number of accepted reverse zones.

func (*Records) SearchDomain

func (r *Records) SearchDomain() string

SearchDomain returns the accepted search domain, or empty when the node has none.

func (*Records) ZoneCount

func (r *Records) ZoneCount() int

ZoneCount returns the number of accepted zones.

type Registrar

type Registrar interface {
	// Apply registers reg, replacing whatever the link held before. It
	// returns an error wrapping ErrUnavailable when the host has no usable
	// system resolver.
	Apply(ctx context.Context, reg Registration) error
	// Revert removes every resolver setting of the interface named iface. It
	// returns nil when there is nothing to remove, which includes an
	// interface or a system resolver that is gone, so a shutdown on a host
	// without one does not report a failure.
	Revert(ctx context.Context, iface string) error
}

Registrar is the seam to the operating system's resolver. Each platform supplies its own, and tests replace it with a recording fake, so no test changes the resolver settings of the host it runs on.

type Registration

type Registration struct {
	// Interface is the name of the mesh interface the registration is bound
	// to, so the system resolver sends the queries through that link.
	Interface string
	// Server is the address and port the mesh resolver listens on.
	Server netip.AddrPort
	// SearchDomain is the zone of the node's own Project, or empty when the
	// node has none. A search domain is also a routing domain, so it is not
	// listed again in RoutingDomains.
	SearchDomain string
	// RoutingDomains are the zones, reverse zones and forward zones the
	// system resolver sends to Server, without the search domain.
	RoutingDomains []string
	// DefaultRoute makes the link the host's default DNS route, so the
	// system resolver sends Server every name that no domain of another link
	// matches. It is set while the forwarding table has a catch-all
	// resolver.
	DefaultRoute bool
}

Registration is what plexd asks the system resolver to send to the mesh resolver: the queries for RoutingDomains and, through the search domain, the bare host names of the node's own Project, on the mesh interface only, and with DefaultRoute every name no other link claims.

func (Registration) Empty

func (r Registration) Empty() bool

Empty reports whether the registration names no domain at all and does not make the link the default route. Applying one would route nothing to the mesh resolver, so the manager reverts the link instead.

func (Registration) Equal

func (r Registration) Equal(o Registration) bool

Equal reports whether r and o register the same thing, comparing every field and the routing domains in order. The manager compares the wanted registration with the applied one, so a pull that changes no zone issues no call to the system resolver.

type ResolvedRegistrar

type ResolvedRegistrar struct {
	// contains filtered or unexported fields
}

ResolvedRegistrar registers the mesh resolver with systemd-resolved over D-Bus, for the mesh interface only. It holds no connection between calls: systemd-resolved and the bus daemon may start, stop or restart between two pulls, and a connection kept open would need a goroutine and reconnect logic of its own for a handful of calls per change.

func NewResolvedRegistrar

func NewResolvedRegistrar(logger *slog.Logger) *ResolvedRegistrar

NewResolvedRegistrar returns the Registrar for Linux hosts, which talks to systemd-resolved on the system bus.

func (*ResolvedRegistrar) Apply

func (r *ResolvedRegistrar) Apply(ctx context.Context, reg Registration) error

Apply registers reg on its interface. It first reads the Manager property DNSEx, so a systemd-resolved older than 246 is told apart before anything on the link changes; a failed read is followed by no other call. Then it makes seven calls. The default-route flag goes first, so a link that is to answer its domains only stops answering other names before anything else changes, and the server goes last, so a failure halfway leaves a link without a server, which systemd-resolved never asks. A failure after the first step reverts the link, ignoring the result, so the next Apply starts from a clean link. With reg.DefaultRoute the flag is set and the routing domain "." ends the domains, so the link answers every name no other link claims.

When ctx has a deadline, the probe and the steps run under one that is a fifth of the remaining time earlier, and the revert runs under ctx. godbus sends no call whose context is done, and it closes a connection once the context it was opened with ends, so a revert sent after a step ran out ctx would never leave plexd. A ctx that was cancelled rather than timed out sends no revert either. That only happens while plexd stops, and the drain's Shutdown then reverts the link with a context of its own.

The error wraps ErrUnavailable when the bus or systemd-resolved is missing or older than 246.

func (*ResolvedRegistrar) Revert

func (r *ResolvedRegistrar) Revert(ctx context.Context, iface string) error

Revert clears every resolver setting of the interface named iface with RevertLink, including any an operator set there by hand, because plexd owns the link. It returns nil when there is nothing to clear: the interface is gone, the bus or systemd-resolved is unavailable, or systemd-resolved does not know the link. Like every call of the registrar, the RevertLink does not start a stopped systemd-resolved, which then counts as unavailable. Revert makes that one call, so it runs it under ctx: no revert follows that would need time held back.

type Result

type Result int

Result is the kind of answer Lookup gives. The server turns it into a response code and decides which sections it fills.

const (
	// ResultRefused means the name lies outside every accepted zone and
	// reverse zone, or no block arrived yet. The server forwards a query for
	// such a name when its forwarding table routes the name, and otherwise
	// answers REFUSED, so the system resolver treats the name as not plexd's
	// to answer. It is the zero value, so an Answer nobody filled in denies
	// nothing it should not.
	ResultRefused Result = iota
	// ResultNXDomain means the name lies under Zone and does not exist.
	ResultNXDomain
	// ResultNoData means the name exists under Zone but has no record of the
	// asked type, so the server answers NOERROR with an empty answer section.
	ResultNoData
	// ResultFound means the name has a record of the asked type, or is a
	// CNAME the system resolver follows on: the records are in RRs.
	ResultFound
)

func (Result) String

func (r Result) String() string

String returns the name of the result, for log lines and test failures.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server answers DNS queries for the mesh names over UDP and TCP on one address, and forwards a query for any other name that its forwarding table routes to the resolvers the table names. It answers the node itself only: a query from any source other than the listen address or a loopback address is dropped, because plexd's firewall filters forwarded traffic only and nothing else keeps other hosts from using the resolver.

func NewServer

func NewServer(addr netip.AddrPort, logger *slog.Logger) *Server

NewServer returns a server for addr. It binds nothing until Listen, so the caller learns about an occupied port from Listen's error and decides what to do about it before serving starts. The server logs at Debug, except for a forward resolver that stops or starts answering, and adds no attributes of its own to logger.

func (*Server) Addr

func (s *Server) Addr() netip.AddrPort

Addr returns the address the server is bound to. Before Listen, and when addr named a port other than 0, it is addr itself; after Listen on port 0 it carries the port the kernel chose, which is the same for UDP and TCP.

func (*Server) Listen

func (s *Server) Listen() error

Listen binds UDP and TCP on the server's address and port. A resolver that answers on one of them only would fail systemd-resolved as soon as it moves to TCP after repeated UDP losses, so a failure of either bind fails Listen and closes the socket that did bind. With port 0, UDP binds first and TCP takes the port UDP got; when that port is taken for TCP, Listen tries a fresh one, up to listenAttempts times. A server listens once: after a Listen that succeeded, Listen fails, before, during and after Serve.

func (*Server) Serve

func (s *Server) Serve(ctx context.Context) error

Serve answers queries on the sockets Listen bound until ctx ends, then ends the forwarded queries in flight, over UDP and TCP, closes both sockets and every open TCP connection, waits for the goroutine of each connection and each forward to finish, and returns nil. A forwarded query that Serve ends gets no reply, as one that arrives after the close does. A failed UDP read, or a TCP listener closed by anything but Serve, while ctx is live stops serving the same way and is returned, so the caller can log that the resolver stopped. Any other failed accept, such as EMFILE while the process is out of file descriptors, is retried after a wait, so a passing shortage stops neither TCP nor UDP. Serve without a successful Listen returns an error.

func (*Server) SetForwarding

func (s *Server) SetForwarding(f *Forwarding)

SetForwarding replaces the table the server forwards with, as SetRecords replaces the names, and drops the marks of the resolvers f no longer names. A nil f forwards nothing, as the server does before the first call, so a name outside the mesh zones gets REFUSED.

func (*Server) SetRecords

func (s *Server) SetRecords(r *Records)

SetRecords replaces the names the server answers from. The swap is atomic, so a pull never blocks a query: a query in flight finishes with the records it started with, and the next one sees r. A nil r answers no name, as the server does before the first call: a name the forwarding table routes is forwarded, and every other name gets REFUSED.

Jump to

Keyboard shortcuts

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