From 6eaaf6e21fe8c9e46e6d9d758960c02da13b6dfa Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 10:09:09 -0600 Subject: [PATCH 01/17] feat(site): Ship Kea and the synchronizer as a site component Add a site DHCP component: the reservation feed beside the boot service, now served only over TLS, and Kea DHCPv4 instances with their synchronizers on host-networked nodes. The synchronizer gains a CA option and Kea 2.6's socket path. A render check runs in CI, and a lab runs real Kea, the synchronizer and the feed with a DHCP client to prove a boot NIC is answered only while its admission is open. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 + Taskfile.yaml | 5 + cmd/fleet-dhcp-sync/main.go | 22 +++- cmd/fleet-multiplane/main.go | 4 +- cmd/fleet-multiplane/site.go | 4 +- config/site/dhcp/component/dhcp.yaml | 110 ++++++++++++++++++ config/site/dhcp/component/kustomization.yaml | 51 ++++++++ config/site/dhcp/example/base.yaml | 26 +++++ config/site/dhcp/example/kustomization.yaml | 10 ++ docs/operations/boot-network.md | 79 ++++++++++++- hack/boot-network/kea-lab.sh | 94 +++++++++++++++ hack/boot-network/lab/main.go | 82 +++++++++++++ hack/validate-site-dhcp-render.sh | 33 ++++++ internal/site/redfishwork/dhcp.go | 13 ++- internal/site/redfishwork/dhcp_test.go | 8 ++ 15 files changed, 527 insertions(+), 15 deletions(-) create mode 100644 config/site/dhcp/component/dhcp.yaml create mode 100644 config/site/dhcp/component/kustomization.yaml create mode 100644 config/site/dhcp/example/base.yaml create mode 100644 config/site/dhcp/example/kustomization.yaml create mode 100755 hack/boot-network/kea-lab.sh create mode 100644 hack/boot-network/lab/main.go create mode 100755 hack/validate-site-dhcp-render.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5ebf70d0..37d73bd3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -132,6 +132,7 @@ jobs: - name: Install ripgrep for the link check run: sudo apt-get update -qq && sudo apt-get install -y -qq --no-install-recommends ripgrep - run: ./hack/test-run-standalone-smoke.sh + - run: ./hack/validate-site-dhcp-render.sh - run: ./hack/validate-doc-links.sh - run: ./hack/multiplane/test-harness.sh - run: shellcheck -S warning hack/multiplane/*.sh hack/local-vm/start-libvirt hack/local-vm/site-runtime diff --git a/Taskfile.yaml b/Taskfile.yaml index 5210d72d..5d288f83 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -6,6 +6,11 @@ tasks: cmds: - ./hack/run-standalone-smoke.sh + boot-network:kea-lab: + desc: Prove the site DHCP path with real Kea, the synchronizer and the feed on one container bridge. + cmds: + - ./hack/boot-network/kea-lab.sh + multiplane:acceptance: desc: Fresh local Milo/Karmada/kro/PXE acceptance, every service installed by per-cluster Flux from the checkout, in the task-owned Colima profile (exit 0 pass, 1 fail, 2 preflight, 3 blocked, 4 timeout). env: diff --git a/cmd/fleet-dhcp-sync/main.go b/cmd/fleet-dhcp-sync/main.go index 74a7a69a..4393540a 100644 --- a/cmd/fleet-dhcp-sync/main.go +++ b/cmd/fleet-dhcp-sync/main.go @@ -5,6 +5,8 @@ package main import ( "context" + "crypto/tls" + "crypto/x509" "errors" "flag" "fmt" @@ -21,23 +23,24 @@ import ( ) func main() { - var feed, tokenPath, instance, socket, base string + var feed, tokenPath, caPath, instance, socket, base string var interval time.Duration flag.StringVar(&feed, "feed", "", "site DHCP feed origin, https://host[:port]") flag.StringVar(&tokenPath, "token-file", "", "file holding the synchronizer bearer token") + flag.StringVar(&caPath, "ca-file", "", "PEM CA bundle the feed's certificate must chain to; default the system roots") flag.StringVar(&instance, "instance", os.Getenv("POD_NAME"), "stable name of this Kea instance") - flag.StringVar(&socket, "kea-socket", "/run/kea/kea4-ctrl-socket", "Kea DHCPv4 unix control socket") + flag.StringVar(&socket, "kea-socket", "/var/run/kea/kea4-ctrl-socket", "Kea DHCPv4 unix control socket; Kea 2.6 allows only /var/run/kea") flag.StringVar(&base, "base-config", "/etc/kea/kea-dhcp4.conf", "Kea configuration without Fleet reservations") flag.DurationVar(&interval, "interval", 5*time.Second, "feed poll interval") flag.Parse() logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) - if err := run(logger, feed, tokenPath, instance, socket, base, interval); err != nil && !errors.Is(err, context.Canceled) { + if err := run(logger, feed, tokenPath, caPath, instance, socket, base, interval); err != nil && !errors.Is(err, context.Canceled) { logger.Error("dhcp sync stopped", "error", err) os.Exit(1) } } -func run(logger *slog.Logger, feed, tokenPath, instance, socket, base string, interval time.Duration) error { +func run(logger *slog.Logger, feed, tokenPath, caPath, instance, socket, base string, interval time.Duration) error { u, err := url.Parse(feed) if err != nil || u.Scheme != "https" || u.Host == "" || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.User != nil { return errors.New("feed must be an https origin") @@ -48,6 +51,17 @@ func run(logger *slog.Logger, feed, tokenPath, instance, socket, base string, in } transport := http.DefaultTransport.(*http.Transport).Clone() transport.Proxy = nil + if caPath != "" { + pem, err := os.ReadFile(caPath) + if err != nil { + return fmt.Errorf("CA bundle: %w", err) + } + roots := x509.NewCertPool() + if !roots.AppendCertsFromPEM(pem) { + return errors.New("CA bundle holds no certificate") + } + transport.TLSClientConfig = &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12} + } s := &dhcpsync.Syncer{ Feed: u.Scheme + "://" + u.Host, Token: strings.TrimSpace(string(token)), Instance: instance, Socket: socket, Base: base, HTTP: &http.Client{Timeout: 15 * time.Second, Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index aec50164..d87ac8e2 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -54,6 +54,8 @@ func run() error { installationDeadline := fs.Duration("installation-deadline", 0, "replace the installation deadline for operations this coordinator admits (coordinator)") skewMargin := fs.Duration("skew-margin", 0, "replace the margin after a deadline before the coordinator declares it exceeded (coordinator)") instance := fs.String("instance", "", "DHCP instance an operator retires (dhcp-retire)") + tlsCert := fs.String("tls-cert", "", "TLS certificate the DHCP feed serves (dhcp-feed)") + tlsKey := fs.String("tls-key", "", "TLS key of the DHCP feed (dhcp-feed)") if err := fs.Parse(os.Args[2:]); err != nil { return err } @@ -81,7 +83,7 @@ func run() error { fmt.Println(image) return nil case "boot-service", "boot-denials", "dhcp-feed": - return boot(os.Args[1], *origin, *extraMAC, *syncToken) + return boot(os.Args[1], *origin, *extraMAC, *syncToken, *tlsCert, *tlsKey) case "boot-withhold": return armWithhold(fs.Arg(0)) case "dhcp-retire": diff --git a/cmd/fleet-multiplane/site.go b/cmd/fleet-multiplane/site.go index 04ef09d9..2f00d5af 100644 --- a/cmd/fleet-multiplane/site.go +++ b/cmd/fleet-multiplane/site.go @@ -228,7 +228,7 @@ func redfishKinds(work redfishwork.Config, burnIn string) map[string]site.Kind { // boot serves network boots, the DHCP reservation feed, or probes that // every closed admission is denied. -func boot(command, origin, extraMAC, syncToken string) error { +func boot(command, origin, extraMAC, syncToken, tlsCert, tlsKey string) error { store, err := openStore() if err != nil { return err @@ -267,7 +267,7 @@ func boot(command, origin, extraMAC, syncToken string) error { if err != nil { return fmt.Errorf("DHCP synchronizer token: %w", err) } - return server.ServeDHCP(strings.TrimSpace(string(token))) + return server.ServeDHCP(strings.TrimSpace(string(token)), tlsCert, tlsKey) } return serveBoot(server.Handler(), vmwork.DefaultBootWindow*2) } diff --git a/config/site/dhcp/component/dhcp.yaml b/config/site/dhcp/component/dhcp.yaml new file mode 100644 index 00000000..5da29e67 --- /dev/null +++ b/config/site/dhcp/component/dhcp.yaml @@ -0,0 +1,110 @@ +# The feed, reachable only inside the site cluster. +apiVersion: v1 +kind: Service +metadata: + name: fleet-site-dhcp-feed + namespace: fleet-site +spec: + type: ClusterIP + selector: {app.kubernetes.io/name: fleet-site-boot} + ports: + - {name: dhcp-feed, port: 8081, targetPort: 8081, protocol: TCP} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-site-dhcp, namespace: fleet-site} +automountServiceAccountToken: false +--- +# Kea DHCPv4 instances. Each Pod's name is its stable instance name in the +# applied reports. Pods use host networking on nodes that network operations +# labels as DHCP hosts, one per node, and Kea answers only relayed requests on +# that node's address. Scale down only after the instance being removed +# reports an empty feed: an instance removed while serving keeps its +# operations' outcomes unknown until an operator retires it. +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: fleet-site-dhcp + namespace: fleet-site +spec: + serviceName: fleet-site-dhcp + replicas: 2 + podManagementPolicy: Parallel + selector: + matchLabels: {app.kubernetes.io/name: fleet-site-dhcp} + template: + metadata: + labels: {app.kubernetes.io/name: fleet-site-dhcp} + spec: + serviceAccountName: fleet-site-dhcp + automountServiceAccountToken: false + hostNetwork: true + dnsPolicy: ClusterFirstWithHostNet + nodeSelector: {fleet.datumapis.com/dhcp-host: "true"} + affinity: + podAntiAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + - labelSelector: {matchLabels: {app.kubernetes.io/name: fleet-site-dhcp}} + topologyKey: kubernetes.io/hostname + containers: + - name: kea + # ISC's image, pinned by digest. It is built for linux/amd64 only. + image: docker.cloudsmith.io/isc/docker/kea-dhcp4:2.6.3@sha256:c40abb1522b15edb9a6d1119ad22b3765bf818a51d6776f498e874ad13416065 + command: [kea-dhcp4, -c, /etc/kea-base/kea-dhcp4.conf] + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + capabilities: {drop: [ALL], add: [NET_BIND_SERVICE, NET_RAW]} + resources: + requests: {cpu: 50m, memory: 64Mi} + limits: {memory: 256Mi} + volumeMounts: + - {name: base, mountPath: /etc/kea-base, readOnly: true} + - {name: control, mountPath: /var/run/kea} + - name: sync + image: "${FLEET_DHCP_SYNC_IMAGE}" + imagePullPolicy: IfNotPresent + command: + - /fleet-dhcp-sync + - -feed=https://fleet-site-dhcp-feed.fleet-site.svc:8081 + - -token-file=/etc/fleet-dhcp/token + - -ca-file=/etc/fleet-dhcp-tls/ca.crt + - -kea-socket=/var/run/kea/kea4-ctrl-socket + - -base-config=/etc/kea-base/kea-dhcp4.conf + env: + - name: POD_NAME + valueFrom: {fieldRef: {fieldPath: metadata.name}} + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 10m, memory: 16Mi} + limits: {memory: 64Mi} + volumeMounts: + - {name: base, mountPath: /etc/kea-base, readOnly: true} + - {name: control, mountPath: /var/run/kea} + - {name: token, mountPath: /etc/fleet-dhcp, readOnly: true} + - {name: feed-ca, mountPath: /etc/fleet-dhcp-tls, readOnly: true} + volumes: + - name: base + configMap: {name: fleet-site-dhcp-base} + - name: control + emptyDir: {} + - name: token + secret: {secretName: fleet-site-dhcp-sync, defaultMode: 0400} + - name: feed-ca + secret: {secretName: fleet-site-dhcp-feed-tls, defaultMode: 0400, items: [{key: ca.crt, path: ca.crt}]} +--- +# One instance may restart at a time. Draining before scale-down is an +# operator step; see the comment on the StatefulSet. +apiVersion: policy/v1 +kind: PodDisruptionBudget +metadata: + name: fleet-site-dhcp + namespace: fleet-site +spec: + maxUnavailable: 1 + selector: + matchLabels: {app.kubernetes.io/name: fleet-site-dhcp} diff --git a/config/site/dhcp/component/kustomization.yaml b/config/site/dhcp/component/kustomization.yaml new file mode 100644 index 00000000..be334519 --- /dev/null +++ b/config/site/dhcp/component/kustomization.yaml @@ -0,0 +1,51 @@ +# The site DHCP service for a site whose DHCP Fleet synchronizes: the +# reservation feed beside the boot service, and Kea DHCPv4 instances, each +# with its synchronizer. Network operations owns the base configuration +# (ConfigMap fleet-site-dhcp-base) and the relays that point at the Kea +# hosts. The environment supplies two Secrets, never in Git: +# fleet-site-dhcp-sync (key token, at least 32 characters) and +# fleet-site-dhcp-feed-tls (tls.crt, tls.key, ca.crt). See +# docs/operations/boot-network.md. +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component +resources: + - dhcp.yaml +patches: + # The feed reads the site store and writes the applied reports beside the + # boot evidence, so it runs in the boot Pod, which holds the state volume. + - target: {kind: Deployment, name: fleet-site-boot} + patch: |- + - op: add + path: /spec/template/spec/containers/- + value: + name: dhcp-feed + image: "${FLEET_SITE_IMAGE}" + imagePullPolicy: IfNotPresent + command: [fleet-multiplane, dhcp-feed, -sync-token-file, /etc/fleet-dhcp/token, -tls-cert, /etc/fleet-dhcp-tls/tls.crt, -tls-key, /etc/fleet-dhcp-tls/tls.key] + env: + - {name: FLEET_SITE_PROVIDER, value: redfish} + - {name: FLEET_BOOT_EVIDENCE, value: /var/lib/fleet-boot} + ports: + - {name: dhcp-feed, containerPort: 8081} + readinessProbe: + tcpSocket: {port: 8081} + periodSeconds: 5 + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 10m, memory: 32Mi} + limits: {memory: 128Mi} + volumeMounts: + - {name: state, mountPath: /var/lib/fleet-local, subPath: journal, readOnly: true} + - {name: state, mountPath: /var/lib/fleet-boot, subPath: boot-evidence} + - {name: dhcp-sync-token, mountPath: /etc/fleet-dhcp, readOnly: true} + - {name: dhcp-feed-tls, mountPath: /etc/fleet-dhcp-tls, readOnly: true} + - op: add + path: /spec/template/spec/volumes/- + value: {name: dhcp-sync-token, secret: {secretName: fleet-site-dhcp-sync, defaultMode: 0400}} + - op: add + path: /spec/template/spec/volumes/- + value: {name: dhcp-feed-tls, secret: {secretName: fleet-site-dhcp-feed-tls, defaultMode: 0400}} diff --git a/config/site/dhcp/example/base.yaml b/config/site/dhcp/example/base.yaml new file mode 100644 index 00000000..94a9fc58 --- /dev/null +++ b/config/site/dhcp/example/base.yaml @@ -0,0 +1,26 @@ +# A synthetic base configuration. Network operations owns the real one: the +# site's provisioning subnet and gateway, the relay addresses Kea accepts, and +# the boot options. It has no pools, so Kea answers only reserved MACs, and +# Kea 2.6 requires the control socket under /var/run/kea. +apiVersion: v1 +kind: ConfigMap +metadata: + name: fleet-site-dhcp-base + namespace: fleet-site +data: + kea-dhcp4.conf: | + {"Dhcp4": { + "interfaces-config": {"interfaces": ["*"], "dhcp-socket-type": "udp"}, + "control-socket": {"socket-type": "unix", "socket-name": "/var/run/kea/kea4-ctrl-socket"}, + "lease-database": {"type": "memfile", "persist": false}, + "host-reservation-identifiers": ["hw-address"], + "valid-lifetime": 600, + "subnet4": [{ + "id": 1, + "subnet": "198.51.100.0/24", + "relay": {"ip-addresses": ["198.51.100.1"]}, + "option-data": [{"name": "routers", "data": "198.51.100.1"}], + "next-server": "192.0.2.80", + "boot-file-name": "http://192.0.2.80:8080/pxe/boot.ipxe" + }] + }} diff --git a/config/site/dhcp/example/kustomization.yaml b/config/site/dhcp/example/kustomization.yaml new file mode 100644 index 00000000..4fcb1299 --- /dev/null +++ b/config/site/dhcp/example/kustomization.yaml @@ -0,0 +1,10 @@ +# Render check only: the Redfish site services with the site DHCP service and +# a synthetic base configuration. An environment supplies its own base +# configuration from network operations. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../../redfish/services + - base.yaml +components: + - ../component diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index f41b34fd..aa02b193 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -155,8 +155,9 @@ synchronized clocks. ## Feed and reports -The site's `dhcp-feed` role (`fleet-multiplane dhcp-feed -sync-token-file …`) -listens on `:8081`, never on the firmware-facing boot listener. It reads the +The site's `dhcp-feed` role (`fleet-multiplane dhcp-feed -sync-token-file … +-tls-cert … -tls-key …`) listens with TLS on `:8081`, never on the +firmware-facing boot listener. It reads the site store read-only and writes only `dhcp-applied.log` in the boot-evidence directory. Every request needs `Authorization: Bearer `; the token is at least 32 characters. @@ -177,7 +178,10 @@ is treated as corruption, never as evidence. ## Kea synchronizer `fleet-dhcp-sync` (in the manager image) runs beside one Kea DHCPv4 instance, -with a stable instance name such as a StatefulSet pod name. Each cycle it: +with a stable instance name such as a StatefulSet pod name. `-ca-file` names +the CA bundle the feed's certificate must chain to. Kea 2.6 accepts a control +socket only under `/var/run/kea`, which is the synchronizer's default. Each +cycle it: 1. fetches and verifies the feed over HTTPS; 2. reads Kea's PID with `status-get`; @@ -192,6 +196,73 @@ fails the cycle; it is never dropped. A restarted Kea loses its reservations and fails closed until the next cycle re-applies them. Before scaling down, drain the instance being removed until it reports an empty feed. +## Site DHCP service + +The `config/site/dhcp/component` Kustomize component deploys the service at a +synchronized site: + +| Object | What it runs | +| --- | --- | +| `dhcp-feed` container in `fleet-site-boot` | The feed, beside the boot service, so it reads the site store read-only and appends reports to the boot evidence on the same volume | +| `fleet-site-dhcp-feed` Service | The feed on `:8081`, inside the site cluster only | +| `fleet-site-dhcp` StatefulSet | At least two Pods, one per node labeled `fleet.datumapis.com/dhcp-host=true`, with host networking. Each runs ISC's Kea DHCPv4 image, pinned by digest, and the synchronizer, sharing Kea's control socket. The Pod name is the instance name | +| `fleet-site-dhcp` PodDisruptionBudget | One instance down at a time | + +The environment supplies, never in Git: + +- the `fleet-site-dhcp-sync` Secret, with the synchronizer token under `token`; +- the `fleet-site-dhcp-feed-tls` Secret, with `tls.crt` and `tls.key` for the + name `fleet-site-dhcp-feed.fleet-site.svc` and the issuing `ca.crt`; +- the `fleet-site-dhcp-base` ConfigMap from network operations, with + `kea-dhcp4.conf`; and +- the `FLEET_SITE_IMAGE` and `FLEET_DHCP_SYNC_IMAGE` substitutions. + +The base configuration names the site's provisioning subnet and gateway, the +relay addresses Kea accepts, and the boot options. It has no pools, so Kea +answers only reserved MACs, and its control socket is the synchronizer's. +`config/site/dhcp/example` renders the component with a synthetic base +configuration, and `hack/validate-site-dhcp-render.sh` checks that render in +CI. ISC builds the Kea image for `linux/amd64` only. + +## Network operations requirements + +Fleet configures no switch, router or relay. A synchronized site needs: + +1. A provisioning VLAN, untagged on each server's boot NIC port. +2. A private VLAN or equivalent on the provisioning VLAN only, so a server + reaches only the gateway there. Customer VLANs on the same port keep normal + forwarding. +3. Spanning tree edge mode on server ports. +4. LACP fallback to an individual port where the boot NIC is a bond member, + with a fallback timeout below the DHCP timeout of every qualified firmware. +5. On the provisioning subnet's gateway, a DHCP relay to the address of every + node labeled as a DHCP host, with the gateway as the relay address. +6. Routes and filters so the provisioning subnet reaches only the DHCP hosts and + the boot service, and no customer network, BMC network or internet. +7. DHCP snooping and source address binding on the provisioning VLAN. +8. LLDP on server ports. +9. Switch and port names in Fleet's cable records that match the network + owner's. +10. The base configuration above. + +## Boot network lab + +`task boot-network:kea-lab` (`hack/boot-network/kea-lab.sh`) runs ISC's Kea +image, the real synchronizer, and the site's feed listener over TLS on one +container bridge, in the `colima` Docker context by default. A lab program +opens and closes boot admissions in a real site store, and a `udhcpc` client +with a chosen MAC asks for an address. It passes only if: + +1. a boot NIC with no open admission gets no answer; +2. the reserved boot NIC gets exactly its boot address while its admission is + open, and another NIC gets none; and +3. after the admission closes and Kea reports the withdrawal, the boot NIC gets + no answer. + +The lab proves the feed, the synchronizer, Kea's configuration and a real DHCP +exchange. It has no relay, no VLAN, no switch and no firmware, so it proves +none of the network operations requirements. + ## Implemented versus proposed | Behavior | Status | @@ -200,7 +271,7 @@ drain the instance being removed until it reports an empty feed. | Boot NIC from Device inventory through the admission snapshot; enrollment without MACs or addresses | Implemented; unit tested | | Reservation feed, authenticated applied reports, served and withdrawn gates over every reservation of the Device, instance retirement | Implemented; unit tested with a fake BMC and synchronizer, including a silent instance | | Kea synchronizer: containing-subnet placement, restart re-apply, report only after Kea accepted | Implemented; unit tested against a fake Kea control socket | -| Deployment of the feed, TLS to the feed, Kea and the synchronizer as a site component | Proposed | +| Feed over TLS, Kea and the synchronizer as a site component | Implemented; render checked in CI, and the DHCP path proved by the boot network lab with real Kea. Not deployed at a site | | Relay, provisioning VLAN, isolation and LACP fallback at a site | Network operations; see the [server networking enhancement][server-networking] | | Telling firmware what to boot in synced mode (Redfish `HttpBootUri` for UEFI HTTP Boot, or a DHCP boot-file option) | Proposed; the Redfish worker still arms `Pxe`, which relies on site DHCP for the boot file | | DHCPv6 reservations | Proposed; the feed accepts IPv6, the Kea DHCPv4 synchronizer and the claim reject it | diff --git a/hack/boot-network/kea-lab.sh b/hack/boot-network/kea-lab.sh new file mode 100755 index 00000000..b8dfcc23 --- /dev/null +++ b/hack/boot-network/kea-lab.sh @@ -0,0 +1,94 @@ +#!/usr/bin/env bash +# Boot network DHCP lab. Runs real Kea DHCPv4 and the real synchronizer +# against the site's reservation feed over TLS, on one container bridge, and +# proves with a DHCP client that Kea answers a boot NIC only while its boot +# admission is open. There is no relay and no switch: see +# docs/operations/boot-network.md for what this does not prove. +# +# Exit codes: 0 passed, 1 failed. +set -euo pipefail +cd "$(dirname "$0")/../.." +export DOCKER_CONTEXT="${DOCKER_CONTEXT:-colima}" +image=docker.cloudsmith.io/isc/docker/kea-dhcp4:2.6.3@sha256:c40abb1522b15edb9a6d1119ad22b3765bf818a51d6776f498e874ad13416065 +prefix="fleet-kea-lab-$(openssl rand -hex 4)" +state=$(mktemp -d) +mac=02:00:5e:00:53:01 +other=02:00:5e:00:53:02 +address=198.51.100.200 + +cleanup() { + docker rm -f "$prefix-feed" "$prefix-kea" >/dev/null 2>&1 || true + docker network rm "$prefix" >/dev/null 2>&1 || true + rm -rf "$state" +} +trap cleanup EXIT +fail() { echo "FAIL $*" >&2; docker logs "$prefix-kea" 2>&1 | tail -20 >&2 || true; exit 1; } + +echo "building linux/amd64 binaries" +GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o "$state/fleet-dhcp-sync" ./cmd/fleet-dhcp-sync +GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o "$state/lab" ./hack/boot-network/lab +openssl rand -hex 32 > "$state/token" +openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 1 -subj /CN=feed \ + -addext subjectAltName=DNS:feed -keyout "$state/feed.key" -out "$state/feed.crt" 2>/dev/null +# The network owner's base configuration: one provisioning subnet, its +# gateway, no pool, so only reserved MACs get an answer. +cat > "$state/kea.json" <<'EOF' +{"Dhcp4": { + "interfaces-config": {"interfaces": ["eth0"], "dhcp-socket-type": "raw"}, + "control-socket": {"socket-type": "unix", "socket-name": "/var/run/kea/kea4-ctrl-socket"}, + "lease-database": {"type": "memfile", "persist": false}, + "host-reservation-identifiers": ["hw-address"], + "valid-lifetime": 120, + "subnet4": [{"id": 1, "subnet": "198.51.100.0/24", "option-data": [{"name": "routers", "data": "198.51.100.1"}]}] +}} +EOF + +# Docker assigns container addresses from the lower half only, so it never +# hands out the reserved address. +docker network create --subnet 198.51.100.0/24 --ip-range 198.51.100.0/25 --gateway 198.51.100.1 "$prefix" >/dev/null +docker create --name "$prefix-feed" --platform linux/amd64 --user 0 --network "$prefix" --network-alias feed --entrypoint sh "$image" \ + -c 'mkdir -p -m 0700 /state/store /state/boot && exec /lab/lab serve -store /state/store -boot /state/boot -token-file /lab/token -cert /lab/feed.crt -key /lab/feed.key' >/dev/null +docker create --name "$prefix-kea" --platform linux/amd64 --user 0 --network "$prefix" --cap-add NET_ADMIN --cap-add NET_RAW --entrypoint sh "$image" \ + -c 'mkdir -p /var/run/kea && (kea-dhcp4 -c /lab/kea.json &) && sleep 2 && exec /lab/fleet-dhcp-sync -feed https://feed:8081 -token-file /lab/token -instance kea-a -kea-socket /var/run/kea/kea4-ctrl-socket -base-config /lab/kea.json -ca-file /lab/feed.crt -interval 1s' >/dev/null +for container in feed kea; do + docker cp "$state/." "$prefix-$container:/lab" >/dev/null + docker start "$prefix-$container" >/dev/null +done + +lab() { docker exec "$prefix-feed" /lab/lab "$1" -store /state/store -boot /state/boot "${@:2}"; } +reports() { docker exec "$prefix-feed" cat /state/boot/dhcp-applied.log 2>/dev/null || true; } +# latest prints kea-a's most recent applied feed. +latest() { reports | grep '"instance":"kea-a"' | tail -1; } +await() { + local what=$1 check=$2 + for _ in $(seq 1 90); do + if eval "$check"; then return 0; fi + sleep 1 + done + fail "timed out: $what" +} +client() { + docker run --rm --platform linux/amd64 --network "$prefix" --mac-address "$1" --cap-add NET_ADMIN --cap-add NET_RAW --entrypoint udhcpc "$image" \ + -i eth0 -n -q -f -t 4 -T 2 -s /bin/true 2>&1 || true +} + +await "Kea applies and reports the empty feed" '[ -n "$(latest)" ]' +latest | grep -q '"reservations":\[\]' || fail "the first report was not empty" +client "$mac" | grep -q 'lease of' && fail "Kea answered a boot NIC with no open admission" +echo "PASS no answer before admission" + +lab open -operation 00000000-0000-4000-8000-000000000101 -fence 1 -mac "$mac" -address "$address" +await "Kea serves the reservation" 'latest | grep -q "\"$address\""' +lease=$(client "$mac") +echo "$lease" | grep -q "lease of $address obtained" || fail "the reserved NIC did not get $address: $lease" +echo "PASS the reserved boot NIC got $address while its admission was open" +client "$other" | grep -q 'lease of' && fail "Kea answered an unreserved NIC" +echo "PASS an unreserved NIC got no answer" + +lab close -operation 00000000-0000-4000-8000-000000000101 +await "Kea withdraws the reservation" '! latest | grep -q "\"$address\""' +client "$mac" | grep -q 'lease of' && fail "Kea answered the boot NIC after its admission closed" +echo "PASS no answer after the admission closed" + +reports > "$state/evidence.log" +echo "PASS boot network DHCP lab: $(grep -c '' "$state/evidence.log") retained reports from kea-a" diff --git a/hack/boot-network/lab/main.go b/hack/boot-network/lab/main.go new file mode 100644 index 00000000..b0816cf8 --- /dev/null +++ b/hack/boot-network/lab/main.go @@ -0,0 +1,82 @@ +// Command lab drives the boot network lab: it serves a site's reservation +// feed from a site store over TLS, and opens and closes boot admissions in +// that store as a Redfish worker would. The lab script runs it beside real Kea +// and the real synchronizer. It is a lab seam, never deployed. +package main + +import ( + "errors" + "flag" + "fmt" + "os" + "strings" + "time" + + "go.datum.net/fleet/internal/bootnet" + "go.datum.net/fleet/internal/site" + "go.datum.net/fleet/internal/site/redfishwork" +) + +func main() { + if err := run(); err != nil { + fmt.Fprintln(os.Stderr, "lab:", err) + os.Exit(1) + } +} + +func run() error { + if len(os.Args) < 2 { + return errors.New("usage: lab serve|open|close|retire [flags]") + } + fs := flag.NewFlagSet(os.Args[1], flag.ContinueOnError) + storeDir := fs.String("store", "", "site store directory") + bootDir := fs.String("boot", "", "boot evidence directory") + tokenFile := fs.String("token-file", "", "synchronizer token file (serve)") + cert := fs.String("cert", "", "TLS certificate (serve)") + key := fs.String("key", "", "TLS key (serve)") + device := fs.String("device", "fleet-provider/server-example-001", "Device namespace/name") + operation := fs.String("operation", "", "operation UID (open, close)") + fence := fs.Int64("fence", 1, "operation fence (open)") + mac := fs.String("mac", "", "boot NIC MAC (open)") + address := fs.String("address", "", "boot address (open)") + instance := fs.String("instance", "", "DHCP instance (retire)") + if err := fs.Parse(os.Args[2:]); err != nil { + return err + } + if os.Args[1] == "retire" { + return redfishwork.RetireInstance(*bootDir, *instance) + } + store, err := site.OpenStore(*storeDir, nil) + if err != nil { + return err + } + switch os.Args[1] { + case "serve": + token, err := os.ReadFile(*tokenFile) + if err != nil { + return err + } + // The same listener the site's dhcp-feed role runs, on :8081. + return redfishwork.BootServer{Store: store, BootRoot: *bootDir}.ServeDHCP(strings.TrimSpace(string(token)), *cert, *key) + case "open": + normalized, ok := bootnet.NormalizeMAC(*mac) + if !ok || *operation == "" { + return errors.New("open needs an operation and a MAC") + } + if err := store.Raise(*device, *fence); err != nil { + return err + } + now := time.Now().UTC() + boot := redfishwork.Boot{Operation: *operation, Fence: *fence, Mode: "install", MAC: normalized, Address: *address, Receipt: "lab", Token: strings.Repeat("0", 64), Created: now, Expires: now.Add(20 * time.Minute)} + return store.PutRecord(*device, *fence, "boot", *operation, boot) + case "close": + var boot redfishwork.Boot + found, err := store.GetRecord(*device, "boot", *operation, &boot) + if err != nil || !found { + return fmt.Errorf("no boot admission %s: %v", *operation, err) + } + boot.Closed = true + return store.PutRecord(*device, boot.Fence, "boot", *operation, boot) + } + return errors.New("unknown command") +} diff --git a/hack/validate-site-dhcp-render.sh b/hack/validate-site-dhcp-render.sh new file mode 100755 index 00000000..8e0fb6f4 --- /dev/null +++ b/hack/validate-site-dhcp-render.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# Renders the site DHCP service with its synthetic base configuration and +# checks the contract docs/operations/boot-network.md states. +set -euo pipefail +cd "$(dirname "$0")/.." +kustomize build config/site/dhcp/example | python3 -c ' +import json, sys +import yaml +docs = [d for d in yaml.safe_load_all(sys.stdin) if d] +def one(kind, name): + found = [d for d in docs if d["kind"] == kind and d["metadata"]["name"] == name] + assert len(found) == 1, (kind, name) + return found[0] +assert not [d for d in docs if d["kind"] == "Secret"], "the render must carry no Secret" +boot = one("Deployment", "fleet-site-boot")["spec"]["template"]["spec"] +feed = next(c for c in boot["containers"] if c["name"] == "dhcp-feed") +assert feed["command"][:2] == ["fleet-multiplane", "dhcp-feed"] and "-tls-cert" in feed["command"] and "-tls-key" in feed["command"], feed["command"] +assert {"name": "state", "mountPath": "/var/lib/fleet-local", "subPath": "journal", "readOnly": True} in feed["volumeMounts"], "the feed reads the store read-only" +service = one("Service", "fleet-site-dhcp-feed") +assert service["spec"]["type"] == "ClusterIP" and service["spec"]["ports"][0]["port"] == 8081 +kea = one("StatefulSet", "fleet-site-dhcp")["spec"] +assert kea["replicas"] >= 2 and kea["template"]["spec"]["hostNetwork"] is True +containers = {c["name"]: c for c in kea["template"]["spec"]["containers"]} +assert "@sha256:" in containers["kea"]["image"], "Kea is pinned by digest" +sync = containers["sync"]["command"] +assert "-ca-file=/etc/fleet-dhcp-tls/ca.crt" in sync and any(a.startswith("-feed=https://") for a in sync), sync +socket = next(a for a in sync if a.startswith("-kea-socket=")).split("=", 1)[1] +base = json.loads(one("ConfigMap", "fleet-site-dhcp-base")["data"]["kea-dhcp4.conf"])["Dhcp4"] +assert base["control-socket"]["socket-name"] == socket and socket.startswith("/var/run/kea/"), "Kea and the synchronizer share one socket under /var/run/kea" +assert all("pools" not in s for s in base["subnet4"]), "the base configuration has no pools" +assert any(e["name"] == "POD_NAME" for e in containers["sync"]["env"]), "the instance name is the Pod name" +print("PASS site DHCP render: %d objects, feed over TLS, Kea pinned, no Secret, no pool" % len(docs)) +' diff --git a/internal/site/redfishwork/dhcp.go b/internal/site/redfishwork/dhcp.go index f76d2397..2e382ea5 100644 --- a/internal/site/redfishwork/dhcp.go +++ b/internal/site/redfishwork/dhcp.go @@ -4,6 +4,7 @@ import ( "bufio" "context" "crypto/subtle" + "crypto/tls" "encoding/json" "errors" "io" @@ -102,14 +103,18 @@ func (b BootServer) DHCPHandler(token string) (http.Handler, error) { }), nil } -// ServeDHCP listens on :8081, apart from the boot listener. -func (b BootServer) ServeDHCP(token string) error { +// ServeDHCP listens with TLS on :8081, apart from the boot listener. The +// synchronizer accepts the feed only over TLS. +func (b BootServer) ServeDHCP(token, certFile, keyFile string) error { + if certFile == "" || keyFile == "" { + return errors.New("the DHCP feed needs a TLS certificate and key") + } handler, err := b.DHCPHandler(token) if err != nil { return err } - server := &http.Server{Addr: ":8081", Handler: handler, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 30 * time.Second} - return server.ListenAndServe() + server := &http.Server{Addr: ":8081", Handler: handler, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12}, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 30 * time.Second} + return server.ListenAndServeTLS(certFile, keyFile) } // retain appends one report and syncs it before acknowledging. diff --git a/internal/site/redfishwork/dhcp_test.go b/internal/site/redfishwork/dhcp_test.go index 66d5eb32..4f2ac661 100644 --- a/internal/site/redfishwork/dhcp_test.go +++ b/internal/site/redfishwork/dhcp_test.go @@ -310,3 +310,11 @@ func TestWithdrawalCoversEveryReservationOfTheDevice(t *testing.T) { t.Fatalf("feed after a newer fence = %+v, %v", feed, err) } } + +// TestTheFeedServesOnlyOverTLS refuses to start the feed without a +// certificate and key: the synchronizer fetches it only over HTTPS. +func TestTheFeedServesOnlyOverTLS(t *testing.T) { + if err := (BootServer{}).ServeDHCP(syncToken, "", ""); err == nil { + t.Fatal("the feed started without TLS") + } +} From 8c719203c0c7de19bd28ca5ad7606817c98f25db Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 10:15:36 -0600 Subject: [PATCH 02/17] fix(site): Start Kea with a 0750 control socket directory Kea 2.6 refuses a control socket directory that is not 0750, and an emptyDir is created 0777, so Kea's command sets the mode first. The lab now runs Kea with the component's capabilities and socket directory and requires the client's "no lease" for every refusal. The render check covers the mode, volume mounts and selectors, and the docs state the relay filter, required Secrets, rotation, and what the lab proves. Co-Authored-By: Claude Opus 5.5 --- config/site/dhcp/component/dhcp.yaml | 8 ++++--- config/site/dhcp/example/base.yaml | 5 ++-- docs/operations/boot-network.md | 26 +++++++++++++------- hack/boot-network/kea-lab.sh | 36 +++++++++++++++++++++------- hack/validate-site-dhcp-render.sh | 10 ++++++++ 5 files changed, 63 insertions(+), 22 deletions(-) diff --git a/config/site/dhcp/component/dhcp.yaml b/config/site/dhcp/component/dhcp.yaml index 5da29e67..47a348c1 100644 --- a/config/site/dhcp/component/dhcp.yaml +++ b/config/site/dhcp/component/dhcp.yaml @@ -17,8 +17,8 @@ automountServiceAccountToken: false --- # Kea DHCPv4 instances. Each Pod's name is its stable instance name in the # applied reports. Pods use host networking on nodes that network operations -# labels as DHCP hosts, one per node, and Kea answers only relayed requests on -# that node's address. Scale down only after the instance being removed +# labels as DHCP hosts, one per node. The base configuration's relay filter +# limits Kea to relayed requests from the site's relays. Scale down only after the instance being removed # reports an empty feed: an instance removed while serving keeps its # operations' outcomes unknown until an operator retires it. apiVersion: apps/v1 @@ -50,7 +50,9 @@ spec: - name: kea # ISC's image, pinned by digest. It is built for linux/amd64 only. image: docker.cloudsmith.io/isc/docker/kea-dhcp4:2.6.3@sha256:c40abb1522b15edb9a6d1119ad22b3765bf818a51d6776f498e874ad13416065 - command: [kea-dhcp4, -c, /etc/kea-base/kea-dhcp4.conf] + # Kea 2.6 refuses a control socket directory that is not 0750, + # and an emptyDir is created 0777. + command: [sh, -c, 'chmod 0750 /var/run/kea && exec kea-dhcp4 -c /etc/kea-base/kea-dhcp4.conf'] securityContext: runAsUser: 0 allowPrivilegeEscalation: false diff --git a/config/site/dhcp/example/base.yaml b/config/site/dhcp/example/base.yaml index 94a9fc58..3e49dd22 100644 --- a/config/site/dhcp/example/base.yaml +++ b/config/site/dhcp/example/base.yaml @@ -1,7 +1,8 @@ # A synthetic base configuration. Network operations owns the real one: the # site's provisioning subnet and gateway, the relay addresses Kea accepts, and -# the boot options. It has no pools, so Kea answers only reserved MACs, and -# Kea 2.6 requires the control socket under /var/run/kea. +# the boot options. Kea listens on every node address, so the relay filter +# limits it to the site's relays. It has no pools, so Kea answers only +# reserved MACs, and Kea 2.6 requires the control socket under /var/run/kea. apiVersion: v1 kind: ConfigMap metadata: diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index aa02b193..5ca2c656 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -205,7 +205,7 @@ synchronized site: | --- | --- | | `dhcp-feed` container in `fleet-site-boot` | The feed, beside the boot service, so it reads the site store read-only and appends reports to the boot evidence on the same volume | | `fleet-site-dhcp-feed` Service | The feed on `:8081`, inside the site cluster only | -| `fleet-site-dhcp` StatefulSet | At least two Pods, one per node labeled `fleet.datumapis.com/dhcp-host=true`, with host networking. Each runs ISC's Kea DHCPv4 image, pinned by digest, and the synchronizer, sharing Kea's control socket. The Pod name is the instance name | +| `fleet-site-dhcp` StatefulSet | At least two Pods, one per node labeled `fleet.datumapis.com/dhcp-host=true`, with host networking. Each runs ISC's Kea DHCPv4 image, pinned by digest, and the synchronizer, sharing Kea's control socket on an `emptyDir` that Kea's command makes `0750`, as Kea 2.6 requires. The Pod name is the instance name | | `fleet-site-dhcp` PodDisruptionBudget | One instance down at a time | The environment supplies, never in Git: @@ -218,8 +218,15 @@ The environment supplies, never in Git: - the `FLEET_SITE_IMAGE` and `FLEET_DHCP_SYNC_IMAGE` substitutions. The base configuration names the site's provisioning subnet and gateway, the -relay addresses Kea accepts, and the boot options. It has no pools, so Kea -answers only reserved MACs, and its control socket is the synchronizer's. +relay addresses Kea accepts, and the boot options. Kea listens on every +address of its node, so the subnet's relay filter is what limits it to the +site's relays. The configuration has no pools, so Kea answers only reserved +MACs, and its control socket is the synchronizer's. + +Both Secrets are required: without them the boot Pod, and so the boot service, +does not start. The feed loads its certificate and the synchronizer its CA +once, so rotating either Secret takes a restart of the boot Pod or the Kea +Pods. `config/site/dhcp/example` renders the component with a synthetic base configuration, and `hack/validate-site-dhcp-render.sh` checks that render in CI. ISC builds the Kea image for `linux/amd64` only. @@ -249,7 +256,8 @@ Fleet configures no switch, router or relay. A synchronized site needs: `task boot-network:kea-lab` (`hack/boot-network/kea-lab.sh`) runs ISC's Kea image, the real synchronizer, and the site's feed listener over TLS on one -container bridge, in the `colima` Docker context by default. A lab program +container bridge, in the `colima` Docker context by default. Kea runs with the +component's capabilities and socket directory. A lab program opens and closes boot admissions in a real site store, and a `udhcpc` client with a chosen MAC asks for an address. It passes only if: @@ -259,9 +267,11 @@ with a chosen MAC asks for an address. It passes only if: 3. after the admission closes and Kea reports the withdrawal, the boot NIC gets no answer. -The lab proves the feed, the synchronizer, Kea's configuration and a real DHCP -exchange. It has no relay, no VLAN, no switch and no firmware, so it proves -none of the network operations requirements. +The lab proves the feed, the synchronizer and reservation-gated answers in a +real DHCP exchange. With no relay, its Kea answers the client directly on a raw +socket, where a site's Kea answers relays on a UDP socket. It has no VLAN, no +switch and no firmware, so it proves none of the network operations +requirements. ## Implemented versus proposed @@ -271,7 +281,7 @@ none of the network operations requirements. | Boot NIC from Device inventory through the admission snapshot; enrollment without MACs or addresses | Implemented; unit tested | | Reservation feed, authenticated applied reports, served and withdrawn gates over every reservation of the Device, instance retirement | Implemented; unit tested with a fake BMC and synchronizer, including a silent instance | | Kea synchronizer: containing-subnet placement, restart re-apply, report only after Kea accepted | Implemented; unit tested against a fake Kea control socket | -| Feed over TLS, Kea and the synchronizer as a site component | Implemented; render checked in CI, and the DHCP path proved by the boot network lab with real Kea. Not deployed at a site | +| Feed over TLS, Kea and the synchronizer as a site component | Implemented; render checked in CI, and reservation-gated answers proved by the boot network lab with real Kea. Not deployed at a site, and relayed requests are not exercised | | Relay, provisioning VLAN, isolation and LACP fallback at a site | Network operations; see the [server networking enhancement][server-networking] | | Telling firmware what to boot in synced mode (Redfish `HttpBootUri` for UEFI HTTP Boot, or a DHCP boot-file option) | Proposed; the Redfish worker still arms `Pxe`, which relies on site DHCP for the boot file | | DHCPv6 reservations | Proposed; the feed accepts IPv6, the Kea DHCPv4 synchronizer and the claim reject it | diff --git a/hack/boot-network/kea-lab.sh b/hack/boot-network/kea-lab.sh index b8dfcc23..5a62351c 100755 --- a/hack/boot-network/kea-lab.sh +++ b/hack/boot-network/kea-lab.sh @@ -2,8 +2,10 @@ # Boot network DHCP lab. Runs real Kea DHCPv4 and the real synchronizer # against the site's reservation feed over TLS, on one container bridge, and # proves with a DHCP client that Kea answers a boot NIC only while its boot -# admission is open. There is no relay and no switch: see -# docs/operations/boot-network.md for what this does not prove. +# admission is open. Kea runs with the site component's capabilities and +# control socket directory. There is no relay and no switch, so Kea uses a raw +# socket here: see docs/operations/boot-network.md for what this does not +# prove. # # Exit codes: 0 passed, 1 failed. set -euo pipefail @@ -48,8 +50,15 @@ EOF docker network create --subnet 198.51.100.0/24 --ip-range 198.51.100.0/25 --gateway 198.51.100.1 "$prefix" >/dev/null docker create --name "$prefix-feed" --platform linux/amd64 --user 0 --network "$prefix" --network-alias feed --entrypoint sh "$image" \ -c 'mkdir -p -m 0700 /state/store /state/boot && exec /lab/lab serve -store /state/store -boot /state/boot -token-file /lab/token -cert /lab/feed.crt -key /lab/feed.key' >/dev/null -docker create --name "$prefix-kea" --platform linux/amd64 --user 0 --network "$prefix" --cap-add NET_ADMIN --cap-add NET_RAW --entrypoint sh "$image" \ - -c 'mkdir -p /var/run/kea && (kea-dhcp4 -c /lab/kea.json &) && sleep 2 && exec /lab/fleet-dhcp-sync -feed https://feed:8081 -token-file /lab/token -instance kea-a -kea-socket /var/run/kea/kea4-ctrl-socket -base-config /lab/kea.json -ca-file /lab/feed.crt -interval 1s' >/dev/null +# As in the site component: the socket directory starts 0777, like an +# emptyDir, and Kea's command makes it 0750 before Kea starts. +docker create --name "$prefix-kea" --platform linux/amd64 --user 0 --network "$prefix" --cap-drop ALL --cap-add NET_BIND_SERVICE --cap-add NET_RAW --tmpfs /var/run/kea:mode=0777 --entrypoint sh "$image" \ + -c '(sh -c "chmod 0750 /var/run/kea && exec kea-dhcp4 -c /lab/kea.json" &) && sleep 2 && exec /lab/fleet-dhcp-sync -feed https://feed:8081 -token-file /lab/token -instance kea-a -kea-socket /var/run/kea/kea4-ctrl-socket -base-config /lab/kea.json -ca-file /lab/feed.crt -interval 1s' >/dev/null +# The containers run as root without CAP_DAC_OVERRIDE, as the component's do, +# so the lab files must be readable by any user. They are synthetic and +# deleted on exit. +chmod 0755 "$state" +chmod 0644 "$state"/token "$state"/feed.key "$state"/feed.crt "$state"/kea.json for container in feed kea; do docker cp "$state/." "$prefix-$container:/lab" >/dev/null docker start "$prefix-$container" >/dev/null @@ -67,14 +76,22 @@ await() { done fail "timed out: $what" } +# client asks for an address with one MAC. udhcpc prints "lease of" on an +# answer and "no lease" after its retries; anything else is a lab failure. client() { docker run --rm --platform linux/amd64 --network "$prefix" --mac-address "$1" --cap-add NET_ADMIN --cap-add NET_RAW --entrypoint udhcpc "$image" \ -i eth0 -n -q -f -t 4 -T 2 -s /bin/true 2>&1 || true } +refused() { + local out + out=$(client "$1") + echo "$out" | grep -q 'lease of' && fail "$2" + echo "$out" | grep -q 'no lease' || fail "the DHCP client did not run: $out" +} await "Kea applies and reports the empty feed" '[ -n "$(latest)" ]' latest | grep -q '"reservations":\[\]' || fail "the first report was not empty" -client "$mac" | grep -q 'lease of' && fail "Kea answered a boot NIC with no open admission" +refused "$mac" "Kea answered a boot NIC with no open admission" echo "PASS no answer before admission" lab open -operation 00000000-0000-4000-8000-000000000101 -fence 1 -mac "$mac" -address "$address" @@ -82,13 +99,14 @@ await "Kea serves the reservation" 'latest | grep -q "\"$address\""' lease=$(client "$mac") echo "$lease" | grep -q "lease of $address obtained" || fail "the reserved NIC did not get $address: $lease" echo "PASS the reserved boot NIC got $address while its admission was open" -client "$other" | grep -q 'lease of' && fail "Kea answered an unreserved NIC" +refused "$other" "Kea answered an unreserved NIC" echo "PASS an unreserved NIC got no answer" lab close -operation 00000000-0000-4000-8000-000000000101 await "Kea withdraws the reservation" '! latest | grep -q "\"$address\""' -client "$mac" | grep -q 'lease of' && fail "Kea answered the boot NIC after its admission closed" +refused "$mac" "Kea answered the boot NIC after its admission closed" echo "PASS no answer after the admission closed" -reports > "$state/evidence.log" -echo "PASS boot network DHCP lab: $(grep -c '' "$state/evidence.log") retained reports from kea-a" +echo "Applied reports the site retained:" +reports +echo "PASS boot network DHCP lab" diff --git a/hack/validate-site-dhcp-render.sh b/hack/validate-site-dhcp-render.sh index 8e0fb6f4..61a21a1a 100755 --- a/hack/validate-site-dhcp-render.sh +++ b/hack/validate-site-dhcp-render.sh @@ -29,5 +29,15 @@ base = json.loads(one("ConfigMap", "fleet-site-dhcp-base")["data"]["kea-dhcp4.co assert base["control-socket"]["socket-name"] == socket and socket.startswith("/var/run/kea/"), "Kea and the synchronizer share one socket under /var/run/kea" assert all("pools" not in s for s in base["subnet4"]), "the base configuration has no pools" assert any(e["name"] == "POD_NAME" for e in containers["sync"]["env"]), "the instance name is the Pod name" +assert "chmod 0750 /var/run/kea" in " ".join(containers["kea"]["command"]), "Kea 2.6 needs its socket directory 0750" +for pod in (boot, kea["template"]["spec"]): + volumes = {v["name"] for v in pod["volumes"]} + for container in pod["containers"]: + missing = {m["name"] for m in container.get("volumeMounts", [])} - volumes + assert not missing, (container["name"], missing) +labels = one("Deployment", "fleet-site-boot")["spec"]["template"]["metadata"]["labels"] +assert all(labels.get(k) == v for k, v in service["spec"]["selector"].items()), "the feed Service selects the boot Pod" +budget = one("PodDisruptionBudget", "fleet-site-dhcp")["spec"]["selector"]["matchLabels"] +assert budget == kea["selector"]["matchLabels"], "the budget covers the Kea Pods" print("PASS site DHCP render: %d objects, feed over TLS, Kea pinned, no Secret, no pool" % len(docs)) ' From 292a660b767a00f58ae77214d050551e7fbaeceb Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 15:11:58 -0600 Subject: [PATCH 03/17] fix(site): Run the DHCP feed without boot artifacts The feed reads only the site store and writes reports beside the boot evidence, but it built a full boot server, so it needed a boot origin and the installer artifacts that the feed container does not have. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-multiplane/site.go | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/cmd/fleet-multiplane/site.go b/cmd/fleet-multiplane/site.go index 2f00d5af..e2c0d448 100644 --- a/cmd/fleet-multiplane/site.go +++ b/cmd/fleet-multiplane/site.go @@ -256,19 +256,25 @@ func boot(command, origin, extraMAC, syncToken, tlsCert, tlsKey string) error { fmt.Println(summary) return nil } + if redfishMode() && command == "dhcp-feed" { + // Reservations come from the admitted operations in the store, and + // reports go beside the boot evidence. The feed serves no boot + // artifacts, so it needs no boot origin or installer image. + root, err := bootRoot() + if err != nil { + return err + } + token, err := os.ReadFile(syncToken) + if err != nil { + return fmt.Errorf("DHCP synchronizer token: %w", err) + } + return redfishwork.BootServer{Store: store, BootRoot: root}.ServeDHCP(strings.TrimSpace(string(token)), tlsCert, tlsKey) + } if redfishMode() { server, err := redfishBootServer(store) if err != nil { return err } - if command == "dhcp-feed" { - // Reservations come from the admitted operations in the store. - token, err := os.ReadFile(syncToken) - if err != nil { - return fmt.Errorf("DHCP synchronizer token: %w", err) - } - return server.ServeDHCP(strings.TrimSpace(string(token)), tlsCert, tlsKey) - } return serveBoot(server.Handler(), vmwork.DefaultBootWindow*2) } if command == "dhcp-feed" { From 166a6d08b0efc5edbd63044d83d0fed67c8511a7 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 15:11:58 -0600 Subject: [PATCH 04/17] test(multiplane): Run the Redfish lab with synchronized DHCP Add run.sh --redfish --synced-dhcp. The lab network loses its own DHCP; Kea and the synchronizer run in the runtime Pod on the lab bridge, the reservation feed runs beside the boot service, and a synthetic IPAM stand-in binds boot address claims. A new phase requires each install and wipe to carry its own claim, Kea to serve each reservation only while its boot is open, and firmware to lease from Kea, not dnsmasq. The feed becomes its own component, shared with the site Kea one. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-multiplane/main.go | 9 ++ config/site/dhcp/component/dhcp.yaml | 12 -- config/site/dhcp/component/kustomization.yaml | 41 +----- config/site/dhcp/feed/kustomization.yaml | 49 +++++++ config/site/dhcp/feed/service.yaml | 11 ++ .../redfish/synced/graph/kustomization.yaml | 17 +++ config/site/redfish/synced/services/kea.yaml | 24 ++++ .../synced/services/kustomization.yaml | 87 +++++++++++ docs/operations/boot-network.md | 2 +- docs/operations/redfish-lab.md | 52 +++++++ hack/local-vm/Containerfile | 7 +- hack/multiplane/acceptance-redfish.sh | 3 + hack/multiplane/evidence.py | 9 +- hack/multiplane/flux.py | 15 +- hack/multiplane/milo.py | 14 +- hack/multiplane/redfish_steps.py | 136 +++++++++++++++++- hack/multiplane/run.sh | 25 ++-- hack/multiplane/test-redfish.py | 66 +++++++++ hack/redfish-lab/fleet_lab_adapter.py | 17 ++- hack/redfish-lab/test_adapter.py | 11 ++ internal/multiplane/ipam.go | 72 ++++++++++ internal/multiplane/ipam_test.go | 68 +++++++++ internal/multiplane/runner.go | 11 ++ 23 files changed, 686 insertions(+), 72 deletions(-) create mode 100644 config/site/dhcp/feed/kustomization.yaml create mode 100644 config/site/dhcp/feed/service.yaml create mode 100644 config/site/redfish/synced/graph/kustomization.yaml create mode 100644 config/site/redfish/synced/services/kea.yaml create mode 100644 config/site/redfish/synced/services/kustomization.yaml create mode 100644 internal/multiplane/ipam.go create mode 100644 internal/multiplane/ipam_test.go diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index d87ac8e2..383fecb2 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -163,6 +163,15 @@ func phase(name, configPath string, once bool) error { }[name] last := "" for { + // With synchronized lab DHCP, bind the boot address claims this phase + // is waiting on, in IPAM's place. + if r.IPAM != nil { + if bound, bindErr := r.IPAM.Bind(ctx); bindErr != nil { + fmt.Printf("%s: lab IPAM stand-in: %v\n", name, bindErr) + } else if bound > 0 { + fmt.Printf("%s: lab IPAM stand-in bound %d boot address claim(s)\n", name, bound) + } + } err = action(ctx) // Report each new reason a phase is waiting, so a phase that times // out shows what it waited for. diff --git a/config/site/dhcp/component/dhcp.yaml b/config/site/dhcp/component/dhcp.yaml index 47a348c1..060db454 100644 --- a/config/site/dhcp/component/dhcp.yaml +++ b/config/site/dhcp/component/dhcp.yaml @@ -1,15 +1,3 @@ -# The feed, reachable only inside the site cluster. -apiVersion: v1 -kind: Service -metadata: - name: fleet-site-dhcp-feed - namespace: fleet-site -spec: - type: ClusterIP - selector: {app.kubernetes.io/name: fleet-site-boot} - ports: - - {name: dhcp-feed, port: 8081, targetPort: 8081, protocol: TCP} ---- apiVersion: v1 kind: ServiceAccount metadata: {name: fleet-site-dhcp, namespace: fleet-site} diff --git a/config/site/dhcp/component/kustomization.yaml b/config/site/dhcp/component/kustomization.yaml index be334519..8eb92c17 100644 --- a/config/site/dhcp/component/kustomization.yaml +++ b/config/site/dhcp/component/kustomization.yaml @@ -10,42 +10,5 @@ apiVersion: kustomize.config.k8s.io/v1alpha1 kind: Component resources: - dhcp.yaml -patches: - # The feed reads the site store and writes the applied reports beside the - # boot evidence, so it runs in the boot Pod, which holds the state volume. - - target: {kind: Deployment, name: fleet-site-boot} - patch: |- - - op: add - path: /spec/template/spec/containers/- - value: - name: dhcp-feed - image: "${FLEET_SITE_IMAGE}" - imagePullPolicy: IfNotPresent - command: [fleet-multiplane, dhcp-feed, -sync-token-file, /etc/fleet-dhcp/token, -tls-cert, /etc/fleet-dhcp-tls/tls.crt, -tls-key, /etc/fleet-dhcp-tls/tls.key] - env: - - {name: FLEET_SITE_PROVIDER, value: redfish} - - {name: FLEET_BOOT_EVIDENCE, value: /var/lib/fleet-boot} - ports: - - {name: dhcp-feed, containerPort: 8081} - readinessProbe: - tcpSocket: {port: 8081} - periodSeconds: 5 - securityContext: - runAsUser: 0 - allowPrivilegeEscalation: false - readOnlyRootFilesystem: true - capabilities: {drop: [ALL]} - resources: - requests: {cpu: 10m, memory: 32Mi} - limits: {memory: 128Mi} - volumeMounts: - - {name: state, mountPath: /var/lib/fleet-local, subPath: journal, readOnly: true} - - {name: state, mountPath: /var/lib/fleet-boot, subPath: boot-evidence} - - {name: dhcp-sync-token, mountPath: /etc/fleet-dhcp, readOnly: true} - - {name: dhcp-feed-tls, mountPath: /etc/fleet-dhcp-tls, readOnly: true} - - op: add - path: /spec/template/spec/volumes/- - value: {name: dhcp-sync-token, secret: {secretName: fleet-site-dhcp-sync, defaultMode: 0400}} - - op: add - path: /spec/template/spec/volumes/- - value: {name: dhcp-feed-tls, secret: {secretName: fleet-site-dhcp-feed-tls, defaultMode: 0400}} +components: + - ../feed diff --git a/config/site/dhcp/feed/kustomization.yaml b/config/site/dhcp/feed/kustomization.yaml new file mode 100644 index 00000000..75d7b697 --- /dev/null +++ b/config/site/dhcp/feed/kustomization.yaml @@ -0,0 +1,49 @@ +# The reservation feed: a container beside the boot service, which reads the +# site store and writes the applied reports beside the boot evidence, and a +# Service reachable only inside the site cluster. The environment supplies +# the Secrets fleet-site-dhcp-sync (key token) and fleet-site-dhcp-feed-tls +# (tls.crt, tls.key, ca.crt), never in Git. The Kea component and the +# Redfish lab's synchronized DHCP both use it. +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component +resources: + - service.yaml +patches: + # The feed reads the site store and writes the applied reports beside the + # boot evidence, so it runs in the boot Pod, which holds the state volume. + - target: {kind: Deployment, name: fleet-site-boot} + patch: |- + - op: add + path: /spec/template/spec/containers/- + value: + name: dhcp-feed + image: "${FLEET_SITE_IMAGE}" + imagePullPolicy: IfNotPresent + command: [fleet-multiplane, dhcp-feed, -sync-token-file, /etc/fleet-dhcp/token, -tls-cert, /etc/fleet-dhcp-tls/tls.crt, -tls-key, /etc/fleet-dhcp-tls/tls.key] + env: + - {name: FLEET_SITE_PROVIDER, value: redfish} + - {name: FLEET_BOOT_EVIDENCE, value: /var/lib/fleet-boot} + ports: + - {name: dhcp-feed, containerPort: 8081} + readinessProbe: + tcpSocket: {port: 8081} + periodSeconds: 5 + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 10m, memory: 32Mi} + limits: {memory: 128Mi} + volumeMounts: + - {name: state, mountPath: /var/lib/fleet-local, subPath: journal, readOnly: true} + - {name: state, mountPath: /var/lib/fleet-boot, subPath: boot-evidence} + - {name: dhcp-sync-token, mountPath: /etc/fleet-dhcp, readOnly: true} + - {name: dhcp-feed-tls, mountPath: /etc/fleet-dhcp-tls, readOnly: true} + - op: add + path: /spec/template/spec/volumes/- + value: {name: dhcp-sync-token, secret: {secretName: fleet-site-dhcp-sync, defaultMode: 0400}} + - op: add + path: /spec/template/spec/volumes/- + value: {name: dhcp-feed-tls, secret: {secretName: fleet-site-dhcp-feed-tls, defaultMode: 0400}} diff --git a/config/site/dhcp/feed/service.yaml b/config/site/dhcp/feed/service.yaml new file mode 100644 index 00000000..642ec089 --- /dev/null +++ b/config/site/dhcp/feed/service.yaml @@ -0,0 +1,11 @@ +# The feed, reachable only inside the site cluster. +apiVersion: v1 +kind: Service +metadata: + name: fleet-site-dhcp-feed + namespace: fleet-site +spec: + type: ClusterIP + selector: {app.kubernetes.io/name: fleet-site-boot} + ports: + - {name: dhcp-feed, port: 8081, targetPort: 8081, protocol: TCP} diff --git a/config/site/redfish/synced/graph/kustomization.yaml b/config/site/redfish/synced/graph/kustomization.yaml new file mode 100644 index 00000000..a1ea51dd --- /dev/null +++ b/config/site/redfish/synced/graph/kustomization.yaml @@ -0,0 +1,17 @@ +# Redfish lab with synchronized DHCP (run.sh --redfish --synced-dhcp): the +# Redfish graph with the site enrollment's DHCP mode set to synced, so a +# network boot needs a boot address and waits for the site's Kea to apply and +# later withdraw its reservation. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../../graph +patches: + - target: {kind: ResourceGraphDefinition, name: fleet-handoff-dispatcher} + patch: |- + - op: test + path: /spec/resources/9/template/spec/template/spec/containers/0/env/6/name + value: FLEET_REDFISH_ENROLLMENT + - op: replace + path: /spec/resources/9/template/spec/template/spec/containers/0/env/6/value + value: '{"dhcp":"synced","targets":[{"device":"fleet-provider/synthetic-device-central-01","endpoint":"https://10.96.0.81:8443","systemID":"System-1","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a","diskBytes":2147483648,"console":"target-a.log"},{"device":"fleet-provider/synthetic-device-central-02","endpoint":"https://10.96.0.81:8443","systemID":"System-2","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b","diskBytes":2147483648,"console":"target-b.log"}]}' diff --git a/config/site/redfish/synced/services/kea.yaml b/config/site/redfish/synced/services/kea.yaml new file mode 100644 index 00000000..41498f0b --- /dev/null +++ b/config/site/redfish/synced/services/kea.yaml @@ -0,0 +1,24 @@ +# The lab's base Kea configuration, in the network owner's role: the +# provisioning subnet on the lab bridge, its gateway and the boot program. It +# has no pools, so Kea answers only the MACs the reservation feed names. Kea +# keeps its leases on the site volume as evidence of each answer. +apiVersion: v1 +kind: ConfigMap +metadata: + name: fleet-site-dhcp-base + namespace: fleet-site +data: + kea-dhcp4.conf: | + {"Dhcp4": { + "interfaces-config": {"interfaces": ["fleetpxe0"], "dhcp-socket-type": "raw"}, + "control-socket": {"socket-type": "unix", "socket-name": "/var/run/kea/kea4-ctrl-socket"}, + "lease-database": {"type": "memfile", "persist": true, "name": "/var/lib/kea/dhcp4.leases", "lfc-interval": 0}, + "host-reservation-identifiers": ["hw-address"], + "valid-lifetime": 600, + "subnet4": [{ + "id": 1, + "subnet": "192.168.77.0/24", + "option-data": [{"name": "routers", "data": "192.168.77.1"}], + "boot-file-name": "http://${FLEET_BOOT_SERVICE_IP}:8080/pxe/boot.ipxe" + }] + }} diff --git a/config/site/redfish/synced/services/kustomization.yaml b/config/site/redfish/synced/services/kustomization.yaml new file mode 100644 index 00000000..1dbfe4fe --- /dev/null +++ b/config/site/redfish/synced/services/kustomization.yaml @@ -0,0 +1,87 @@ +# Redfish lab with synchronized DHCP (run.sh --redfish --synced-dhcp). The lab +# provisioning network keeps its bridge but has no DHCP of its own; Kea, fed by +# Fleet's reservation feed, is the only DHCP server on it. Kea and its +# synchronizer run in the runtime Pod because the bridge lives in that Pod's +# network namespace. The feed runs beside the boot service, as at a site. +# The harness creates the Secrets fleet-site-dhcp-sync and +# fleet-site-dhcp-feed-tls before this layer reconciles; they are never in Git. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../../services + - kea.yaml +components: + - ../../../dhcp/feed +patches: + - target: {kind: Deployment, name: fleet-site-bmc} + patch: |- + - op: add + path: /spec/template/spec/containers/0/env/- + value: {name: FLEET_LAB_DHCP, value: synced} + - target: {kind: Deployment, name: fleet-site-runtime} + patch: |- + - op: add + path: /spec/template/spec/containers/- + value: + name: kea + image: "${FLEET_SITE_IMAGE}" + imagePullPolicy: IfNotPresent + # Kea starts once the lab BMC adapter has created the bridge. Kea + # refuses a control socket directory that is not 0750. + command: [sh, -c, 'mkdir -p /var/run/kea && chmod 0750 /var/run/kea && until [ -e /sys/class/net/fleetpxe0 ]; do sleep 2; done && exec kea-dhcp4 -c /etc/kea-base/kea-dhcp4.conf'] + env: + - {name: KEA_PIDFILE_DIR, value: /var/run/kea} + - {name: KEA_LOCKFILE_DIR, value: none} + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + capabilities: {drop: [ALL], add: [NET_BIND_SERVICE, NET_RAW]} + resources: + requests: {cpu: 20m, memory: 32Mi} + limits: {memory: 256Mi} + volumeMounts: + - {name: dhcp-base, mountPath: /etc/kea-base, readOnly: true} + - {name: kea-control, mountPath: /var/run/kea} + - {name: state, mountPath: /var/lib/kea, subPath: kea-leases} + - op: add + path: /spec/template/spec/containers/- + value: + name: dhcp-sync + image: "${FLEET_SITE_IMAGE}" + imagePullPolicy: IfNotPresent + # One instance with a fixed name: a restarted Pod reports as the + # same instance, so its earlier reports never strand a withdrawal. + command: + - /usr/local/bin/fleet-dhcp-sync + - -feed=https://fleet-site-dhcp-feed.fleet-site.svc:8081 + - -token-file=/etc/fleet-dhcp/token + - -ca-file=/etc/fleet-dhcp-tls/ca.crt + - -instance=lab-kea + - -kea-socket=/var/run/kea/kea4-ctrl-socket + - -base-config=/etc/kea-base/kea-dhcp4.conf + - -interval=2s + securityContext: + runAsUser: 0 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 10m, memory: 16Mi} + limits: {memory: 64Mi} + volumeMounts: + - {name: dhcp-base, mountPath: /etc/kea-base, readOnly: true} + - {name: kea-control, mountPath: /var/run/kea} + - {name: dhcp-sync-token, mountPath: /etc/fleet-dhcp, readOnly: true} + - {name: dhcp-feed-ca, mountPath: /etc/fleet-dhcp-tls, readOnly: true} + - op: add + path: /spec/template/spec/volumes/- + value: {name: dhcp-base, configMap: {name: fleet-site-dhcp-base}} + - op: add + path: /spec/template/spec/volumes/- + value: {name: kea-control, emptyDir: {}} + - op: add + path: /spec/template/spec/volumes/- + value: {name: dhcp-sync-token, secret: {secretName: fleet-site-dhcp-sync, defaultMode: 0400}} + - op: add + path: /spec/template/spec/volumes/- + value: {name: dhcp-feed-ca, secret: {secretName: fleet-site-dhcp-feed-tls, defaultMode: 0400, items: [{key: ca.crt, path: ca.crt}]}} diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index 5ca2c656..b2d5649a 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -285,6 +285,6 @@ requirements. | Relay, provisioning VLAN, isolation and LACP fallback at a site | Network operations; see the [server networking enhancement][server-networking] | | Telling firmware what to boot in synced mode (Redfish `HttpBootUri` for UEFI HTTP Boot, or a DHCP boot-file option) | Proposed; the Redfish worker still arms `Pxe`, which relies on site DHCP for the boot file | | DHCPv6 reservations | Proposed; the feed accepts IPv6, the Kea DHCPv4 synchronizer and the claim reject it | -| Lab acceptance in synced mode | Not run; the lab uses static DHCP | +| Lab acceptance in synced mode | Implemented as `run.sh --redfish --synced-dhcp`, with a synthetic IPAM stand-in; see the [Redfish lab](redfish-lab.md#synchronized-dhcp-mode) for its result | [server-networking]: https://github.com/datum-cloud/fleet/pull/186 diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index e86ffbba..0a3109fd 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -340,6 +340,58 @@ These are documented lab seams, not production designs: phase proves each denial as kro's identity, and evidence re-checks every real worker Job spec. +## Synchronized DHCP mode + +`hack/multiplane/run.sh --redfish --synced-dhcp` runs the same Redfish +acceptance with the site's synchronized DHCP instead of the static leases. It +exercises boot addresses, reservations and Kea end to end in the lab: + +- **No lab DHCP.** The lab BMC defines the provisioning network with + `FLEET_LAB_DHCP=synced`: the same bridge and NAT, with no `` element, so + libvirt starts no dnsmasq. +- **Kea on the bridge.** The bridge lives in the runtime Pod's network + namespace, so Kea and `fleet-dhcp-sync` run as two more containers in that + Pod (`config/site/redfish/synced/services`). Kea is Debian's + `kea-dhcp4-server` from the site image, which is native to the arm64 lab; + ISC's image is amd64 only. Kea is not privileged: it adds only `NET_RAW` and + `NET_BIND_SERVICE`. It listens on `fleetpxe0` with a raw socket, has no pool, + and keeps its leases on the site volume. The synchronizer reports as the one + fixed instance `lab-kea`, so a restarted runtime Pod never strands a + withdrawal. +- **Feed.** The `dhcp-feed` container from `config/site/dhcp/feed` runs beside + the boot service over TLS. Redfish enrollment generates the synchronizer + token and a self-signed feed key per run, as Secrets in `fleet-site`, never + in Git or evidence. +- **Worker mode.** `config/site/redfish/synced/graph` sets the worker + enrollment's `dhcp` to `synced`, so every network boot needs a boot address + and waits for Kea to apply and withdraw its reservation. +- **IPAM stand-in.** The lab has no IPAM service. The provider project serves + IPAM's `IPClaim` kind from a CRD, and the acceptance runner binds each + unbound claim, with the bootstrap identity, to the lowest free address in + 192.168.77.100–199, as IPAM would on create. Fleet's own code claims, + checks at admission and releases the addresses. The static leases (.10 and + .11) are outside that range. + +The `redfish-dhcp-synced` phase runs after `boot-denials` and writes +`evidence/redfish-dhcp.json`. It fails unless: + +1. every installation and wipe carried a boot address from its own claim + (`-boot`), within the stand-in range, and no claim remains after + both releases; +2. each operation that ran at the site published the snapshot's boot MAC at its + address, and Kea reported serving it after that boot opened and reported it + withdrawn later; +3. Kea holds a lease for the boot MAC at that address for every operation whose + boot script was delivered, at least one installation and both wipes, and + leased no static or out-of-range address; +4. the lab network has no `` element and no dnsmasq runs; and +5. Kea's last report serves nothing. + +Consumer B's installation on the same server and both release wipes each get +their own claim and reservation. The stand-in may hand a released address out +again, as IPAM may, so freshness is judged by claim and by report time, not by +address. + ## Acceptance phases `hack/multiplane/acceptance-redfish.sh` runs every scenario of the diff --git a/hack/local-vm/Containerfile b/hack/local-vm/Containerfile index 14e4afe6..64952e68 100644 --- a/hack/local-vm/Containerfile +++ b/hack/local-vm/Containerfile @@ -14,9 +14,14 @@ ENV FLEET_LOCAL_VM=disposable-container LIBVIRT_DEFAULT_URI=qemu:///system # fleet-multiplane binary from the named build context "fleetbin". Runtime, # boot service, observer and per-operation worker Jobs all use this image. FROM tcg AS site +# Kea and the DHCP synchronizer serve the Redfish lab's synchronized DHCP +# mode from the runtime Pod, on the provisioning bridge. Debian's Kea is the +# native-architecture build; ISC publishes its image for amd64 only. +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends kea-dhcp4-server && rm -rf /var/lib/apt/lists/* COPY site-runtime /usr/local/bin/fleet-site-runtime COPY --from=fleetbin fleet-multiplane /usr/local/bin/fleet-multiplane -RUN chmod 755 /usr/local/bin/fleet-site-runtime /usr/local/bin/fleet-multiplane && printf '%s\n' 'unix_sock_dir = "/run/fleet-libvirt"' >> /etc/libvirt/libvirtd.conf +COPY --from=fleetbin fleet-dhcp-sync /usr/local/bin/fleet-dhcp-sync +RUN chmod 755 /usr/local/bin/fleet-site-runtime /usr/local/bin/fleet-multiplane /usr/local/bin/fleet-dhcp-sync && printf '%s\n' 'unix_sock_dir = "/run/fleet-libvirt"' >> /etc/libvirt/libvirtd.conf FROM fleet-vm-local AS kvm USER root diff --git a/hack/multiplane/acceptance-redfish.sh b/hack/multiplane/acceptance-redfish.sh index eb1088bf..1c64e2c0 100755 --- a/hack/multiplane/acceptance-redfish.sh +++ b/hack/multiplane/acceptance-redfish.sh @@ -72,6 +72,9 @@ if runs release; then step rebuild 1200 step wrong-location 300 step boot-denials 300 + # Synchronized lab DHCP (run.sh --synced-dhcp): every boot's reservation came + # from its own IPAM claim and Kea served it only while the boot was open. + [[ ${FLEET_LAB_DHCP:-static} != synced ]] || rf dhcp-synced 300 fi step flux-final 900 rf isolation 600 diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index 5d05dd5d..1dac3cfa 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -28,6 +28,7 @@ # the shell's trace of that printf shows the format, not a receipt. PARTITIONED = re.compile(r'FLEET-PARTITIONED:([0-9a-f]{64})') REDFISH = (s / 'site-provider').exists() and (s / 'site-provider').read_text().strip() == 'redfish' +SYNCED = (s / 'lab-dhcp').exists() and (s / 'lab-dhcp').read_text().strip() == 'synced' def out(*args): @@ -112,6 +113,11 @@ def copy_out(source, destination): if not set(FLUX_MARKERS + RELEASE_MARKERS) <= set(markers): fail('a group marker is not an acceptance marker') skipped = RELEASE_MARKERS if GROUP == 'flux' else FLUX_MARKERS if GROUP == 'release' else () +# The synchronized DHCP check needs the release group's installations and wipes. +if SYNCED and GROUP != 'flux': + markers += ('redfish-dhcp-synced: ',) + if not (s / 'evidence' / 'redfish-dhcp.json').exists(): + fail('synchronized lab DHCP left no redfish-dhcp.json evidence') if REDFISH: markers += ('bmc-upstream: DMTF Redfish-Interface-Emulator 1.2.2 archive verified', 'bmc-self-test: upstream emulator and lab adapter self-test passed', 'redfish-enroll: synthetic per-Device BMC credentials', 'redfish-baseline: both lab target disks present', 'redfish-discovery-faults: real emulator discovery', @@ -591,7 +597,8 @@ def flux_evidence(): summary['seams'] = [x for x in summary['seams'] if 'root libvirtd' not in x] + [ 'DMTF Redfish Interface Emulator with a lab-only adapter in place of a physical BMC; libvirt/QEMU TCG VMs in place of servers', 'Basic authentication over TLS pinned to a lab key generated per run, with synthetic per-Device credential Secrets enrolled by the harness (no rotation or vault)', - 'static lab provisioning network (libvirt dnsmasq) with MAC-chained iPXE; MAC is routing, not authentication', + ('synchronized lab DHCP: Kea in the runtime Pod fed by the site reservation feed, boot addresses from a synthetic IPAM stand-in, no relay or switch' + if SYNCED else 'static lab provisioning network (libvirt dnsmasq)') + ' with MAC-chained iPXE; MAC is routing, not authentication', 'installation receipts read from a read-only serial-console capture (stand-in for SOL or an installer callback)', 'trusted graph authors: worker Jobs list the site BMC credential Secrets; only the runtime and the lab BMC hold the libvirt socket', 'one allocatable lab target; the site store fences each Device separately'] diff --git a/hack/multiplane/flux.py b/hack/multiplane/flux.py index 162a0e8f..09d8904d 100644 --- a/hack/multiplane/flux.py +++ b/hack/multiplane/flux.py @@ -101,11 +101,20 @@ if PROVIDER == 'redfish': SHARED.update({('deployments', SITE, 'fleet-site-bmc'): 'fleet-site-services', ('services', SITE, 'fleet-site-bmc'): 'fleet-site-services', ('serviceaccounts', SITE, 'fleet-site-bmc'): 'fleet-site-base'}) +# Lab DHCP: static (libvirt dnsmasq) or synced (run.sh --synced-dhcp, Redfish +# only): the site's Kea, fed by Fleet's reservation feed, from the +# config/site/redfish/synced overlays. +LAB_DHCP = os.environ.get('FLEET_LAB_DHCP', 'static') +if LAB_DHCP not in ('static', 'synced') or (LAB_DHCP == 'synced' and PROVIDER != 'redfish'): + raise SystemExit('FLEET_LAB_DHCP=synced needs the Redfish provider') +SYNCED_OBJECTS = ['fleet-site_fleet-site-dhcp-base__ConfigMap', 'fleet-site_fleet-site-dhcp-feed__Service'] if LAB_DHCP == 'synced' else [] +if LAB_DHCP == 'synced': + SHARED.update({('configmaps', SITE, 'fleet-site-dhcp-base'): 'fleet-site-services', ('services', SITE, 'fleet-site-dhcp-feed'): 'fleet-site-services'}) LAYER_INVENTORY = { 'flux-system/fleet-site-services': sorted(['fleet-site_fleet-site-boot__Service', 'fleet-site_fleet-site-worker-policy__ConfigMap', 'fleet-site_fleet-site-runtime_apps_Deployment', 'fleet-site_fleet-site-boot_apps_Deployment', 'fleet-site_fleet-site-observer_apps_Deployment'] + ( - ['fleet-site_fleet-site-bmc__Service', 'fleet-site_fleet-site-bmc_apps_Deployment'] if PROVIDER == 'redfish' else [])), + ['fleet-site_fleet-site-bmc__Service', 'fleet-site_fleet-site-bmc_apps_Deployment'] if PROVIDER == 'redfish' else []) + SYNCED_OBJECTS), 'flux-system/fleet-site-graph': ['_fleet-handoff-dispatcher_kro.run_ResourceGraphDefinition'], 'flux-system/fleet-site-dispatch': ['fleet-site_dispatcher_site.fleet.datumapis.com_HandoffDispatcher'], } @@ -272,7 +281,9 @@ def stage(args): # Environment selection, as a commit would make it: the cell's # site layers reconcile the Redfish overlays of the same source. for layer in ('fleet-site-base', 'fleet-site-graph') + (('fleet-site-services',) if args.site != 'absent' else ()): - patches.append(child_path(layer, './config/site/redfish/' + layer.rsplit('-', 1)[1])) + kind = layer.rsplit('-', 1)[1] + overlay = 'synced/' + kind if LAB_DHCP == 'synced' and kind != 'base' else kind + patches.append(child_path(layer, './config/site/redfish/' + overlay)) if args.site != 'absent': data.update(FLEET_BMC_IMAGE=env['bmcImage'], FLEET_BMC_SERVICE_IP=BMC_SERVICE_IP) if args.site != 'absent': diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py index 58f2011b..622a0912 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -80,7 +80,11 @@ def wait(fn,seconds,what): apply(config,{'apiVersion':'v1','kind':'Namespace','metadata':{'name':ns}}) rules=[{'apiGroups':[''],'resources':['namespaces'],'verbs':['get']},{'apiGroups':['metal.datumapis.com'],'resources':['machineclasses','machineprofiles','machinecapacities','machines','installations'],'verbs':['get','list','watch']}] if role=='provider': - for crds in ('config/components/inventory/crds/fleet.datumapis.com.yaml','config/components/device-operations/crds/fleet.datumapis.com.yaml'): + # Synchronized lab DHCP claims boot addresses from IPAM. The lab has no + # IPAM service, so a CRD with IPAM's claim kind stands in for its API, and + # the acceptance runner binds claims in IPAM's place. + synced=os.environ.get('FLEET_LAB_DHCP')=='synced' + for crds in ('config/components/inventory/crds/fleet.datumapis.com.yaml','config/components/device-operations/crds/fleet.datumapis.com.yaml')+(('internal/bootaddress/testdata/ipclaims.yaml',) if synced else ()): kubectl(config,'apply','-f',crds,stdout=subprocess.DEVNULL) kubectl(config,'wait','--for=condition=Established','crd','--all','--timeout=90s',stdout=subprocess.DEVNULL) # The CRD rule check writes its synthetic objects here, away from the @@ -93,6 +97,10 @@ def wait(fn,seconds,what): rules+=[{'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch','create','delete']},{'apiGroups':['metal.datumapis.com'],'resources':['machineallocations/status'],'verbs':['get','update']}, {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations'],'verbs':['get','list','watch','create']}, {'apiGroups':['fleet.datumapis.com'],'resources':['devices','devicecustodies','devicecommissionings','devicecommissioningplans','devicecommissioningplanapprovals'],'verbs':['get','list','watch']}] + # Each requester claims and releases its own boot addresses; the release + # controller reads custody to keep a held operation's claim. + claims={'apiGroups':['ipam.miloapis.com'],'resources':['ipclaims'],'verbs':['get','list','create','delete']} + if synced:rules.append(claims) # The coordinator rules mirror config/components/device-operations/roles/ # coordinator.yaml: it lists and settles every registered operation kind. components={ @@ -100,8 +108,8 @@ def wait(fn,seconds,what): {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations','devicewipes','devicepoweroperations','devicerecoveries','devicecommissionings'],'verbs':['get','list','watch','delete']}, {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations/status','devicewipes/status','devicepoweroperations/status','devicerecoveries/status','devicecommissionings/status'],'verbs':['get','update']}, {'apiGroups':['fleet.datumapis.com'],'resources':['devicecommissioningplans','devicecommissioningplanapprovals'],'verbs':['get','list','watch']}, - {'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch']}], - 'release':[{'apiGroups':['fleet.datumapis.com'],'resources':['devicewipes'],'verbs':['get','create']}], + {'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch']}]+([{'apiGroups':['ipam.miloapis.com'],'resources':['ipclaims'],'verbs':['get']}] if synced else []), + 'release':[{'apiGroups':['fleet.datumapis.com'],'resources':['devicewipes'],'verbs':['get','create']}]+([claims,{'apiGroups':['fleet.datumapis.com'],'resources':['devicecustodies'],'verbs':['get']}] if synced else []), # The capacity projector is the only writer of capacity status. 'projector':[{'apiGroups':['metal.datumapis.com'],'resources':['machinecapacities'],'verbs':['get','list','watch']},{'apiGroups':['metal.datumapis.com'],'resources':['machinecapacities/status'],'verbs':['get','update']}, {'apiGroups':['fleet.datumapis.com'],'resources':['devices','devicecustodies','devicecommissionings','devicecommissioningplans','devicecommissioningplanapprovals'],'verbs':['get','list','watch']}], diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index 40491d2a..cbc6cc16 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -135,6 +135,28 @@ def credential_name(device): return 'bmc-' + hashlib.sha256(device.encode()).hexdigest()[:20] +def synced(s): + """Whether this run's lab DHCP is synchronized (run.sh --synced-dhcp).""" + p = s / 'lab-dhcp' + return p.exists() and p.read_text().strip() == 'synced' + + +def enroll_dhcp(s, d): + """The synchronizer's token and the feed's TLS key, generated per run and + never committed: Secrets the site DHCP layer mounts.""" + (d / 'dhcp-sync.token').write_text(secrets.token_hex(32) + '\n') + subprocess.run(['openssl', 'req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes', '-keyout', str(d / 'dhcp-feed.key'), + '-out', str(d / 'dhcp-feed.crt'), '-days', '2', '-subj', '/CN=fleet-site-dhcp-feed', + '-addext', 'subjectAltName=DNS:fleet-site-dhcp-feed.fleet-site.svc'], check=True, capture_output=True) + for p in d.iterdir(): + p.chmod(0o600) + kubectl(s, '-n', SITE, 'create', 'secret', 'generic', 'fleet-site-dhcp-sync', '--from-file=token=%s' % (d / 'dhcp-sync.token')) + # The certificate is self-signed, so it is also the CA the synchronizer + # trusts. + kubectl(s, '-n', SITE, 'create', 'secret', 'generic', 'fleet-site-dhcp-feed-tls', '--from-file=tls.crt=%s' % (d / 'dhcp-feed.crt'), + '--from-file=tls.key=%s' % (d / 'dhcp-feed.key'), '--from-file=ca.crt=%s' % (d / 'dhcp-feed.crt')) + + def enroll(s): d = s / 'redfish' d.mkdir(mode=0o700, exist_ok=True) @@ -154,6 +176,8 @@ def enroll(s): p.chmod(0o600) kubectl(s, '-n', SITE, 'create', 'secret', 'generic', SECRET, '--from-file=username=%s' % (d / 'bmc-username'), '--from-file=password=%s' % (d / 'bmc-password.token')) kubectl(s, '-n', SITE, 'create', 'secret', 'tls', TLS_SECRET, '--cert=%s' % (d / 'bmc-tls.crt'), '--key=%s' % (d / 'bmc-tls.key')) + if synced(s): + enroll_dhcp(s, d) # One credential Secret per Device, by the BMC discovery contract. if kubectl(s, 'get', 'namespace', CREDENTIALS, check=False).returncode != 0: kubectl(s, 'create', 'namespace', CREDENTIALS) @@ -433,6 +457,116 @@ def commission_audit(s): return audit(s)[json.loads((s / 'redfish' / 'commission.json').read_text())['auditEntries']:] +LAB_IPAM_FIRST, LAB_IPAM_LAST = '192.168.77.100', '192.168.77.199' + + +def at(text): + """A Go RFC 3339 time as an aware datetime, to compare report and boot times.""" + text = text.replace('Z', '+00:00') + head, _, rest = text.partition('.') + if rest: + digits = rest[:len(rest) - len(rest.lstrip('0123456789'))] + zone = rest[len(digits):] + text = head + '.' + (digits + '000000')[:6] + zone + return datetime.datetime.fromisoformat(text) + + +def dhcp_synced(s): + """Synchronized lab DHCP: every installation and wipe carried a boot address + from its own IPAM claim, the site published its reservation for the boot + NIC only while its boot was open, Kea answered the firmware with that + address, and the lab network had no DHCP of its own.""" + if not synced(s): + die('dhcp-synced runs only with --synced-dhcp') + bootstrap = s / 'provider' / 'bootstrap-project.json' + def provider(*args): + r = subprocess.run(['kubectl', '--kubeconfig', str(bootstrap), '--request-timeout=30s', '-n', 'fleet-provider', *args, '-o', 'json'], text=True, capture_output=True, timeout=60) + if r.returncode: + die('provider read failed: %s' % r.stderr.strip()[-300:]) + return json.loads(r.stdout)['items'] + mac = json.loads(pathlib.Path('hack/redfish-lab/targets.json').read_text())[0]['mac'].lower() + first, last = [tuple(int(x) for x in a.split('.')) for a in (LAB_IPAM_FIRST, LAB_IPAM_LAST)] + ops = [] + for kind in ('deviceinstallations', 'devicewipes'): + for o in provider('get', kind): + network = o['spec'].get('bootNetwork') + if not network: + die('%s %s carries no boot address' % (o['kind'], o['metadata']['name'])) + if network['addressClaim']['name'] != o['metadata']['name'] + '-boot': + die('%s %s names a claim other than its own' % (o['kind'], o['metadata']['name'])) + if not first <= tuple(int(x) for x in network['address'].split('.')) <= last: + die('%s %s boot address %s is outside the lab IPAM range' % (o['kind'], o['metadata']['name'], network['address'])) + ops.append({'kind': o['kind'], 'name': o['metadata']['name'], 'uid': o['metadata']['uid'], 'phase': o.get('status', {}).get('phase'), + 'address': network['address'], 'claimUID': network['addressClaim']['uid'], + 'snapshotMAC': (o.get('status', {}).get('snapshot') or {}).get('bootMACAddress', '').lower()}) + kinds = [o['kind'] for o in ops] + if kinds.count('DeviceInstallation') < 2 or kinds.count('DeviceWipe') < 2: + die('expected at least two installations and two wipes, got %s' % kinds) + if len({o['claimUID'] for o in ops}) != len(ops): + die('two operations shared one boot address claim') + leftover = provider('get', 'ipclaims') + if leftover: + die('boot address claims remain after every release: %s' % [c['metadata']['name'] for c in leftover]) + + def run(*command, container='libvirt'): + return kubectl(s, '-n', SITE, 'exec', 'deploy/fleet-site-runtime', '-c', container, '--', *command, check=False, timeout=120) + device = harness.device_dir() + applied = [json.loads(l) for l in run('cat', '/var/lib/fleet-boot/dhcp-applied.log').stdout.splitlines() if l.strip()] + if not applied or {r['instance'] for r in applied} != {'lab-kea'}: + die('the site retained no applied report, or one from an instance other than lab-kea') + def serves(report, address): + return any(r['mac'] == mac and r['address'] == address for r in report['feed']['reservations']) + leases = run('cat', '/var/lib/kea/dhcp4.leases', container='kea').stdout.splitlines() + header = leases[0].split(',') if leases else [] + rows = [dict(zip(header, l.split(','))) for l in leases[1:] if l.strip()] + answered = {(r.get('address'), r.get('hwaddr', '').lower()) for r in rows} + record = {'observedAt': now(), 'bootMAC': mac, 'operations': []} + for o in ops: + boot = run('cat', '%s/boot/%s.json' % (device, o['uid'])) + entry = {k: o[k] for k in ('kind', 'name', 'phase', 'address')} + if boot.returncode: + # Admitted but never run at the site, or refused before any + # effect: no reservation was ever published for it. + if o['phase'] not in ('Failed', 'Cancelled'): + die('%s %s ended %s with no boot admission at the site' % (o['kind'], o['name'], o['phase'])) + entry['published'] = False + record['operations'].append(entry) + continue + b = json.loads(boot.stdout) + if b.get('mac') != mac or b.get('address') != o['address'] or o['snapshotMAC'] != mac: + die('%s %s published %s at %s, want the inventory boot MAC %s at %s' % (o['kind'], o['name'], b.get('mac'), b.get('address'), mac, o['address'])) + opened = at(b['created']) + served = [r for r in applied if at(r['at']) > opened and serves(r, o['address'])] + if not served: + die('%s %s: Kea never reported serving its reservation after its boot opened' % (o['kind'], o['name'])) + withdrawn = [r for r in applied if at(r['at']) > at(served[0]['at']) and not serves(r, o['address'])] + if not withdrawn: + die('%s %s: Kea never reported its reservation withdrawn' % (o['kind'], o['name'])) + delivered = run('sh', '-c', 'cat /var/lib/fleet-boot/%s/boot-delivery.log 2>/dev/null; true' % harness.key(o['uid'])).stdout + entry.update(published=True, servedAt=served[0]['at'], withdrawnAt=withdrawn[0]['at'], bootScriptDelivered='admitted boot.ipxe' in delivered, + keaAnswered=(o['address'], mac) in answered) + if entry['bootScriptDelivered'] and not entry['keaAnswered']: + die('%s %s booted over the network, but Kea holds no lease for %s at %s' % (o['kind'], o['name'], mac, o['address'])) + record['operations'].append(entry) + if applied[-1]['feed']['reservations']: + die('Kea still serves a reservation after the last operation ended') + booted = [e for e in record['operations'] if e.get('bootScriptDelivered')] + if sum(e['kind'] == 'DeviceWipe' for e in booted) < 2 or not any(e['kind'] == 'DeviceInstallation' for e in booted): + die('expected network boots of at least one installation and two wipes, got %s' % [(e['kind'], e['name']) for e in booted]) + static = {t['ip'] for t in json.loads(pathlib.Path('hack/redfish-lab/targets.json').read_text())} + if any(a in static for a, _ in answered) or any(not first <= tuple(int(x) for x in a.split('.')) <= last for a, _ in answered if a): + die('Kea leased an address outside the lab IPAM range: %s' % sorted(answered)) + network = runtime(s, 'virsh', '--connect', harness.LIBVIRT_URI, 'net-dumpxml', 'fleet-lab-pxe').stdout + dnsmasq = run('sh', '-c', 'for p in /proc/[0-9]*/comm; do cat "$p" 2>/dev/null; done | grep -c dnsmasq; true').stdout.strip() + if '&2; exit 64; } -preflight_only=0 bootstrap=() keep=0 leave=0 skip_tests=() provider=libvirt +usage() { echo 'usage: hack/multiplane/run.sh [--redfish [--synced-dhcp]] [--preflight-only] [--bootstrap] [--keep] [--leave-running] [--skip-readiness-tests]' >&2; exit 64; } +preflight_only=0 bootstrap=() keep=0 leave=0 skip_tests=() provider=libvirt lab_dhcp=static for arg in "$@"; do case "$arg" in --preflight-only) preflight_only=1 ;; @@ -21,9 +21,14 @@ for arg in "$@"; do # Redfish mode: workers drive lab VMs only through the DMTF Redfish emulator # and its lab adapter (docs/operations/redfish-lab.md). --redfish) provider=redfish ;; + # Synchronized DHCP: the site's Kea, fed by Fleet's reservation feed, is the + # lab bridge's only DHCP server, and boot addresses come from a synthetic + # IPAM stand-in (docs/operations/redfish-lab.md). + --synced-dhcp) lab_dhcp=synced ;; *) usage ;; esac done +[[ $lab_dhcp == static || $provider == redfish ]] || usage # Run parameters (docs/operations/multiplane.md#ci-mode). The defaults are the # task-owned Colima profile: arm64 runtime, TCG guest. Preflight validates them # before any resource exists. @@ -31,12 +36,13 @@ export FLEET_MULTIPLANE_RUNTIME=${FLEET_MULTIPLANE_RUNTIME:-colima} FLEET_MULTIP export FLEET_MULTIPLANE_ARCH=${FLEET_MULTIPLANE_ARCH:-arm64} FLEET_MULTIPLANE_ACCEL=${FLEET_MULTIPLANE_ACCEL:-tcg} # Scenario group: all by default; CI shards each suite into flux and release. export FLEET_MULTIPLANE_GROUP=${FLEET_MULTIPLANE_GROUP:-all} -export DOCKER_CONTEXT=$FLEET_MULTIPLANE_DOCKER_CONTEXT KIND_EXPERIMENTAL_PROVIDER=docker FLEET_SITE_PROVIDER=$provider +export DOCKER_CONTEXT=$FLEET_MULTIPLANE_DOCKER_CONTEXT KIND_EXPERIMENTAL_PROVIDER=docker FLEET_SITE_PROVIDER=$provider FLEET_LAB_DHCP=$lab_dhcp harness=(python3 hack/multiplane/harness.py) state=$(mktemp -d "${FLEET_MULTIPLANE_STATE_ROOT:-/tmp}/fleet-multiplane.XXXXXX") mkdir -m 0700 "$state/evidence" printf '%s\n' "$provider" > "$state/site-provider" -printf 'Private run state: %s\nShareable evidence: %s/evidence\nSite provider: %s\nScenario group: %s\n' "$state" "$state" "$provider" "$FLEET_MULTIPLANE_GROUP" +printf '%s\n' "$lab_dhcp" > "$state/lab-dhcp" +printf 'Private run state: %s\nShareable evidence: %s/evidence\nSite provider: %s\nScenario group: %s\nLab DHCP: %s\n' "$state" "$state" "$provider" "$FLEET_MULTIPLANE_GROUP" "$lab_dhcp" finish() { code=$1 @@ -98,11 +104,12 @@ PY flux=(python3 hack/multiplane/flux.py) # The site binary is built into its own directory: it is the only build context # input besides hack/local-vm, so no private state can enter the image. -ph build 600 sh -c 'mkdir -m 0700 "$1/site-bin" && go build -o "$1/fleet-multiplane-host" ./cmd/fleet-multiplane && CGO_ENABLED=0 GOOS=linux GOARCH="$FLEET_MULTIPLANE_ARCH" go build -o "$1/site-bin/fleet-multiplane" ./cmd/fleet-multiplane && cp "$1/site-bin/fleet-multiplane" "$1/fleet-multiplane"' sh "$state" +ph build 600 sh -c 'mkdir -m 0700 "$1/site-bin" && go build -o "$1/fleet-multiplane-host" ./cmd/fleet-multiplane && CGO_ENABLED=0 GOOS=linux GOARCH="$FLEET_MULTIPLANE_ARCH" go build -o "$1/site-bin/fleet-multiplane" ./cmd/fleet-multiplane && CGO_ENABLED=0 GOOS=linux GOARCH="$FLEET_MULTIPLANE_ARCH" go build -o "$1/site-bin/fleet-dhcp-sync" ./cmd/fleet-dhcp-sync && cp "$1/site-bin/fleet-multiplane" "$1/fleet-multiplane"' sh "$state" ph site-image 2400 docker build --target site --build-context "fleetbin=$state/site-bin" -t "$prefix-site-image" -f hack/local-vm/Containerfile hack/local-vm ph site-image-verify 120 sh -c ' sum=$(shasum -a 256 "$2/site-bin/fleet-multiplane" | cut -d" " -f1) - printf "%s /usr/local/bin/fleet-multiplane\n" "$sum" | docker run --rm -i --entrypoint sha256sum "$1-site-image" -c - >/dev/null + sync=$(shasum -a 256 "$2/site-bin/fleet-dhcp-sync" | cut -d" " -f1) + printf "%s /usr/local/bin/fleet-multiplane\n%s /usr/local/bin/fleet-dhcp-sync\n" "$sum" "$sync" | docker run --rm -i --entrypoint sha256sum "$1-site-image" -c - >/dev/null docker run --rm -e "FLEET_LOCAL_VM_ACCEL=$FLEET_MULTIPLANE_ACCEL" --entrypoint fleet-multiplane "$1-site-image" image > "$2/image" echo "site image: checksum-verified executable; artifact reference recorded"' sh "$prefix" "$state" if [[ $provider == redfish ]]; then @@ -130,11 +137,13 @@ ph federation-enrollment 600 python3 hack/multiplane/roles.py "$state" # Redfish mode enrolls the per-Device BMC credentials and the lab BMC's TLS # key first: fixture discovery reports that key's digest. [[ $provider != redfish ]] || ph redfish-enroll 120 python3 hack/multiplane/redfish_steps.py enroll "$state" -python3 - "$state" "$provider" <<'PY' +python3 - "$state" "$provider" "$lab_dhcp" <<'PY' import json,pathlib,sys s=pathlib.Path(sys.argv[1]).resolve() enrollment=json.loads((s/'redfish'/'fixture-enrollment.json').read_text() if sys.argv[2]=='redfish' else pathlib.Path('config/site/base/enrollment.json').read_text()) -c={'State':str(s),'HubKubeconfig':str(s/'management-hub.json'),'Cell':(s/'prefix').read_text().strip()+'-cell','Image':(s/'image').read_text().strip(),'Enrollment':enrollment};(s/'acceptance.json').write_text(json.dumps(c)) +c={'State':str(s),'HubKubeconfig':str(s/'management-hub.json'),'Cell':(s/'prefix').read_text().strip()+'-cell','Image':(s/'image').read_text().strip(),'Enrollment':enrollment} +if sys.argv[3]=='synced':c['BootAddressClass']='lab-provisioning' +(s/'acceptance.json').write_text(json.dumps(c)) PY ph seed 600 "$state/fleet-multiplane-host" seed --config "$state/acceptance.json" ph coordinator 120 bash hack/multiplane/coordinator.sh start "$state" diff --git a/hack/multiplane/test-redfish.py b/hack/multiplane/test-redfish.py index 0812d6bf..ff431713 100644 --- a/hack/multiplane/test-redfish.py +++ b/hack/multiplane/test-redfish.py @@ -8,10 +8,12 @@ contacts a container runtime or cluster. """ import argparse +import importlib import json import os import pathlib import re +import shutil import subprocess import sys import tempfile @@ -100,6 +102,54 @@ def build(path): check('every site role selects the Redfish provider', all(any(e.get('name') == 'FLEET_SITE_PROVIDER' and e.get('value') == 'redfish' for e in deployments[n]['spec']['template']['spec']['containers'][0].get('env', [])) for n in ('fleet-site-runtime', 'fleet-site-boot', 'fleet-site-observer'))) +check('static Redfish services run no DHCP of their own', not any(c['name'] in ('kea', 'dhcp-sync', 'dhcp-feed') for d in deployments.values() for c in d['spec']['template']['spec']['containers'])) + +# Synchronized lab DHCP (run.sh --synced-dhcp). +synced_graph = build(root / 'config/site/redfish/synced/graph') +synced_rgd = next((d for d in synced_graph if d.get('kind') == 'ResourceGraphDefinition'), {}) +synced_env = {e['name']: e.get('value') for e in next((r for r in synced_rgd.get('spec', {}).get('resources', []) if r['id'] == 'workers'), {}).get('template', {}).get('spec', {}).get('template', {}).get('spec', {}).get('containers', [{}])[0].get('env', [])} +synced_enrollment = json.loads(synced_env.get('FLEET_REDFISH_ENROLLMENT', '{}')) +check('synced graph changes only the DHCP mode', synced_enrollment.get('dhcp') == 'synced' and dict(synced_enrollment, dhcp='static') == enrollment + and {k: v for k, v in synced_env.items() if k != 'FLEET_REDFISH_ENROLLMENT'} == {k: v for k, v in env.items() if k != 'FLEET_REDFISH_ENROLLMENT'}) +synced_services = build(root / 'config/site/redfish/synced/services') +synced_deployments = {d['metadata']['name']: d for d in synced_services if d.get('kind') == 'Deployment'} +pod = lambda n: synced_deployments.get(n, {}).get('spec', {}).get('template', {}).get('spec', {}) +runtime_containers = {c['name']: c for c in pod('fleet-site-runtime').get('containers', [])} +check('synced runtime adds Kea and the synchronizer beside libvirt', sorted(runtime_containers) == ['dhcp-sync', 'kea', 'libvirt'], str(sorted(runtime_containers))) +check('Kea and the synchronizer are not privileged and add only the network capabilities Kea needs', + not any(runtime_containers.get(n, {}).get('securityContext', {}).get('privileged') for n in ('kea', 'dhcp-sync')) + and runtime_containers.get('kea', {}).get('securityContext', {}).get('capabilities') == {'drop': ['ALL'], 'add': ['NET_BIND_SERVICE', 'NET_RAW']} + and runtime_containers.get('dhcp-sync', {}).get('securityContext', {}).get('capabilities') == {'drop': ['ALL']}) +sync_args = runtime_containers.get('dhcp-sync', {}).get('command', []) +check('the synchronizer reports as one fixed instance over TLS', '-instance=lab-kea' in sync_args and '-feed=https://fleet-site-dhcp-feed.fleet-site.svc:8081' in sync_args + and '-ca-file=/etc/fleet-dhcp-tls/ca.crt' in sync_args, str(sync_args)) +check('Kea makes its control socket directory 0750 and waits for the lab bridge', 'chmod 0750 /var/run/kea' in ' '.join(runtime_containers.get('kea', {}).get('command', [])) + and 'fleetpxe0' in ' '.join(runtime_containers.get('kea', {}).get('command', []))) +check('the feed runs beside the boot service', any(c['name'] == 'dhcp-feed' and c['command'][:2] == ['fleet-multiplane', 'dhcp-feed'] for c in pod('fleet-site-boot').get('containers', []))) +check('the lab BMC defines the network without DHCP', any(e == {'name': 'FLEET_LAB_DHCP', 'value': 'synced'} for e in pod('fleet-site-bmc').get('containers', [{}])[0].get('env', []))) +kea_config = json.loads(next((d['data']['kea-dhcp4.conf'] for d in synced_services if d.get('kind') == 'ConfigMap' and d['metadata']['name'] == 'fleet-site-dhcp-base'), '{}')) +subnets = kea_config.get('Dhcp4', {}).get('subnet4', []) +check('lab Kea serves the bridge subnet from reservations only, with the boot program', kea_config.get('Dhcp4', {}).get('interfaces-config', {}).get('interfaces') == ['fleetpxe0'] + and len(subnets) == 1 and subnets[0].get('subnet') == '192.168.77.0/24' and 'pools' not in subnets[0] + and subnets[0].get('boot-file-name') == 'http://${FLEET_BOOT_SERVICE_IP}:8080/pxe/boot.ipxe' + and kea_config['Dhcp4'].get('control-socket', {}).get('socket-name') == '/var/run/kea/kea4-ctrl-socket', json.dumps(kea_config)[:300]) +check('no Secret in the synced services', not any(d.get('kind') == 'Secret' for d in synced_services)) +for name, d in synced_deployments.items(): + volumes = {v['name'] for v in d['spec']['template']['spec'].get('volumes', [])} + missing = {m['name'] for c in d['spec']['template']['spec']['containers'] for m in c.get('volumeMounts', [])} - volumes + check('synced %s mounts only volumes it declares' % name, not missing, str(missing)) +os.environ['FLEET_LAB_DHCP'] = 'synced' +importlib.reload(flux) +check('synced Flux inventory holds the base configuration and the feed Service', + {'fleet-site_fleet-site-dhcp-base__ConfigMap', 'fleet-site_fleet-site-dhcp-feed__Service'} <= set(flux.LAYER_INVENTORY['flux-system/fleet-site-services'])) +os.environ['FLEET_LAB_DHCP'] = 'static' +importlib.reload(flux) +check('run.sh accepts --synced-dhcp only with --redfish', "--synced-dhcp) lab_dhcp=synced" in (root / 'hack/multiplane/run.sh').read_text() + and '[[ $lab_dhcp == static || $provider == redfish ]] || usage' in (root / 'hack/multiplane/run.sh').read_text()) +check('the synced acceptance asserts the DHCP evidence', 'rf dhcp-synced' in (root / 'hack/multiplane/acceptance-redfish.sh').read_text()) +check('synced evidence requires the DHCP phase', "markers += ('redfish-dhcp-synced: ',)" in (root / 'hack/multiplane/evidence.py').read_text() + and "print('redfish-dhcp-synced: " in (root / 'hack/multiplane/redfish_steps.py').read_text()) + base = build(root / 'config/site/redfish/base') policy = next((d for d in base if d.get('kind') == 'ValidatingAdmissionPolicy' and d['metadata']['name'] == 'fleet-site-kro-worker-jobs'), {}) text = json.dumps(policy) @@ -143,6 +193,22 @@ def build(path): used |= set(re.findall(r'\$\{(FLEET_[A-Z_]+)\}', f.read_text())) defined = set(re.findall(r'^ (FLEET_[A-Z_]+): ', cell, re.M)) check('Redfish substituted variables defined', used <= defined, str(sorted(used - defined))) + # The same revision with synchronized lab DHCP selects the synced graph + # and services and keeps the Redfish base. + os.environ['FLEET_LAB_DHCP'] = 'synced' + importlib.reload(flux) + flux.INSTALL_SHA256 = flux.sha256(s / 'flux-tools' / 'install.yaml') + shutil.rmtree(s / 'gitops') + check('stage a synced Redfish revision', flux.stage(args) == 0) + cell = subprocess.run(['kustomize', 'build', str(s / 'gitops/r2/environment/cell')], text=True, capture_output=True).stdout + check('synced cell layers use the synced overlays', 'path: ./config/site/redfish/synced/services' in cell and 'path: ./config/site/redfish/synced/graph' in cell + and 'path: ./config/site/redfish/base' in cell) + used = set() + for f in (root / 'config/site/redfish/synced/services').glob('*.yaml'): + used |= set(re.findall(r'\$\{(FLEET_[A-Z_]+)\}', f.read_text())) + check('synced substituted variables defined', used <= set(re.findall(r'^ (FLEET_[A-Z_]+): ', cell, re.M)), str(sorted(used))) + os.environ['FLEET_LAB_DHCP'] = 'static' + importlib.reload(flux) check('ownership audit expects the BMC', ('deployments', 'fleet-site', 'fleet-site-bmc') in flux.SHARED and 'fleet-site-bmc' in flux.SITE_DEPLOYMENTS) # Every Redfish phase is implemented, and the lab fault hooks stay in the lab. diff --git a/hack/redfish-lab/fleet_lab_adapter.py b/hack/redfish-lab/fleet_lab_adapter.py index 91dbae8c..aa77c3b0 100755 --- a/hack/redfish-lab/fleet_lab_adapter.py +++ b/hack/redfish-lab/fleet_lab_adapter.py @@ -57,6 +57,10 @@ # starts a target only while the two agree, with no software fallback. ACCEL = os.environ.get('FLEET_LAB_ACCEL', '') RUNTIME_ACCELERATOR = os.environ.get('FLEET_LAB_RUNTIME_ACCELERATOR', '/run/fleet-libvirt/accelerator') +# Lab DHCP mode. static: libvirt's dnsmasq hands each target a fixed lease. +# synced: the network has no DHCP of its own, and the site's Kea, fed by +# Fleet's reservation feed, is the only DHCP server on the bridge. +LAB_DHCP = os.environ.get('FLEET_LAB_DHCP', 'static') LOCK = threading.RLock() @@ -145,12 +149,17 @@ def domain_xml(t, boot): "").format(boot=boot, **t) -def network_xml(targets, boot_ip): +def network_xml(targets, boot_ip, dhcp=None): + head = ("" + NETWORK + "" + "") + if (dhcp or LAB_DHCP) == 'synced': + return head + "" + if (dhcp or LAB_DHCP) != 'static': + raise ValueError('FLEET_LAB_DHCP must be static or synced') hosts = ''.join("" % (t['mac'], t['ip']) for t in targets.values()) ips = sorted(t['ip'] for t in targets.values()) - return ("" + NETWORK + "" - "%s" - "") % (ips[0], ips[-1], hosts, boot_ip) + return head + ("%s" + "") % (ips[0], ips[-1], hosts, boot_ip) class Lab: diff --git a/hack/redfish-lab/test_adapter.py b/hack/redfish-lab/test_adapter.py index fb899a22..3b0357d8 100644 --- a/hack/redfish-lab/test_adapter.py +++ b/hack/redfish-lab/test_adapter.py @@ -166,6 +166,17 @@ def test_5b_power_faults_and_reset_time(self): self.assertEqual(self.audit()[-1]['fault'], 'drop-response-after-effect') self.assertEqual(system()['PowerState'], 'Off') + def test_7_synced_dhcp_network_has_no_dhcp_server(self): + targets = {'System-1': {'mac': '52:54:00:77:01:0a', 'ip': '192.168.77.10'}} + static = adapter.network_xml(targets, '10.96.0.80', 'static') + synced = adapter.network_xml(targets, '10.96.0.80', 'synced') + self.assertIn('', static) + self.assertNotIn('dhcp', synced) + self.assertNotIn('52:54:00:77:01:0a', synced) + self.assertIn(" 0 { + return bound, fmt.Errorf("the lab IPAM range %s-%s is exhausted", p.First, p.Last) + } + claim.Object["status"] = map[string]any{"phase": "Bound", "address": next.String(), "allocatedCIDR": next.String() + "/32"} + if err := p.Client.Status().Update(ctx, claim); err != nil { + return bound, err + } + used[next] = true + bound++ + } + return bound, nil +} diff --git a/internal/multiplane/ipam_test.go b/internal/multiplane/ipam_test.go new file mode 100644 index 00000000..d78c105e --- /dev/null +++ b/internal/multiplane/ipam_test.go @@ -0,0 +1,68 @@ +package multiplane + +import ( + "context" + "net/netip" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + "go.datum.net/fleet/internal/bootaddress" +) + +func claim(name string, created time.Time, status map[string]any) *unstructured.Unstructured { + c := &unstructured.Unstructured{} + c.SetGroupVersionKind(bootaddress.GVK) + c.SetNamespace(DeviceNamespace) + c.SetName(name) + c.SetCreationTimestamp(metav1.NewTime(created)) + if status != nil { + c.Object["status"] = status + } + return c +} + +// TestStandInIPAMBindsTheLowestFreeAddressOldestFirst binds unbound claims +// in creation order to the lowest addresses no claim holds, leaves bound +// claims alone, and refuses when the range is exhausted. +func TestStandInIPAMBindsTheLowestFreeAddressOldestFirst(t *testing.T) { + ctx := context.Background() + scheme := runtime.NewScheme() + scheme.AddKnownTypeWithName(bootaddress.GVK, &unstructured.Unstructured{}) + scheme.AddKnownTypeWithName(bootaddress.GVK.GroupVersion().WithKind("IPClaimList"), &unstructured.UnstructuredList{}) + now := time.Now().Truncate(time.Second) + api := fake.NewClientBuilder().WithScheme(scheme).WithObjects( + claim("held", now.Add(-time.Hour), map[string]any{"phase": "Bound", "address": "192.0.2.100"}), + claim("newer", now, nil), + claim("older", now.Add(-time.Minute), nil), + ).WithStatusSubresource(claim("x", now, nil)).Build() + ipam := StandInIPAM{Client: api, Namespace: DeviceNamespace, First: netip.MustParseAddr("192.0.2.100"), Last: netip.MustParseAddr("192.0.2.102")} + if bound, err := ipam.Bind(ctx); err != nil || bound != 2 { + t.Fatalf("bound %d, %v", bound, err) + } + address := func(name string) string { + c := claim(name, now, nil) + if err := api.Get(ctx, client.ObjectKeyFromObject(c), c); err != nil { + t.Fatal(err) + } + value, _, _ := unstructured.NestedString(c.Object, "status", "address") + return value + } + if address("held") != "192.0.2.100" || address("older") != "192.0.2.101" || address("newer") != "192.0.2.102" { + t.Fatalf("addresses = %s %s %s", address("held"), address("older"), address("newer")) + } + if bound, err := ipam.Bind(ctx); err != nil || bound != 0 { + t.Fatalf("a second pass bound %d, %v", bound, err) + } + if err := api.Create(ctx, claim("extra", now.Add(time.Minute), nil)); err != nil { + t.Fatal(err) + } + if _, err := ipam.Bind(ctx); err == nil { + t.Fatal("an exhausted range bound a claim") + } +} diff --git a/internal/multiplane/runner.go b/internal/multiplane/runner.go index 321331a2..a3ef4b13 100644 --- a/internal/multiplane/runner.go +++ b/internal/multiplane/runner.go @@ -9,6 +9,7 @@ import ( "encoding/json" "errors" "fmt" + "net/netip" "os" "path/filepath" "strings" @@ -84,6 +85,9 @@ type Runner struct { Consumers [2]Project Allocator *allocation.Allocator Hub *coordination.Hub + // IPAM binds boot address claims in IPAM's place when the lab's DHCP is + // synchronized. Nil otherwise. + IPAM *StandInIPAM } func Scheme() *runtime.Scheme { @@ -265,6 +269,13 @@ func New(ctx context.Context, c Config) (*Runner, error) { } if c.BootAddressClass != "" { r.Allocator.BootAddresses = &bootaddress.Claimer{Class: c.BootAddressClass, Scope: map[string]bootaddress.ScopeRef{"location": {APIGroup: "networking.datumapis.com", Kind: "Location", Name: Location}}} + bootstrap, err := API(filepath.Join(c.State, "provider", "bootstrap-project.json")) + if err != nil { + return nil, err + } + // The lab bridge is 192.168.77.0/24. Its static leases sit below .100, + // so a boot address from this range is never a static lease. + r.IPAM = &StandInIPAM{Client: bootstrap, Namespace: DeviceNamespace, First: netip.MustParseAddr("192.168.77.100"), Last: netip.MustParseAddr("192.168.77.199")} } return r, nil } From 0f25246527426b91d7e150050180fc28ae2f9424 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 15:44:54 -0600 Subject: [PATCH 05/17] test(multiplane): Tie each Kea lease to its own boot window Require a Kea lease for the boot MAC at each operation's address granted inside that operation's boot window, for every operation that powered on for a network boot, two installations and two wipes. Start Kea only once the lab bridge has its address, describe the held second installation plainly, and mark the synced mode as not yet run. Co-Authored-By: Claude Opus 5.5 --- .../synced/services/kustomization.yaml | 7 +++-- docs/operations/boot-network.md | 2 +- docs/operations/redfish-lab.md | 20 +++++++----- hack/multiplane/redfish_steps.py | 31 ++++++++++++++----- internal/bootaddress/testdata/ipclaims.yaml | 7 +++-- 5 files changed, 45 insertions(+), 22 deletions(-) diff --git a/config/site/redfish/synced/services/kustomization.yaml b/config/site/redfish/synced/services/kustomization.yaml index 1dbfe4fe..93f5ff2d 100644 --- a/config/site/redfish/synced/services/kustomization.yaml +++ b/config/site/redfish/synced/services/kustomization.yaml @@ -26,9 +26,10 @@ patches: name: kea image: "${FLEET_SITE_IMAGE}" imagePullPolicy: IfNotPresent - # Kea starts once the lab BMC adapter has created the bridge. Kea - # refuses a control socket directory that is not 0750. - command: [sh, -c, 'mkdir -p /var/run/kea && chmod 0750 /var/run/kea && until [ -e /sys/class/net/fleetpxe0 ]; do sleep 2; done && exec kea-dhcp4 -c /etc/kea-base/kea-dhcp4.conf'] + # Kea starts once the lab BMC adapter has created the bridge and + # libvirt has given it its address. Kea refuses a control socket + # directory that is not 0750. + command: [sh, -c, 'mkdir -p /var/run/kea && chmod 0750 /var/run/kea && until [ -e /sys/class/net/fleetpxe0 ] && grep -qw 192.168.77.1 /proc/net/fib_trie; do sleep 2; done && exec kea-dhcp4 -c /etc/kea-base/kea-dhcp4.conf'] env: - {name: KEA_PIDFILE_DIR, value: /var/run/kea} - {name: KEA_LOCKFILE_DIR, value: none} diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index b2d5649a..396886f6 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -285,6 +285,6 @@ requirements. | Relay, provisioning VLAN, isolation and LACP fallback at a site | Network operations; see the [server networking enhancement][server-networking] | | Telling firmware what to boot in synced mode (Redfish `HttpBootUri` for UEFI HTTP Boot, or a DHCP boot-file option) | Proposed; the Redfish worker still arms `Pxe`, which relies on site DHCP for the boot file | | DHCPv6 reservations | Proposed; the feed accepts IPv6, the Kea DHCPv4 synchronizer and the claim reject it | -| Lab acceptance in synced mode | Implemented as `run.sh --redfish --synced-dhcp`, with a synthetic IPAM stand-in; see the [Redfish lab](redfish-lab.md#synchronized-dhcp-mode) for its result | +| Lab acceptance in synced mode | Implemented as `run.sh --redfish --synced-dhcp`, with a synthetic IPAM stand-in; not yet run. See the [Redfish lab](redfish-lab.md#synchronized-dhcp-mode) | [server-networking]: https://github.com/datum-cloud/fleet/pull/186 diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 0a3109fd..dcf80aa8 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -381,16 +381,22 @@ The `redfish-dhcp-synced` phase runs after `boot-denials` and writes 2. each operation that ran at the site published the snapshot's boot MAC at its address, and Kea reported serving it after that boot opened and reported it withdrawn later; -3. Kea holds a lease for the boot MAC at that address for every operation whose - boot script was delivered, at least one installation and both wipes, and - leased no static or out-of-range address; +3. for every operation that powered on for a network boot, Kea leased the boot + MAC that operation's address during that operation's own boot window; at + least two installations and two wipes did, and Kea leased no static or + out-of-range address; 4. the lab network has no `` element and no dnsmasq runs; and 5. Kea's last report serves nothing. -Consumer B's installation on the same server and both release wipes each get -their own claim and reservation. The stand-in may hand a released address out -again, as IPAM may, so freshness is judged by claim and by report time, not by -address. +The second installation is consumer B's, on the same server after consumer +A's release. It gets its own claim and reservation, and its firmware leases +that address from Kea, but the failure scenarios withhold its boot script and +hold it at its deadline, so it never installs. Both release wipes boot and +complete. The stand-in may hand a released address out again, as IPAM may, so +freshness is judged by claim and by lease and report times, not by address. + +The mode is implemented and its offline checks pass. No synced run has passed +yet. ## Acceptance phases diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index cbc6cc16..0f051e0f 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -519,7 +519,14 @@ def serves(report, address): leases = run('cat', '/var/lib/kea/dhcp4.leases', container='kea').stdout.splitlines() header = leases[0].split(',') if leases else [] rows = [dict(zip(header, l.split(','))) for l in leases[1:] if l.strip()] + if not rows or not {'address', 'hwaddr', 'expire', 'valid_lifetime'} <= set(header): + die('Kea recorded no leases') answered = {(r.get('address'), r.get('hwaddr', '').lower()) for r in rows} + # When Kea granted each lease: its expiry less its lifetime, in seconds. + granted = [(r['address'], r['hwaddr'].lower(), int(r['expire']) - int(r['valid_lifetime'])) for r in rows] + # An operation asked for a network boot once its power-on was journaled, + # whether or not the boot server then served it. + network_boots = {o['operation'] for o in journal(s) if any(n in ('installer-power-on', 'wipe-power-on') for n, _ in o['steps'])} record = {'observedAt': now(), 'bootMAC': mac, 'operations': []} for o in ops: boot = run('cat', '%s/boot/%s.json' % (device, o['uid'])) @@ -543,16 +550,23 @@ def serves(report, address): if not withdrawn: die('%s %s: Kea never reported its reservation withdrawn' % (o['kind'], o['name'])) delivered = run('sh', '-c', 'cat /var/lib/fleet-boot/%s/boot-delivery.log 2>/dev/null; true' % harness.key(o['uid'])).stdout - entry.update(published=True, servedAt=served[0]['at'], withdrawnAt=withdrawn[0]['at'], bootScriptDelivered='admitted boot.ipxe' in delivered, - keaAnswered=(o['address'], mac) in answered) - if entry['bootScriptDelivered'] and not entry['keaAnswered']: - die('%s %s booted over the network, but Kea holds no lease for %s at %s' % (o['kind'], o['name'], mac, o['address'])) + # Kea leased this operation's address to the boot NIC inside this + # operation's own window: after its boot opened and before Kea + # withdrew its reservation, with five seconds for clock rounding. + start, end = opened.timestamp() - 5, at(withdrawn[0]['at']).timestamp() + 5 + leased = [g for a, m, g in granted if a == o['address'] and m == mac and start <= g <= end] + entry.update(published=True, servedAt=served[0]['at'], withdrawnAt=withdrawn[0]['at'], networkBoot=o['uid'] in network_boots, + bootScriptDelivered='admitted boot.ipxe' in delivered, keaLeasesInWindow=len(leased)) + if entry['networkBoot'] and not leased: + die('%s %s powered on for a network boot, but Kea leased %s no address %s during its boot' % (o['kind'], o['name'], mac, o['address'])) + if entry['bootScriptDelivered'] and not entry['networkBoot']: + die('%s %s delivered a boot script with no journaled network boot' % (o['kind'], o['name'])) record['operations'].append(entry) if applied[-1]['feed']['reservations']: die('Kea still serves a reservation after the last operation ended') - booted = [e for e in record['operations'] if e.get('bootScriptDelivered')] - if sum(e['kind'] == 'DeviceWipe' for e in booted) < 2 or not any(e['kind'] == 'DeviceInstallation' for e in booted): - die('expected network boots of at least one installation and two wipes, got %s' % [(e['kind'], e['name']) for e in booted]) + booted = [e for e in record['operations'] if e.get('networkBoot')] + if sum(e['kind'] == 'DeviceWipe' for e in booted) < 2 or sum(e['kind'] == 'DeviceInstallation' for e in booted) < 2: + die('expected Kea-leased network boots of two installations and two wipes, got %s' % [(e['kind'], e['name']) for e in booted]) static = {t['ip'] for t in json.loads(pathlib.Path('hack/redfish-lab/targets.json').read_text())} if any(a in static for a, _ in answered) or any(not first <= tuple(int(x) for x in a.split('.')) <= last for a, _ in answered if a): die('Kea leased an address outside the lab IPAM range: %s' % sorted(answered)) @@ -564,7 +578,8 @@ def serves(report, address): claimsRemaining=0, distinctClaims=len(ops)) write(s / 'evidence' / 'redfish-dhcp.json', record) print('redfish-dhcp-synced: %d operations each carried their own IPAM boot address; Kea served each reservation only after its boot opened and reported it withdrawn; ' - 'firmware leased every booted address from Kea; the lab network had no DHCP; no claim remains' % len(ops)) + 'firmware leased each operation\'s address from Kea during its own boot (%d network boots, two installations and two wipes); the lab network had no DHCP; no claim remains' + % (len(ops), len(booted))) def audit_mark(s): diff --git a/internal/bootaddress/testdata/ipclaims.yaml b/internal/bootaddress/testdata/ipclaims.yaml index 561f8905..da73ce77 100644 --- a/internal/bootaddress/testdata/ipclaims.yaml +++ b/internal/bootaddress/testdata/ipclaims.yaml @@ -1,6 +1,7 @@ -# A test stand-in for IPAM's IPClaim. IPAM serves the real kind from its own -# aggregated API server; envtest has none, so this CRD keeps only the fields -# Fleet reads. It is never shipped. +# A stand-in for IPAM's IPClaim. IPAM serves the real kind from its own +# aggregated API server. Envtest and the Redfish lab's synchronized DHCP mode +# have none, so this CRD keeps only the fields Fleet reads. No deployment +# bundle includes it. apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: From dda8921647fc1a9433855c2023fbb8f5a7ee9f2c Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 16:33:11 -0600 Subject: [PATCH 06/17] test(multiplane): Tell boot address claims apart by name Operations no longer carry their claim's UID, so the synced DHCP phase requires distinct claim names, which derive from distinct operations. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/redfish_steps.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index 0f051e0f..4de03e3d 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -497,12 +497,13 @@ def provider(*args): if not first <= tuple(int(x) for x in network['address'].split('.')) <= last: die('%s %s boot address %s is outside the lab IPAM range' % (o['kind'], o['metadata']['name'], network['address'])) ops.append({'kind': o['kind'], 'name': o['metadata']['name'], 'uid': o['metadata']['uid'], 'phase': o.get('status', {}).get('phase'), - 'address': network['address'], 'claimUID': network['addressClaim']['uid'], + 'address': network['address'], 'claim': network['addressClaim']['name'], 'snapshotMAC': (o.get('status', {}).get('snapshot') or {}).get('bootMACAddress', '').lower()}) kinds = [o['kind'] for o in ops] if kinds.count('DeviceInstallation') < 2 or kinds.count('DeviceWipe') < 2: die('expected at least two installations and two wipes, got %s' % kinds) - if len({o['claimUID'] for o in ops}) != len(ops): + # Claim names derive from operation names, which differ per operation. + if len({o['claim'] for o in ops}) != len(ops): die('two operations shared one boot address claim') leftover = provider('get', 'ipclaims') if leftover: From a2e4f8f95559b639e5cb284cc0495c976c4b5f12 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 20:28:11 -0600 Subject: [PATCH 07/17] feat(site): Run each site's Kea centrally DHCP no longer runs at the site. The Kea component deploys once per site to a central cluster: no host networking, Kea on a UDP socket for relayed requests only and not authoritative, and several replicas behind one UDP 67 load-balancer address that the site's relays reach over the WAN link. Client-IP affinity keeps each relay on one replica, so the replicas give availability, not load sharing per relay. The synchronizer reaches the site's feed over TLS at FLEET_DHCP_FEED_URL, and the feed component stays beside the boot service. The example base configuration drops the TFTP server and answers the UEFI HTTP boot vendor class with the boot service's loader URL. The docs state the reply path, the WAN dependency, why the fence and the withdrawal proof still hold, and that serving the HTTP boot loader from a central boot service is still proposed. The render check covers the new shape. Co-Authored-By: Claude Opus 5.5 --- config/site/dhcp/component/dhcp.yaml | 49 +++++++--- config/site/dhcp/component/kustomization.yaml | 16 ++-- config/site/dhcp/example/base.yaml | 16 +++- config/site/dhcp/example/kustomization.yaml | 8 +- config/site/dhcp/feed/kustomization.yaml | 2 +- config/site/dhcp/feed/service.yaml | 3 +- docs/operations/boot-network.md | 89 +++++++++++++------ docs/operations/redfish-lab.md | 4 +- hack/validate-site-dhcp-render.sh | 14 ++- 9 files changed, 143 insertions(+), 58 deletions(-) diff --git a/config/site/dhcp/component/dhcp.yaml b/config/site/dhcp/component/dhcp.yaml index 060db454..8f859e61 100644 --- a/config/site/dhcp/component/dhcp.yaml +++ b/config/site/dhcp/component/dhcp.yaml @@ -3,12 +3,16 @@ kind: ServiceAccount metadata: {name: fleet-site-dhcp, namespace: fleet-site} automountServiceAccountToken: false --- -# Kea DHCPv4 instances. Each Pod's name is its stable instance name in the -# applied reports. Pods use host networking on nodes that network operations -# labels as DHCP hosts, one per node. The base configuration's relay filter -# limits Kea to relayed requests from the site's relays. Scale down only after the instance being removed -# reports an empty feed: an instance removed while serving keeps its -# operations' outcomes unknown until an operator retires it. +# One site's Kea DHCPv4 instances, in a central cluster rather than at the +# site. Each Pod's name is its stable instance name in the applied reports, +# so a StatefulSet, never a Deployment: a replaced Pod keeps its name and its +# last report. The instances share one load-balancer address on UDP 67 +# (below), which the site's relays reach over the WAN link. Kea answers only relayed +# requests, on a UDP socket, so it needs no host networking; the base +# configuration's relay filter limits it to the site's relays. Scale down +# only after the instance being removed reports an empty feed: an instance +# removed while serving keeps its operations' outcomes unknown until an +# operator retires it. apiVersion: apps/v1 kind: StatefulSet metadata: @@ -26,9 +30,6 @@ spec: spec: serviceAccountName: fleet-site-dhcp automountServiceAccountToken: false - hostNetwork: true - dnsPolicy: ClusterFirstWithHostNet - nodeSelector: {fleet.datumapis.com/dhcp-host: "true"} affinity: podAntiAffinity: requiredDuringSchedulingIgnoredDuringExecution: @@ -41,10 +42,12 @@ spec: # Kea 2.6 refuses a control socket directory that is not 0750, # and an emptyDir is created 0777. command: [sh, -c, 'chmod 0750 /var/run/kea && exec kea-dhcp4 -c /etc/kea-base/kea-dhcp4.conf'] + ports: + - {name: dhcp, containerPort: 67, protocol: UDP} securityContext: runAsUser: 0 allowPrivilegeEscalation: false - capabilities: {drop: [ALL], add: [NET_BIND_SERVICE, NET_RAW]} + capabilities: {drop: [ALL], add: [NET_BIND_SERVICE]} resources: requests: {cpu: 50m, memory: 64Mi} limits: {memory: 256Mi} @@ -56,7 +59,9 @@ spec: imagePullPolicy: IfNotPresent command: - /fleet-dhcp-sync - - -feed=https://fleet-site-dhcp-feed.fleet-site.svc:8081 + # The site's feed, over TLS only, wherever the site's boot Pod + # runs. + - -feed=${FLEET_DHCP_FEED_URL} - -token-file=/etc/fleet-dhcp/token - -ca-file=/etc/fleet-dhcp-tls/ca.crt - -kea-socket=/var/run/kea/kea4-ctrl-socket @@ -98,3 +103,25 @@ spec: maxUnavailable: 1 selector: matchLabels: {app.kubernetes.io/name: fleet-site-dhcp} +--- +# One load-balancer address on UDP 67 for all of the site's instances, which +# the site's relays forward to. Any instance may answer a request. Each +# instance applies the same feed through its own synchronizer and reports it +# under its own stable name, so the withdrawal gate covers every instance; +# an instance that has not applied a reservation yet stays silent, because +# Kea is not authoritative, and the firmware retries. Client-IP affinity +# keeps one relay's exchange on one instance. Kea replies to the relay +# address in each request; the site's relays must accept replies from the +# cluster's egress address. +apiVersion: v1 +kind: Service +metadata: + name: fleet-site-dhcp + namespace: fleet-site +spec: + type: LoadBalancer + externalTrafficPolicy: Local + sessionAffinity: ClientIP + selector: {app.kubernetes.io/name: fleet-site-dhcp} + ports: + - {name: dhcp, port: 67, targetPort: 67, protocol: UDP} diff --git a/config/site/dhcp/component/kustomization.yaml b/config/site/dhcp/component/kustomization.yaml index 8eb92c17..3aa57dc6 100644 --- a/config/site/dhcp/component/kustomization.yaml +++ b/config/site/dhcp/component/kustomization.yaml @@ -1,14 +1,14 @@ -# The site DHCP service for a site whose DHCP Fleet synchronizes: the -# reservation feed beside the boot service, and Kea DHCPv4 instances, each -# with its synchronizer. Network operations owns the base configuration -# (ConfigMap fleet-site-dhcp-base) and the relays that point at the Kea -# hosts. The environment supplies two Secrets, never in Git: +# One synchronized site's DHCP service, deployed to a central cluster: Kea +# DHCPv4 instances, each with its synchronizer, behind one load-balancer +# address on UDP 67. The site's feed is the separate ../feed component, +# beside the site's boot service. Network operations owns the base +# configuration (ConfigMap fleet-site-dhcp-base) and the relays that point at +# the instances' addresses. The environment supplies the Secrets # fleet-site-dhcp-sync (key token, at least 32 characters) and -# fleet-site-dhcp-feed-tls (tls.crt, tls.key, ca.crt). See +# fleet-site-dhcp-feed-tls (ca.crt), never in Git, and the +# FLEET_DHCP_FEED_URL and FLEET_DHCP_SYNC_IMAGE substitutions. See # docs/operations/boot-network.md. apiVersion: kustomize.config.k8s.io/v1alpha1 kind: Component resources: - dhcp.yaml -components: - - ../feed diff --git a/config/site/dhcp/example/base.yaml b/config/site/dhcp/example/base.yaml index 3e49dd22..8a24fa47 100644 --- a/config/site/dhcp/example/base.yaml +++ b/config/site/dhcp/example/base.yaml @@ -1,8 +1,10 @@ # A synthetic base configuration. Network operations owns the real one: the # site's provisioning subnet and gateway, the relay addresses Kea accepts, and -# the boot options. Kea listens on every node address, so the relay filter -# limits it to the site's relays. It has no pools, so Kea answers only -# reserved MACs, and Kea 2.6 requires the control socket under /var/run/kea. +# the boot options. Kea answers only relayed requests on a UDP socket, and the +# relay filter limits it to the site's relays. It has no pools, so Kea answers +# only reserved MACs, and Kea 2.6 requires the control socket under +# /var/run/kea. Firmware boots over UEFI HTTP boot, never TFTP: requests from +# the HTTP boot vendor class get the boot service's loader URL. apiVersion: v1 kind: ConfigMap metadata: @@ -15,13 +17,19 @@ data: "control-socket": {"socket-type": "unix", "socket-name": "/var/run/kea/kea4-ctrl-socket"}, "lease-database": {"type": "memfile", "persist": false}, "host-reservation-identifiers": ["hw-address"], + "authoritative": false, + "client-classes": [{ + "name": "HTTPClient", + "test": "substring(option[60].hex,0,10) == 'HTTPClient'", + "option-data": [{"name": "vendor-class-identifier", "data": "HTTPClient"}], + "boot-file-name": "http://192.0.2.80:8080/pxe/ipxe.efi" + }], "valid-lifetime": 600, "subnet4": [{ "id": 1, "subnet": "198.51.100.0/24", "relay": {"ip-addresses": ["198.51.100.1"]}, "option-data": [{"name": "routers", "data": "198.51.100.1"}], - "next-server": "192.0.2.80", "boot-file-name": "http://192.0.2.80:8080/pxe/boot.ipxe" }] }} diff --git a/config/site/dhcp/example/kustomization.yaml b/config/site/dhcp/example/kustomization.yaml index 4fcb1299..abfbca7e 100644 --- a/config/site/dhcp/example/kustomization.yaml +++ b/config/site/dhcp/example/kustomization.yaml @@ -1,10 +1,12 @@ -# Render check only: the Redfish site services with the site DHCP service and -# a synthetic base configuration. An environment supplies its own base -# configuration from network operations. +# Render check only: the Redfish site services with the feed, and the site's +# central DHCP instances with a synthetic base configuration, in one render. +# An environment deploys the two to different clusters and supplies its own +# base configuration from network operations. apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - ../../redfish/services - base.yaml components: + - ../feed - ../component diff --git a/config/site/dhcp/feed/kustomization.yaml b/config/site/dhcp/feed/kustomization.yaml index 75d7b697..bfd8c1e1 100644 --- a/config/site/dhcp/feed/kustomization.yaml +++ b/config/site/dhcp/feed/kustomization.yaml @@ -1,6 +1,6 @@ # The reservation feed: a container beside the boot service, which reads the # site store and writes the applied reports beside the boot evidence, and a -# Service reachable only inside the site cluster. The environment supplies +# Service. The site's central DHCP instances reach it over TLS only. The environment supplies # the Secrets fleet-site-dhcp-sync (key token) and fleet-site-dhcp-feed-tls # (tls.crt, tls.key, ca.crt), never in Git. The Kea component and the # Redfish lab's synchronized DHCP both use it. diff --git a/config/site/dhcp/feed/service.yaml b/config/site/dhcp/feed/service.yaml index 642ec089..57cd234c 100644 --- a/config/site/dhcp/feed/service.yaml +++ b/config/site/dhcp/feed/service.yaml @@ -1,4 +1,5 @@ -# The feed, reachable only inside the site cluster. +# The feed, over TLS only. An environment exposes it to the cluster that +# runs the site's DHCP instances, which authenticate with the site's token. apiVersion: v1 kind: Service metadata: diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index 396886f6..cd7cb90c 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -8,6 +8,10 @@ reservation for that NIC and address only while the operation's network boot is admitted, and DHCP reports what it applied. Those reports are the evidence that the boot was reachable and that the reservation was later withdrawn. +DHCP does not run at the site. Each site's Kea instances and their +synchronizers run in a central cluster, reached by the site's relays over the +site's WAN link, and firmware boots over UEFI HTTP boot, never TFTP. + This page describes the implemented contract. The design is the [server networking enhancement][server-networking], which replaces the enrollment values of the [boot network enhancement](../enhancements/boot-network/README.md). What @@ -143,7 +147,7 @@ The worker gates its effects on reports: reservation, so a later success settles the hold safely. An instance that went silent while serving keeps the outcome unknown. After -making sure its server no longer answers, an operator at the site retires it: +making sure its server no longer answers, an operator retires it for the site: ```sh FLEET_BOOT_EVIDENCE=/var/lib/fleet-boot fleet-multiplane dhcp-retire -instance dhcp-a @@ -153,6 +157,15 @@ A later report from a retired instance counts again. Report times are the boot service's clock and admission times the worker's, so both roles must run on synchronized clocks. +These gates do not depend on where Kea runs. The feed comes only from the +site's admitted operations at the Device's stored fence, and every report +names its instance and the exact feed it applied. A WAN outage between the +site and the central cluster makes the instances silent: an operation waiting +to power on does not, and one whose reservation an instance last reported +serving stays unknown until that instance reports it withdrawn or is retired. +An instance that cannot reach the feed keeps its last applied configuration, +which its last report shows. + ## Feed and reports The site's `dhcp-feed` role (`fleet-multiplane dhcp-feed -sync-token-file … @@ -196,32 +209,50 @@ fails the cycle; it is never dropped. A restarted Kea loses its reservations and fails closed until the next cycle re-applies them. Before scaling down, drain the instance being removed until it reports an empty feed. -## Site DHCP service - -The `config/site/dhcp/component` Kustomize component deploys the service at a -synchronized site: - -| Object | What it runs | -| --- | --- | -| `dhcp-feed` container in `fleet-site-boot` | The feed, beside the boot service, so it reads the site store read-only and appends reports to the boot evidence on the same volume | -| `fleet-site-dhcp-feed` Service | The feed on `:8081`, inside the site cluster only | -| `fleet-site-dhcp` StatefulSet | At least two Pods, one per node labeled `fleet.datumapis.com/dhcp-host=true`, with host networking. Each runs ISC's Kea DHCPv4 image, pinned by digest, and the synchronizer, sharing Kea's control socket on an `emptyDir` that Kea's command makes `0750`, as Kea 2.6 requires. The Pod name is the instance name | -| `fleet-site-dhcp` PodDisruptionBudget | One instance down at a time | +## DHCP service + +Two Kustomize components deploy a synchronized site's DHCP service, to two +places: + +| Component | Object | What it runs | +| --- | --- | --- | +| `config/site/dhcp/feed`, beside the site's boot service | `dhcp-feed` container in `fleet-site-boot` | The feed, so it reads the site store read-only and appends reports to the boot evidence on the same volume | +| | `fleet-site-dhcp-feed` Service | The feed on `:8081`, over TLS only. The environment exposes it to the central cluster | +| `config/site/dhcp/component`, in a central cluster, once per site | `fleet-site-dhcp` StatefulSet | At least two Pods without host networking, with stable names, so a replaced Pod keeps its instance name and its last report. Each runs ISC's Kea DHCPv4 image, pinned by digest, answering relayed requests on a UDP socket, and the synchronizer, sharing Kea's control socket on an `emptyDir` that Kea's command makes `0750`, as Kea 2.6 requires. The Pod name is the instance name | +| | `fleet-site-dhcp` Service | One load-balancer address on UDP 67 in front of every instance, with local traffic policy and client-IP affinity. The site's relays forward to it | +| | `fleet-site-dhcp` PodDisruptionBudget | One instance down at a time | + +Any instance may answer a request. Each applies the same feed through its own +synchronizer and reports under its own name, so the power-on gate needs one +instance serving and the withdrawal gate covers every instance that ever +reported. An instance that has not applied a reservation yet stays silent, +because Kea is not authoritative, and the firmware retries; client-IP affinity +keeps one relay's exchange on one instance. + +Kea answers each relayed request at the relay address the request carries, on +UDP 67. Its reply leaves through the cluster's egress, which is not always the +load-balancer address the relay forwarded to, so the cluster must route to +every relay address and each relay must accept replies from the cluster's +egress address. Every boot at the site then depends on the central cluster and +the site's WAN link. The environment supplies, never in Git: -- the `fleet-site-dhcp-sync` Secret, with the synchronizer token under `token`; +- the `fleet-site-dhcp-sync` Secret in both places, with the synchronizer + token under `token`; - the `fleet-site-dhcp-feed-tls` Secret, with `tls.crt` and `tls.key` for the - name `fleet-site-dhcp-feed.fleet-site.svc` and the issuing `ca.crt`; + feed's name beside the boot service, and the issuing `ca.crt` in both places; - the `fleet-site-dhcp-base` ConfigMap from network operations, with `kea-dhcp4.conf`; and -- the `FLEET_SITE_IMAGE` and `FLEET_DHCP_SYNC_IMAGE` substitutions. +- the `FLEET_SITE_IMAGE`, `FLEET_DHCP_SYNC_IMAGE` and `FLEET_DHCP_FEED_URL` + substitutions. The base configuration names the site's provisioning subnet and gateway, the -relay addresses Kea accepts, and the boot options. Kea listens on every -address of its node, so the subnet's relay filter is what limits it to the -site's relays. The configuration has no pools, so Kea answers only reserved -MACs, and its control socket is the synchronizer's. +relay addresses Kea accepts, and the boot options. Kea answers only relayed +requests, so the subnet's relay filter is what limits it to the site's relays. +It has no pools, so Kea answers only reserved MACs, and its control socket is +the synchronizer's. It sets no TFTP server: firmware in the HTTP boot vendor +class gets the boot service's loader URL. Both Secrets are required: without them the boot Pod, and so the boot service, does not start. The feed loads its certificate and the synchronizer its CA @@ -242,15 +273,20 @@ Fleet configures no switch, router or relay. A synchronized site needs: 3. Spanning tree edge mode on server ports. 4. LACP fallback to an individual port where the boot NIC is a bond member, with a fallback timeout below the DHCP timeout of every qualified firmware. -5. On the provisioning subnet's gateway, a DHCP relay to the address of every - node labeled as a DHCP host, with the gateway as the relay address. -6. Routes and filters so the provisioning subnet reaches only the DHCP hosts and - the boot service, and no customer network, BMC network or internet. +5. On the provisioning subnet's gateway, a DHCP relay to the instances' + load-balancer address in the central cluster, with the gateway as the relay + address, accepting replies from the cluster's egress address. +6. Routes and filters over the site's WAN link so the provisioning subnet + reaches only the central DHCP and boot service addresses, and no customer + network, BMC network or other internet address, and so the central cluster + reaches every relay address. 7. DHCP snooping and source address binding on the provisioning VLAN. 8. LLDP on server ports. 9. Switch and port names in Fleet's cable records that match the network owner's. 10. The base configuration above. +11. Firmware that boots over UEFI HTTP boot, with its DHCP timeout measured + against the round trip over the WAN link during qualification. ## Boot network lab @@ -269,7 +305,7 @@ with a chosen MAC asks for an address. It passes only if: The lab proves the feed, the synchronizer and reservation-gated answers in a real DHCP exchange. With no relay, its Kea answers the client directly on a raw -socket, where a site's Kea answers relays on a UDP socket. It has no VLAN, no +socket, where the central Kea answers relays on a UDP socket. It has no VLAN, no switch and no firmware, so it proves none of the network operations requirements. @@ -281,9 +317,10 @@ requirements. | Boot NIC from Device inventory through the admission snapshot; enrollment without MACs or addresses | Implemented; unit tested | | Reservation feed, authenticated applied reports, served and withdrawn gates over every reservation of the Device, instance retirement | Implemented; unit tested with a fake BMC and synchronizer, including a silent instance | | Kea synchronizer: containing-subnet placement, restart re-apply, report only after Kea accepted | Implemented; unit tested against a fake Kea control socket | -| Feed over TLS, Kea and the synchronizer as a site component | Implemented; render checked in CI, and reservation-gated answers proved by the boot network lab with real Kea. Not deployed at a site, and relayed requests are not exercised | +| Feed over TLS beside the boot service; Kea and the synchronizer as a central component, several instances behind one UDP 67 load balancer | Implemented; render checked in CI, and reservation-gated answers proved by the boot network lab with real Kea. Not deployed, and relayed requests across a WAN are not exercised | +| Boot service and boot files in the central cluster, serving a UEFI HTTP boot loader | Proposed; the boot service runs in the site's boot Pod beside the site store, and serves the iPXE script but no EFI loader yet | | Relay, provisioning VLAN, isolation and LACP fallback at a site | Network operations; see the [server networking enhancement][server-networking] | -| Telling firmware what to boot in synced mode (Redfish `HttpBootUri` for UEFI HTTP Boot, or a DHCP boot-file option) | Proposed; the Redfish worker still arms `Pxe`, which relies on site DHCP for the boot file | +| Telling firmware what to boot in synced mode (Redfish `HttpBootUri` for UEFI HTTP boot, or the DHCP boot-file option above) | Proposed; the Redfish worker still arms `Pxe`, and the base configuration's HTTP boot class names a loader the boot service does not serve yet | | DHCPv6 reservations | Proposed; the feed accepts IPv6, the Kea DHCPv4 synchronizer and the claim reject it | | Lab acceptance in synced mode | Implemented as `run.sh --redfish --synced-dhcp`, with a synthetic IPAM stand-in; not yet run. See the [Redfish lab](redfish-lab.md#synchronized-dhcp-mode) | diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index dcf80aa8..a98485c0 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -357,7 +357,9 @@ exercises boot addresses, reservations and Kea end to end in the lab: `NET_BIND_SERVICE`. It listens on `fleetpxe0` with a raw socket, has no pool, and keeps its leases on the site volume. The synchronizer reports as the one fixed instance `lab-kea`, so a restarted runtime Pod never strands a - withdrawal. + withdrawal. In production Kea runs in a central cluster behind the site's + relays; the lab has no WAN link or relay, so its Kea sits on the emulated + site's bridge instead. The feed, the reports and the gates are the same. - **Feed.** The `dhcp-feed` container from `config/site/dhcp/feed` runs beside the boot service over TLS. Redfish enrollment generates the synchronizer token and a self-signed feed key per run, as Secrets in `fleet-site`, never diff --git a/hack/validate-site-dhcp-render.sh b/hack/validate-site-dhcp-render.sh index 61a21a1a..5cb049b3 100755 --- a/hack/validate-site-dhcp-render.sh +++ b/hack/validate-site-dhcp-render.sh @@ -19,15 +19,23 @@ assert {"name": "state", "mountPath": "/var/lib/fleet-local", "subPath": "journa service = one("Service", "fleet-site-dhcp-feed") assert service["spec"]["type"] == "ClusterIP" and service["spec"]["ports"][0]["port"] == 8081 kea = one("StatefulSet", "fleet-site-dhcp")["spec"] -assert kea["replicas"] >= 2 and kea["template"]["spec"]["hostNetwork"] is True +assert kea["replicas"] >= 2 and not kea["template"]["spec"].get("hostNetwork"), "Kea runs in the central cluster without host networking" +lb = one("Service", "fleet-site-dhcp")["spec"] +assert lb["type"] == "LoadBalancer" and lb["ports"] == [{"name": "dhcp", "port": 67, "targetPort": 67, "protocol": "UDP"}], lb +assert lb["selector"] == kea["selector"]["matchLabels"], "one address in front of every instance" +assert lb.get("sessionAffinity") == "ClientIP", "one relay exchange stays on one instance" containers = {c["name"]: c for c in kea["template"]["spec"]["containers"]} assert "@sha256:" in containers["kea"]["image"], "Kea is pinned by digest" sync = containers["sync"]["command"] -assert "-ca-file=/etc/fleet-dhcp-tls/ca.crt" in sync and any(a.startswith("-feed=https://") for a in sync), sync +assert "-ca-file=/etc/fleet-dhcp-tls/ca.crt" in sync and "-feed=${FLEET_DHCP_FEED_URL}" in sync, sync socket = next(a for a in sync if a.startswith("-kea-socket=")).split("=", 1)[1] base = json.loads(one("ConfigMap", "fleet-site-dhcp-base")["data"]["kea-dhcp4.conf"])["Dhcp4"] assert base["control-socket"]["socket-name"] == socket and socket.startswith("/var/run/kea/"), "Kea and the synchronizer share one socket under /var/run/kea" assert all("pools" not in s for s in base["subnet4"]), "the base configuration has no pools" +assert base["interfaces-config"]["dhcp-socket-type"] == "udp", "Kea answers relayed requests on a UDP socket" +assert base.get("authoritative") is False, "an instance without the reservation stays silent instead of refusing" +assert all("next-server" not in s for s in base["subnet4"]), "no TFTP server" +assert any(c["name"] == "HTTPClient" and c["boot-file-name"].startswith("http") for c in base["client-classes"]), "UEFI HTTP boot" assert any(e["name"] == "POD_NAME" for e in containers["sync"]["env"]), "the instance name is the Pod name" assert "chmod 0750 /var/run/kea" in " ".join(containers["kea"]["command"]), "Kea 2.6 needs its socket directory 0750" for pod in (boot, kea["template"]["spec"]): @@ -39,5 +47,5 @@ labels = one("Deployment", "fleet-site-boot")["spec"]["template"]["metadata"]["l assert all(labels.get(k) == v for k, v in service["spec"]["selector"].items()), "the feed Service selects the boot Pod" budget = one("PodDisruptionBudget", "fleet-site-dhcp")["spec"]["selector"]["matchLabels"] assert budget == kea["selector"]["matchLabels"], "the budget covers the Kea Pods" -print("PASS site DHCP render: %d objects, feed over TLS, Kea pinned, no Secret, no pool" % len(docs)) +print("PASS site DHCP render: %d objects, feed over TLS, Kea pinned behind one UDP 67 load balancer, HTTP boot, no Secret, no pool" % len(docs)) ' From af0da23b8d760eeab45d9a884ce95f7ec69af316 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 20:59:04 -0600 Subject: [PATCH 08/17] feat(site): Declare the site's DHCP instances A synced Redfish enrollment now names its expected DHCP instances (dhcpInstances). The workers and the reservation feed read the same enrollment. The feed serves a feed only to an expected instance, named on the request, and refuses and does not retain a report from any other. Every served feed carries the time it was issued, outside its revision. Withdrawal is proven only when every expected instance's latest report is of a feed issued after the admission was stored and serves none of the Device's reservations. An expected instance that never reported, or that fetched the reservation and stopped before reporting, keeps the outcome unknown. The admission records when it was stored (published), because its creation time is read before the store write. Retiring an instance is now only shrinking the expected set; the dhcp-retire command and the lab's retire path are gone, and retained retirement records are ignored. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-multiplane/main.go | 6 +- cmd/fleet-multiplane/site.go | 15 +- config/site/dhcp/component/dhcp.yaml | 15 +- config/site/dhcp/example/enrollment.yaml | 10 + config/site/dhcp/example/kustomization.yaml | 1 + config/site/dhcp/feed/kustomization.yaml | 9 +- .../redfish/synced/graph/kustomization.yaml | 6 +- .../redfish/synced/services/enrollment.yaml | 9 + .../synced/services/kustomization.yaml | 3 + docs/operations/boot-network.md | 123 ++++-- docs/operations/redfish-lab.md | 6 +- hack/boot-network/kea-lab.sh | 5 +- hack/boot-network/lab/main.go | 19 +- hack/multiplane/flux.py | 5 +- hack/multiplane/redfish_steps.py | 7 +- hack/multiplane/test-redfish.py | 13 +- hack/validate-site-dhcp-render.sh | 6 +- internal/bootnet/feed.go | 21 +- internal/bootnet/feed_test.go | 39 ++ internal/dhcpsync/sync.go | 5 + internal/dhcpsync/sync_test.go | 36 +- internal/redfish/enrollment.go | 39 +- internal/redfish/enrollment_test.go | 26 ++ internal/site/redfishwork/boot.go | 5 +- internal/site/redfishwork/dhcp.go | 128 ++++-- internal/site/redfishwork/dhcp_test.go | 377 ++++++++++++++---- internal/site/redfishwork/kinds.go | 19 +- 27 files changed, 754 insertions(+), 199 deletions(-) create mode 100644 config/site/dhcp/example/enrollment.yaml create mode 100644 config/site/redfish/synced/services/enrollment.yaml diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index 383fecb2..8a3c452f 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -21,7 +21,6 @@ import ( "go.datum.net/fleet/internal/multiplane" "go.datum.net/fleet/internal/redfish" "go.datum.net/fleet/internal/site" - "go.datum.net/fleet/internal/site/redfishwork" ) func main() { @@ -33,7 +32,7 @@ func main() { func run() error { if len(os.Args) < 2 { - return fmt.Errorf("usage: fleet-multiplane coordinator|site-worker|site-observer|image|boot-service|boot-withhold|boot-denials|dhcp-feed|dhcp-retire|redfish-probe| [flags]") + return fmt.Errorf("usage: fleet-multiplane coordinator|site-worker|site-observer|image|boot-service|boot-withhold|boot-denials|dhcp-feed|redfish-probe| [flags]") } fs := flag.NewFlagSet(os.Args[1], flag.ContinueOnError) once := fs.Bool("once", false, "one attempt, for fault injection") @@ -53,7 +52,6 @@ func run() error { syncToken := fs.String("sync-token-file", "", "file holding the DHCP synchronizer bearer token (dhcp-feed)") installationDeadline := fs.Duration("installation-deadline", 0, "replace the installation deadline for operations this coordinator admits (coordinator)") skewMargin := fs.Duration("skew-margin", 0, "replace the margin after a deadline before the coordinator declares it exceeded (coordinator)") - instance := fs.String("instance", "", "DHCP instance an operator retires (dhcp-retire)") tlsCert := fs.String("tls-cert", "", "TLS certificate the DHCP feed serves (dhcp-feed)") tlsKey := fs.String("tls-key", "", "TLS key of the DHCP feed (dhcp-feed)") if err := fs.Parse(os.Args[2:]); err != nil { @@ -86,8 +84,6 @@ func run() error { return boot(os.Args[1], *origin, *extraMAC, *syncToken, *tlsCert, *tlsKey) case "boot-withhold": return armWithhold(fs.Arg(0)) - case "dhcp-retire": - return redfishwork.RetireInstance(os.Getenv("FLEET_BOOT_EVIDENCE"), *instance) case "site-worker", "site-observer": default: return fmt.Errorf("unknown command") diff --git a/cmd/fleet-multiplane/site.go b/cmd/fleet-multiplane/site.go index e2c0d448..c3d5e74e 100644 --- a/cmd/fleet-multiplane/site.go +++ b/cmd/fleet-multiplane/site.go @@ -170,7 +170,7 @@ func redfishConfig() (redfishwork.Config, redfish.Enrollment, error) { if err != nil { return redfishwork.Config{}, redfish.Enrollment{}, err } - return redfishwork.Config{ConsoleRoot: console, BootRoot: boot, Synced: enrollment.DHCP == redfish.DHCPSynced}, enrollment, nil + return redfishwork.Config{ConsoleRoot: console, BootRoot: boot, Synced: enrollment.DHCP == redfish.DHCPSynced, DHCPInstances: enrollment.DHCPInstances}, enrollment, nil } // siteRunner is the site runner for this cell's mode. A Redfish worker reads @@ -259,16 +259,25 @@ func boot(command, origin, extraMAC, syncToken, tlsCert, tlsKey string) error { if redfishMode() && command == "dhcp-feed" { // Reservations come from the admitted operations in the store, and // reports go beside the boot evidence. The feed serves no boot - // artifacts, so it needs no boot origin or installer image. + // artifacts, so it needs no boot origin or installer image. It reads + // the workers' enrollment for one thing: the expected DHCP instances, + // the only ones it serves and takes reports from. root, err := bootRoot() if err != nil { return err } + enrollment, err := redfish.ParseEnrollment([]byte(os.Getenv("FLEET_REDFISH_ENROLLMENT"))) + if err != nil { + return err + } + if enrollment.DHCP != redfish.DHCPSynced { + return errors.New("the DHCP reservation feed serves only a site whose enrollment has synced DHCP") + } token, err := os.ReadFile(syncToken) if err != nil { return fmt.Errorf("DHCP synchronizer token: %w", err) } - return redfishwork.BootServer{Store: store, BootRoot: root}.ServeDHCP(strings.TrimSpace(string(token)), tlsCert, tlsKey) + return redfishwork.BootServer{Store: store, BootRoot: root, DHCPInstances: enrollment.DHCPInstances}.ServeDHCP(strings.TrimSpace(string(token)), tlsCert, tlsKey) } if redfishMode() { server, err := redfishBootServer(store) diff --git a/config/site/dhcp/component/dhcp.yaml b/config/site/dhcp/component/dhcp.yaml index 8f859e61..075fe673 100644 --- a/config/site/dhcp/component/dhcp.yaml +++ b/config/site/dhcp/component/dhcp.yaml @@ -9,10 +9,11 @@ automountServiceAccountToken: false # last report. The instances share one load-balancer address on UDP 67 # (below), which the site's relays reach over the WAN link. Kea answers only relayed # requests, on a UDP socket, so it needs no host networking; the base -# configuration's relay filter limits it to the site's relays. Scale down -# only after the instance being removed reports an empty feed: an instance -# removed while serving keeps its operations' outcomes unknown until an -# operator retires it. +# configuration's relay filter limits it to the site's relays. The site's +# enrollment lists these Pods' names as its expected DHCP instances. To +# retire one, make sure it no longer answers, scale down (the highest +# ordinal goes first), shrink the enrollment's dhcpInstances to match, and +# restart the site's workers and feed. apiVersion: apps/v1 kind: StatefulSet metadata: @@ -92,8 +93,8 @@ spec: - name: feed-ca secret: {secretName: fleet-site-dhcp-feed-tls, defaultMode: 0400, items: [{key: ca.crt, path: ca.crt}]} --- -# One instance may restart at a time. Draining before scale-down is an -# operator step; see the comment on the StatefulSet. +# One instance may restart at a time. Retiring an instance is an operator +# step; see the comment on the StatefulSet. apiVersion: policy/v1 kind: PodDisruptionBudget metadata: @@ -107,7 +108,7 @@ spec: # One load-balancer address on UDP 67 for all of the site's instances, which # the site's relays forward to. Any instance may answer a request. Each # instance applies the same feed through its own synchronizer and reports it -# under its own stable name, so the withdrawal gate covers every instance; +# under its own stable name, so the withdrawal gate covers every expected one; # an instance that has not applied a reservation yet stays silent, because # Kea is not authoritative, and the firmware retries. Client-IP affinity # keeps one relay's exchange on one instance. Kea replies to the relay diff --git a/config/site/dhcp/example/enrollment.yaml b/config/site/dhcp/example/enrollment.yaml new file mode 100644 index 00000000..a4574d87 --- /dev/null +++ b/config/site/dhcp/example/enrollment.yaml @@ -0,0 +1,10 @@ +# A synthetic synced enrollment for the render check. An environment supplies +# the same enrollment its site workers get, naming the StatefulSet's Pods as +# the expected DHCP instances. +apiVersion: v1 +kind: ConfigMap +metadata: + name: fleet-site-redfish-enrollment + namespace: fleet-site +data: + enrollment: '{"dhcp":"synced","dhcpInstances":["fleet-site-dhcp-0","fleet-site-dhcp-1"],"targets":[{"device":"fleet-provider/server-example-001","endpoint":"https://192.0.2.10:8443","systemID":"System-1","systemUUID":"00000000-0000-4000-8000-000000000001","diskBytes":2147483648,"console":"server-example-001.log"}]}' diff --git a/config/site/dhcp/example/kustomization.yaml b/config/site/dhcp/example/kustomization.yaml index abfbca7e..7514db36 100644 --- a/config/site/dhcp/example/kustomization.yaml +++ b/config/site/dhcp/example/kustomization.yaml @@ -7,6 +7,7 @@ kind: Kustomization resources: - ../../redfish/services - base.yaml + - enrollment.yaml components: - ../feed - ../component diff --git a/config/site/dhcp/feed/kustomization.yaml b/config/site/dhcp/feed/kustomization.yaml index bfd8c1e1..b3d7f108 100644 --- a/config/site/dhcp/feed/kustomization.yaml +++ b/config/site/dhcp/feed/kustomization.yaml @@ -2,8 +2,11 @@ # site store and writes the applied reports beside the boot evidence, and a # Service. The site's central DHCP instances reach it over TLS only. The environment supplies # the Secrets fleet-site-dhcp-sync (key token) and fleet-site-dhcp-feed-tls -# (tls.crt, tls.key, ca.crt), never in Git. The Kea component and the -# Redfish lab's synchronized DHCP both use it. +# (tls.crt, tls.key, ca.crt), never in Git, and the ConfigMap +# fleet-site-redfish-enrollment (key enrollment): the same synced Redfish +# enrollment the site's workers get. The feed serves, and takes reports from, +# only the enrollment's dhcpInstances. The Kea component and the Redfish +# lab's synchronized DHCP both use it. apiVersion: kustomize.config.k8s.io/v1alpha1 kind: Component resources: @@ -23,6 +26,8 @@ patches: env: - {name: FLEET_SITE_PROVIDER, value: redfish} - {name: FLEET_BOOT_EVIDENCE, value: /var/lib/fleet-boot} + - name: FLEET_REDFISH_ENROLLMENT + valueFrom: {configMapKeyRef: {name: fleet-site-redfish-enrollment, key: enrollment}} ports: - {name: dhcp-feed, containerPort: 8081} readinessProbe: diff --git a/config/site/redfish/synced/graph/kustomization.yaml b/config/site/redfish/synced/graph/kustomization.yaml index a1ea51dd..9b9b7ab1 100644 --- a/config/site/redfish/synced/graph/kustomization.yaml +++ b/config/site/redfish/synced/graph/kustomization.yaml @@ -1,7 +1,9 @@ # Redfish lab with synchronized DHCP (run.sh --redfish --synced-dhcp): the # Redfish graph with the site enrollment's DHCP mode set to synced, so a # network boot needs a boot address and waits for the site's Kea to apply and -# later withdraw its reservation. +# later withdraw its reservation. The lab's one Kea instance, lab-kea, is the +# expected DHCP instance set; the feed reads the same enrollment from the +# ConfigMap in ../services. apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: @@ -14,4 +16,4 @@ patches: value: FLEET_REDFISH_ENROLLMENT - op: replace path: /spec/resources/9/template/spec/template/spec/containers/0/env/6/value - value: '{"dhcp":"synced","targets":[{"device":"fleet-provider/synthetic-device-central-01","endpoint":"https://10.96.0.81:8443","systemID":"System-1","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a","diskBytes":2147483648,"console":"target-a.log"},{"device":"fleet-provider/synthetic-device-central-02","endpoint":"https://10.96.0.81:8443","systemID":"System-2","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b","diskBytes":2147483648,"console":"target-b.log"}]}' + value: '{"dhcp":"synced","dhcpInstances":["lab-kea"],"targets":[{"device":"fleet-provider/synthetic-device-central-01","endpoint":"https://10.96.0.81:8443","systemID":"System-1","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a","diskBytes":2147483648,"console":"target-a.log"},{"device":"fleet-provider/synthetic-device-central-02","endpoint":"https://10.96.0.81:8443","systemID":"System-2","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b","diskBytes":2147483648,"console":"target-b.log"}]}' diff --git a/config/site/redfish/synced/services/enrollment.yaml b/config/site/redfish/synced/services/enrollment.yaml new file mode 100644 index 00000000..2302ab58 --- /dev/null +++ b/config/site/redfish/synced/services/enrollment.yaml @@ -0,0 +1,9 @@ +# The feed's copy of the synced lab enrollment. It must equal the workers' +# enrollment in ../graph exactly; hack/multiplane/test-redfish.py checks it. +apiVersion: v1 +kind: ConfigMap +metadata: + name: fleet-site-redfish-enrollment + namespace: fleet-site +data: + enrollment: '{"dhcp":"synced","dhcpInstances":["lab-kea"],"targets":[{"device":"fleet-provider/synthetic-device-central-01","endpoint":"https://10.96.0.81:8443","systemID":"System-1","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a","diskBytes":2147483648,"console":"target-a.log"},{"device":"fleet-provider/synthetic-device-central-02","endpoint":"https://10.96.0.81:8443","systemID":"System-2","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0b","diskBytes":2147483648,"console":"target-b.log"}]}' diff --git a/config/site/redfish/synced/services/kustomization.yaml b/config/site/redfish/synced/services/kustomization.yaml index 93f5ff2d..bc8b4a2c 100644 --- a/config/site/redfish/synced/services/kustomization.yaml +++ b/config/site/redfish/synced/services/kustomization.yaml @@ -5,11 +5,14 @@ # network namespace. The feed runs beside the boot service, as at a site. # The harness creates the Secrets fleet-site-dhcp-sync and # fleet-site-dhcp-feed-tls before this layer reconciles; they are never in Git. +# enrollment.yaml gives the feed the synced graph's enrollment, whose one +# expected DHCP instance is lab-kea. apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - ../../services - kea.yaml + - enrollment.yaml components: - ../../../dhcp/feed patches: diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index cd7cb90c..0b44daa1 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -88,12 +88,14 @@ IPAM permission. ## Enrollment The site enrollment (`FLEET_REDFISH_ENROLLMENT`) is the explicit mapping of the -Devices a Redfish site serves. It sets the site's DHCP mode and, per target, the -BMC endpoint, the Redfish System, the disk size and the console capture: +Devices a Redfish site serves. It sets the site's DHCP mode, the DHCP +instances a synced site expects and, per target, the BMC endpoint, the Redfish +System, the disk size and the console capture: ```json { "dhcp": "synced", + "dhcpInstances": ["fleet-site-dhcp-0", "fleet-site-dhcp-1"], "targets": [{ "device": "default/server-example-001", "endpoint": "https://192.0.2.20:443", @@ -115,6 +117,13 @@ BMC endpoint, the Redfish System, the disk size and the console capture: out fixed leases. The simulator and local VM sites refuse a boot address too. - **`dhcp: synced`** means Fleet publishes reservations. The site refuses a network boot without a boot address (`BootNetworkRequired`). +- **`dhcpInstances`** is the expected set: every DHCP instance that may serve + the site's reservations, by the stable name it reports under (the + StatefulSet's Pod names). It is required, non-empty and without duplicates + when `dhcp` is `synced`, and must be absent when it is `static`. The feed + serves only these instances and takes reports only from them, and + withdrawal is proven only when every one of them reported it. The workers + and the feed read the same enrollment. The enrollment names no MAC and no address. Before it sends anything, the site worker checks the BMC endpoint and system UUID against the admitted snapshot. @@ -136,33 +145,50 @@ withdrawal is proven. The worker gates its effects on reports: +Only reports from expected instances count. + 1. **Before powering on for a network boot** it waits, with no effect, until - some DHCP instance reports a feed that serves the boot NIC at the exact + some expected instance reports a feed that serves the boot NIC at the exact address, accepted after this operation's boot admission was created. If the boot window expires first, the outcome is unknown. 2. **Before reporting success** it waits, for up to ten minutes, until some - instance served the reservation during this operation and no instance's - latest report, however old, serves any MAC or address the site ever - published for the Device. That covers an earlier, held operation's - reservation, so a later success settles the hold safely. - -An instance that went silent while serving keeps the outcome unknown. After -making sure its server no longer answers, an operator retires it for the site: - -```sh -FLEET_BOOT_EVIDENCE=/var/lib/fleet-boot fleet-multiplane dhcp-retire -instance dhcp-a -``` - -A later report from a retired instance counts again. Report times are the boot -service's clock and admission times the worker's, so both roles must run on -synchronized clocks. + expected instance served the reservation during this operation, and every + expected instance's latest report is of a feed issued after the admission + was stored that serves no MAC or address the site ever published for the + Device. That covers an earlier, held operation's reservation, so a later + success settles the hold safely. Past ten minutes the outcome is unknown. + +Every feed carries the time the feed server issued it. While the admission is +open, every feed issued after it was stored carries the reservation, so a +report of a later feed without it proves the instance dropped it, and every +later feed lacks it too. An instance that fetched a feed with the reservation +and stopped before reporting still has a latest report that is older than the +admission or serves the reservation, so it keeps the outcome unknown. So does +an expected instance that never reported. Issue times are the feed's clock and +admission times the worker's, so both roles must run on the same clock; they +share the site's state volume. + +### Retiring a DHCP instance + +Removing an instance from the expected set is the only way to stop waiting for +it. To retire one on purpose: + +1. make sure it no longer answers, then scale the StatefulSet down. A + StatefulSet removes its highest ordinals first, so the instances left are + the lowest ones; +2. shrink `dhcpInstances` to match the Pods that remain; and +3. restart the site's workers and its feed, so both read the new set. + +The feed then refuses the removed instance, and a later report from it is +rejected and not retained. An instance removed while it may still answer could +serve a reservation that nothing tracks, so check it first. These gates do not depend on where Kea runs. The feed comes only from the site's admitted operations at the Device's stored fence, and every report names its instance and the exact feed it applied. A WAN outage between the site and the central cluster makes the instances silent: an operation waiting -to power on does not, and one whose reservation an instance last reported -serving stays unknown until that instance reports it withdrawn or is retired. +to power on does not, and one waiting for withdrawal stays unknown until every +expected instance reports it withdrawn, or the set shrinks. An instance that cannot reach the feed keeps its last applied configuration, which its last report shows. @@ -172,26 +198,36 @@ The site's `dhcp-feed` role (`fleet-multiplane dhcp-feed -sync-token-file … -tls-cert … -tls-key …`) listens with TLS on `:8081`, never on the firmware-facing boot listener. It reads the site store read-only and writes only `dhcp-applied.log` in the boot-evidence -directory. Every request needs `Authorization: Bearer `; the token is at -least 32 characters. - -- `GET /dhcp/v1/reservations` returns the canonical feed: - `{"revision": "", "reservations": [{"mac", "address", "expires"}]}`. - An address is one host address with no prefix. Reservations are sorted by MAC; - the revision is the SHA-256 of their canonical JSON, so a feed is - self-verifying. -- `POST /dhcp/v1/applied` takes `{"instance": "", "feed": }`. The - feed must be canonical with a matching revision; anything else is rejected and - not retained. An accepted report is synced to disk before `204`. - -The retained log holds MACs, addresses, revisions, instance names and -retirements. It holds no token, receipt or boot capability. An unreadable line -is treated as corruption, never as evidence. +directory. It reads the expected set from the site's synced enrollment, and +refuses to start without one. Every request needs `Authorization: Bearer +`; the token is at least 32 characters. + +- `GET /dhcp/v1/reservations` needs `X-Fleet-DHCP-Instance: ` naming an + expected instance; otherwise it is refused with `403` and nothing is served. + It returns the canonical feed: + `{"revision": "", "reservations": [{"mac", "address", "expires"}], + "issued": ""}`. An address is one host address with no prefix. + Reservations are sorted by MAC; the revision is the SHA-256 of their + canonical JSON, so a feed is self-verifying. `issued` is the feed server's + clock, to the second, read before it read the reservations. It is not part + of the revision. +- `POST /dhcp/v1/applied` takes `{"instance": "", "feed": }`, with + the feed exactly as it was served. The feed must be canonical with a + matching revision, and the instance must be expected; anything else is + rejected and not retained. An accepted report is synced to disk before + `204`. + +The retained log holds MACs, addresses, revisions, issue times and instance +names. It holds no token, receipt or boot capability. An unreadable line is +treated as corruption, never as evidence. A report retained before feeds +carried an issue time counts as issued at the zero time, so it can never prove +a withdrawal. A record left by the removed retirement command is ignored. ## Kea synchronizer `fleet-dhcp-sync` (in the manager image) runs beside one Kea DHCPv4 instance, -with a stable instance name such as a StatefulSet pod name. `-ca-file` names +with a stable instance name such as a StatefulSet pod name, which it sends on +every feed request and report. `-ca-file` names the CA bundle the feed's certificate must chain to. Kea 2.6 accepts a control socket only under `/var/run/kea`, which is the synchronizer's default. Each cycle it: @@ -201,13 +237,13 @@ cycle it: 3. when the revision changed or Kea restarted, adds each reservation to the one base subnet that contains its address and sends `config-set` over Kea's control socket; -4. reports the feed only after Kea accepted it, once per revision. +4. reports the feed, unchanged, only after Kea accepted it, once per revision. The base configuration supplies each subnet's prefix, gateway (`routers`) and boot options. A reservation that no base subnet contains, or that two contain, fails the cycle; it is never dropped. A restarted Kea loses its reservations -and fails closed until the next cycle re-applies them. Before scaling down, -drain the instance being removed until it reports an empty feed. +and fails closed until the next cycle re-applies them. To remove an instance, +see [Retiring a DHCP instance](#retiring-a-dhcp-instance). ## DHCP service @@ -216,7 +252,7 @@ places: | Component | Object | What it runs | | --- | --- | --- | -| `config/site/dhcp/feed`, beside the site's boot service | `dhcp-feed` container in `fleet-site-boot` | The feed, so it reads the site store read-only and appends reports to the boot evidence on the same volume | +| `config/site/dhcp/feed`, beside the site's boot service | `dhcp-feed` container in `fleet-site-boot` | The feed, so it reads the site store read-only and appends reports to the boot evidence on the same volume. It reads the enrollment from the `fleet-site-redfish-enrollment` ConfigMap, which the environment supplies with the same enrollment its workers get | | | `fleet-site-dhcp-feed` Service | The feed on `:8081`, over TLS only. The environment exposes it to the central cluster | | `config/site/dhcp/component`, in a central cluster, once per site | `fleet-site-dhcp` StatefulSet | At least two Pods without host networking, with stable names, so a replaced Pod keeps its instance name and its last report. Each runs ISC's Kea DHCPv4 image, pinned by digest, answering relayed requests on a UDP socket, and the synchronizer, sharing Kea's control socket on an `emptyDir` that Kea's command makes `0750`, as Kea 2.6 requires. The Pod name is the instance name | | | `fleet-site-dhcp` Service | One load-balancer address on UDP 67 in front of every instance, with local traffic policy and client-IP affinity. The site's relays forward to it | @@ -224,8 +260,8 @@ places: Any instance may answer a request. Each applies the same feed through its own synchronizer and reports under its own name, so the power-on gate needs one -instance serving and the withdrawal gate covers every instance that ever -reported. An instance that has not applied a reservation yet stays silent, +expected instance serving and the withdrawal gate needs every expected +instance. An instance that has not applied a reservation yet stays silent, because Kea is not authoritative, and the firmware retries; client-IP affinity keeps one relay's exchange on one instance. @@ -315,7 +351,8 @@ requirements. | --- | --- | | Boot addresses claimed from IPAM per operation, checked at admission, and released only after the operation ended unheld | Implemented; tested against a real API server with a stand-in for IPAM's claim API. No run sets a class, and IPAM itself is not exercised | | Boot NIC from Device inventory through the admission snapshot; enrollment without MACs or addresses | Implemented; unit tested | -| Reservation feed, authenticated applied reports, served and withdrawn gates over every reservation of the Device, instance retirement | Implemented; unit tested with a fake BMC and synchronizer, including a silent instance | +| Reservation feed, authenticated applied reports, served and withdrawn gates over every reservation of the Device | Implemented; unit tested with a fake BMC and synchronizer | +| Expected DHCP instance set in the enrollment: the feed refuses other instances, withdrawal needs every expected instance's report of a feed issued after the admission, and retirement only by shrinking the set | Implemented; unit tested, including an instance that never reported and one that stopped after fetching the reservation. Restarting the workers and the feed after a change is an operator step | | Kea synchronizer: containing-subnet placement, restart re-apply, report only after Kea accepted | Implemented; unit tested against a fake Kea control socket | | Feed over TLS beside the boot service; Kea and the synchronizer as a central component, several instances behind one UDP 67 load balancer | Implemented; render checked in CI, and reservation-gated answers proved by the boot network lab with real Kea. Not deployed, and relayed requests across a WAN are not exercised | | Boot service and boot files in the central cluster, serving a UEFI HTTP boot loader | Proposed; the boot service runs in the site's boot Pod beside the site store, and serves the iPXE script but no EFI loader yet | diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index a98485c0..47b43560 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -365,8 +365,10 @@ exercises boot addresses, reservations and Kea end to end in the lab: token and a self-signed feed key per run, as Secrets in `fleet-site`, never in Git or evidence. - **Worker mode.** `config/site/redfish/synced/graph` sets the worker - enrollment's `dhcp` to `synced`, so every network boot needs a boot address - and waits for Kea to apply and withdraw its reservation. + enrollment's `dhcp` to `synced`, with `lab-kea` as its one expected DHCP + instance, so every network boot needs a boot address and waits for Kea to + apply and withdraw its reservation. The feed reads the same enrollment from + a ConfigMap in `config/site/redfish/synced/services`. - **IPAM stand-in.** The lab has no IPAM service. The provider project serves IPAM's `IPClaim` kind from a CRD, and the acceptance runner binds each unbound claim, with the bootstrap identity, to the lowest free address in diff --git a/hack/boot-network/kea-lab.sh b/hack/boot-network/kea-lab.sh index 5a62351c..29cdca22 100755 --- a/hack/boot-network/kea-lab.sh +++ b/hack/boot-network/kea-lab.sh @@ -48,7 +48,10 @@ EOF # Docker assigns container addresses from the lower half only, so it never # hands out the reserved address. docker network create --subnet 198.51.100.0/24 --ip-range 198.51.100.0/25 --gateway 198.51.100.1 "$prefix" >/dev/null -docker create --name "$prefix-feed" --platform linux/amd64 --user 0 --network "$prefix" --network-alias feed --entrypoint sh "$image" \ +# The feed reads the site's synced enrollment, as the site's dhcp-feed role +# does: it serves, and takes reports from, only the expected instance kea-a. +enrollment='{"dhcp":"synced","dhcpInstances":["kea-a"],"targets":[{"device":"fleet-provider/server-example-001","endpoint":"https://192.0.2.10:8443","systemID":"System-1","systemUUID":"00000000-0000-4000-8000-000000000001","diskBytes":2147483648,"console":"lab.log"}]}' +docker create --name "$prefix-feed" --platform linux/amd64 --user 0 --network "$prefix" --network-alias feed -e FLEET_REDFISH_ENROLLMENT="$enrollment" --entrypoint sh "$image" \ -c 'mkdir -p -m 0700 /state/store /state/boot && exec /lab/lab serve -store /state/store -boot /state/boot -token-file /lab/token -cert /lab/feed.crt -key /lab/feed.key' >/dev/null # As in the site component: the socket directory starts 0777, like an # emptyDir, and Kea's command makes it 0750 before Kea starts. diff --git a/hack/boot-network/lab/main.go b/hack/boot-network/lab/main.go index b0816cf8..2358abc1 100644 --- a/hack/boot-network/lab/main.go +++ b/hack/boot-network/lab/main.go @@ -13,6 +13,7 @@ import ( "time" "go.datum.net/fleet/internal/bootnet" + "go.datum.net/fleet/internal/redfish" "go.datum.net/fleet/internal/site" "go.datum.net/fleet/internal/site/redfishwork" ) @@ -26,7 +27,7 @@ func main() { func run() error { if len(os.Args) < 2 { - return errors.New("usage: lab serve|open|close|retire [flags]") + return errors.New("usage: lab serve|open|close [flags]") } fs := flag.NewFlagSet(os.Args[1], flag.ContinueOnError) storeDir := fs.String("store", "", "site store directory") @@ -39,13 +40,9 @@ func run() error { fence := fs.Int64("fence", 1, "operation fence (open)") mac := fs.String("mac", "", "boot NIC MAC (open)") address := fs.String("address", "", "boot address (open)") - instance := fs.String("instance", "", "DHCP instance (retire)") if err := fs.Parse(os.Args[2:]); err != nil { return err } - if os.Args[1] == "retire" { - return redfishwork.RetireInstance(*bootDir, *instance) - } store, err := site.OpenStore(*storeDir, nil) if err != nil { return err @@ -56,8 +53,16 @@ func run() error { if err != nil { return err } - // The same listener the site's dhcp-feed role runs, on :8081. - return redfishwork.BootServer{Store: store, BootRoot: *bootDir}.ServeDHCP(strings.TrimSpace(string(token)), *cert, *key) + // The same listener the site's dhcp-feed role runs, on :8081, serving + // the expected DHCP instances of the same synced enrollment. + enrollment, err := redfish.ParseEnrollment([]byte(os.Getenv("FLEET_REDFISH_ENROLLMENT"))) + if err != nil { + return err + } + if enrollment.DHCP != redfish.DHCPSynced { + return errors.New("the lab feed needs a synced enrollment") + } + return redfishwork.BootServer{Store: store, BootRoot: *bootDir, DHCPInstances: enrollment.DHCPInstances}.ServeDHCP(strings.TrimSpace(string(token)), *cert, *key) case "open": normalized, ok := bootnet.NormalizeMAC(*mac) if !ok || *operation == "" { diff --git a/hack/multiplane/flux.py b/hack/multiplane/flux.py index 09d8904d..b1cbba97 100644 --- a/hack/multiplane/flux.py +++ b/hack/multiplane/flux.py @@ -107,9 +107,10 @@ LAB_DHCP = os.environ.get('FLEET_LAB_DHCP', 'static') if LAB_DHCP not in ('static', 'synced') or (LAB_DHCP == 'synced' and PROVIDER != 'redfish'): raise SystemExit('FLEET_LAB_DHCP=synced needs the Redfish provider') -SYNCED_OBJECTS = ['fleet-site_fleet-site-dhcp-base__ConfigMap', 'fleet-site_fleet-site-dhcp-feed__Service'] if LAB_DHCP == 'synced' else [] +SYNCED_OBJECTS = ['fleet-site_fleet-site-dhcp-base__ConfigMap', 'fleet-site_fleet-site-dhcp-feed__Service', 'fleet-site_fleet-site-redfish-enrollment__ConfigMap'] if LAB_DHCP == 'synced' else [] if LAB_DHCP == 'synced': - SHARED.update({('configmaps', SITE, 'fleet-site-dhcp-base'): 'fleet-site-services', ('services', SITE, 'fleet-site-dhcp-feed'): 'fleet-site-services'}) + SHARED.update({('configmaps', SITE, 'fleet-site-dhcp-base'): 'fleet-site-services', ('services', SITE, 'fleet-site-dhcp-feed'): 'fleet-site-services', + ('configmaps', SITE, 'fleet-site-redfish-enrollment'): 'fleet-site-services'}) LAYER_INVENTORY = { 'flux-system/fleet-site-services': sorted(['fleet-site_fleet-site-boot__Service', 'fleet-site_fleet-site-worker-policy__ConfigMap', 'fleet-site_fleet-site-runtime_apps_Deployment', 'fleet-site_fleet-site-boot_apps_Deployment', diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index 4de03e3d..41246002 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -181,7 +181,10 @@ def enroll(s): # One credential Secret per Device, by the BMC discovery contract. if kubectl(s, 'get', 'namespace', CREDENTIALS, check=False).returncode != 0: kubectl(s, 'create', 'namespace', CREDENTIALS) - enrollment = json.loads(next(l for l in pathlib.Path('config/site/redfish/graph/kustomization.yaml').read_text().splitlines() if l.strip().startswith("value: '{")).split("'")[1]) + # The enrollment this run's workers get: the synced graph's, with its + # expected DHCP instance, under --synced-dhcp. + graph = 'config/site/redfish/synced/graph/kustomization.yaml' if synced(s) else 'config/site/redfish/graph/kustomization.yaml' + enrollment = json.loads(next(l for l in pathlib.Path(graph).read_text().splitlines() if l.strip().startswith("value: '{")).split("'")[1]) # The boot NIC is a Device inventory fact; the lab's VM definitions # record it. lab_macs = {t['system']: t['mac'] for t in json.loads(pathlib.Path('hack/redfish-lab/targets.json').read_text())} @@ -515,6 +518,8 @@ def run(*command, container='libvirt'): applied = [json.loads(l) for l in run('cat', '/var/lib/fleet-boot/dhcp-applied.log').stdout.splitlines() if l.strip()] if not applied or {r['instance'] for r in applied} != {'lab-kea'}: die('the site retained no applied report, or one from an instance other than lab-kea') + if not all(r['feed'].get('issued', '0001-01-01T00:00:00Z') != '0001-01-01T00:00:00Z' for r in applied): + die('a retained report has no feed issue time') def serves(report, address): return any(r['mac'] == mac and r['address'] == address for r in report['feed']['reservations']) leases = run('cat', '/var/lib/kea/dhcp4.leases', container='kea').stdout.splitlines() diff --git a/hack/multiplane/test-redfish.py b/hack/multiplane/test-redfish.py index ff431713..f8326dea 100644 --- a/hack/multiplane/test-redfish.py +++ b/hack/multiplane/test-redfish.py @@ -83,6 +83,7 @@ def build(path): by_system = {t['system']: t for t in targets} check('every enrolled BMC endpoint is the fixed BMC Service', enrollment.get('targets') and all(t.get('endpoint') == 'https://%s:8443' % flux.BMC_SERVICE_IP for t in enrollment['targets'])) check('lab DHCP is static and the enrollment names no boot NIC or address', enrollment.get('dhcp') == 'static' and not any('provisioning' in t or 'mac' in t for t in enrollment.get('targets', []))) +check('a static enrollment names no DHCP instances', 'dhcpInstances' not in enrollment, str(enrollment.get('dhcpInstances'))) check('enrollment matches the lab targets exactly', len(enrollment.get('targets', [])) == 2 and all( t['systemID'] in by_system and by_system[t['systemID']]['uuid'] == t['systemUUID'] and by_system[t['systemID']]['console'].endswith('/' + t['console']) for t in enrollment.get('targets', [])), json.dumps(enrollment)[:300]) @@ -109,7 +110,8 @@ def build(path): synced_rgd = next((d for d in synced_graph if d.get('kind') == 'ResourceGraphDefinition'), {}) synced_env = {e['name']: e.get('value') for e in next((r for r in synced_rgd.get('spec', {}).get('resources', []) if r['id'] == 'workers'), {}).get('template', {}).get('spec', {}).get('template', {}).get('spec', {}).get('containers', [{}])[0].get('env', [])} synced_enrollment = json.loads(synced_env.get('FLEET_REDFISH_ENROLLMENT', '{}')) -check('synced graph changes only the DHCP mode', synced_enrollment.get('dhcp') == 'synced' and dict(synced_enrollment, dhcp='static') == enrollment +check('synced graph changes only the DHCP mode and declares the one lab instance', synced_enrollment.get('dhcp') == 'synced' and synced_enrollment.get('dhcpInstances') == ['lab-kea'] + and {k: v for k, v in dict(synced_enrollment, dhcp='static').items() if k != 'dhcpInstances'} == enrollment and {k: v for k, v in synced_env.items() if k != 'FLEET_REDFISH_ENROLLMENT'} == {k: v for k, v in env.items() if k != 'FLEET_REDFISH_ENROLLMENT'}) synced_services = build(root / 'config/site/redfish/synced/services') synced_deployments = {d['metadata']['name']: d for d in synced_services if d.get('kind') == 'Deployment'} @@ -126,6 +128,11 @@ def build(path): check('Kea makes its control socket directory 0750 and waits for the lab bridge', 'chmod 0750 /var/run/kea' in ' '.join(runtime_containers.get('kea', {}).get('command', [])) and 'fleetpxe0' in ' '.join(runtime_containers.get('kea', {}).get('command', []))) check('the feed runs beside the boot service', any(c['name'] == 'dhcp-feed' and c['command'][:2] == ['fleet-multiplane', 'dhcp-feed'] for c in pod('fleet-site-boot').get('containers', []))) +feed_env = next((c.get('env', []) for c in pod('fleet-site-boot').get('containers', []) if c['name'] == 'dhcp-feed'), []) +feed_ref = next((e.get('valueFrom', {}).get('configMapKeyRef', {}) for e in feed_env if e['name'] == 'FLEET_REDFISH_ENROLLMENT'), {}) +feed_enrollment = json.loads(next((d['data'].get(feed_ref.get('key'), '{}') for d in synced_services if d.get('kind') == 'ConfigMap' and d['metadata']['name'] == feed_ref.get('name')), '{}')) +check('the feed reads exactly the workers\' synced enrollment', feed_ref and feed_enrollment == synced_enrollment, json.dumps(feed_ref)) +check('the expected DHCP instance set is the one synchronizer\'s instance', ['-instance=' + i for i in feed_enrollment.get('dhcpInstances', [])] == [a for a in sync_args if a.startswith('-instance=')], str(feed_enrollment.get('dhcpInstances'))) check('the lab BMC defines the network without DHCP', any(e == {'name': 'FLEET_LAB_DHCP', 'value': 'synced'} for e in pod('fleet-site-bmc').get('containers', [{}])[0].get('env', []))) kea_config = json.loads(next((d['data']['kea-dhcp4.conf'] for d in synced_services if d.get('kind') == 'ConfigMap' and d['metadata']['name'] == 'fleet-site-dhcp-base'), '{}')) subnets = kea_config.get('Dhcp4', {}).get('subnet4', []) @@ -140,8 +147,8 @@ def build(path): check('synced %s mounts only volumes it declares' % name, not missing, str(missing)) os.environ['FLEET_LAB_DHCP'] = 'synced' importlib.reload(flux) -check('synced Flux inventory holds the base configuration and the feed Service', - {'fleet-site_fleet-site-dhcp-base__ConfigMap', 'fleet-site_fleet-site-dhcp-feed__Service'} <= set(flux.LAYER_INVENTORY['flux-system/fleet-site-services'])) +check('synced Flux inventory holds the base configuration, the feed enrollment and the feed Service', + {'fleet-site_fleet-site-dhcp-base__ConfigMap', 'fleet-site_fleet-site-dhcp-feed__Service', 'fleet-site_fleet-site-redfish-enrollment__ConfigMap'} <= set(flux.LAYER_INVENTORY['flux-system/fleet-site-services'])) os.environ['FLEET_LAB_DHCP'] = 'static' importlib.reload(flux) check('run.sh accepts --synced-dhcp only with --redfish', "--synced-dhcp) lab_dhcp=synced" in (root / 'hack/multiplane/run.sh').read_text() diff --git a/hack/validate-site-dhcp-render.sh b/hack/validate-site-dhcp-render.sh index 5cb049b3..c89e39ea 100755 --- a/hack/validate-site-dhcp-render.sh +++ b/hack/validate-site-dhcp-render.sh @@ -16,6 +16,8 @@ boot = one("Deployment", "fleet-site-boot")["spec"]["template"]["spec"] feed = next(c for c in boot["containers"] if c["name"] == "dhcp-feed") assert feed["command"][:2] == ["fleet-multiplane", "dhcp-feed"] and "-tls-cert" in feed["command"] and "-tls-key" in feed["command"], feed["command"] assert {"name": "state", "mountPath": "/var/lib/fleet-local", "subPath": "journal", "readOnly": True} in feed["volumeMounts"], "the feed reads the store read-only" +ref = next(e["valueFrom"]["configMapKeyRef"] for e in feed["env"] if e["name"] == "FLEET_REDFISH_ENROLLMENT") +enrollment = json.loads(one("ConfigMap", ref["name"])["data"][ref["key"]]) service = one("Service", "fleet-site-dhcp-feed") assert service["spec"]["type"] == "ClusterIP" and service["spec"]["ports"][0]["port"] == 8081 kea = one("StatefulSet", "fleet-site-dhcp")["spec"] @@ -37,6 +39,8 @@ assert base.get("authoritative") is False, "an instance without the reservation assert all("next-server" not in s for s in base["subnet4"]), "no TFTP server" assert any(c["name"] == "HTTPClient" and c["boot-file-name"].startswith("http") for c in base["client-classes"]), "UEFI HTTP boot" assert any(e["name"] == "POD_NAME" for e in containers["sync"]["env"]), "the instance name is the Pod name" +pods = ["%s-%d" % (one("StatefulSet", "fleet-site-dhcp")["metadata"]["name"], i) for i in range(kea["replicas"])] +assert enrollment["dhcp"] == "synced" and enrollment["dhcpInstances"] == pods, "the expected DHCP instances are exactly the StatefulSet Pods: %s" % enrollment["dhcpInstances"] assert "chmod 0750 /var/run/kea" in " ".join(containers["kea"]["command"]), "Kea 2.6 needs its socket directory 0750" for pod in (boot, kea["template"]["spec"]): volumes = {v["name"] for v in pod["volumes"]} @@ -47,5 +51,5 @@ labels = one("Deployment", "fleet-site-boot")["spec"]["template"]["metadata"]["l assert all(labels.get(k) == v for k, v in service["spec"]["selector"].items()), "the feed Service selects the boot Pod" budget = one("PodDisruptionBudget", "fleet-site-dhcp")["spec"]["selector"]["matchLabels"] assert budget == kea["selector"]["matchLabels"], "the budget covers the Kea Pods" -print("PASS site DHCP render: %d objects, feed over TLS, Kea pinned behind one UDP 67 load balancer, HTTP boot, no Secret, no pool" % len(docs)) +print("PASS site DHCP render: %d objects, feed over TLS to the expected instances, Kea pinned behind one UDP 67 load balancer, HTTP boot, no Secret, no pool" % len(docs)) ' diff --git a/internal/bootnet/feed.go b/internal/bootnet/feed.go index 349d5873..9f7abe51 100644 --- a/internal/bootnet/feed.go +++ b/internal/bootnet/feed.go @@ -28,12 +28,21 @@ type Reservation struct { } // Feed is the complete desired reservation set. Revision is derived from the -// reservations, so a report of an applied Feed is self-verifying. +// reservations, so a report of an applied Feed is self-verifying. Issued is +// when the site's feed server took its clock, in UTC to the second, before it +// read the reservations it served; it is not part of the revision, so the +// same reservations served at different times are the same revision. A feed +// built here, or a report retained before feeds carried it, has the zero +// time. type Feed struct { Revision string `json:"revision"` Reservations []Reservation `json:"reservations"` + Issued time.Time `json:"issued"` } +// InstanceHeader names, on a feed request, the DHCP instance fetching it. +const InstanceHeader = "X-Fleet-DHCP-Instance" + // Applied reports that one DHCP instance now serves exactly Feed. type Applied struct { Instance string `json:"instance"` @@ -42,6 +51,10 @@ type Applied struct { var instanceName = regexp.MustCompile(`^[a-z0-9]([a-z0-9.-]{0,61}[a-z0-9])?$`) +// ValidInstance reports whether name can be a DHCP instance name: a +// StatefulSet Pod name or another DNS label-like name. +func ValidInstance(name string) bool { return instanceName.MatchString(name) } + // NormalizeMAC returns the canonical lower-case colon form of a 48-bit MAC. func NormalizeMAC(v string) (string, bool) { hw, err := net.ParseMAC(v) @@ -101,12 +114,14 @@ func NewFeed(rs []Reservation) (Feed, error) { return Feed{Revision: revision(out), Reservations: out}, nil } -// Verify accepts only a feed already in canonical form whose revision matches. +// Verify accepts only a feed already in canonical form whose revision +// matches, with Issued in UTC to the second. Issued is outside the revision. func (f Feed) Verify() error { want, err := NewFeed(f.Reservations) if err != nil { return err } + want.Issued = f.Issued.UTC().Truncate(time.Second) got, _ := json.Marshal(f) exact, _ := json.Marshal(want) if string(got) != string(exact) { @@ -117,7 +132,7 @@ func (f Feed) Verify() error { // Verify checks the instance name and the applied feed. func (a Applied) Verify() error { - if !instanceName.MatchString(a.Instance) { + if !ValidInstance(a.Instance) { return errors.New("invalid DHCP instance name") } return a.Feed.Verify() diff --git a/internal/bootnet/feed_test.go b/internal/bootnet/feed_test.go index efb206b6..16fad42d 100644 --- a/internal/bootnet/feed_test.go +++ b/internal/bootnet/feed_test.go @@ -1,6 +1,7 @@ package bootnet import ( + "encoding/json" "testing" "time" ) @@ -53,3 +54,41 @@ func TestFeedIsCanonicalAndSelfVerifying(t *testing.T) { t.Fatal("instance names not checked") } } + +// TestIssuedIsOutsideTheRevision: the same reservations issued at different +// times are one revision, both verify, and a feed retained before feeds +// carried an issue time still verifies with the zero time. Issued must be +// UTC to the second. +func TestIssuedIsOutsideTheRevision(t *testing.T) { + r := Reservation{MAC: "52:54:00:77:01:0a", Address: "192.0.2.10", Expires: time.Date(2030, 1, 2, 3, 4, 5, 0, time.UTC)} + a, _ := NewFeed([]Reservation{r}) + b := a + a.Issued = time.Date(2030, 1, 1, 0, 0, 0, 0, time.UTC) + b.Issued = a.Issued.Add(time.Hour) + if a.Revision != b.Revision || a.Verify() != nil || b.Verify() != nil { + t.Fatalf("issue time changed the revision or failed verification: %+v %+v", a, b) + } + encoded, _ := json.Marshal(a) + var decoded Feed + if json.Unmarshal(encoded, &decoded) != nil || decoded.Verify() != nil || !decoded.Issued.Equal(a.Issued) { + t.Fatalf("issue time did not round-trip: %s", encoded) + } + again, _ := json.Marshal(decoded) + if string(again) != string(encoded) { + t.Fatalf("encoding is not deterministic: %s != %s", again, encoded) + } + var old Feed + if err := json.Unmarshal([]byte(`{"revision":"`+a.Revision+`","reservations":[{"mac":"52:54:00:77:01:0a","address":"192.0.2.10","expires":"2030-01-02T03:04:05Z"}]}`), &old); err != nil || old.Verify() != nil || !old.Issued.IsZero() { + t.Fatalf("a feed without an issue time: %v, %v", err, old.Verify()) + } + for name, issued := range map[string]time.Time{ + "sub-second": a.Issued.Add(time.Millisecond), + "not UTC": a.Issued.In(time.FixedZone("x", 3600)), + } { + f := a + f.Issued = issued + if f.Verify() == nil { + t.Errorf("%s issue time verified", name) + } + } +} diff --git a/internal/dhcpsync/sync.go b/internal/dhcpsync/sync.go index 68a5c092..eebaa5ad 100644 --- a/internal/dhcpsync/sync.go +++ b/internal/dhcpsync/sync.go @@ -76,6 +76,8 @@ func (s *Syncer) request(ctx context.Context, method, path string, body []byte) return nil, err } q.Header.Set("Authorization", "Bearer "+s.Token) + // The site serves its feed only to an instance it expects. + q.Header.Set(bootnet.InstanceHeader, s.Instance) if body != nil { q.Header.Set("Content-Type", "application/json") } @@ -97,6 +99,9 @@ func (s *Syncer) fetch(ctx context.Context) (bootnet.Feed, error) { return feed, nil } +// report echoes the applied feed exactly as the site served it, issue time +// included: the site proves withdrawal from when each reported feed was +// issued. func (s *Syncer) report(ctx context.Context, feed bootnet.Feed) error { b, _ := json.Marshal(bootnet.Applied{Instance: s.Instance, Feed: feed}) resp, err := s.request(ctx, http.MethodPost, "/dhcp/v1/applied", b) diff --git a/internal/dhcpsync/sync_test.go b/internal/dhcpsync/sync_test.go index 1206463a..3d9389a4 100644 --- a/internal/dhcpsync/sync_test.go +++ b/internal/dhcpsync/sync_test.go @@ -73,13 +73,17 @@ func (k *fakeKea) applied() int { return len(k.configs) } -// fakeSite serves a feed and records applied reports. +// fakeSite serves a feed, stamped with a later issue time on each request, +// only to an instance that names itself, and records applied reports. type fakeSite struct { mu sync.Mutex feed bootnet.Feed + served int reports []bootnet.Applied } +var issuedBase = time.Date(2030, 1, 2, 3, 4, 5, 0, time.UTC) + func (f *fakeSite) handler(t *testing.T) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, q *http.Request) { if q.Header.Get("Authorization") != "Bearer "+token { @@ -90,7 +94,14 @@ func (f *fakeSite) handler(t *testing.T) http.Handler { defer f.mu.Unlock() switch q.URL.Path { case "/dhcp/v1/reservations": - _ = json.NewEncoder(w).Encode(f.feed) + if q.Header.Get(bootnet.InstanceHeader) != "kea-0" { + w.WriteHeader(http.StatusForbidden) + return + } + f.served++ + feed := f.feed + feed.Issued = issuedBase.Add(time.Duration(f.served) * time.Second) + _ = json.NewEncoder(w).Encode(feed) case "/dhcp/v1/applied": var a bootnet.Applied b, _ := io.ReadAll(q.Body) @@ -154,7 +165,12 @@ func TestAppliesReservationIntoItsContainingSubnetThenReports(t *testing.T) { if len(reports) != 2 || !reports[1].Feed.Has(reservation.MAC, reservation.Address) || reports[1].Instance != "kea-0" { t.Fatalf("applied revision not reported: %+v", reports) } - // An unchanged feed is neither re-applied nor re-reported; a restarted + // The report echoes the feed as served, issue time included. + if !reports[1].Feed.Issued.Equal(issuedBase.Add(2*time.Second)) || !reports[0].Feed.Issued.Equal(issuedBase.Add(time.Second)) { + t.Fatalf("report did not echo the served feed's issue time: %+v", reports) + } + // An unchanged feed, though issued later, is neither re-applied nor + // re-reported; a restarted // Kea (new pid) lost its reservations and is re-applied without a report. if err := s.Cycle(ctx); err != nil || kea.applied() != 2 || len(site.reported()) != 2 { t.Fatalf("unchanged feed churned: %v", err) @@ -202,6 +218,20 @@ func TestNothingIsReportedThatKeaDidNotAccept(t *testing.T) { } } +// TestTheSynchronizerNamesItselfOnTheFeedRequest: the site serves its feed +// only to an expected instance, so the request carries the instance name. +func TestTheSynchronizerNamesItselfOnTheFeedRequest(t *testing.T) { + s, kea, site := newSyncer(t) + s.Instance = "kea-9" + if err := s.Cycle(context.Background()); err == nil || kea.applied() != 0 || len(site.reported()) != 0 { + t.Fatal("a feed refused to this instance was applied") + } + s.Instance = "kea-0" + if err := s.Cycle(context.Background()); err != nil || kea.applied() != 1 { + t.Fatalf("the named instance was not served: %v", err) + } +} + func TestForgedFeedIsRejectedBeforeKea(t *testing.T) { s, kea, site := newSyncer(t) site.set(t, reservation) diff --git a/internal/redfish/enrollment.go b/internal/redfish/enrollment.go index bf6ff560..16088aee 100644 --- a/internal/redfish/enrollment.go +++ b/internal/redfish/enrollment.go @@ -12,6 +12,8 @@ import ( "path/filepath" "strconv" "strings" + + "go.datum.net/fleet/internal/bootnet" ) // Target is one enrolled server: the Device it is, its BMC endpoint and its @@ -41,9 +43,17 @@ const ( ) // Enrollment is the site's explicit Device to BMC mapping. +// +// DHCPInstances is, at a synced site, the complete set of DHCP instances +// that may serve the site's reservations: each is the stable name an +// instance reports under, such as a StatefulSet Pod name. The feed serves +// and accepts reports only from these instances, and withdrawal is proven +// only when every one of them reported it. Retiring an instance means +// removing it from this set. A static site names none. type Enrollment struct { - DHCP string `json:"dhcp"` - Targets []Target `json:"targets"` + DHCP string `json:"dhcp"` + DHCPInstances []string `json:"dhcpInstances,omitempty"` + Targets []Target `json:"targets"` } // Target returns the enrolled server of a "/" Device. @@ -63,6 +73,9 @@ func ParseEnrollment(b []byte) (Enrollment, error) { if err := d.Decode(&e); err != nil || len(e.Targets) == 0 || (e.DHCP != DHCPStatic && e.DHCP != DHCPSynced) { return Enrollment{}, errors.New("invalid Redfish enrollment") } + if err := checkInstances(e.DHCP, e.DHCPInstances); err != nil { + return Enrollment{}, err + } seen := map[string]bool{} for i, t := range e.Targets { endpoint, err := ParseEndpoint(t.Endpoint) @@ -78,6 +91,28 @@ func ParseEnrollment(b []byte) (Enrollment, error) { return e, nil } +// checkInstances requires a non-empty set of unique, valid DHCP instance +// names at a synced site, and none at a static one. +func checkInstances(mode string, instances []string) error { + if mode == DHCPStatic { + if len(instances) != 0 { + return errors.New("a static DHCP site names no DHCP instances") + } + return nil + } + if len(instances) == 0 { + return errors.New("a synced DHCP site must name its DHCP instances") + } + seen := map[string]bool{} + for _, instance := range instances { + if !bootnet.ValidInstance(instance) || seen[instance] { + return errors.New("invalid or duplicate DHCP instance in the Redfish enrollment") + } + seen[instance] = true + } + return nil +} + // ParseBootOrigin accepts only a literal http://IPv4:port origin. func ParseBootOrigin(value string) (string, error) { u, err := url.Parse(value) diff --git a/internal/redfish/enrollment_test.go b/internal/redfish/enrollment_test.go index 2f6dbe33..ac222681 100644 --- a/internal/redfish/enrollment_test.go +++ b/internal/redfish/enrollment_test.go @@ -45,3 +45,29 @@ func TestEnrollmentNamesEachDeviceOnce(t *testing.T) { } } } + +// TestASyncedSiteNamesItsDHCPInstances requires a synced enrollment to name a +// non-empty set of unique, valid DHCP instances, and a static one to name +// none. +func TestASyncedSiteNamesItsDHCPInstances(t *testing.T) { + with := func(dhcp, instances string) string { + return `{"dhcp":"` + dhcp + `"` + instances + `,"targets":[` + targetA + `]}` + } + parsed, err := ParseEnrollment([]byte(with("synced", `,"dhcpInstances":["fleet-site-dhcp-0","fleet-site-dhcp-1"]`))) + if err != nil || len(parsed.DHCPInstances) != 2 || parsed.DHCPInstances[1] != "fleet-site-dhcp-1" { + t.Fatalf("synced enrollment = %+v, %v", parsed, err) + } + for name, body := range map[string]string{ + "synced without instances": with("synced", ""), + "synced with an empty set": with("synced", `,"dhcpInstances":[]`), + "static with instances": with("static", `,"dhcpInstances":["fleet-site-dhcp-0"]`), + "duplicate instance": with("synced", `,"dhcpInstances":["fleet-site-dhcp-0","fleet-site-dhcp-0"]`), + "invalid instance": with("synced", `,"dhcpInstances":["Fleet_DHCP"]`), + "empty instance name": with("synced", `,"dhcpInstances":[""]`), + "instance name with prefix": with("synced", `,"dhcpInstances":["-kea"]`), + } { + if _, err := ParseEnrollment([]byte(body)); err == nil { + t.Errorf("%s: enrollment accepted", name) + } + } +} diff --git a/internal/site/redfishwork/boot.go b/internal/site/redfishwork/boot.go index 9b3d84c3..cd48d73c 100644 --- a/internal/site/redfishwork/boot.go +++ b/internal/site/redfishwork/boot.go @@ -37,7 +37,10 @@ type BootServer struct { // BootRoot holds the per-operation delivery evidence and the retained // DHCP reports the workers read. BootRoot string - Now func() time.Time + // DHCPInstances is the enrollment's expected DHCP instance set. The + // reservation feed serves, and retains reports from, only these. + DHCPInstances []string + Now func() time.Time } func (b BootServer) now() time.Time { diff --git a/internal/site/redfishwork/dhcp.go b/internal/site/redfishwork/dhcp.go index 2e382ea5..aac00baa 100644 --- a/internal/site/redfishwork/dhcp.go +++ b/internal/site/redfishwork/dhcp.go @@ -19,7 +19,7 @@ import ( ) // withdrawalWindow bounds how long a worker waits, after the network boot -// closed, for every DHCP instance that served the reservation to report it +// closed, for every expected DHCP instance to report the reservation // withdrawn. Past it the outcome stays unknown, and a resumed worker waits // again. const withdrawalWindow = 10 * time.Minute @@ -27,14 +27,30 @@ const withdrawalWindow = 10 * time.Minute const dhcpLog = "dhcp-applied.log" // report is one retained applied report: when the boot server accepted it, -// and which DHCP instance applied which exact feed. A Retired record is an -// operator's statement that the instance is gone and serves nothing; a later -// report from the same instance counts again. +// and which DHCP instance applied which exact feed, as the feed server issued +// it. type report struct { At time.Time `json:"at"` Instance string `json:"instance"` Feed bootnet.Feed `json:"feed"` - Retired bool `json:"retired,omitempty"` +} + +// retainedLine is how a retained line is read. A line carrying "retired" was +// written by the operator retirement command this site no longer has; it +// is ignored and has no effect: it is neither a report nor evidence, and an +// instance is retired only by leaving the enrollment's expected set. +type retainedLine struct { + report + Retired bool `json:"retired"` +} + +// expected is the enrollment's expected DHCP instance set. +func expected(instances []string) map[string]bool { + out := map[string]bool{} + for _, instance := range instances { + out[instance] = true + } + return out } // Reservations is the complete desired reservation set: each boot NIC whose @@ -61,13 +77,29 @@ func (b BootServer) Reservations() (bootnet.Feed, error) { return bootnet.NewFeed(reservations) } +// Issue is the feed served now: the clock is read before the reservations, +// so every reservation stored before Issued is in the feed. +func (b BootServer) Issue() (bootnet.Feed, error) { + issued := b.now().UTC().Truncate(time.Second) + feed, err := b.Reservations() + feed.Issued = issued + return feed, err +} + // DHCPHandler serves the reservation feed and accepts applied reports from // the DHCP owner's synchronizer, authenticated by a bearer token. It is -// never served on the firmware-facing boot listener. +// never served on the firmware-facing boot listener. It serves a feed only +// to, and retains a report only from, an instance in the enrollment's +// expected set, so an instance outside it never gets a reservation to +// serve; a feed request names its instance in bootnet.InstanceHeader. func (b BootServer) DHCPHandler(token string) (http.Handler, error) { if len(token) < 32 || strings.ContainsAny(token, " \t\r\n") { return nil, errors.New("the DHCP synchronizer token must be at least 32 characters without whitespace") } + if len(b.DHCPInstances) == 0 { + return nil, errors.New("the DHCP feed needs the enrollment's expected DHCP instances") + } + allowed := expected(b.DHCPInstances) return http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) { w.Header().Set("Cache-Control", "no-store") got, ok := strings.CutPrefix(request.Header.Get("Authorization"), "Bearer ") @@ -77,7 +109,11 @@ func (b BootServer) DHCPHandler(token string) (http.Handler, error) { } switch { case request.Method == http.MethodGet && request.URL.Path == "/dhcp/v1/reservations" && request.URL.RawQuery == "": - feed, err := b.Reservations() + if !allowed[request.Header.Get(bootnet.InstanceHeader)] { + http.Error(w, "not an expected DHCP instance", http.StatusForbidden) + return + } + feed, err := b.Issue() if err != nil { http.Error(w, "reservations unavailable", http.StatusServiceUnavailable) return @@ -92,6 +128,10 @@ func (b BootServer) DHCPHandler(token string) (http.Handler, error) { http.Error(w, "invalid applied report", http.StatusBadRequest) return } + if !allowed[applied.Instance] { + http.Error(w, "not an expected DHCP instance", http.StatusForbidden) + return + } if err := b.retain(applied); err != nil { http.Error(w, "applied report not retained", http.StatusServiceUnavailable) return @@ -126,23 +166,10 @@ func (b BootServer) retain(applied bootnet.Applied) error { return appendEvidence(b.BootRoot, dhcpLog, string(data)+"\n") } -// RetireInstance records that a DHCP instance is gone. Withdrawal then stops -// waiting for it. Only an operator at the site runs it, after making sure the -// instance's server no longer answers. -func RetireInstance(root, instance string) error { - empty, _ := bootnet.NewFeed(nil) - if err := (bootnet.Applied{Instance: instance, Feed: empty}).Verify(); err != nil { - return err - } - data, err := json.Marshal(report{At: time.Now().UTC(), Instance: instance, Feed: empty, Retired: true}) - if err != nil { - return err - } - return appendEvidence(root, dhcpLog, string(data)+"\n") -} - // reports reads every retained report in order. An unreadable line is -// corruption, never evidence in either direction. +// corruption, never evidence in either direction. A report retained before +// feeds carried an issue time reads as issued at the zero time, so it can +// never prove a withdrawal. A retired line is skipped (see retainedLine). func reports(root string) ([]report, error) { file, err := os.Open(filepath.Join(root, dhcpLog)) if os.IsNotExist(err) { @@ -156,27 +183,30 @@ func reports(root string) ([]report, error) { scanner := bufio.NewScanner(file) scanner.Buffer(make([]byte, 0, 64<<10), 1<<20) for scanner.Scan() { - var r report - if json.Unmarshal(scanner.Bytes(), &r) != nil || r.At.IsZero() || (bootnet.Applied{Instance: r.Instance, Feed: r.Feed}).Verify() != nil { + var line retainedLine + if json.Unmarshal(scanner.Bytes(), &line) != nil || line.At.IsZero() || (bootnet.Applied{Instance: line.Instance, Feed: line.Feed}).Verify() != nil { return nil, errors.New("invalid retained DHCP report") } - out = append(out, r) + if !line.Retired { + out = append(out, line.report) + } } return out, scanner.Err() } -// awaitReservation waits, without any effect, until some DHCP instance -// reports serving the boot NIC at the operation's exact address since this -// operation's boot admission was created. +// awaitReservation waits, without any effect, until some expected DHCP +// instance reports serving the boot NIC at the operation's exact address +// since this operation's boot admission was created. func (c Config) awaitReservation(ctx context.Context, boot Boot) error { poll, _, _, _ := c.durations() + allowed := expected(c.DHCPInstances) for { retained, err := reports(c.BootRoot) if err != nil { return err } for _, r := range retained { - if !r.Retired && r.At.After(boot.Created) && r.Feed.Has(boot.MAC, boot.Address) { + if allowed[r.Instance] && r.At.After(boot.Created) && r.Feed.Has(boot.MAC, boot.Address) { return nil } } @@ -189,15 +219,29 @@ func (c Config) awaitReservation(ctx context.Context, boot Boot) error { } } -// awaitWithdrawal requires that some DHCP instance served the reservation -// during this operation, and that no instance's latest report, however old, -// serves any MAC or address this site ever published for the Device. An -// instance that went silent while serving one keeps the outcome unknown -// until an operator retires it, so a success also proves that every earlier -// reservation for the Device, such as a held operation's, is withdrawn. +// awaitWithdrawal requires that some expected DHCP instance reported +// serving the reservation during this operation, and that every expected +// instance's latest report is of a feed issued after the admission was +// published (Boot.Published) that serves no MAC or address this site ever +// published for the Device. Reports from instances outside the enrollment's +// expected set never count. +// +// While the admission is open, every feed issued after it was published +// carries the reservation. So a report of a feed issued after that without +// it was issued after the reservation left the feed, and every later feed +// lacks it too. An instance that fetched a feed with the reservation and +// stopped before reporting it still has a latest report that was either +// issued before the admission was published or serves the reservation, so +// it blocks; so does an expected instance that never reported. Blocking +// keeps the outcome unknown past withdrawalWindow; it never passes. The +// feed server and the worker read one site clock: both mount the site's +// state volume. A success also proves that every earlier reservation for +// the Device, such as a held operation's, is withdrawn. The only way past an +// instance that is gone is to remove it from the expected set. func (c Config) awaitWithdrawal(ctx context.Context, store *site.Store, device string, boot Boot) error { poll, _, _, _ := c.durations() deadline := c.now().Add(withdrawalWindow) + allowed := expected(c.DHCPInstances) for { published, err := publishedFor(store, device) if err != nil { @@ -209,8 +253,7 @@ func (c Config) awaitWithdrawal(ctx context.Context, store *site.Store, device s } served, latest := false, map[string]bootnet.Feed{} for _, r := range retained { - if r.Retired { - delete(latest, r.Instance) + if !allowed[r.Instance] { continue } if r.At.After(boot.Created) && r.Feed.Has(boot.MAC, boot.Address) { @@ -218,8 +261,13 @@ func (c Config) awaitWithdrawal(ctx context.Context, store *site.Store, device s } latest[r.Instance] = r.Feed } - withdrawn := served - for _, feed := range latest { + withdrawn := served && !boot.Published.IsZero() && len(allowed) > 0 + for instance := range allowed { + feed, reported := latest[instance] + if !reported || !feed.Issued.After(boot.Published) { + withdrawn = false + continue + } for _, p := range published { if feed.Serves(p.MAC, p.Address) { withdrawn = false diff --git a/internal/site/redfishwork/dhcp_test.go b/internal/site/redfishwork/dhcp_test.go index 4f2ac661..c2ef7d75 100644 --- a/internal/site/redfishwork/dhcp_test.go +++ b/internal/site/redfishwork/dhcp_test.go @@ -36,7 +36,7 @@ func bootNetwork() *ops.BootNetworkInput { } // synchronizer stands in for one Kea instance and its synchronizer: each -// tick it applies the site's current feed and reports it. +// tick it fetches the site's feed as that instance and reports it. type synchronizer struct { server BootServer instance string @@ -55,8 +55,12 @@ func (s *synchronizer) run(ctx context.Context, t *testing.T) { paused := s.paused s.mu.Unlock() if !paused { - feed, err := s.server.Reservations() - if err == nil { + fetch, _ := newRequest("GET", "/dhcp/v1/reservations", "") + fetch.Header.Set(bootnet.InstanceHeader, s.instance) + fetched := httptest.NewRecorder() + handler.ServeHTTP(fetched, fetch) + var feed bootnet.Feed + if fetched.Code == http.StatusOK && json.Unmarshal(fetched.Body.Bytes(), &feed) == nil { data, _ := json.Marshal(bootnet.Applied{Instance: s.instance, Feed: feed}) request, _ := newRequest("POST", "/dhcp/v1/applied", string(data)) recorder := httptest.NewRecorder() @@ -78,7 +82,7 @@ func TestASyncedInstallServesItsAddressOnlyWhileItRuns(t *testing.T) { l := newLab(t) r := runner(t, l) synced(r) - server := BootServer{Store: r.Store, BootRoot: l.bootRoot} + server := BootServer{Store: r.Store, BootRoot: l.bootRoot, DHCPInstances: []string{"dhcp-a"}} seen := make(chan bootnet.Feed, 1) l.onHook = func() { feed, _ := server.Reservations() @@ -116,10 +120,10 @@ func synced(r *site.Runner) { for name, kind := range r.Kinds { switch k := kind.(type) { case Installation: - k.Synced = true + k.Synced, k.DHCPInstances = true, []string{"dhcp-a"} r.Kinds[name] = k case Wipe: - k.Synced = true + k.Synced, k.DHCPInstances = true, []string{"dhcp-a"} r.Kinds[name] = k } } @@ -208,11 +212,18 @@ func TestAPublishedReservationNeverEndsFailed(t *testing.T) { } } -// TestWithdrawalCoversEveryReservationOfTheDevice holds a later operation's -// success while any instance's latest report, however old, serves a -// reservation the site published for the Device, until that instance -// reports again or an operator retires it. -func TestWithdrawalCoversEveryReservationOfTheDevice(t *testing.T) { +// gate is a site store, a feed server expecting dhcp-a and dhcp-b, and a +// worker configuration reading the same reports, on a fixed site clock. +type gate struct { + t *testing.T + store *site.Store + server BootServer + handler http.Handler + config Config + now time.Time +} + +func newGate(t *testing.T) *gate { root := t.TempDir() for _, dir := range []string{"store", "boot"} { if err := os.Mkdir(filepath.Join(root, dir), 0o700); err != nil { @@ -223,91 +234,321 @@ func TestWithdrawalCoversEveryReservationOfTheDevice(t *testing.T) { if err != nil { t.Fatal(err) } - now := time.Now().UTC().Truncate(time.Second) - clock := func() time.Time { return now } - server := BootServer{Store: store, BootRoot: filepath.Join(root, "boot"), Now: clock} - handler, err := server.DHCPHandler(syncToken) - if err != nil { + g := &gate{t: t, store: store, now: time.Now().UTC().Truncate(time.Second)} + clock := func() time.Time { return g.now } + instances := []string{"dhcp-a", "dhcp-b"} + g.server = BootServer{Store: store, BootRoot: filepath.Join(root, "boot"), DHCPInstances: instances, Now: clock} + if g.handler, err = g.server.DHCPHandler(syncToken); err != nil { t.Fatal(err) } - post := func(instance string, rs ...bootnet.Reservation) { - t.Helper() - feed, err := bootnet.NewFeed(rs) - if err != nil { - t.Fatal(err) - } - data, _ := json.Marshal(bootnet.Applied{Instance: instance, Feed: feed}) - request, _ := newRequest("POST", "/dhcp/v1/applied", string(data)) - recorder := httptest.NewRecorder() - handler.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { - t.Fatalf("applied report = %d", recorder.Code) - } + g.config = Config{BootRoot: g.server.BootRoot, Poll: 5 * time.Millisecond, Now: clock, Synced: true, DHCPInstances: instances} + return g +} + +// serve sends one request to the feed handler. +func (g *gate) serve(method, path, instance, body string) *httptest.ResponseRecorder { + request, _ := newRequest(method, path, body) + if instance != "" { + request.Header.Set(bootnet.InstanceHeader, instance) + } + recorder := httptest.NewRecorder() + g.handler.ServeHTTP(recorder, request) + return recorder +} + +// fetch is the feed one instance gets now. +func (g *gate) fetch(instance string) bootnet.Feed { + g.t.Helper() + recorder := g.serve("GET", "/dhcp/v1/reservations", instance, "") + var feed bootnet.Feed + if recorder.Code != http.StatusOK || json.Unmarshal(recorder.Body.Bytes(), &feed) != nil || feed.Verify() != nil { + g.t.Fatalf("feed for %s = %d %s", instance, recorder.Code, recorder.Body) + } + return feed +} + +// post reports that instance applied feed, and returns the status. +func (g *gate) post(instance string, feed bootnet.Feed) int { + data, _ := json.Marshal(bootnet.Applied{Instance: instance, Feed: feed}) + return g.serve("POST", "/dhcp/v1/applied", "", string(data)).Code +} + +// apply fetches the current feed as instance and reports it. +func (g *gate) apply(instance string) bootnet.Feed { + g.t.Helper() + feed := g.fetch(instance) + if code := g.post(instance, feed); code != http.StatusNoContent { + g.t.Fatalf("applied report from %s = %d", instance, code) + } + return feed +} + +// tick moves the site clock on by a second, the feed's issue precision. +func (g *gate) tick() { g.now = g.now.Add(time.Second) } + +// admit stores an open admission at fence, published one second after it +// was created. +func (g *gate) admit(operation string, fence int64, address string) Boot { + g.t.Helper() + if err := g.store.Raise(device, fence); err != nil { + g.t.Fatal(err) + } + boot := Boot{Operation: operation, Fence: fence, MAC: mac, Address: address, Token: strings.Repeat("a", 64), Created: g.now, Published: g.now.Add(time.Second), Expires: g.now.Add(time.Hour)} + if err := g.store.PutRecord(device, fence, bootRecords, operation, boot); err != nil { + g.t.Fatal(err) + } + g.tick() + g.tick() + return boot +} + +func (g *gate) close(boot Boot) { + g.t.Helper() + boot.Closed = true + if err := g.store.PutRecord(device, boot.Fence, bootRecords, boot.Operation, boot); err != nil { + g.t.Fatal(err) + } + g.tick() +} + +// withdrawn runs the withdrawal gate briefly. +func (g *gate) withdrawn(boot Boot) error { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Millisecond) + defer cancel() + return g.config.awaitWithdrawal(ctx, g.store, device, boot) +} + +func (g *gate) reserved(boot Boot) error { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Millisecond) + defer cancel() + return g.config.awaitReservation(ctx, boot) +} + +// TestTheFeedServesOnlyExpectedInstances refuses a feed request without an +// instance or from an instance outside the expected set, and refuses and +// does not retain such an instance's report. An expected instance gets the +// feed stamped with the site clock. +func TestTheFeedServesOnlyExpectedInstances(t *testing.T) { + g := newGate(t) + if code := g.serve("GET", "/dhcp/v1/reservations", "", "").Code; code != http.StatusForbidden { + t.Fatalf("feed without an instance = %d", code) + } + if code := g.serve("GET", "/dhcp/v1/reservations", "dhcp-c", "").Code; code != http.StatusForbidden { + t.Fatalf("feed for an unexpected instance = %d", code) } request, _ := newRequest("GET", "/dhcp/v1/reservations", "") request.Header.Del("Authorization") + request.Header.Set(bootnet.InstanceHeader, "dhcp-a") recorder := httptest.NewRecorder() - handler.ServeHTTP(recorder, request) + g.handler.ServeHTTP(recorder, request) if recorder.Code != http.StatusUnauthorized { t.Fatalf("unauthenticated feed = %d", recorder.Code) } + feed := g.fetch("dhcp-a") + if !feed.Issued.Equal(g.now) || feed.Issued.Location() != time.UTC { + t.Fatalf("feed issued %v, want the site clock %v", feed.Issued, g.now) + } + if code := g.post("dhcp-c", feed); code != http.StatusForbidden { + t.Fatalf("report from an unexpected instance = %d", code) + } + if retained, err := reports(g.server.BootRoot); err != nil || len(retained) != 0 { + t.Fatalf("an unexpected instance's report was retained: %+v, %v", retained, err) + } + if code := g.post("dhcp-a", feed); code != http.StatusNoContent { + t.Fatalf("report from an expected instance = %d", code) + } + if retained, err := reports(g.server.BootRoot); err != nil || len(retained) != 1 || !retained[0].Feed.Issued.Equal(feed.Issued) { + t.Fatalf("retained %+v, %v", retained, err) + } + if _, err := (BootServer{}).DHCPHandler(syncToken); err == nil { + t.Fatal("a feed without an expected instance set started") + } +} - // A held operation at fence 2 published 192.0.2.30, and instance - // dhcp-b reported serving it before it went silent. - held := Boot{Operation: "op-held", Fence: 2, MAC: mac, Address: "192.0.2.30", Token: strings.Repeat("b", 64), Created: now.Add(-time.Hour), Expires: now.Add(-30 * time.Minute)} - if err := store.Raise(device, 2); err != nil { - t.Fatal(err) +// TestWithdrawalNeedsEveryExpectedInstance holds success while an expected +// instance never reported, even though the other reported the reservation +// served and withdrawn. Past the window the outcome stays unknown. +func TestWithdrawalNeedsEveryExpectedInstance(t *testing.T) { + g := newGate(t) + g.apply("dhcp-a") + boot := g.admit("op-a", 1, address) + if feed := g.apply("dhcp-a"); !feed.Has(mac, address) { + t.Fatalf("feed = %+v", feed) + } + if err := g.reserved(boot); err != nil { + t.Fatalf("served reservation not seen: %v", err) + } + g.close(boot) + g.apply("dhcp-a") + if err := g.withdrawn(boot); err == nil { + t.Fatal("withdrawal proven without dhcp-b ever reporting") + } + // Past the window the gate gives up, leaving the outcome unknown. + start := g.now + steps := 0 + g.config.Now = func() time.Time { steps++; return start.Add(time.Duration(steps) * withdrawalWindow / 2) } + if err := g.config.awaitWithdrawal(context.Background(), g.store, device, boot); err == nil || !strings.Contains(err.Error(), "not reported the boot reservation withdrawn") { + t.Fatalf("gate past its window = %v", err) } - if err := store.PutRecord(device, 2, bootRecords, held.Operation, held); err != nil { - t.Fatal(err) +} + +// TestAnInstanceThatStoppedAfterFetchingTheReservationBlocks: dhcp-b's latest +// report is of a feed issued before the admission, which serves nothing, but +// it fetched a feed carrying the reservation and stopped before reporting +// it. It may serve the reservation, so withdrawal stays unproven. +func TestAnInstanceThatStoppedAfterFetchingTheReservationBlocks(t *testing.T) { + g := newGate(t) + g.apply("dhcp-a") + g.apply("dhcp-b") + boot := g.admit("op-a", 1, address) + g.apply("dhcp-a") + if feed := g.fetch("dhcp-b"); !feed.Has(mac, address) { + t.Fatalf("feed = %+v", feed) + } + g.close(boot) + g.apply("dhcp-a") + if err := g.withdrawn(boot); err == nil { + t.Fatal("withdrawal proven from dhcp-b's report older than the admission") } - post("dhcp-b", bootnet.Reservation{MAC: mac, Address: held.Address, Expires: now.Add(time.Hour)}) - // The later operation at fence 3. - if err := store.Raise(device, 3); err != nil { +} + +// TestWithdrawalIsProvenByEveryExpectedInstance: each expected instance +// reported a feed issued after the admission was published without the +// reservation, so it is withdrawn everywhere. A report from an instance +// outside the set, retained earlier, neither blocks nor serves. +func TestWithdrawalIsProvenByEveryExpectedInstance(t *testing.T) { + g := newGate(t) + // A removed instance's earlier report, retained while it was expected, + // served the address. + removed := g.server + removed.DHCPInstances = []string{"dhcp-a", "dhcp-b", "dhcp-c"} + handler, err := removed.DHCPHandler(syncToken) + if err != nil { t.Fatal(err) } - boot := Boot{Operation: "op-later", Fence: 3, MAC: mac, Address: address, Token: strings.Repeat("a", 64), Created: now.Add(-time.Minute), Expires: now.Add(time.Hour)} - if err := store.PutRecord(device, 3, bootRecords, boot.Operation, boot); err != nil { - t.Fatal(err) + g.handler, handler = handler, g.handler + boot := g.admit("op-a", 1, address) + g.apply("dhcp-c") + g.handler = handler + if err := g.reserved(boot); err == nil { + t.Fatal("a report from an instance outside the expected set counted as served") + } + g.apply("dhcp-a") + g.apply("dhcp-b") + if err := g.withdrawn(boot); err == nil { + t.Fatal("withdrawal proven while the admission is open") + } + g.close(boot) + g.apply("dhcp-a") + if err := g.withdrawn(boot); err == nil { + t.Fatal("withdrawal proven before dhcp-b reported it") + } + g.apply("dhcp-b") + if err := g.withdrawn(boot); err != nil { + t.Fatalf("withdrawal reported by every expected instance: %v", err) + } + // An admission that was never published proves nothing. + unpublished := boot + unpublished.Published = time.Time{} + if err := g.withdrawn(unpublished); err == nil { + t.Fatal("withdrawal proven for an admission without a publication time") } - feed, err := server.Reservations() - if err != nil || len(feed.Reservations) != 1 || !feed.Has(mac, address) { - t.Fatalf("feed = %+v, %v: only the current admission is published", feed, err) +} + +// TestOnlyAnExpectedInstanceProvesTheReservationServed: an instance removed +// from the expected set served the reservation, and both expected instances +// reported it withdrawn without ever serving it. Nothing expected served it, +// so withdrawal stays unproven. +func TestOnlyAnExpectedInstanceProvesTheReservationServed(t *testing.T) { + g := newGate(t) + removed := g.server + removed.DHCPInstances = []string{"dhcp-a", "dhcp-b", "dhcp-c"} + handler, err := removed.DHCPHandler(syncToken) + if err != nil { + t.Fatal(err) } - config := Config{BootRoot: server.BootRoot, Poll: 5 * time.Millisecond, Now: clock, Synced: true} - short := func() context.Context { - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - t.Cleanup(cancel) - return ctx + boot := g.admit("op-a", 1, address) + g.handler, handler = handler, g.handler + g.apply("dhcp-c") + g.handler = handler + g.close(boot) + g.apply("dhcp-a") + g.apply("dhcp-b") + if err := g.withdrawn(boot); err == nil { + t.Fatal("a report from an instance outside the expected set proved the reservation served") } - if err := config.awaitReservation(short(), boot); err == nil { +} + +// TestWithdrawalCoversEveryReservationOfTheDevice holds a later operation's +// success while an expected instance's latest report serves a reservation +// the site published for the Device, such as a held operation's. +func TestWithdrawalCoversEveryReservationOfTheDevice(t *testing.T) { + g := newGate(t) + held := g.admit("op-held", 2, "192.0.2.30") + g.apply("dhcp-a") + if feed := g.apply("dhcp-b"); !feed.Has(mac, held.Address) { + t.Fatalf("feed = %+v", feed) + } + boot := g.admit("op-later", 3, address) + feed := g.fetch("dhcp-a") + if len(feed.Reservations) != 1 || !feed.Has(mac, address) { + t.Fatalf("feed = %+v: only the current admission is published", feed) + } + if err := g.reserved(boot); err == nil { t.Fatal("a worker booted before DHCP applied the reservation") } - post("dhcp-a", feed.Reservations...) - if err := config.awaitReservation(short(), boot); err != nil { + g.apply("dhcp-a") + if err := g.reserved(boot); err != nil { t.Fatalf("applied reservation not seen: %v", err) } - post("dhcp-a") - if err := config.awaitWithdrawal(short(), store, device, boot); err == nil { - t.Fatal("a silent instance serving the held reservation did not block success") + g.close(boot) + g.apply("dhcp-a") + if err := g.withdrawn(boot); err == nil { + t.Fatal("dhcp-b, last serving the held reservation, did not block success") + } + g.apply("dhcp-b") + if err := g.withdrawn(boot); err != nil { + t.Fatalf("withdrawal after every instance reported: %v", err) } - if err := RetireInstance(server.BootRoot, "dhcp-b"); err != nil { + // A newer fence supersedes the admission: its reservation goes. + if err := g.store.Raise(device, 4); err != nil { t.Fatal(err) } - if err := config.awaitWithdrawal(short(), store, device, boot); err != nil { - t.Fatalf("withdrawal after retiring the silent instance: %v", err) + if feed, err := g.server.Reservations(); err != nil || len(feed.Reservations) != 0 { + t.Fatalf("feed after a newer fence = %+v, %v", feed, err) } - // A retired instance that reports again counts again. - post("dhcp-b", bootnet.Reservation{MAC: mac, Address: held.Address, Expires: now.Add(time.Hour)}) - if err := config.awaitWithdrawal(short(), store, device, boot); err == nil { - t.Fatal("a report after retirement was ignored") +} + +// TestOldRetainedLinesAreNoEvidence reads reports retained before feeds +// carried an issue time, and records of the removed retirement command. An +// old report reads as issued at the zero time, so it cannot prove a +// withdrawal; a retirement record is skipped and changes nothing. +func TestOldRetainedLinesAreNoEvidence(t *testing.T) { + g := newGate(t) + boot := g.admit("op-a", 1, address) + g.apply("dhcp-a") + g.close(boot) + g.apply("dhcp-a") + empty, _ := bootnet.NewFeed(nil) + at := g.now.Format(time.RFC3339) + old := `{"at":"` + at + `","instance":"dhcp-b","feed":{"revision":"` + empty.Revision + `","reservations":[]}}` + "\n" + retired := `{"at":"` + at + `","instance":"dhcp-b","feed":{"revision":"` + empty.Revision + `","reservations":[]},"retired":true}` + "\n" + if err := appendEvidence(g.server.BootRoot, dhcpLog, old+retired); err != nil { + t.Fatal(err) } - // A newer fence supersedes the admission: its reservation goes. - if err := store.Raise(device, 4); err != nil { + retained, err := reports(g.server.BootRoot) + if err != nil || len(retained) != 3 || !retained[2].Feed.Issued.IsZero() || retained[2].Instance != "dhcp-b" { + t.Fatalf("retained = %+v, %v", retained, err) + } + if err := g.withdrawn(boot); err == nil { + t.Fatal("a report without an issue time, or a retirement record, proved withdrawal") + } + g.apply("dhcp-b") + if err := appendEvidence(g.server.BootRoot, dhcpLog, retired); err != nil { t.Fatal(err) } - if feed, err := server.Reservations(); err != nil || len(feed.Reservations) != 0 { - t.Fatalf("feed after a newer fence = %+v, %v", feed, err) + if err := g.withdrawn(boot); err != nil { + t.Fatalf("a retirement record after dhcp-b's withdrawal report changed the outcome: %v", err) } } diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index cff5ca26..bad80066 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -71,9 +71,12 @@ type Config struct { PowerOffBound time.Duration // Synced means the site's DHCP is synchronized: a network boot waits // until DHCP applied the boot NIC's reservation, and the operation ends - // only once every DHCP instance that served it withdrew it. + // only once every expected DHCP instance reported it withdrawn. Synced bool - Now func() time.Time + // DHCPInstances is the enrollment's expected DHCP instance set. Only + // their reports count, and withdrawal needs every one of them. + DHCPInstances []string + Now func() time.Time } func (c Config) now() time.Time { @@ -258,7 +261,13 @@ type Boot struct { // Created is when the admission was created; DHCP reports before it // are not this operation's. Created time.Time `json:"created"` - Expires time.Time `json:"expires"` + // Published is the worker's clock read after the admission was first + // stored, before any network boot it admits. Every feed issued after it + // carries the reservation while the admission is open. Created is not + // enough: the clock is read before the admission is stored, so a feed + // issued between the two lacks the reservation without proving it gone. + Published time.Time `json:"published,omitempty"` + Expires time.Time `json:"expires"` // DurationSeconds is how long a burn-in image runs. Other modes omit it. DurationSeconds int64 `json:"durationSeconds,omitempty"` // Phase is the network-booting phase, set while it may boot. @@ -342,6 +351,10 @@ func (c Config) run(ctx context.Context, work *site.Work, phases []phase) ([]ops } if ph.mode != "" { boot.Phase = ph.name + // c.boot stored the admission, so this read follows it. + if boot.Published.IsZero() { + boot.Published = c.now().UTC() + } if err := c.saveBoot(work, boot); err != nil { return nil, err } From 6aacbd92ebd35ef98ce703cd42bc576e9fc28f18 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 21:18:02 -0600 Subject: [PATCH 09/17] feat(site): Block withdrawal on refused contacts Removing a name from dhcpInstances drops that instance from the withdrawal proof, but not its replica, which could keep serving its last reservations behind the shared load balancer. The feed now retains each authenticated contact it refuses for a missing or undeclared instance, {at, instance, rejected: true}, synced before the 403, at most once per instance name every 30 seconds. A failure to retain still refuses; unauthenticated requests are never recorded. The withdrawal gate blocks while any refused contact was retained at or after the admission was published, and passes no earlier than 45 seconds after it, so the rate limit cannot hide a replica that is still polling. Refused contacts are never evidence of serving or withdrawal. A replica whose synchronizer stopped while Kea keeps serving is still not seen; the docs state that limit. Co-Authored-By: Claude Opus 5.5 --- docs/operations/boot-network.md | 37 ++++-- internal/site/redfishwork/dhcp.go | 102 ++++++++++++++-- internal/site/redfishwork/dhcp_test.go | 159 ++++++++++++++++++++++++- internal/site/redfishwork/kinds.go | 5 +- 4 files changed, 279 insertions(+), 24 deletions(-) diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index 0b44daa1..c6ec6b8f 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -179,9 +179,21 @@ it. To retire one on purpose: 2. shrink `dhcpInstances` to match the Pods that remain; and 3. restart the site's workers and its feed, so both read the new set. -The feed then refuses the removed instance, and a later report from it is -rejected and not retained. An instance removed while it may still answer could -serve a reservation that nothing tracks, so check it first. +The feed then refuses the removed instance: a later report from it is +rejected and not retained as a report. Removing a name does not stop its +replica, and one still running behind the load balancer could keep serving +its last reservations. So the feed records each refused contact from a +synchronizer holding the site's token, at most once per instance name every +30 seconds, and the withdrawal proof refuses to pass while any contact was +recorded after the operation's admission was stored. It also waits at least +45 seconds after that, so the rate limit cannot hide a replica that is still +polling. Stopping an instance before removing it is therefore enforced for any +instance whose synchronizer still runs: its operations stay unknown until it +stops, and later operations pass. + +**Known limit:** the feed cannot see Pods, so a replica whose synchronizer +stopped while its Kea keeps serving is not detected. Making sure Kea no longer +answers before removing its name still rests on the operator. These gates do not depend on where Kea runs. The feed comes only from the site's admitted operations at the Device's stored fence, and every report @@ -203,7 +215,8 @@ refuses to start without one. Every request needs `Authorization: Bearer `; the token is at least 32 characters. - `GET /dhcp/v1/reservations` needs `X-Fleet-DHCP-Instance: ` naming an - expected instance; otherwise it is refused with `403` and nothing is served. + expected instance; otherwise it is refused with `403`, nothing is served and + the contact is recorded (see [Retiring a DHCP instance](#retiring-a-dhcp-instance)). It returns the canonical feed: `{"revision": "", "reservations": [{"mac", "address", "expires"}], "issued": ""}`. An address is one host address with no prefix. @@ -214,11 +227,16 @@ refuses to start without one. Every request needs `Authorization: Bearer - `POST /dhcp/v1/applied` takes `{"instance": "", "feed": }`, with the feed exactly as it was served. The feed must be canonical with a matching revision, and the instance must be expected; anything else is - rejected and not retained. An accepted report is synced to disk before - `204`. - -The retained log holds MACs, addresses, revisions, issue times and instance -names. It holds no token, receipt or boot capability. An unreadable line is + rejected and not retained as a report. A report from an instance outside + the set is recorded as a refused contact. An accepted report is synced to + disk before `204`. + +The retained log holds MACs, addresses, revisions, issue times, instance +names and refused contacts: `{"at", "instance", "rejected": true}`, synced +before the `403`, with an empty instance when the request named none. A +refused contact is never evidence that a reservation was served or withdrawn; +it only blocks the proof. A request without the site's token is never +recorded, and a contact that cannot be recorded is still refused. It holds no token, receipt or boot capability. An unreadable line is treated as corruption, never as evidence. A report retained before feeds carried an issue time counts as issued at the zero time, so it can never prove a withdrawal. A record left by the removed retirement command is ignored. @@ -353,6 +371,7 @@ requirements. | Boot NIC from Device inventory through the admission snapshot; enrollment without MACs or addresses | Implemented; unit tested | | Reservation feed, authenticated applied reports, served and withdrawn gates over every reservation of the Device | Implemented; unit tested with a fake BMC and synchronizer | | Expected DHCP instance set in the enrollment: the feed refuses other instances, withdrawal needs every expected instance's report of a feed issued after the admission, and retirement only by shrinking the set | Implemented; unit tested, including an instance that never reported and one that stopped after fetching the reservation. Restarting the workers and the feed after a change is an operator step | +| Refused contacts recorded and blocking withdrawal, so a removed instance whose synchronizer still polls keeps its operations unknown | Implemented; unit tested, including the rate limit, an unauthenticated request and a log that cannot be written. A removed replica whose synchronizer stopped while Kea serves is not detected | | Kea synchronizer: containing-subnet placement, restart re-apply, report only after Kea accepted | Implemented; unit tested against a fake Kea control socket | | Feed over TLS beside the boot service; Kea and the synchronizer as a central component, several instances behind one UDP 67 load balancer | Implemented; render checked in CI, and reservation-gated answers proved by the boot network lab with real Kea. Not deployed, and relayed requests across a WAN are not exercised | | Boot service and boot files in the central cluster, serving a UEFI HTTP boot loader | Proposed; the boot service runs in the site's boot Pod beside the site store, and serves the iPXE script but no EFI loader yet | diff --git a/internal/site/redfishwork/dhcp.go b/internal/site/redfishwork/dhcp.go index aac00baa..e514ccd0 100644 --- a/internal/site/redfishwork/dhcp.go +++ b/internal/site/redfishwork/dhcp.go @@ -12,6 +12,7 @@ import ( "os" "path/filepath" "strings" + "sync" "time" "go.datum.net/fleet/internal/bootnet" @@ -26,13 +27,37 @@ const withdrawalWindow = 10 * time.Minute const dhcpLog = "dhcp-applied.log" +// contactInterval is the least time between two retained refused contacts +// from one instance name, so a polling replica outside the expected set +// grows the log slowly. +const contactInterval = 30 * time.Second + +// contactQuiet is how long after an admission was published the withdrawal +// gate waits before it can pass: one contactInterval plus a synchronizer +// poll (five seconds by default; at most fifteen is assumed), so an instance +// still polling after the admission was published has a retained contact +// by then. +const contactQuiet = contactInterval + 15*time.Second + // report is one retained applied report: when the boot server accepted it, // and which DHCP instance applied which exact feed, as the feed server issued -// it. +// it. A Rejected record is instead an authenticated contact the feed refused +// because its instance was missing or outside the expected set: it has no +// feed, and its instance may be empty or not a valid name. It is never +// evidence that anything was served or withdrawn; it only shows that an +// instance the proof does not watch was still running at At. type report struct { At time.Time `json:"at"` Instance string `json:"instance"` Feed bootnet.Feed `json:"feed"` + Rejected bool `json:"rejected,omitempty"` +} + +// contact is how a refused contact is retained. +type contact struct { + At time.Time `json:"at"` + Instance string `json:"instance"` + Rejected bool `json:"rejected"` } // retainedLine is how a retained line is read. A line carrying "retired" was @@ -100,6 +125,32 @@ func (b BootServer) DHCPHandler(token string) (http.Handler, error) { return nil, errors.New("the DHCP feed needs the enrollment's expected DHCP instances") } allowed := expected(b.DHCPInstances) + var mu sync.Mutex + recorded := map[string]time.Time{} + // refuse retains, at most once per instance name per contactInterval, + // that an authenticated instance outside the expected set is still + // running, then answers 403 whether or not that was retained. + refuse := func(w http.ResponseWriter, instance string) { + if len(instance) > 253 { + instance = instance[:253] + } + mu.Lock() + now := b.now().UTC() + if last, ok := recorded[instance]; !ok || now.Sub(last) >= contactInterval { + if len(recorded) > 1024 { + for name, at := range recorded { + if now.Sub(at) >= contactInterval { + delete(recorded, name) + } + } + } + if b.retainContact(contact{At: now, Instance: instance, Rejected: true}) == nil { + recorded[instance] = now + } + } + mu.Unlock() + http.Error(w, "not an expected DHCP instance", http.StatusForbidden) + } return http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) { w.Header().Set("Cache-Control", "no-store") got, ok := strings.CutPrefix(request.Header.Get("Authorization"), "Bearer ") @@ -109,8 +160,8 @@ func (b BootServer) DHCPHandler(token string) (http.Handler, error) { } switch { case request.Method == http.MethodGet && request.URL.Path == "/dhcp/v1/reservations" && request.URL.RawQuery == "": - if !allowed[request.Header.Get(bootnet.InstanceHeader)] { - http.Error(w, "not an expected DHCP instance", http.StatusForbidden) + if instance := request.Header.Get(bootnet.InstanceHeader); !allowed[instance] { + refuse(w, instance) return } feed, err := b.Issue() @@ -129,7 +180,7 @@ func (b BootServer) DHCPHandler(token string) (http.Handler, error) { return } if !allowed[applied.Instance] { - http.Error(w, "not an expected DHCP instance", http.StatusForbidden) + refuse(w, applied.Instance) return } if err := b.retain(applied); err != nil { @@ -166,10 +217,20 @@ func (b BootServer) retain(applied bootnet.Applied) error { return appendEvidence(b.BootRoot, dhcpLog, string(data)+"\n") } +// retainContact appends one refused contact and syncs it. +func (b BootServer) retainContact(c contact) error { + data, err := json.Marshal(c) + if err != nil { + return err + } + return appendEvidence(b.BootRoot, dhcpLog, string(data)+"\n") +} + // reports reads every retained report in order. An unreadable line is // corruption, never evidence in either direction. A report retained before // feeds carried an issue time reads as issued at the zero time, so it can -// never prove a withdrawal. A retired line is skipped (see retainedLine). +// never prove a withdrawal. A retired line is skipped (see retainedLine). A +// rejected contact carries no feed to verify. func reports(root string) ([]report, error) { file, err := os.Open(filepath.Join(root, dhcpLog)) if os.IsNotExist(err) { @@ -184,7 +245,8 @@ func reports(root string) ([]report, error) { scanner.Buffer(make([]byte, 0, 64<<10), 1<<20) for scanner.Scan() { var line retainedLine - if json.Unmarshal(scanner.Bytes(), &line) != nil || line.At.IsZero() || (bootnet.Applied{Instance: line.Instance, Feed: line.Feed}).Verify() != nil { + if json.Unmarshal(scanner.Bytes(), &line) != nil || line.At.IsZero() || (line.Rejected && line.Retired) || + (!line.Rejected && (bootnet.Applied{Instance: line.Instance, Feed: line.Feed}).Verify() != nil) { return nil, errors.New("invalid retained DHCP report") } if !line.Retired { @@ -206,7 +268,7 @@ func (c Config) awaitReservation(ctx context.Context, boot Boot) error { return err } for _, r := range retained { - if allowed[r.Instance] && r.At.After(boot.Created) && r.Feed.Has(boot.MAC, boot.Address) { + if !r.Rejected && allowed[r.Instance] && r.At.After(boot.Created) && r.Feed.Has(boot.MAC, boot.Address) { return nil } } @@ -238,6 +300,14 @@ func (c Config) awaitReservation(ctx context.Context, boot Boot) error { // state volume. A success also proves that every earlier reservation for // the Device, such as a held operation's, is withdrawn. The only way past an // instance that is gone is to remove it from the expected set. +// +// Removing a name does not stop its replica. A removed replica whose +// synchronizer still polls is refused by the feed, which retains that +// contact, so the gate also blocks while any refused contact was retained +// after the admission was published, and passes no earlier than +// contactQuiet after it, by which time a still-polling replica has been +// retained despite the rate limit. A replica whose synchronizer stopped +// while its Kea keeps serving is not seen. func (c Config) awaitWithdrawal(ctx context.Context, store *site.Store, device string, boot Boot) error { poll, _, _, _ := c.durations() deadline := c.now().Add(withdrawalWindow) @@ -251,8 +321,14 @@ func (c Config) awaitWithdrawal(ctx context.Context, store *site.Store, device s if err != nil { return err } - served, latest := false, map[string]bootnet.Feed{} + served, contacted, latest := false, false, map[string]bootnet.Feed{} for _, r := range retained { + if r.Rejected { + if !r.At.Before(boot.Published) { + contacted = true + } + continue + } if !allowed[r.Instance] { continue } @@ -261,7 +337,7 @@ func (c Config) awaitWithdrawal(ctx context.Context, store *site.Store, device s } latest[r.Instance] = r.Feed } - withdrawn := served && !boot.Published.IsZero() && len(allowed) > 0 + withdrawn := served && !contacted && !boot.Published.IsZero() && len(allowed) > 0 && !c.now().Before(boot.Published.Add(c.quiet())) for instance := range allowed { feed, reported := latest[instance] if !reported || !feed.Issued.After(boot.Published) { @@ -308,3 +384,11 @@ func publishedFor(store *site.Store, device string) ([]Boot, error) { } return out, nil } + +// quiet is contactQuiet unless a test shortens it. +func (c Config) quiet() time.Duration { + if c.ContactQuiet > 0 { + return c.ContactQuiet + } + return contactQuiet +} diff --git a/internal/site/redfishwork/dhcp_test.go b/internal/site/redfishwork/dhcp_test.go index c2ef7d75..efd02ab6 100644 --- a/internal/site/redfishwork/dhcp_test.go +++ b/internal/site/redfishwork/dhcp_test.go @@ -120,10 +120,10 @@ func synced(r *site.Runner) { for name, kind := range r.Kinds { switch k := kind.(type) { case Installation: - k.Synced, k.DHCPInstances = true, []string{"dhcp-a"} + k.Synced, k.DHCPInstances, k.ContactQuiet = true, []string{"dhcp-a"}, time.Millisecond r.Kinds[name] = k case Wipe: - k.Synced, k.DHCPInstances = true, []string{"dhcp-a"} + k.Synced, k.DHCPInstances, k.ContactQuiet = true, []string{"dhcp-a"}, time.Millisecond r.Kinds[name] = k } } @@ -241,7 +241,7 @@ func newGate(t *testing.T) *gate { if g.handler, err = g.server.DHCPHandler(syncToken); err != nil { t.Fatal(err) } - g.config = Config{BootRoot: g.server.BootRoot, Poll: 5 * time.Millisecond, Now: clock, Synced: true, DHCPInstances: instances} + g.config = Config{BootRoot: g.server.BootRoot, Poll: 5 * time.Millisecond, Now: clock, Synced: true, DHCPInstances: instances, ContactQuiet: time.Second} return g } @@ -324,6 +324,155 @@ func (g *gate) reserved(boot Boot) error { return g.config.awaitReservation(ctx, boot) } +// applied is the retained applied reports, without refused contacts. +func applied(retained []report) []report { + var out []report + for _, r := range retained { + if !r.Rejected { + out = append(out, r) + } + } + return out +} + +// contacts is the retained refused contacts, by instance name. +func (g *gate) contacts() []string { + g.t.Helper() + retained, err := reports(g.server.BootRoot) + if err != nil { + g.t.Fatal(err) + } + var out []string + for _, r := range retained { + if r.Rejected { + out = append(out, r.Instance) + } + } + return out +} + +// removed is a handler of the same feed that still expects dhcp-c, as the +// feed did before dhcp-c was removed from the enrollment. +func (g *gate) removed() http.Handler { + g.t.Helper() + before := g.server + before.DHCPInstances = []string{"dhcp-a", "dhcp-b", "dhcp-c"} + handler, err := before.DHCPHandler(syncToken) + if err != nil { + g.t.Fatal(err) + } + return handler +} + +// TestARemovedInstanceStillPollingBlocksWithdrawal: dhcp-c was removed from +// the expected set while its replica still runs. Its last report served +// nothing, but it keeps polling the feed, which refuses and retains each +// contact, so withdrawal stays unproven. Once it stops, a later boot's +// withdrawal is proven. +func TestARemovedInstanceStillPollingBlocksWithdrawal(t *testing.T) { + g := newGate(t) + current := g.handler + g.handler = g.removed() + g.apply("dhcp-c") + g.handler = current + boot := g.admit("op-a", 1, address) + g.apply("dhcp-a") + g.apply("dhcp-b") + if code := g.serve("GET", "/dhcp/v1/reservations", "dhcp-c", "").Code; code != http.StatusForbidden { + t.Fatalf("removed instance's feed = %d", code) + } + g.close(boot) + g.apply("dhcp-a") + g.apply("dhcp-b") + if err := g.withdrawn(boot); err == nil { + t.Fatal("withdrawal proven while a removed instance still polls the feed") + } + // dhcp-c stopped. A later boot, published after its last contact, + // passes. + later := g.admit("op-b", 2, "192.0.2.21") + g.apply("dhcp-a") + g.apply("dhcp-b") + g.close(later) + g.apply("dhcp-a") + g.apply("dhcp-b") + if err := g.withdrawn(later); err != nil { + t.Fatalf("withdrawal after the removed instance stopped: %v", err) + } +} + +// TestTheRateLimitCannotHideAPollingInstance: contacts are retained at most +// once per contactInterval, so the gate cannot pass before contactQuiet +// after the admission was published; by then a still-polling instance has +// been retained again. +func TestTheRateLimitCannotHideAPollingInstance(t *testing.T) { + g := newGate(t) + g.config.ContactQuiet = 0 + g.serve("GET", "/dhcp/v1/reservations", "dhcp-c", "") + boot := g.admit("op-a", 1, address) + g.apply("dhcp-a") + g.apply("dhcp-b") + g.close(boot) + g.apply("dhcp-a") + g.apply("dhcp-b") + // dhcp-c polls again within the interval: refused, not retained. + g.serve("GET", "/dhcp/v1/reservations", "dhcp-c", "") + if got := g.contacts(); len(got) != 1 { + t.Fatalf("contacts = %q", got) + } + if err := g.withdrawn(boot); err == nil { + t.Fatal("withdrawal proven before a rate-limited contact could be retained") + } + g.now = g.now.Add(contactInterval) + g.serve("GET", "/dhcp/v1/reservations", "dhcp-c", "") + if err := g.withdrawn(boot); err == nil { + t.Fatal("withdrawal proven while a removed instance still polls the feed") + } +} + +// TestRefusedContactsAreRetainedOncePerInterval retains one record per +// instance name per contactInterval, for a missing name too, for a refused +// feed request and a refused report alike, and never for an unauthenticated +// request. A contact that cannot be retained is still refused. +func TestRefusedContactsAreRetainedOncePerInterval(t *testing.T) { + g := newGate(t) + request, _ := newRequest("GET", "/dhcp/v1/reservations", "") + request.Header.Set("Authorization", "Bearer wrong-token-wrong-token-wrong-token-0000") + request.Header.Set(bootnet.InstanceHeader, "dhcp-c") + recorder := httptest.NewRecorder() + g.handler.ServeHTTP(recorder, request) + if recorder.Code != http.StatusUnauthorized || len(g.contacts()) != 0 { + t.Fatalf("unauthenticated contact = %d, retained %q", recorder.Code, g.contacts()) + } + empty, _ := bootnet.NewFeed(nil) + for i := 0; i < 3; i++ { + g.serve("GET", "/dhcp/v1/reservations", "dhcp-c", "") + g.serve("GET", "/dhcp/v1/reservations", "", "") + if code := g.post("dhcp-c", empty); code != http.StatusForbidden { + t.Fatalf("report from a removed instance = %d", code) + } + g.tick() + } + if got := g.contacts(); len(got) != 2 || got[0] != "dhcp-c" || got[1] != "" { + t.Fatalf("contacts within one interval = %q", got) + } + g.now = g.now.Add(contactInterval) + g.post("dhcp-c", empty) + if got := g.contacts(); len(got) != 3 || got[2] != "dhcp-c" { + t.Fatalf("contacts after the interval = %q", got) + } + // The log cannot be written: still refused. + broken := g.server + broken.BootRoot = filepath.Join(g.server.BootRoot, dhcpLog) + handler, err := broken.DHCPHandler(syncToken) + if err != nil { + t.Fatal(err) + } + g.handler = handler + if code := g.serve("GET", "/dhcp/v1/reservations", "dhcp-d", "").Code; code != http.StatusForbidden { + t.Fatalf("an unretained contact = %d", code) + } +} + // TestTheFeedServesOnlyExpectedInstances refuses a feed request without an // instance or from an instance outside the expected set, and refuses and // does not retain such an instance's report. An expected instance gets the @@ -351,13 +500,13 @@ func TestTheFeedServesOnlyExpectedInstances(t *testing.T) { if code := g.post("dhcp-c", feed); code != http.StatusForbidden { t.Fatalf("report from an unexpected instance = %d", code) } - if retained, err := reports(g.server.BootRoot); err != nil || len(retained) != 0 { + if retained, err := reports(g.server.BootRoot); err != nil || len(applied(retained)) != 0 { t.Fatalf("an unexpected instance's report was retained: %+v, %v", retained, err) } if code := g.post("dhcp-a", feed); code != http.StatusNoContent { t.Fatalf("report from an expected instance = %d", code) } - if retained, err := reports(g.server.BootRoot); err != nil || len(retained) != 1 || !retained[0].Feed.Issued.Equal(feed.Issued) { + if retained, err := reports(g.server.BootRoot); err != nil || len(applied(retained)) != 1 || !applied(retained)[0].Feed.Issued.Equal(feed.Issued) { t.Fatalf("retained %+v, %v", retained, err) } if _, err := (BootServer{}).DHCPHandler(syncToken); err == nil { diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index bad80066..ed482d76 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -76,7 +76,10 @@ type Config struct { // DHCPInstances is the enrollment's expected DHCP instance set. Only // their reports count, and withdrawal needs every one of them. DHCPInstances []string - Now func() time.Time + // ContactQuiet replaces contactQuiet, the least time after an admission + // was published before withdrawal can be proven. Tests shorten it. + ContactQuiet time.Duration + Now func() time.Time } func (c Config) now() time.Time { From 7b0c00b6eb070ef63d17c04e659dfa145bb4531e Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 21:18:49 -0600 Subject: [PATCH 10/17] docs(site): Say affinity gives availability only Client-IP affinity sends all of one relay's traffic to one Kea instance, so the replicas give availability, not load sharing per relay. Co-Authored-By: Claude Opus 5.5 --- config/site/dhcp/component/dhcp.yaml | 5 ++++- docs/operations/boot-network.md | 6 ++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/config/site/dhcp/component/dhcp.yaml b/config/site/dhcp/component/dhcp.yaml index 075fe673..1e08f3b7 100644 --- a/config/site/dhcp/component/dhcp.yaml +++ b/config/site/dhcp/component/dhcp.yaml @@ -111,7 +111,10 @@ spec: # under its own stable name, so the withdrawal gate covers every expected one; # an instance that has not applied a reservation yet stays silent, because # Kea is not authoritative, and the firmware retries. Client-IP affinity -# keeps one relay's exchange on one instance. Kea replies to the relay +# sends all of one relay's traffic to one instance, so the replicas give +# availability, not load sharing per relay; a relay's retries keep reaching +# the same instance until its synchronizer applies the reservation, within +# one poll. Kea replies to the relay # address in each request; the site's relays must accept replies from the # cluster's egress address. apiVersion: v1 diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index c6ec6b8f..8b8811ec 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -280,8 +280,10 @@ Any instance may answer a request. Each applies the same feed through its own synchronizer and reports under its own name, so the power-on gate needs one expected instance serving and the withdrawal gate needs every expected instance. An instance that has not applied a reservation yet stays silent, -because Kea is not authoritative, and the firmware retries; client-IP affinity -keeps one relay's exchange on one instance. +because Kea is not authoritative, and the firmware retries. Client-IP affinity +sends all of one relay's traffic to one instance, so the replicas give +availability, not load sharing per relay, and a relay's retries keep reaching +that instance until its synchronizer applies the reservation, within one poll. Kea answers each relayed request at the relay address the request carries, on UDP 67. Its reply leaves through the cluster's egress, which is not always the From a1b120961b93d2fa880865192aedc57e53eab5e1 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 21:28:41 -0600 Subject: [PATCH 11/17] fix(dhcpsync): Re-report an unchanged feed An expected instance that applied the empty feed before an admission was published and never fetched the reservation's revision kept a latest report issued before publication, and never reported again, so the withdrawal proof waited forever on a healthy instance. The synchronizer now also reports its applied feed again, with the issue time of its latest fetch, once that time is newer than its last report's and the refresh interval (default 30 s, -refresh) has passed. A changed revision is still reported at once, and a refused report is not taken as sent. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-dhcp-sync/main.go | 9 +++--- internal/dhcpsync/sync.go | 35 +++++++++++++++++++--- internal/dhcpsync/sync_test.go | 53 ++++++++++++++++++++++++++++++++-- 3 files changed, 87 insertions(+), 10 deletions(-) diff --git a/cmd/fleet-dhcp-sync/main.go b/cmd/fleet-dhcp-sync/main.go index 4393540a..e52e468d 100644 --- a/cmd/fleet-dhcp-sync/main.go +++ b/cmd/fleet-dhcp-sync/main.go @@ -24,7 +24,7 @@ import ( func main() { var feed, tokenPath, caPath, instance, socket, base string - var interval time.Duration + var interval, refresh time.Duration flag.StringVar(&feed, "feed", "", "site DHCP feed origin, https://host[:port]") flag.StringVar(&tokenPath, "token-file", "", "file holding the synchronizer bearer token") flag.StringVar(&caPath, "ca-file", "", "PEM CA bundle the feed's certificate must chain to; default the system roots") @@ -32,15 +32,16 @@ func main() { flag.StringVar(&socket, "kea-socket", "/var/run/kea/kea4-ctrl-socket", "Kea DHCPv4 unix control socket; Kea 2.6 allows only /var/run/kea") flag.StringVar(&base, "base-config", "/etc/kea/kea-dhcp4.conf", "Kea configuration without Fleet reservations") flag.DurationVar(&interval, "interval", 5*time.Second, "feed poll interval") + flag.DurationVar(&refresh, "refresh", dhcpsync.DefaultRefresh, "least time between two reports of an unchanged applied feed") flag.Parse() logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) - if err := run(logger, feed, tokenPath, caPath, instance, socket, base, interval); err != nil && !errors.Is(err, context.Canceled) { + if err := run(logger, feed, tokenPath, caPath, instance, socket, base, interval, refresh); err != nil && !errors.Is(err, context.Canceled) { logger.Error("dhcp sync stopped", "error", err) os.Exit(1) } } -func run(logger *slog.Logger, feed, tokenPath, caPath, instance, socket, base string, interval time.Duration) error { +func run(logger *slog.Logger, feed, tokenPath, caPath, instance, socket, base string, interval, refresh time.Duration) error { u, err := url.Parse(feed) if err != nil || u.Scheme != "https" || u.Host == "" || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.User != nil { return errors.New("feed must be an https origin") @@ -63,7 +64,7 @@ func run(logger *slog.Logger, feed, tokenPath, caPath, instance, socket, base st transport.TLSClientConfig = &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12} } s := &dhcpsync.Syncer{ - Feed: u.Scheme + "://" + u.Host, Token: strings.TrimSpace(string(token)), Instance: instance, Socket: socket, Base: base, + Feed: u.Scheme + "://" + u.Host, Token: strings.TrimSpace(string(token)), Instance: instance, Socket: socket, Base: base, Refresh: refresh, HTTP: &http.Client{Timeout: 15 * time.Second, Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, } ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) diff --git a/internal/dhcpsync/sync.go b/internal/dhcpsync/sync.go index eebaa5ad..5b4365ff 100644 --- a/internal/dhcpsync/sync.go +++ b/internal/dhcpsync/sync.go @@ -29,14 +29,29 @@ type Syncer struct { Socket string // Kea's unix control socket Base string // Kea configuration without Fleet reservations HTTP *http.Client + // Refresh is the least time between two reports of one unchanged + // revision. It defaults to DefaultRefresh. + Refresh time.Duration + Now func() time.Time applied, reported string + reportedIssued time.Time + reportedAt time.Time pid float64 } +// DefaultRefresh is how often an unchanged applied feed is reported again. +const DefaultRefresh = 30 * time.Second + // Cycle fetches the feed, applies it when it changed or Kea restarted, and -// reports a newly applied revision. Any failure leaves the last report as the -// site's evidence; nothing is reported that Kea did not accept. +// reports it: at once when the applied revision changed, and otherwise again +// with the issue time of this fetch once Refresh has passed since the last +// report. The site proves withdrawal only from a report of a feed issued +// after the admission was published, so an instance whose applied revision +// never changed, because it never fetched the reservation, must still report +// a fresh issue. Any failure leaves the last report as the site's evidence, +// and a refused report is sent again on a later cycle; nothing is reported +// that Kea did not accept. func (s *Syncer) Cycle(ctx context.Context) error { feed, err := s.fetch(ctx) if err != nil { @@ -60,16 +75,28 @@ func (s *Syncer) Cycle(ctx context.Context) error { } s.applied, s.pid = feed.Revision, pid } - if s.reported == s.applied { + now := s.now() + refresh := s.Refresh + if refresh <= 0 { + refresh = DefaultRefresh + } + if s.reported == s.applied && (!feed.Issued.After(s.reportedIssued) || now.Sub(s.reportedAt) < refresh) { return nil } if err := s.report(ctx, feed); err != nil { return err } - s.reported = feed.Revision + s.reported, s.reportedIssued, s.reportedAt = feed.Revision, feed.Issued, now return nil } +func (s *Syncer) now() time.Time { + if s.Now != nil { + return s.Now() + } + return time.Now() +} + func (s *Syncer) request(ctx context.Context, method, path string, body []byte) (*http.Response, error) { q, err := http.NewRequestWithContext(ctx, method, s.Feed+path, bytes.NewReader(body)) if err != nil { diff --git a/internal/dhcpsync/sync_test.go b/internal/dhcpsync/sync_test.go index 3d9389a4..58ab00e7 100644 --- a/internal/dhcpsync/sync_test.go +++ b/internal/dhcpsync/sync_test.go @@ -79,6 +79,7 @@ type fakeSite struct { mu sync.Mutex feed bootnet.Feed served int + refuse bool reports []bootnet.Applied } @@ -109,6 +110,10 @@ func (f *fakeSite) handler(t *testing.T) http.Handler { w.WriteHeader(http.StatusBadRequest) return } + if f.refuse { + w.WriteHeader(http.StatusConflict) + return + } f.reports = append(f.reports, a) w.WriteHeader(http.StatusNoContent) } @@ -170,8 +175,8 @@ func TestAppliesReservationIntoItsContainingSubnetThenReports(t *testing.T) { t.Fatalf("report did not echo the served feed's issue time: %+v", reports) } // An unchanged feed, though issued later, is neither re-applied nor - // re-reported; a restarted - // Kea (new pid) lost its reservations and is re-applied without a report. + // re-reported before the refresh interval; a restarted Kea (new pid) + // lost its reservations and is re-applied without a report. if err := s.Cycle(ctx); err != nil || kea.applied() != 2 || len(site.reported()) != 2 { t.Fatalf("unchanged feed churned: %v", err) } @@ -187,6 +192,50 @@ func TestAppliesReservationIntoItsContainingSubnetThenReports(t *testing.T) { } } +// TestAnUnchangedFeedIsReportedAgainAfterTheRefreshInterval: an instance +// whose applied revision never changes still reports, once per refresh +// interval, the feed with the issue time of its latest fetch, without +// applying it again. A refused report is sent again on the next cycle. +func TestAnUnchangedFeedIsReportedAgainAfterTheRefreshInterval(t *testing.T) { + s, kea, site := newSyncer(t) + ctx := context.Background() + now := time.Date(2030, 1, 1, 0, 0, 0, 0, time.UTC) + s.Now = func() time.Time { return now } + if err := s.Cycle(ctx); err != nil || len(site.reported()) != 1 { + t.Fatalf("first report: %v", err) + } + now = now.Add(DefaultRefresh - time.Second) + if err := s.Cycle(ctx); err != nil || len(site.reported()) != 1 { + t.Fatalf("re-reported before the refresh interval: %v, %d", err, len(site.reported())) + } + now = now.Add(time.Second) + if err := s.Cycle(ctx); err != nil || len(site.reported()) != 2 || kea.applied() != 1 { + t.Fatalf("not re-reported after the refresh interval, or re-applied: %v, %d reports, %d applies", err, len(site.reported()), kea.applied()) + } + if r := site.reported(); r[1].Feed.Revision != r[0].Feed.Revision || !r[1].Feed.Issued.Equal(issuedBase.Add(3*time.Second)) { + t.Fatalf("refreshed report = %+v, want the latest fetch's issue time", r[1].Feed) + } + // The site refuses a report: it is not believed sent. + site.mu.Lock() + site.refuse = true + site.mu.Unlock() + now = now.Add(DefaultRefresh) + if err := s.Cycle(ctx); err == nil { + t.Fatal("a refused report was not an error") + } + site.mu.Lock() + site.refuse = false + site.mu.Unlock() + if err := s.Cycle(ctx); err != nil || len(site.reported()) != 3 || !site.reported()[2].Feed.Issued.Equal(issuedBase.Add(5*time.Second)) { + t.Fatalf("refused report not sent again with the next fetch: %v, %+v", err, site.reported()) + } + // A changed revision is reported at once, inside the interval. + site.set(t, reservation) + if err := s.Cycle(ctx); err != nil || len(site.reported()) != 4 || !site.reported()[3].Feed.Has(reservation.MAC, reservation.Address) { + t.Fatalf("changed revision not reported at once: %v", err) + } +} + func TestNothingIsReportedThatKeaDidNotAccept(t *testing.T) { s, kea, site := newSyncer(t) ctx := context.Background() From 84adb8ad196786a7cc726c63bb2b57627f021240 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 21:28:41 -0600 Subject: [PATCH 12/17] fix(site): Accept only reports of served feeds A token holder could post an empty feed with any issue time and satisfy the withdrawal proof. The feed now remembers, in memory, the last 32 (issue time, revision) pairs it served to each instance and refuses with 409, without retaining it, a report matching none. After a feed restart reports are refused until the instance fetches again. Co-Authored-By: Claude Opus 5.5 --- internal/site/redfishwork/dhcp.go | 39 +++++++++++++++++ internal/site/redfishwork/dhcp_test.go | 59 ++++++++++++++++++++++++++ 2 files changed, 98 insertions(+) diff --git a/internal/site/redfishwork/dhcp.go b/internal/site/redfishwork/dhcp.go index e514ccd0..94132997 100644 --- a/internal/site/redfishwork/dhcp.go +++ b/internal/site/redfishwork/dhcp.go @@ -39,6 +39,15 @@ const contactInterval = 30 * time.Second // by then. const contactQuiet = contactInterval + 15*time.Second +// issuesKept is how many served feeds the feed remembers per instance. +const issuesKept = 32 + +// issue is one feed the feed server served: a report must echo one. +type issue struct { + issued time.Time + revision string +} + // report is one retained applied report: when the boot server accepted it, // and which DHCP instance applied which exact feed, as the feed server issued // it. A Rejected record is instead an authenticated contact the feed refused @@ -117,6 +126,14 @@ func (b BootServer) Issue() (bootnet.Feed, error) { // to, and retains a report only from, an instance in the enrollment's // expected set, so an instance outside it never gets a reservation to // serve; a feed request names its instance in bootnet.InstanceHeader. +// +// A report is retained only if it echoes a feed this handler served to the +// same instance, by issue time and revision, among the last issuesKept it +// served it; any other is refused with 409 and not retained. So a report's +// issue time is one the site's clock gave, never one a token holder chose. +// The handler remembers issues in memory only: after a restart, reports are +// refused until the instance fetches again, which its synchronizer does on +// its next cycle before it reports again. func (b BootServer) DHCPHandler(token string) (http.Handler, error) { if len(token) < 32 || strings.ContainsAny(token, " \t\r\n") { return nil, errors.New("the DHCP synchronizer token must be at least 32 characters without whitespace") @@ -127,6 +144,8 @@ func (b BootServer) DHCPHandler(token string) (http.Handler, error) { allowed := expected(b.DHCPInstances) var mu sync.Mutex recorded := map[string]time.Time{} + var issuedMu sync.Mutex + issues := map[string][]issue{} // refuse retains, at most once per instance name per contactInterval, // that an authenticated instance outside the expected set is still // running, then answers 403 whether or not that was retained. @@ -169,6 +188,14 @@ func (b BootServer) DHCPHandler(token string) (http.Handler, error) { http.Error(w, "reservations unavailable", http.StatusServiceUnavailable) return } + instance := request.Header.Get(bootnet.InstanceHeader) + issuedMu.Lock() + kept := append(issues[instance], issue{issued: feed.Issued, revision: feed.Revision}) + if len(kept) > issuesKept { + kept = kept[len(kept)-issuesKept:] + } + issues[instance] = kept + issuedMu.Unlock() w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(feed) case request.Method == http.MethodPost && request.URL.Path == "/dhcp/v1/applied" && request.URL.RawQuery == "": @@ -183,6 +210,18 @@ func (b BootServer) DHCPHandler(token string) (http.Handler, error) { refuse(w, applied.Instance) return } + served := false + issuedMu.Lock() + for _, i := range issues[applied.Instance] { + if i.issued.Equal(applied.Feed.Issued) && i.revision == applied.Feed.Revision { + served = true + } + } + issuedMu.Unlock() + if !served { + http.Error(w, "the report echoes no feed served to this instance", http.StatusConflict) + return + } if err := b.retain(applied); err != nil { http.Error(w, "applied report not retained", http.StatusServiceUnavailable) return diff --git a/internal/site/redfishwork/dhcp_test.go b/internal/site/redfishwork/dhcp_test.go index efd02ab6..240031da 100644 --- a/internal/site/redfishwork/dhcp_test.go +++ b/internal/site/redfishwork/dhcp_test.go @@ -473,6 +473,65 @@ func TestRefusedContactsAreRetainedOncePerInterval(t *testing.T) { } } +// TestAReportMustEchoAServedFeed refuses, and does not retain, a report +// whose issue time and revision the feed never served to that instance: a +// forged future issue time, or a feed served to another instance. After the +// feed restarts it remembers nothing, so an earlier fetch is refused, and +// the next fetch and report are accepted. +func TestAReportMustEchoAServedFeed(t *testing.T) { + g := newGate(t) + fetched := g.fetch("dhcp-a") + forged := fetched + forged.Issued = g.now.Add(365 * 24 * time.Hour) + if code := g.post("dhcp-a", forged); code != http.StatusConflict { + t.Fatalf("report with a forged issue time = %d", code) + } + if code := g.post("dhcp-b", fetched); code != http.StatusConflict { + t.Fatalf("report of a feed served to another instance = %d", code) + } + if retained, _ := reports(g.server.BootRoot); len(retained) != 0 { + t.Fatalf("a refused report was retained: %+v", retained) + } + restarted, err := g.server.DHCPHandler(syncToken) + if err != nil { + t.Fatal(err) + } + g.handler = restarted + if code := g.post("dhcp-a", fetched); code != http.StatusConflict { + t.Fatalf("report of a feed served before the restart = %d", code) + } + g.tick() + if feed := g.apply("dhcp-a"); !feed.Issued.After(fetched.Issued) { + t.Fatalf("refetched feed issued %v", feed.Issued) + } + if retained, _ := reports(g.server.BootRoot); len(retained) != 1 { + t.Fatalf("retained %+v", retained) + } +} + +// TestARefreshedReportProvesWithdrawal: dhcp-b applied the empty feed before +// the admission was published and never fetched the reservation's revision. +// After the admission closes the revision is the same as its last report's, +// and its refreshed report, of a feed issued after publication, proves +// withdrawal. +func TestARefreshedReportProvesWithdrawal(t *testing.T) { + g := newGate(t) + before := g.apply("dhcp-b") + boot := g.admit("op-a", 1, address) + g.apply("dhcp-a") + g.close(boot) + g.apply("dhcp-a") + if err := g.withdrawn(boot); err == nil { + t.Fatal("withdrawal proven from dhcp-b's report before publication") + } + if refreshed := g.apply("dhcp-b"); refreshed.Revision != before.Revision || !refreshed.Issued.After(boot.Published) { + t.Fatalf("refreshed feed = %+v, earlier %+v", refreshed, before) + } + if err := g.withdrawn(boot); err != nil { + t.Fatalf("withdrawal after dhcp-b's refreshed report: %v", err) + } +} + // TestTheFeedServesOnlyExpectedInstances refuses a feed request without an // instance or from an instance outside the expected set, and refuses and // does not retain such an instance's report. An expected instance gets the From 4f2bdf288c9d7546d4551d10b2371a7afbc04f11 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 21:28:42 -0600 Subject: [PATCH 13/17] docs(site): Say published, one clock and refresh The withdrawal rule compares against the admission's publication time. The single-clock assumption rests on the feed and workers sharing a ReadWriteOnce volume, so one node. State the refresh interval and the log growth it causes, the 409 for unbound reports, and that production Kea uses a UDP socket with NET_BIND_SERVICE only. Co-Authored-By: Claude Opus 5.5 --- docs/operations/boot-network.md | 36 +++++++++++++++++++++++++-------- docs/operations/redfish-lab.md | 4 +++- 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index 8b8811ec..f86a7cda 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -154,19 +154,31 @@ Only reports from expected instances count. 2. **Before reporting success** it waits, for up to ten minutes, until some expected instance served the reservation during this operation, and every expected instance's latest report is of a feed issued after the admission - was stored that serves no MAC or address the site ever published for the - Device. That covers an earlier, held operation's reservation, so a later + was published that serves no MAC or address the site ever published for + the Device. An admission is published when the worker reads its clock + after storing it, before the network boot. That covers an earlier, held operation's reservation, so a later success settles the hold safely. Past ten minutes the outcome is unknown. Every feed carries the time the feed server issued it. While the admission is -open, every feed issued after it was stored carries the reservation, so a +open, every feed issued after it was published carries the reservation, so a report of a later feed without it proves the instance dropped it, and every later feed lacks it too. An instance that fetched a feed with the reservation and stopped before reporting still has a latest report that is older than the admission or serves the reservation, so it keeps the outcome unknown. So does an expected instance that never reported. Issue times are the feed's clock and -admission times the worker's, so both roles must run on the same clock; they -share the site's state volume. +publication times the worker's, so both must read the same clock. This +assumes the feed and the workers run on one node: they mount the site's state +volume, which is ReadWriteOnce. A site whose feed and workers run on +different nodes needs synchronized clocks, and the proof is only as good as +that synchronization. + +An expected instance whose applied feed does not change still reports it +again, with the issue time of its latest fetch, once every refresh interval +(30 seconds by default, `fleet-dhcp-sync -refresh`). So an instance that +never fetched the reservation, because it restarted or a fetch failed while +the admission was open, still proves the withdrawal once it reports a feed +issued after publication. The retained log grows by about one line per +instance per refresh interval, plus one per changed revision. ### Retiring a DHCP instance @@ -185,7 +197,7 @@ replica, and one still running behind the load balancer could keep serving its last reservations. So the feed records each refused contact from a synchronizer holding the site's token, at most once per instance name every 30 seconds, and the withdrawal proof refuses to pass while any contact was -recorded after the operation's admission was stored. It also waits at least +recorded after the operation's admission was published. It also waits at least 45 seconds after that, so the rate limit cannot hide a replica that is still polling. Stopping an instance before removing it is therefore enforced for any instance whose synchronizer still runs: its operations stay unknown until it @@ -227,7 +239,12 @@ refuses to start without one. Every request needs `Authorization: Bearer - `POST /dhcp/v1/applied` takes `{"instance": "", "feed": }`, with the feed exactly as it was served. The feed must be canonical with a matching revision, and the instance must be expected; anything else is - rejected and not retained as a report. A report from an instance outside + rejected and not retained as a report. The feed remembers, in memory, the + last 32 feeds it served to each instance, and refuses with `409` a report + whose issue time and revision match none of them, so a report's issue time + is always one the feed gave. After the feed restarts, reports are refused + until the instance fetches again, which its synchronizer does on its next + cycle before it reports again. A report from an instance outside the set is recorded as a refused contact. An accepted report is synced to disk before `204`. @@ -255,7 +272,9 @@ cycle it: 3. when the revision changed or Kea restarted, adds each reservation to the one base subnet that contains its address and sends `config-set` over Kea's control socket; -4. reports the feed, unchanged, only after Kea accepted it, once per revision. +4. reports the feed, unchanged, only after Kea accepted it: at once when the + revision changed, and otherwise again once the refresh interval has passed + since its last report. A refused report is sent again on a later cycle. The base configuration supplies each subnet's prefix, gateway (`routers`) and boot options. A reservation that no base subnet contains, or that two contain, @@ -372,6 +391,7 @@ requirements. | Boot addresses claimed from IPAM per operation, checked at admission, and released only after the operation ended unheld | Implemented; tested against a real API server with a stand-in for IPAM's claim API. No run sets a class, and IPAM itself is not exercised | | Boot NIC from Device inventory through the admission snapshot; enrollment without MACs or addresses | Implemented; unit tested | | Reservation feed, authenticated applied reports, served and withdrawn gates over every reservation of the Device | Implemented; unit tested with a fake BMC and synchronizer | +| Reports bound to feeds the feed served, and refreshed reports of an unchanged feed | Implemented; unit tested, including a forged issue time, another instance's feed, a feed restart and an instance that never fetched the reservation | | Expected DHCP instance set in the enrollment: the feed refuses other instances, withdrawal needs every expected instance's report of a feed issued after the admission, and retirement only by shrinking the set | Implemented; unit tested, including an instance that never reported and one that stopped after fetching the reservation. Restarting the workers and the feed after a change is an operator step | | Refused contacts recorded and blocking withdrawal, so a removed instance whose synchronizer still polls keeps its operations unknown | Implemented; unit tested, including the rate limit, an unauthenticated request and a log that cannot be written. A removed replica whose synchronizer stopped while Kea serves is not detected | | Kea synchronizer: containing-subnet placement, restart re-apply, report only after Kea accepted | Implemented; unit tested against a fake Kea control socket | diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index 47b43560..f9c94577 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -355,7 +355,9 @@ exercises boot addresses, reservations and Kea end to end in the lab: `kea-dhcp4-server` from the site image, which is native to the arm64 lab; ISC's image is amd64 only. Kea is not privileged: it adds only `NET_RAW` and `NET_BIND_SERVICE`. It listens on `fleetpxe0` with a raw socket, has no pool, - and keeps its leases on the site volume. The synchronizer reports as the one + and keeps its leases on the site volume. The production component differs: + its Kea answers relayed requests on a UDP socket and adds only + `NET_BIND_SERVICE`. The synchronizer reports as the one fixed instance `lab-kea`, so a restarted runtime Pod never strands a withdrawal. In production Kea runs in a central cluster behind the site's relays; the lab has no WAN link or relay, so its Kea sits on the emulated From 1dd9e7ab3f4cd27e2a1c69482758a25acf13c3fe Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 17:14:46 -0600 Subject: [PATCH 14/17] test(multiplane): Key synchronized DHCP evidence by operation admission The site now keys each admission's records by its kind, name and fence, not by the operation's object UID. The synchronized DHCP check reads each operation's boot record and boot log under that key, and runs only in the scenario groups that release the lab target. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/acceptance-redfish.sh | 7 ++++--- hack/multiplane/redfish_steps.py | 14 +++++++++----- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/hack/multiplane/acceptance-redfish.sh b/hack/multiplane/acceptance-redfish.sh index 1c64e2c0..2772690f 100755 --- a/hack/multiplane/acceptance-redfish.sh +++ b/hack/multiplane/acceptance-redfish.sh @@ -72,10 +72,11 @@ if runs release; then step rebuild 1200 step wrong-location 300 step boot-denials 300 - # Synchronized lab DHCP (run.sh --synced-dhcp): every boot's reservation came - # from its own IPAM claim and Kea served it only while the boot was open. - [[ ${FLEET_LAB_DHCP:-static} != synced ]] || rf dhcp-synced 300 fi +# Synchronized lab DHCP (run.sh --synced-dhcp): every boot of the release group +# took its reservation from its own IPAM claim, and Kea served it only while the +# boot was open. +if runs release && [[ ${FLEET_LAB_DHCP:-static} == synced ]]; then rf dhcp-synced 300; fi step flux-final 900 rf isolation 600 ph evidence 600 python3 hack/multiplane/evidence.py "$state" diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index 41246002..b50e6115 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -499,7 +499,11 @@ def provider(*args): die('%s %s names a claim other than its own' % (o['kind'], o['metadata']['name'])) if not first <= tuple(int(x) for x in network['address'].split('.')) <= last: die('%s %s boot address %s is outside the lab IPAM range' % (o['kind'], o['metadata']['name'], network['address'])) - ops.append({'kind': o['kind'], 'name': o['metadata']['name'], 'uid': o['metadata']['uid'], 'phase': o.get('status', {}).get('phase'), + # The site keys each admission by kind, name and fence; an + # operation never admitted has no fence and no site records. + fence = o.get('status', {}).get('fence') + key = harness.operation_key(o['kind'], o['metadata']['name'], fence) if fence else '' + ops.append({'kind': o['kind'], 'name': o['metadata']['name'], 'key': key, 'phase': o.get('status', {}).get('phase'), 'address': network['address'], 'claim': network['addressClaim']['name'], 'snapshotMAC': (o.get('status', {}).get('snapshot') or {}).get('bootMACAddress', '').lower()}) kinds = [o['kind'] for o in ops] @@ -535,9 +539,9 @@ def serves(report, address): network_boots = {o['operation'] for o in journal(s) if any(n in ('installer-power-on', 'wipe-power-on') for n, _ in o['steps'])} record = {'observedAt': now(), 'bootMAC': mac, 'operations': []} for o in ops: - boot = run('cat', '%s/boot/%s.json' % (device, o['uid'])) + boot = run('cat', '%s/boot/%s.json' % (device, o['key'])) if o['key'] else None entry = {k: o[k] for k in ('kind', 'name', 'phase', 'address')} - if boot.returncode: + if boot is None or boot.returncode: # Admitted but never run at the site, or refused before any # effect: no reservation was ever published for it. if o['phase'] not in ('Failed', 'Cancelled'): @@ -555,13 +559,13 @@ def serves(report, address): withdrawn = [r for r in applied if at(r['at']) > at(served[0]['at']) and not serves(r, o['address'])] if not withdrawn: die('%s %s: Kea never reported its reservation withdrawn' % (o['kind'], o['name'])) - delivered = run('sh', '-c', 'cat /var/lib/fleet-boot/%s/boot-delivery.log 2>/dev/null; true' % harness.key(o['uid'])).stdout + delivered = run('sh', '-c', 'cat /var/lib/fleet-boot/%s/boot-delivery.log 2>/dev/null; true' % harness.key(o['key'])).stdout # Kea leased this operation's address to the boot NIC inside this # operation's own window: after its boot opened and before Kea # withdrew its reservation, with five seconds for clock rounding. start, end = opened.timestamp() - 5, at(withdrawn[0]['at']).timestamp() + 5 leased = [g for a, m, g in granted if a == o['address'] and m == mac and start <= g <= end] - entry.update(published=True, servedAt=served[0]['at'], withdrawnAt=withdrawn[0]['at'], networkBoot=o['uid'] in network_boots, + entry.update(published=True, servedAt=served[0]['at'], withdrawnAt=withdrawn[0]['at'], networkBoot=o['key'] in network_boots, bootScriptDelivered='admitted boot.ipxe' in delivered, keaLeasesInWindow=len(leased)) if entry['networkBoot'] and not leased: die('%s %s powered on for a network boot, but Kea leased %s no address %s during its boot' % (o['kind'], o['name'], mac, o['address'])) From b2f37d69b99a5323c2e5dd156d574527eee2605e Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 18:30:30 -0600 Subject: [PATCH 15/17] test(site): Prove synchronized DHCP is off by default A render check builds every kustomization root under config/ and fails if any root other than the DHCP components, their example and the Redfish lab's synchronized mode renders a Kea server, the synchronizer, the reservation feed, a UDP 67 listener or a synced enrollment. Each opt-in root must render one, so the list stays exact. CI runs it beside the DHCP render check. The feed's refusal of a static enrollment moves into one function with a test. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 + cmd/fleet-multiplane/site.go | 19 ++++- cmd/fleet-multiplane/site_test.go | 23 ++++++ docs/operations/boot-network.md | 8 ++ hack/validate-network-boot-inactive.sh | 102 +++++++++++++++++++++++++ 5 files changed, 149 insertions(+), 4 deletions(-) create mode 100755 hack/validate-network-boot-inactive.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 37d73bd3..0e16be7a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -133,6 +133,7 @@ jobs: run: sudo apt-get update -qq && sudo apt-get install -y -qq --no-install-recommends ripgrep - run: ./hack/test-run-standalone-smoke.sh - run: ./hack/validate-site-dhcp-render.sh + - run: ./hack/validate-network-boot-inactive.sh - run: ./hack/validate-doc-links.sh - run: ./hack/multiplane/test-harness.sh - run: shellcheck -S warning hack/multiplane/*.sh hack/local-vm/start-libvirt hack/local-vm/site-runtime diff --git a/cmd/fleet-multiplane/site.go b/cmd/fleet-multiplane/site.go index c3d5e74e..b02fc188 100644 --- a/cmd/fleet-multiplane/site.go +++ b/cmd/fleet-multiplane/site.go @@ -266,13 +266,10 @@ func boot(command, origin, extraMAC, syncToken, tlsCert, tlsKey string) error { if err != nil { return err } - enrollment, err := redfish.ParseEnrollment([]byte(os.Getenv("FLEET_REDFISH_ENROLLMENT"))) + enrollment, err := feedEnrollment([]byte(os.Getenv("FLEET_REDFISH_ENROLLMENT"))) if err != nil { return err } - if enrollment.DHCP != redfish.DHCPSynced { - return errors.New("the DHCP reservation feed serves only a site whose enrollment has synced DHCP") - } token, err := os.ReadFile(syncToken) if err != nil { return fmt.Errorf("DHCP synchronizer token: %w", err) @@ -296,3 +293,17 @@ func boot(command, origin, extraMAC, syncToken, tlsCert, tlsKey string) error { // Emulated firmware takes minutes to fetch the installer. return serveBoot(vm.BootHandler(store), vmwork.DefaultBootWindow) } + +// feedEnrollment is the enrollment the DHCP reservation feed serves. Only a +// site whose enrollment has synced DHCP has a feed; the default, static, +// leaves DHCP to the site and starts no feed. +func feedEnrollment(raw []byte) (redfish.Enrollment, error) { + enrollment, err := redfish.ParseEnrollment(raw) + if err != nil { + return redfish.Enrollment{}, err + } + if enrollment.DHCP != redfish.DHCPSynced { + return redfish.Enrollment{}, errors.New("the DHCP reservation feed serves only a site whose enrollment has synced DHCP") + } + return enrollment, nil +} diff --git a/cmd/fleet-multiplane/site_test.go b/cmd/fleet-multiplane/site_test.go index 4a6e6c32..d0b8d065 100644 --- a/cmd/fleet-multiplane/site_test.go +++ b/cmd/fleet-multiplane/site_test.go @@ -43,3 +43,26 @@ func TestARedfishSiteRunsPowerOperations(t *testing.T) { } } } + +// syntheticEnrollment is a one-target site enrollment with the given DHCP +// fields. +func syntheticEnrollment(dhcp string) []byte { + return []byte(`{` + dhcp + `"targets":[{"device":"fleet-provider/server-example-001","endpoint":"https://192.0.2.10:8443","systemID":"System-1",` + + `"systemUUID":"00000000-0000-4000-8000-000000000001","diskBytes":2147483648,"console":"server-example-001.log"}]}`) +} + +// TestTheDHCPFeedStartsOnlyForSyncedDHCP refuses to start the reservation +// feed for an enrollment that leaves DHCP to the site, or names no DHCP +// mode. +func TestTheDHCPFeedStartsOnlyForSyncedDHCP(t *testing.T) { + if _, err := feedEnrollment(syntheticEnrollment(`"dhcp":"static",`)); err == nil || !strings.Contains(err.Error(), "synced DHCP") { + t.Errorf("static DHCP: the feed started: %v", err) + } + if _, err := feedEnrollment(syntheticEnrollment(``)); err == nil { + t.Error("no DHCP mode: the feed started") + } + enrollment, err := feedEnrollment(syntheticEnrollment(`"dhcp":"synced","dhcpInstances":["fleet-site-dhcp-0"],`)) + if err != nil || len(enrollment.DHCPInstances) != 1 { + t.Fatalf("synced DHCP: %+v, %v", enrollment, err) + } +} diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index f86a7cda..daba5283 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -337,6 +337,14 @@ Pods. configuration, and `hack/validate-site-dhcp-render.sh` checks that render in CI. ISC builds the Kea image for `linux/amd64` only. +Synchronized DHCP is off by default. No overlay or site base includes either +component, a site enrollment must name its `dhcp` mode, and the feed refuses +to start for a `static` enrollment. In CI, +`hack/validate-network-boot-inactive.sh` renders every kustomization root under +`config/`. It checks that only the DHCP components, their example and the +Redfish lab's synchronized mode render a Kea server, the synchronizer, the +feed, a UDP 67 listener or a synced enrollment. + ## Network operations requirements Fleet configures no switch, router or relay. A synchronized site needs: diff --git a/hack/validate-network-boot-inactive.sh b/hack/validate-network-boot-inactive.sh new file mode 100755 index 00000000..c78d246e --- /dev/null +++ b/hack/validate-network-boot-inactive.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash +# Synchronized DHCP is opt in (docs/operations/boot-network.md). Renders every +# kustomization root under config/ and checks that only the opt-in roots +# listed here start any part of it: a Kea server, the reservation +# synchronizer, the reservation feed, a DHCP listener on UDP 67, or a site +# enrollment with synced DHCP. Every other root, including every overlay an +# environment deploys, renders none of them. Each opt-in root must render one, +# so the list stays exact. +set -euo pipefail +cd "$(dirname "$0")/.." +opt_in=( + config/site/dhcp/component + config/site/dhcp/example + config/site/dhcp/feed + config/site/redfish/synced/graph + config/site/redfish/synced/services +) +roots=$(find config -name kustomization.yaml -exec dirname {} \; | sort) +python3 - "${opt_in[*]}" $roots <<'PY' +import json, subprocess, sys +import yaml + +opt_in = set(sys.argv[1].split()) +roots = sys.argv[2:] +missing = opt_in - set(roots) +assert not missing, 'opt-in roots that do not exist: %s' % sorted(missing) + + +def strings(value): + if isinstance(value, dict): + for v in value.values(): + yield from strings(v) + elif isinstance(value, list): + for v in value: + yield from strings(v) + elif isinstance(value, str): + yield value + + +def containers(value): + if isinstance(value, dict): + for key in ('containers', 'initContainers'): + for c in value.get(key) or []: + if isinstance(c, dict): + yield c + for v in value.values(): + yield from containers(v) + elif isinstance(value, list): + for v in value: + yield from containers(v) + + +def synced(text): + # A site enrollment is JSON; a synced one names "dhcp": "synced". + if '"dhcp"' not in text: + return False + try: + return json.loads(text).get('dhcp') == 'synced' + except (ValueError, AttributeError): + return False + + +def found(doc): + out = set() + for c in containers(doc): + command = [str(a) for a in (c.get('command') or []) + (c.get('args') or [])] + if 'kea-dhcp4' in str(c.get('image', '')): + out.add('Kea server') + if any(a.endswith('fleet-dhcp-sync') for a in command): + out.add('reservation synchronizer') + if command[:2] == ['fleet-multiplane', 'dhcp-feed']: + out.add('reservation feed') + if doc.get('kind') == 'Service': + # Built alone, the feed component renders only its Service. + if (doc.get('metadata') or {}).get('name') == 'fleet-site-dhcp-feed': + out.add('reservation feed') + for port in (doc.get('spec') or {}).get('ports') or []: + if port.get('port') == 67 and port.get('protocol', 'TCP') == 'UDP': + out.add('DHCP listener') + if any(synced(s) for s in strings(doc)): + out.add('synced enrollment') + return out + + +failures = [] +for root in roots: + render = subprocess.run(['kustomize', 'build', root], capture_output=True, text=True) + if render.returncode: + failures.append('%s does not render: %s' % (root, render.stderr.strip()[-300:])) + continue + parts = set() + for doc in yaml.safe_load_all(render.stdout): + if doc: + parts |= found(doc) + if root in opt_in and not parts: + failures.append('%s is listed as opt in but renders no synchronized DHCP' % root) + if root not in opt_in and parts: + failures.append('%s renders %s, which only an opt-in root may' % (root, ', '.join(sorted(parts)))) +if failures: + sys.exit('FAIL network boot inactive by default:\n ' + '\n '.join(failures)) +print('PASS network boot inactive by default: %d roots render no synchronized DHCP; only the %d opt-in roots do' % (len(roots) - len(opt_in), len(opt_in))) +PY From f9664ed269ef96cb4d8e363ca2b748bf3fa62af4 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 19:30:02 -0600 Subject: [PATCH 16/17] test(site): Close gaps in the network boot render check The check now finds the feed and the synchronizer by binary name, by path or inside a shell command, and Kea by image or command. It flags UDP 67 on a container or a Service's target port, the lab's synced DHCP switch, and any role granting IPAM permissions outside the boot address roles. It also renders roots under every kustomization file name. The synchronized DHCP evidence skips refused contacts, which carry no feed, and the boot network doc says which lab mode sets a boot address class. Co-Authored-By: Claude Opus 5.5 --- docs/operations/boot-network.md | 14 +++++----- hack/multiplane/redfish_steps.py | 3 ++- hack/validate-network-boot-inactive.sh | 37 +++++++++++++++++++------- 3 files changed, 37 insertions(+), 17 deletions(-) diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index daba5283..6325ac77 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -35,8 +35,9 @@ without the other, and needs a dedicated provisioning network on the boot NIC. When the allocator is configured with a provisioning IPAM class, each requester claims a boot address before it creates its operation. The multi-plane -composition takes the class from its `BootAddressClass` setting; the lab leaves -it empty because its DHCP is static. Each requester is: +composition takes the class from its `BootAddressClass` setting. The lab leaves +it empty in its default, static DHCP mode and sets it only in its synchronized +DHCP mode. Each requester is: - the Metal provider, for a `DeviceInstallation`; and - the release controller, for a `DeviceWipe`. @@ -337,13 +338,14 @@ Pods. configuration, and `hack/validate-site-dhcp-render.sh` checks that render in CI. ISC builds the Kea image for `linux/amd64` only. -Synchronized DHCP is off by default. No overlay or site base includes either -component, a site enrollment must name its `dhcp` mode, and the feed refuses +Synchronized DHCP is off by default. Outside the opt-in roots below, no +overlay or site base includes either component, a site enrollment must name its `dhcp` mode, and the feed refuses to start for a `static` enrollment. In CI, `hack/validate-network-boot-inactive.sh` renders every kustomization root under `config/`. It checks that only the DHCP components, their example and the Redfish lab's synchronized mode render a Kea server, the synchronizer, the -feed, a UDP 67 listener or a synced enrollment. +feed, a UDP 67 listener, or a synced enrollment or lab switch, and that only +the boot address roles grant IPAM permissions. ## Network operations requirements @@ -396,7 +398,7 @@ requirements. | Behavior | Status | | --- | --- | -| Boot addresses claimed from IPAM per operation, checked at admission, and released only after the operation ended unheld | Implemented; tested against a real API server with a stand-in for IPAM's claim API. No run sets a class, and IPAM itself is not exercised | +| Boot addresses claimed from IPAM per operation, checked at admission, and released only after the operation ended unheld | Implemented; tested against a real API server with a stand-in for IPAM's claim API. Only the lab's synchronized DHCP mode sets a class, against a stand-in, and IPAM itself is not exercised | | Boot NIC from Device inventory through the admission snapshot; enrollment without MACs or addresses | Implemented; unit tested | | Reservation feed, authenticated applied reports, served and withdrawn gates over every reservation of the Device | Implemented; unit tested with a fake BMC and synchronizer | | Reports bound to feeds the feed served, and refreshed reports of an unchanged feed | Implemented; unit tested, including a forged issue time, another instance's feed, a feed restart and an instance that never fetched the reservation | diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index b50e6115..94c24df7 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -519,7 +519,8 @@ def provider(*args): def run(*command, container='libvirt'): return kubectl(s, '-n', SITE, 'exec', 'deploy/fleet-site-runtime', '-c', container, '--', *command, check=False, timeout=120) device = harness.device_dir() - applied = [json.loads(l) for l in run('cat', '/var/lib/fleet-boot/dhcp-applied.log').stdout.splitlines() if l.strip()] + # The log also keeps refused contacts, which carry no feed. + applied = [r for r in (json.loads(l) for l in run('cat', '/var/lib/fleet-boot/dhcp-applied.log').stdout.splitlines() if l.strip()) if not r.get('rejected')] if not applied or {r['instance'] for r in applied} != {'lab-kea'}: die('the site retained no applied report, or one from an instance other than lab-kea') if not all(r['feed'].get('issued', '0001-01-01T00:00:00Z') != '0001-01-01T00:00:00Z' for r in applied): diff --git a/hack/validate-network-boot-inactive.sh b/hack/validate-network-boot-inactive.sh index c78d246e..ae0de758 100755 --- a/hack/validate-network-boot-inactive.sh +++ b/hack/validate-network-boot-inactive.sh @@ -2,20 +2,22 @@ # Synchronized DHCP is opt in (docs/operations/boot-network.md). Renders every # kustomization root under config/ and checks that only the opt-in roots # listed here start any part of it: a Kea server, the reservation -# synchronizer, the reservation feed, a DHCP listener on UDP 67, or a site -# enrollment with synced DHCP. Every other root, including every overlay an +# synchronizer, the reservation feed, a DHCP listener on UDP 67, a site +# enrollment or lab switch with synced DHCP, or a grant of IPAM permissions +# for boot address claims. Every other root, including every overlay an # environment deploys, renders none of them. Each opt-in root must render one, # so the list stays exact. set -euo pipefail cd "$(dirname "$0")/.." opt_in=( + config/components/boot-addresses config/site/dhcp/component config/site/dhcp/example config/site/dhcp/feed config/site/redfish/synced/graph config/site/redfish/synced/services ) -roots=$(find config -name kustomization.yaml -exec dirname {} \; | sort) +roots=$(find config \( -name kustomization.yaml -o -name kustomization.yml -o -name Kustomization \) -exec dirname {} \; | sort -u) python3 - "${opt_in[*]}" $roots <<'PY' import json, subprocess, sys import yaml @@ -64,19 +66,34 @@ def found(doc): out = set() for c in containers(doc): command = [str(a) for a in (c.get('command') or []) + (c.get('args') or [])] - if 'kea-dhcp4' in str(c.get('image', '')): + text = ' '.join(command) + names = [a.rsplit('/', 1)[-1] for a in command] + image = str(c.get('image', '')).rsplit('/', 1)[-1] + # By binary name, by path or inside a shell command. + if image.startswith('kea') or 'kea-dhcp4' in text: out.add('Kea server') - if any(a.endswith('fleet-dhcp-sync') for a in command): + if 'fleet-dhcp-sync' in names or 'fleet-dhcp-sync' in text: out.add('reservation synchronizer') - if command[:2] == ['fleet-multiplane', 'dhcp-feed']: + if names[:2] == ['fleet-multiplane', 'dhcp-feed'] or 'fleet-multiplane dhcp-feed' in text: out.add('reservation feed') - if doc.get('kind') == 'Service': + for port in c.get('ports') or []: + if 67 in (port.get('containerPort'), port.get('hostPort')) and port.get('protocol', 'TCP') == 'UDP': + out.add('DHCP listener') + for env in c.get('env') or []: + if env.get('name') == 'FLEET_LAB_DHCP' and env.get('value') == 'synced': + out.add('synced lab switch') + kind, metadata = doc.get('kind'), doc.get('metadata') or {} + if kind == 'Service': # Built alone, the feed component renders only its Service. - if (doc.get('metadata') or {}).get('name') == 'fleet-site-dhcp-feed': + if metadata.get('name') == 'fleet-site-dhcp-feed': out.add('reservation feed') for port in (doc.get('spec') or {}).get('ports') or []: - if port.get('port') == 67 and port.get('protocol', 'TCP') == 'UDP': + if 67 in (port.get('port'), port.get('targetPort')) and port.get('protocol', 'TCP') == 'UDP': out.add('DHCP listener') + if kind == 'ConfigMap' and (doc.get('data') or {}).get('FLEET_LAB_DHCP') == 'synced': + out.add('synced lab switch') + if kind == 'Role' and any(str(p).startswith('ipam.miloapis.com/') for p in (doc.get('spec') or {}).get('includedPermissions') or []): + out.add('IPAM grant') if any(synced(s) for s in strings(doc)): out.add('synced enrollment') return out @@ -98,5 +115,5 @@ for root in roots: failures.append('%s renders %s, which only an opt-in root may' % (root, ', '.join(sorted(parts)))) if failures: sys.exit('FAIL network boot inactive by default:\n ' + '\n '.join(failures)) -print('PASS network boot inactive by default: %d roots render no synchronized DHCP; only the %d opt-in roots do' % (len(roots) - len(opt_in), len(opt_in))) +print('PASS network boot inactive by default: %d roots render no synchronized DHCP or IPAM grant; only the %d opt-in roots do' % (len(roots) - len(opt_in), len(opt_in))) PY From 5617a9299ce338350e6f0bb90c67b0cbca8fa988 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 20:12:47 -0600 Subject: [PATCH 17/17] docs(site): Rewrap the off-by-default paragraph Co-Authored-By: Claude Opus 5.5 --- docs/operations/boot-network.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index 6325ac77..54fa0908 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -339,8 +339,9 @@ configuration, and `hack/validate-site-dhcp-render.sh` checks that render in CI. ISC builds the Kea image for `linux/amd64` only. Synchronized DHCP is off by default. Outside the opt-in roots below, no -overlay or site base includes either component, a site enrollment must name its `dhcp` mode, and the feed refuses -to start for a `static` enrollment. In CI, +overlay or site base includes either component, a site enrollment must name +its `dhcp` mode, and the feed refuses to start for a `static` enrollment. In +CI, `hack/validate-network-boot-inactive.sh` renders every kustomization root under `config/`. It checks that only the DHCP components, their example and the Redfish lab's synchronized mode render a Kea server, the synchronizer, the