Architecture

TAK-OS DNS serves externally facing authoritative data from Kubernetes, static configuration and directly contacted peer sites (configured or discovered). It has no recursive or forwarding path and does not replace Kubernetes cluster DNS. This document explains runtime and consistency boundaries; record syntax belongs in the record reference, and the transports are described in DNS behaviour and the peer protocol.

Runtime components

One Go process owns the DNS UDP/TCP listeners, the internal HTTP listener, the source cache, a local refresh worker and a peer manager. Kubernetes mode also runs a complete custom-resource change detector. The HTTP console and management API use the same process and state as DNS; browser assets are embedded in the executable.

flowchart LR
  CM[DNSZone / DNSRecords / PeerSite CRs or local JSON file] --> E[Configuration validation]
  E --> L[Local snapshot worker]
  K[Kubernetes resource lists] --> L
  L --> S[Source-owned snapshots]
  P[Direct peer snapshots] --> S
  S --> V[Immutable authoritative view]
  V --> D[UDP and TCP DNS]
  L --> X[Local-only peer exports]
  H[Internal HTTP console and API] --> E
  V --> H

All replicas independently load their configuration and sources. Kubernetes Kubernetes resource versions coordinate observations; there is no elected DNS leader, cross-pod memory sharing or persistent imported-data store. Convergence means replicas have observed equivalent source snapshots, not that an update becomes visible everywhere in one transaction.

The Kubernetes resource reference covers the objects the deployment creates and accesses. Running the service covers its listeners, Service exposure and process configuration.

Three representations of DNS data

Representation Contents and purpose
Configuration Local zone settings, static definitions, peer endpoints and the query-logging switch. Kubernetes saves each CR independently; file mode saves one versioned document.
Source snapshots One independently owned snapshot per cluster identity. Each contains zone metadata, flattened records, source versions and a content fingerprint.
Serving view The effective, merged authoritative data after deduplication, TTL reconciliation and conflict handling. Queries use this immutable view.

model.Snapshot contains clusterID, revision, versions, zones and records. Snapshot zones carry metadata without embedded records. Every record retains its source and optional zone. CR static records use dnsrecords/<UID>; file static records use static, and generated records use identifiers such as service/<UID>, node/<UID>, ingress/<UID> and externalipbinding/<UID>. Collection and object versions accompany the snapshot, with CR collection/object versions and the settings version.

The local source is separate from every imported source even when their records are identical. Store.Local() exports only the local snapshot. It never reads the merged view, so imported data cannot leak into a later export. A chain of peer connections therefore does not propagate another cluster's records.

Validation and canonicalization

Complete configuration and snapshot candidates are validated before publication. The model normalizes DNS names and textual RDATA, checks supported record types and wire encodability, validates zone ownership and sorts canonical data. Snapshots reject embedded zone records, source-provided SOA records and apex CNAME records where generated NS/SOA conflicts. Unzoned records are valid. Equivalent duplicate records from the same source collapse with the lower TTL; independently owned contributions remain separate.

A snapshot's revision is lowercase hexadecimal SHA-256 of its canonical JSON with revision set to an empty string and versions omitted. Thus a change to DNS content or ownership changes the fingerprint, while a source-watermark-only change does not. It is a content identity, not a timestamp, monotonic counter or Kubernetes resource version. Wire payload tokens additionally identify exact serialized bytes, including watermarks; see the peer protocol.

Local reconciliation

In Kubernetes mode, a refresh fetches complete Service, Node and Ingress lists plus the optional ExternalIPBinding list across all namespaces, and combines their generated records with static configuration from POD_NAMESPACE. Each list follows pagination, requires one collection resource version across its pages and rejects incomplete or malformed results. A failure in any required list rejects the entire candidate. The resource kinds are separate API observations; they are not a single cross-resource Kubernetes transaction.

The ExternalIPBinding API is probed anew each refresh. Only a missing first page is optional; permission errors and failures after pagination starts reject publication. This allows a CRD registered after process startup to contribute records without restarting pods. Binding names and declared-address semantics are documented in generated records.

Service/Ingress/binding annotations are evaluated from those same complete lists. Ignored Services suppress their own addresses, referenced binding addresses and controller mappings. Nonignored exposed Services opt into a class-to-Service DNS name registry through ingress annotations. Ingresses with an explicit mapped class contribute CNAMEs under their own UID; classless/unmapped Ingresses are skipped. Conflicting Services for one class reject the candidate rather than selecting by list order. No controller name or IngressClass default is inferred. See Kubernetes annotations.

Custom resources are re-read completely by a one-second configuration change detector and by periodic local reconciliation. Complete source reads include CR collection/object watermarks from the exact definitions used to generate the snapshot. Generated resources use periodic complete lists. Across resource kinds these are separate API observations, not a Kubernetes transaction. No informer or per-object generated-resource watch is required.

Local and remote TSIG Secrets reload on each local cycle. A valid local key is created only when initially absent; existing Secrets are never blindly replaced. Accepted rotation changes the dynamic DNS TSIG provider without restarting listeners. Malformed updates retain last-valid keys and expose errors.

File mode reads the configured JSON file and builds a static local snapshot. It disables Kubernetes ingestion but can still import and export peer data. File-mode snapshots have no Kubernetes version watermarks. The file's configuration version is a SHA-256 of its exact bytes, used for optimistic management edits.

Configuration acceptance and source refresh are distinct. Saving valid configuration schedules reconciliation; DNS begins serving the changed records after a complete replacement snapshot is published. A candidate built against an older configuration version is discarded if configuration changes before its publication. See configuration for inputs, defaults, precedence and reload rules.

Cache publication and locking

The store uses a read/write mutex to protect the source map, serving-view pointer and publication generations. A replacement follows these steps:

  1. Clone and normalize the proposed source, then calculate its content identity.
  2. Capture the current generation and immutable source references under a shared lock. Construct the proposed source map outside the lock.
  3. Check the combined source-record limit and build a complete new serving view outside the lock when content changed.
  4. Acquire the exclusive lock. If another writer advanced the generation, retry from the new state; otherwise publish the source map and view together.

An identical content-and-watermark replacement is a no-op. A watermark-only replacement publishes source metadata while retaining the existing serving view. This avoids rebuilding record indexes and SOA hashes for an unchanged observation. The cache still validates incoming candidates before taking these shortcuts.

Readers briefly acquire a shared lock to capture an immutable publication. Lookups copy DNS RRs before returning them, and inspection/export accessors make defensive copies, so callers cannot mutate retained data after a lock is released. Large snapshot copying is performed outside the store lock. Kubernetes requests, peer requests and DNS writes never run while holding that lock.

The store has two publication stamps. Its general generation detects concurrent changes to any source. Its local generation changes only for a local content or watermark publication; imports do not invalidate local peer-export caches. LocalVersioned() captures a coherent local snapshot and local stamp, and LocalGeneration() provides the inexpensive freshness check used by exports.

The engine separately serializes configuration reads, management saves and final local publication with applyMu. It does not hold the readiness/status mutex while constructing the serving view. File reads and saves additionally share a file mutex. These process-local locks do not replace Kubernetes optimistic resource-version checks between pods.

Ownership and the merged view

Records are indexed by owning zone, owner name and type. The most specific hosted zone handles a query. Parent-zone glue and wildcard definitions remain in the parent's indexes; they cannot become authoritative child-zone records, mask a child CNAME or change the child's name-existence tests.

Within a zone, contributors to the same name and type merge by canonical RDATA. Identical values are returned once while all source snapshots retain ownership. Every value in an effective RRset uses the minimum contributing TTL. Removing one contributor therefore preserves an identical value still owned by another. Address answers vary their order to support DNS round-robin.

Any A or AAAA contribution masks CNAME data at that owner throughout the effective view, including CNAME queries. Masking never deletes the source definition. Different CNAME targets, or a remaining CNAME combined with non-address data, mark the owner as conflicting; authoritative resolution reports SERVFAIL rather than choosing a contributor by arrival order. The DNS behaviour document defines alias and delegation handling in detail.

For a shared zone, metadata comes from the lexicographically first contributing cluster identity. All converged replicas make the same choice. Coordinate those zone settings across clusters; metadata selection is deterministic conflict resolution, not a distributed zone-editing protocol.

SOA generation streams the selected metadata and source-owned zone records into a hash rather than repeatedly concatenating a growing zone string. The serial uses the first four digest bytes as a big-endian integer, replacing zero with one. This is reproducible for equal source contents but is not chronological serial arithmetic. Ordinary secondary DNS expiry and serial rules do not govern TAK-OS peer retention.

Retention and explicit removal

TTL controls downstream caching. It does not expire authoritative data from a running process. A failed Kubernetes refresh, failed configuration read, unavailable peer or elapsed SOA expiry interval leaves the last complete accepted source intact. Health/freshness remains observable independently from the served records.

Only an explicit source replacement/removal changes ownership. Absence from a successfully completed snapshot removes that source's earlier contribution. Removing a peer configuration removes its imported source. Removing a DNSZone removes metadata while independent DNSRecords and generated records remain eligible. Removing DNSRecords removes only its contributions; imported zone/data ownership remains independent.

Local and imported snapshots, journals and transfer sessions are memory-only. Definitions persist in CRs or the file; discovery metadata persists in PeerSite status, credentials in Secrets or the TSIG file, and logging in the settings ConfigMap/file. After restart, sources are rebuilt and peer data is fetched again. An all-pod restart can therefore expose a brief warm-up period, extended for any unavailable source cluster.

Readiness and termination

Readiness requires all of the following: an accepted configuration, a successful local snapshot publication, a valid local TSIG key, completion of an initial synchronization attempt for every configured peer, and a process that is not stopping. A peer need not succeed for its initial attempt to count. Later failures retain last-good data and do not automatically revoke readiness; monitor freshness separately.

DNS and HTTP serving start while workers establish initial state. DNS listener startup waits until both UDP and TCP servers are active. A later listener failure is propagated to the engine, which stops rather than leaving an HTTP-healthy process with a broken DNS transport. /livez itself tests HTTP availability.

SIGINT/SIGTERM cancel the engine context, mark readiness false, cancel workers and drain HTTP/DNS listeners within the shutdown budget. HTTP has bounded header, request, write and idle deadlines; DNS and transfer bounds are documented separately. Operational inspection and recovery procedures belong in observability and troubleshooting.

Transitive topology, direct DNS ownership

Authenticated peer sync obtains a separate, paginated site catalogue. It contains site IDs and endpoints but no secrets or DNS records. A learns C through B, persists a pending PeerSite for C, and fetches C directly after an administrator or automation supplies C’s key. B never re-exports C’s imported DNS records. Each transfer direction is independent: A needs C’s local key to read C; C needs A’s local key to read A. Reciprocal PeerSite configuration is not inbound access control. Discovery retains per-advertiser address/path provenance, rejects returning paths and avoids re-advertising route-less learned entries as seeds. Metadata errors are separate from valid DNS snapshot publication. It gives direct self advertisements precedence; see peer administration.

The workload is a DaemonSet behind UDP/TCP53 Services with externalIPs; it does not use host networking. The local topology advertises the intersection of Node ExternalIPs and the configured DNS Service externalIPs. The operator must ensure those addresses are routed/exposed by the Service.

All cached positive answers are authoritative, whether zoned or unzoned. Known names with no requested type return authoritative NOERROR/NODATA, with an SOA only when enabled for the selected zone. Completely unknown names return REFUSED even beneath SOA; the service never emits NXDOMAIN or recurses. The complete DNS behaviour includes DNAME and resolver fallback limits.

The serving index also tracks independent (zone-empty) RRset contributions after masking. Their cached positives/aliases may bypass a parent delegation without reclassifying explicit parent-owned glue or crossing child-zone ownership. This preserves the zone-independent positive-answer contract while keeping referrals for data that is only parent glue.

Cache.Lookup retains normal parent referral results. The DNS listener separately converts an empty-answer, non-authoritative NS referral into REFUSED for RD=true stub queries, stripping referral authority/glue. RD=false iterative queries keep the referral. This policy supplies a useful libc fallback signal without adding recursion or changing independently cached authoritative positives.

Known-name NODATA is scoped to effective RR owners/wildcard synthesis and empty non-terminals established within explicit zones. Unzoned inferred ancestors do not become known merely because a descendant record exists. A bare no-SOA/no-NS zone also does not synthesize apex existence. This prevents standalone private names from asserting NODATA at unrelated public ancestors.

For an independently known owner below a parent delegation, missing-type NODATA does not attach the parent's SOA. Only an applicable uncut zone can supply SOA authority; independent existence does not promote an existing parent-owned glue RRset into an authoritative answer.