From 57bc4332053331687cbca31cfac850d246fb0ff2 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 19:16:58 -0600 Subject: [PATCH 1/4] feat: Claim lab boot addresses from real IPAM In synchronized DHCP mode the multiplane Redfish lab now runs the real IPAM service (milo-os/ipam v0.6.0, manifests and image pinned by digest) on the platform cluster, aggregated by the provider project's Milo API, with its own pinned PostgreSQL. Fleet adds no database. Quota is off because the lab Milo serves no quota API. Bootstrap enrolls the front-proxy, serving and database credentials at run time, registers the APIService, and creates the lab-provisioning class and a pool that allocates only 192.168.77.100-199. The stand-in claim CRD and binder are gone from the lab path; envtests keep their stand-in. A background sampler records IPAM's claims and allocations for the whole run, recording failed reads instead of stopping. The synced DHCP phase ties every Kea lease to IPAM's allocation for that operation's own claim, bridging a window IPAM could not be read only by the same allocation on both sides, requires a recent last sample, and requires every claim and allocation released and the pool back to its reservations. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-multiplane/main.go | 9 -- .../clusters/platform-ipam/ipam.yaml | 98 ++++++++++++ .../clusters/platform-ipam/kustomization.yaml | 4 + config/multiplane/ipam/kustomization.yaml | 11 ++ config/multiplane/ipam/namespace.yaml | 7 + config/multiplane/ipam/networkpolicy.yaml | 27 ++++ config/multiplane/ipam/postgres.yaml | 66 ++++++++ .../milo/provider/kustomization.yaml | 18 +++ docs/operations/boot-network.md | 13 +- docs/operations/gitops.md | 7 + docs/operations/redfish-lab.md | 110 ++++++++++--- hack/multiplane/acceptance-redfish.sh | 8 + hack/multiplane/evidence.py | 19 ++- hack/multiplane/flux.py | 34 ++++ hack/multiplane/milo.py | 113 +++++++++++--- hack/multiplane/redfish_steps.py | 147 +++++++++++++++++- hack/multiplane/run.sh | 5 +- hack/multiplane/test-redfish.py | 70 +++++++++ hack/multiplane/topology.sh | 5 +- internal/multiplane/ipam.go | 72 --------- internal/multiplane/ipam_test.go | 68 -------- internal/multiplane/runner.go | 14 +- 22 files changed, 714 insertions(+), 211 deletions(-) create mode 100644 config/multiplane/clusters/platform-ipam/ipam.yaml create mode 100644 config/multiplane/clusters/platform-ipam/kustomization.yaml create mode 100644 config/multiplane/ipam/kustomization.yaml create mode 100644 config/multiplane/ipam/namespace.yaml create mode 100644 config/multiplane/ipam/networkpolicy.yaml create mode 100644 config/multiplane/ipam/postgres.yaml delete mode 100644 internal/multiplane/ipam.go delete mode 100644 internal/multiplane/ipam_test.go diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index 8a3c452f..245add01 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -159,15 +159,6 @@ 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/multiplane/clusters/platform-ipam/ipam.yaml b/config/multiplane/clusters/platform-ipam/ipam.yaml new file mode 100644 index 00000000..31f5adec --- /dev/null +++ b/config/multiplane/clusters/platform-ipam/ipam.yaml @@ -0,0 +1,98 @@ +# Platform cluster, synchronized lab DHCP mode only (run.sh --synced-dhcp): +# the IPAM service (milo-os/ipam v0.6.0) beside the provider project's Milo +# API, which aggregates it as ipam.miloapis.com. IPAM's own published +# manifests, pinned by digest, as the platform's Flux consumes them; the lab +# patches below are the only changes. Bootstrap enrolls the credentials and +# registers the APIService in the provider Milo API. +apiVersion: source.toolkit.fluxcd.io/v1 +kind: OCIRepository +metadata: {name: ipam-kustomize, namespace: flux-system} +spec: + interval: 1h + url: oci://ghcr.io/milo-os/ipam-kustomize + # v0.6.0 (revision v0.6.0@sha1:1f6f22938dd165e568bb0fb1e4c50167ab09d6ae). + ref: + digest: sha256:62305dde600b8efa10a68a786e60b2e826837897cd93378c9e94d7adbff3f647 +--- +# Namespace, IPAM's PostgreSQL and the NetworkPolicy toward Milo. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: ipam-system, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: fleet-gitops, namespace: flux-system} + path: ./config/multiplane/ipam +--- +# IPAM's published base: the apiserver Deployment, Service, PDB, +# NetworkPolicy and the host-cluster RBAC it ships with. +apiVersion: kustomize.toolkit.fluxcd.io/v1 +kind: Kustomization +metadata: {name: ipam-apiserver, namespace: flux-system} +spec: + interval: 10m + retryInterval: 30s + timeout: 5m + prune: true + wait: true + sourceRef: {kind: OCIRepository, name: ipam-kustomize, namespace: flux-system} + path: ./base + targetNamespace: ipam-system + dependsOn: + - {name: ipam-system, namespace: flux-system} + - {name: milo-provider, namespace: flux-system} + images: + # ghcr.io/milo-os/ipam:v0.6.0 (multi-arch index). + - name: ghcr.io/milo-os/ipam + digest: sha256:18d472179ddff8db77a812fd0f0874248dd08e5a2425197152cc4cc2e9a7ce0d + patches: + # No cert-manager CSI driver in the lab: the serving key is a Secret + # enrolled by bootstrap, whose certificate is the APIService caBundle. + - target: {kind: Deployment, name: ipam-apiserver} + patch: |- + - op: test + path: /spec/template/spec/volumes/0/name + value: tls-certs + - op: replace + path: /spec/template/spec/volumes/0 + value: {name: tls-certs, secret: {secretName: ipam-apiserver-tls, defaultMode: 288}} + # Delegate TokenReview and SubjectAccessReview to the provider Milo API, + # as the platform does, through a kubeconfig bootstrap enrolls. The + # control-plane-ca ConfigMap the base mounts holds Milo's front-proxy CA. + # The lab Milo serves no quota API, so quota is off. One replica and + # smaller requests fit the single platform node. Mode 288 is 0440: IPAM + # runs as 65532 with that fsGroup. + - target: {kind: Deployment, name: ipam-apiserver} + patch: |- + apiVersion: apps/v1 + kind: Deployment + metadata: {name: ipam-apiserver} + spec: + replicas: 1 + template: + spec: + containers: + - name: apiserver + env: + - {name: KUBECONFIG, value: /etc/kubernetes/milo/kubeconfig} + - {name: AUTHENTICATION_KUBECONFIG, value: /etc/kubernetes/milo/kubeconfig} + - {name: AUTHORIZATION_KUBECONFIG, value: /etc/kubernetes/milo/kubeconfig} + - {name: ENABLE_QUOTA, value: "false"} + resources: + requests: {cpu: 50m, memory: 96Mi} + # IPAM publishes a 4Gi limit for production; the lab + # bounds it at 1Gi, well above its startup with five + # informers, so an OOM is not the first failure. + limits: {cpu: "1", memory: 1Gi} + volumeMounts: + - {name: milo-credentials, mountPath: /etc/kubernetes/milo, readOnly: true} + initContainers: + - name: migrate + resources: + requests: {cpu: 10m, memory: 32Mi} + volumes: + - name: milo-credentials + secret: {secretName: ipam-milo-credentials, defaultMode: 288} diff --git a/config/multiplane/clusters/platform-ipam/kustomization.yaml b/config/multiplane/clusters/platform-ipam/kustomization.yaml new file mode 100644 index 00000000..85b2a0b3 --- /dev/null +++ b/config/multiplane/clusters/platform-ipam/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ipam.yaml diff --git a/config/multiplane/ipam/kustomization.yaml b/config/multiplane/ipam/kustomization.yaml new file mode 100644 index 00000000..fd9a3688 --- /dev/null +++ b/config/multiplane/ipam/kustomization.yaml @@ -0,0 +1,11 @@ +# IPAM's namespace and its own PostgreSQL, beside the provider project's Milo +# API (synchronized lab DHCP mode only). The IPAM apiserver itself comes from +# IPAM's published manifests (config/multiplane/clusters/platform-ipam). +# Bootstrap enrolls the database password, IPAM's serving key and its Milo +# credentials as Secrets; none is in the source. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - namespace.yaml + - postgres.yaml + - networkpolicy.yaml diff --git a/config/multiplane/ipam/namespace.yaml b/config/multiplane/ipam/namespace.yaml new file mode 100644 index 00000000..fbcd8543 --- /dev/null +++ b/config/multiplane/ipam/namespace.yaml @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: ipam-system + annotations: + # Holds IPAM's database volume. Never garbage-collect it. + kustomize.toolkit.fluxcd.io/prune: disabled diff --git a/config/multiplane/ipam/networkpolicy.yaml b/config/multiplane/ipam/networkpolicy.yaml new file mode 100644 index 00000000..9344fba7 --- /dev/null +++ b/config/multiplane/ipam/networkpolicy.yaml @@ -0,0 +1,27 @@ +# Additive to the NetworkPolicy in IPAM's published base, which admits only +# kube-system and telemetry-system. Here the front proxy is the provider +# project's Milo API, and IPAM delegates authentication and authorization back +# to it, so both directions name that namespace. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: {name: ipam-apiserver-milo, namespace: ipam-system} +spec: + podSelector: + matchLabels: {app: ipam-apiserver} + policyTypes: [Ingress, Egress] + ingress: + - from: + - namespaceSelector: + matchLabels: {kubernetes.io/metadata.name: milo-provider} + podSelector: + matchLabels: {app.kubernetes.io/name: milo-apiserver} + ports: + - {protocol: TCP, port: 8443} + egress: + - to: + - namespaceSelector: + matchLabels: {kubernetes.io/metadata.name: milo-provider} + podSelector: + matchLabels: {app.kubernetes.io/name: milo-apiserver} + ports: + - {protocol: TCP, port: 6443} diff --git a/config/multiplane/ipam/postgres.yaml b/config/multiplane/ipam/postgres.yaml new file mode 100644 index 00000000..e56abace --- /dev/null +++ b/config/multiplane/ipam/postgres.yaml @@ -0,0 +1,66 @@ +# IPAM's own PostgreSQL. IPAM owns this storage; Fleet never connects to it. +# IPAM's postgres component floats its chart (16.x) and image, so the lab runs +# the official image pinned by digest instead. The postgres-credentials +# Secret (password, and the DSN IPAM reads) is written by bootstrap. +apiVersion: v1 +kind: Service +metadata: {name: ipam-postgres, namespace: ipam-system} +spec: + clusterIP: None + selector: {app.kubernetes.io/name: ipam-postgres} + ports: + - {name: postgres, port: 5432, targetPort: 5432} +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: {name: ipam-postgres, namespace: ipam-system} +spec: + serviceName: ipam-postgres + replicas: 1 + # The database outlives the Pod and the StatefulSet. + persistentVolumeClaimRetentionPolicy: {whenDeleted: Retain, whenScaled: Retain} + selector: + matchLabels: {app.kubernetes.io/name: ipam-postgres} + template: + metadata: + labels: {app.kubernetes.io/name: ipam-postgres} + spec: + automountServiceAccountToken: false + enableServiceLinks: false + securityContext: + runAsNonRoot: true + runAsUser: 70 + runAsGroup: 70 + fsGroup: 70 + seccompProfile: {type: RuntimeDefault} + containers: + - name: postgres + # PostgreSQL 17.10, official Alpine image (multi-arch index). + image: postgres:17.10-alpine@sha256:742f40ea20b9ff2ff31db5458d127452988a2164df9e17441e191f3b72252193 + args: [-c, shared_buffers=32MB, -c, max_connections=50] + env: + - {name: POSTGRES_USER, value: ipam} + - {name: POSTGRES_DB, value: ipam} + - name: POSTGRES_PASSWORD + valueFrom: + secretKeyRef: {name: postgres-credentials, key: password} + - {name: PGDATA, value: /var/lib/postgresql/data/pgdata} + ports: + - {name: postgres, containerPort: 5432} + readinessProbe: + exec: + command: [pg_isready, -U, ipam, -d, ipam, -h, 127.0.0.1] + periodSeconds: 5 + securityContext: + allowPrivilegeEscalation: false + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 25m, memory: 64Mi} + limits: {memory: 256Mi} + volumeMounts: + - {name: data, mountPath: /var/lib/postgresql/data} + volumeClaimTemplates: + - metadata: {name: data} + spec: + accessModes: [ReadWriteOnce] + resources: {requests: {storage: 1Gi}} diff --git a/config/multiplane/milo/provider/kustomization.yaml b/config/multiplane/milo/provider/kustomization.yaml index 64abfc8f..9d4a2d69 100644 --- a/config/multiplane/milo/provider/kustomization.yaml +++ b/config/multiplane/milo/provider/kustomization.yaml @@ -11,3 +11,21 @@ patches: - op: replace path: /spec/ports/0/nodePort value: 30441 + # The aggregation layer, as the platform's Milo runs it: Milo proxies + # aggregated APIs (IPAM, in synchronized lab DHCP mode) with a front-proxy + # client certificate, and the APIs trust its CA for the X-Remote-* identity + # headers, project extras included. Bootstrap enrolls the CA and client key + # in milo-apiserver-private; they are never in the source. + - target: {kind: Deployment, name: milo-apiserver} + patch: |- + - op: test + path: /spec/template/spec/containers/0/name + value: apiserver + - {op: add, path: /spec/template/spec/containers/0/args/-, value: --proxy-client-cert-file=/private/front-proxy-client.crt} + - {op: add, path: /spec/template/spec/containers/0/args/-, value: --proxy-client-key-file=/private/front-proxy-client.key} + - {op: add, path: /spec/template/spec/containers/0/args/-, value: --requestheader-client-ca-file=/private/front-proxy-ca.crt} + - {op: add, path: /spec/template/spec/containers/0/args/-, value: --requestheader-allowed-names=fleet-front-proxy-client} + - {op: add, path: /spec/template/spec/containers/0/args/-, value: --requestheader-username-headers=X-Remote-User} + - {op: add, path: /spec/template/spec/containers/0/args/-, value: --requestheader-uid-headers=X-Remote-Uid} + - {op: add, path: /spec/template/spec/containers/0/args/-, value: --requestheader-group-headers=X-Remote-Group} + - {op: add, path: /spec/template/spec/containers/0/args/-, value: --requestheader-extra-headers-prefix=X-Remote-Extra-} diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index 4e68bb94..439f15cb 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -426,11 +426,20 @@ 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. +The synced Redfish acceptance (`run.sh --redfish --synced-dhcp`) goes further. +Its boot addresses come from the real IPAM service (`milo-os/ipam` v0.6.0), +which runs with its own PostgreSQL and with quota off, and which the provider +project's Milo API aggregates. A lab pool hands out only 192.168.77.100–199. +The acceptance asserts that every address Kea leased was allocated by IPAM to +that operation's own claim during its boot, and that no claim or allocation +remains afterwards. It does not prove quota, Milo's production IAM, or pool +exhaustion through IPAM. See [IPAM in the lab](redfish-lab.md#ipam-in-the-lab). + ## Implemented versus proposed | 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. Only the lab's synchronized DHCP mode sets a class, against a stand-in, 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. The synced Redfish lab claims from real IPAM, but no synced run has passed yet | | 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 | @@ -442,6 +451,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 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) | +| Lab acceptance in synced mode | Implemented as `run.sh --redfish --synced-dhcp`, with IPAM v0.6.0 (its own PostgreSQL, quota off) aggregated by the provider Milo API; not yet run. See [IPAM in the lab](redfish-lab.md#ipam-in-the-lab) | [server-networking]: https://github.com/datum-cloud/fleet/pull/186 diff --git a/docs/operations/gitops.md b/docs/operations/gitops.md index 91c1c14a..f36fc484 100644 --- a/docs/operations/gitops.md +++ b/docs/operations/gitops.md @@ -37,6 +37,13 @@ under [what is not production](#what-is-not-production). RoleBinding and worker Job only ``` +In synchronized lab DHCP mode (`run.sh --redfish --synced-dhcp`), the platform +cluster also reconciles `ipam-system` (IPAM's namespace, its PostgreSQL and a +NetworkPolicy toward the provider Milo API, from `config/multiplane/ipam`) and +`ipam-apiserver` (IPAM's published `ipam-kustomize` bundle, pinned by digest, +from its own OCIRepository). See +[IPAM in the lab](redfish-lab.md#ipam-in-the-lab). + | Surface | Writer | Never written by | | --- | --- | --- | | Flux controllers and sync objects (`flux-system`) | Bootstrap once, then each cluster's own Flux (`fleet-cluster` reconciles `environment//flux-system`) | — | diff --git a/docs/operations/redfish-lab.md b/docs/operations/redfish-lab.md index f9c94577..661fbfb3 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -371,35 +371,98 @@ exercises boot addresses, reservations and Kea end to end in the lab: 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 - 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. +- **IPAM.** Boot addresses come from the real IPAM service, described below. + Fleet's own code claims, checks at admission and releases the addresses. + The static leases (.10 and .11) are outside the range IPAM allocates. + +### IPAM in the lab + +Synced mode runs IPAM (`milo-os/ipam` v0.6.0) on the platform cluster, beside +the provider project's Milo API. It is set up the way the platform runs it: + +- **Published manifests.** The `ipam-apiserver` Flux layer reconciles IPAM's + published Kustomize bundle (`oci://ghcr.io/milo-os/ipam-kustomize`, its + `base`). The bundle and the IPAM image are pinned by digest. The lab changes + only four things: the serving key is a Secret instead of a cert-manager CSI + volume, authentication and authorization go to the provider Milo API, quota + is off, and it runs one smaller replica. +- **Its own PostgreSQL.** The `ipam-system` layer runs a single PostgreSQL + 17.10 StatefulSet, pinned by digest, in IPAM's namespace. IPAM owns this + storage. Fleet adds no database and never connects to it. IPAM's own + PostgreSQL component is not used because its chart version and image float. +- **Aggregated through Milo.** The provider Milo API runs its aggregation layer + with a front-proxy client key and a CA that bootstrap generates per run. + Bootstrap registers the `v1alpha1.ipam.miloapis.com` APIService in that API. + Milo proxies project requests + (`/apis/resourcemanager.miloapis.com/v1alpha1/projects/provider/control-plane/apis/ipam.miloapis.com/...`) + to IPAM, forwarding the caller and the project extras + (`iam.miloapis.com/parent-{api-group,type,name}`) as `X-Remote-*` headers. + IPAM trusts that CA for the headers. It sends TokenReview and + SubjectAccessReview to the same Milo API with its own static token, which is + in `system:masters` like the platform's IPAM client identity. The static-token + RBAC that bootstrap writes therefore decides what each Fleet identity may do + in IPAM. +- **Availability seam.** On the platform, Milo's controller-manager marks a + remote APIService `Available`. The lab runs no controller-manager, so + bootstrap sets the condition once Flux reports IPAM's apiserver Ready. +- **Quota off.** The lab Milo API serves no quota API, so IPAM runs with + `ENABLE_QUOTA=false`. Claims are not counted against any quota, which the + platform does count. +- **Fixtures.** In the provider project, bootstrap creates the `lab-provisioning` + IPClass (IPv4, Private, /32 only, reclaim Delete). It also creates an IPPool + for 192.168.77.0/24 scoped to the lab Location, which reserves the first 100 + and last 56 addresses, so IPAM allocates only .100–.199. Kea's base subnet is + the same /24 with the bridge at .1. +- **Credentials.** Bootstrap generates IPAM's Milo token, serving key, database + password and kubeconfig per run and enrolls them as Secrets in `ipam-system`. + None is in the source or the evidence. `evidence/ipam.json` records the + running image digest, the APIService condition, the class and the pool. The `redfish-dhcp-synced` phase runs after `boot-denials` and writes -`evidence/redfish-dhcp.json`. It fails unless: +`evidence/redfish-dhcp.json`. For the whole acceptance run, a background +sampler (`redfish_steps.py ipam-watch`) reads every IPClaim and IPAllocation in +`fleet-provider` every two seconds. Those records outlive the claims, which +are gone by the time the phase runs. A failed read is recorded as such, never +fatal, and the phase requires the sampler's last state to be under a minute +old. The phase 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 + (`-boot`), within .100–.199; +2. for each operation that ran at the site, while its boot was open, IPAM + recorded that claim Bound to the operation's address and naming an + IPAllocation, and that allocation names the claim back and holds exactly + the address as a /32. If IPAM could not be read for the whole window, + samples just before and just after it must show the same allocation, with + only failed reads between; +3. 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. 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. +4. 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, and + at least two installations and two wipes did. Every lease Kea granted falls + in the boot window of an operation whose claim IPAM held that address for, + and no lease is a static or out-of-range address; +5. after both releases, no IPClaim and no IPAllocation remain in + `fleet-provider`, and the pool reports 156 of 256 addresses allocated: its + reservations and nothing else; +6. the lab network has no `` element and no dnsmasq runs; and +7. Kea's last report serves nothing. 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. +complete. IPAM's first-fit allocation hands a released address out again, so +freshness is judged by claim, allocation, lease and report times, not by +address. + +What the lab proves: Fleet's requesters, admission check and release +verification work against the real IPAM API through Milo's project routing and +aggregation, and Kea serves only addresses IPAM allocated to each operation's +own claim. What it does not prove: quota, Milo's OpenFGA-backed IAM (the lab +uses static-token RBAC), IPAM's high-availability deployment, pool exhaustion +through IPAM (unit tests cover how Fleet handles a 507 `Exhausted`), and +anything about a physical site's IPAM pools. The mode is implemented and its offline checks pass. No synced run has passed yet. @@ -515,7 +578,16 @@ kustomize and checks the following: - variable substitution; - phase coverage; - that no fault hook appears in `internal/redfish`; -- source pins, and no OpenStack dependency. +- source pins, and no OpenStack dependency; +- in synced mode, the IPAM layer's exact inventory, the IPAM bundle and image + digests, the provider Milo API's aggregation flags, and the IPAM evidence + matching (a claim's record inside the boot window, an allocation naming it + back at exactly /32, and each Kea lease belonging to one boot window). + +The `ipam-apiserver` layer renders from IPAM's remote bundle, so CI does not +render it. Its inventory in `flux.py` was taken from the v0.6.0 bundle +rendered with the layer's patches. `flux-verify` checks the inventory, the +pinned source and the running image on every live run. ## Execution record diff --git a/hack/multiplane/acceptance-redfish.sh b/hack/multiplane/acceptance-redfish.sh index 2772690f..d8b04135 100755 --- a/hack/multiplane/acceptance-redfish.sh +++ b/hack/multiplane/acceptance-redfish.sh @@ -17,6 +17,14 @@ flux() { ph "flux-$1" "$2" python3 hack/multiplane/flux.py "$1" "$state"; } # all runs every block. group=${FLEET_MULTIPLANE_GROUP:-all} runs() { [[ $group == all || $group == "$1" ]]; } +# Synchronized lab DHCP: sample IPAM's claims and allocations for the whole +# run, so dhcp-synced can show what IPAM held during each boot. The sampler +# stops when this script exits. +if [[ ${FLEET_LAB_DHCP:-static} == synced ]]; then + python3 hack/multiplane/redfish_steps.py ipam-watch "$state" >/dev/null 2>&1 & + watcher=$! + trap 'kill "$watcher" 2>/dev/null || true' EXIT +fi ph rbac 600 python3 hack/multiplane/verify-rbac.py "$state" ph custody-crd-rules 600 python3 hack/multiplane/custody_crd_rules.py "$state" diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index 1dac3cfa..5560e598 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -116,8 +116,18 @@ def copy_out(source, destination): # The synchronized DHCP check needs the release group's installations and wipes. if SYNCED and GROUP != 'flux': markers += ('redfish-dhcp-synced: ',) + markers += ('ipam: milo-os/ipam v0.6.0 aggregated by the provider Milo API', 'IPAM allocated every leased address') if not (s / 'evidence' / 'redfish-dhcp.json').exists(): fail('synchronized lab DHCP left no redfish-dhcp.json evidence') + if not (s / 'evidence' / 'ipam.json').exists(): + fail('synchronized lab DHCP left no ipam.json evidence') + dhcp = json.loads((s / 'evidence' / 'redfish-dhcp.json').read_text()) + published = [o for o in dhcp['operations'] if o.get('published')] + if not published or any(not o.get('ipam') or o['ipam']['claim'] != o['name'] + '-boot' or o['ipam']['allocationClaimRef'] != o['ipam']['claim'] + or o['ipam']['allocatedCIDR'] != o['address'] + '/32' for o in published): + fail('an operation booted without IPAM allocating its address to its own claim') + if dhcp.get('claimsRemaining') != 0 or dhcp.get('allocationsRemaining') != 0: + fail('IPAM still held boot address claims or allocations after the run') 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', @@ -597,11 +607,18 @@ 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)', - ('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' + ('synchronized lab DHCP: Kea in the runtime Pod fed by the site reservation feed, boot addresses from IPAM (milo-os/ipam v0.6.0, its own PostgreSQL, quota off) ' + 'aggregated by the provider Milo API with a bootstrap-marked Available APIService, 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'] + if SYNCED: + service = json.loads((ev / 'ipam.json').read_text()) + summary['scenarios']['bootAddresses'] = {'evidence': ['ipam.json', 'redfish-dhcp.json'], 'ipam': service['service'], 'image': service['image'], 'imageID': service['imageID'], + 'storage': service['storage'], 'quota': service['quota'], 'pool': service['pool']['spec']['cidr'], + 'operations': [{k: o[k] for k in ('kind', 'name', 'address')} | {'allocation': o['ipam']['allocation']} for o in published], + 'claimsRemaining': 0, 'allocationsRemaining': 0, 'poolCapacityAfter': dhcp['poolCapacityAfter']} (ev / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n') for name in ('source-SHA256SUMS', 'sysctl.json'): if (s / name).exists(): diff --git a/hack/multiplane/flux.py b/hack/multiplane/flux.py index b1cbba97..8bc1f903 100644 --- a/hack/multiplane/flux.py +++ b/hack/multiplane/flux.py @@ -111,6 +111,25 @@ if LAB_DHCP == 'synced': 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'}) +# Synced mode also runs IPAM (milo-os/ipam v0.6.0) on the platform cluster, +# aggregated by the provider project's Milo API: its namespace and PostgreSQL +# from this source, and its apiserver from IPAM's published manifests. The +# published auth-reader RoleBinding renders into ipam-system, not kube-system, +# so it grants nothing; it is inert here because IPAM reads Milo's +# extension-apiserver-authentication through its authentication kubeconfig. +IPAM_KUSTOMIZE_DIGEST = 'sha256:62305dde600b8efa10a68a786e60b2e826837897cd93378c9e94d7adbff3f647' +IPAM_IMAGE = 'ghcr.io/milo-os/ipam@sha256:18d472179ddff8db77a812fd0f0874248dd08e5a2425197152cc4cc2e9a7ce0d' +PLATFORM_LAYER_INVENTORY = { + 'flux-system/ipam-system': sorted(['_ipam-system__Namespace', 'ipam-system_ipam-postgres__Service', 'ipam-system_ipam-postgres_apps_StatefulSet', + 'ipam-system_ipam-apiserver-milo_networking.k8s.io_NetworkPolicy']), + 'flux-system/ipam-apiserver': sorted(['ipam-system_ipam-apiserver__ServiceAccount', '_ipam-apiserver_rbac.authorization.k8s.io_ClusterRole', + 'ipam-system_ipam-apiserver-auth-reader_rbac.authorization.k8s.io_RoleBinding', + '_ipam-apiserver_rbac.authorization.k8s.io_ClusterRoleBinding', + '_ipam-apiserver:system:auth-delegator_rbac.authorization.k8s.io_ClusterRoleBinding', + 'ipam-system_ipam-apiserver__Service', 'ipam-system_ipam-apiserver_apps_Deployment', + 'ipam-system_ipam-apiserver_policy_PodDisruptionBudget', 'ipam-system_ipam-apiserver_networking.k8s.io_NetworkPolicy']), +} if LAB_DHCP == 'synced' else {} +EXPECTED['platform'] += list(PLATFORM_LAYER_INVENTORY) 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', @@ -274,6 +293,8 @@ def stage(args): data = {'FLEET_CELL': env['cell'], 'FLEET_CELL_ENDPOINT': env['cellEndpoint'], 'FLEET_SOURCE_MARKER': marker} maps = [] patches = [] + if cluster == 'platform' and LAB_DHCP == 'synced': + resources.insert(2, '../../config/multiplane/clusters/platform-ipam') if cluster == 'hub': # Karmada-API Kustomizations live beside their kubeconfig Secret. maps.append(config_map('fleet-environment', 'karmada-system', data)) @@ -684,6 +705,19 @@ def verify(args): karmada_hist = (hub['helmReleases'].get('flux-system/karmada', {}).get('history') or [{}])[0] if karmada_hist.get('chartVersion') != 'v1.16.0' or karmada_hist.get('status') != 'deployed': problems.append('karmada release history: %s' % karmada_hist) + if PLATFORM_LAYER_INVENTORY: + platform = snaps['platform'] + ipam_src = platform['sources'].get('flux-system/ipam-kustomize', {}) + if (ipam_src.get('ref') or {}).get('digest') != IPAM_KUSTOMIZE_DIGEST or not str(ipam_src.get('artifactRevision', '')).endswith(IPAM_KUSTOMIZE_DIGEST): + problems.append('IPAM manifests source not at pinned digest: %s' % ipam_src) + for layer, expected in PLATFORM_LAYER_INVENTORY.items(): + got = platform['kustomizations'].get(layer, {}).get('inventory') + if got != expected: + problems.append('%s inventory is not exactly %s: %s' % (layer, expected, got)) + images = sorted({c['image'] for p in kget(s, 'platform', '-n', 'ipam-system', 'get', 'pods', '-l', 'app=ipam-apiserver')['items'] + for c in p['spec']['containers'] + p['spec'].get('initContainers', [])}) + if images != [IPAM_IMAGE]: + problems.append('IPAM Pods do not run only the pinned image %s: %s' % (IPAM_IMAGE, images)) # Ownership: Flux layers own the shared site; kro alone owns per-operation workers. owners, owner_problems = ownership(s, snaps) problems += owner_problems diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py index 4981059f..ad4aa613 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -6,13 +6,18 @@ source revision must never hold: - credential enrollment: per-API static tokens and a self-signed serving key, - written as the milo-apiserver-private Secret (local credential seam); + written as the milo-apiserver-private Secret (local credential seam), and + the provider API's front-proxy CA and client key for its aggregation layer; - tenant fixture bootstrap through each API: the Project, static-token RBAC grants and the metal CRDs inside the project, and in the provider project the inventory and Device custody CRDs. The provider project's Fleet components each get their own token: the Metal provider (management), the custody coordinator, the release controller and fixture discovery. A staff token creates recoveries. +- in synchronized lab DHCP mode (FLEET_LAB_DHCP=synced), IPAM's credentials + (its Milo token, serving key and database password), the APIService that + aggregates IPAM into the provider API, and the boot address class and pool + inside the provider project. Production uses Milo's own project provisioning, service catalog and IAM; this is not that machinery. """ @@ -22,37 +27,109 @@ if not a.prefix.startswith('fleet-mp-'):raise SystemExit('task-owned fleet-mp- prefix required') os.environ['DOCKER_CONTEXT']=os.environ.get('FLEET_MULTIPLANE_DOCKER_CONTEXT','colima-fleet-acceptance-tcg') platform=root/'platform-admin.yaml' +synced=os.environ.get('FLEET_LAB_DHCP')=='synced' ports=json.loads((root/'platform-ports.json').read_text()) def run(*args,**kw):return subprocess.run(args,check=True,text=True,**kw) def kubectl(config,*args,**kw):return run('kubectl','--kubeconfig',str(config),'--request-timeout=15s',*args,**kw) def apply(config,obj):kubectl(config,'apply','-f','-',input=json.dumps(obj),stdout=subprocess.DEVNULL) def kube(path,server,token,ca): path.write_text(json.dumps({'apiVersion':'v1','kind':'Config','clusters':[{'name':'local','cluster':{'server':server,'certificate-authority-data':base64.b64encode(ca).decode()}}],'users':[{'name':'role','user':{'token':token}}],'contexts':[{'name':'role','context':{'cluster':'local','user':'role'}}],'current-context':'role'}));path.chmod(0o600) +def enroll(ns,*create): + obj=kubectl(platform,'-n',ns,'create',*create,'--dry-run=client','-o','json',capture_output=True).stdout + kubectl(platform,'apply','--server-side','--field-manager=fleet-credential-enrollment','-f','-',input=obj,stdout=subprocess.DEVNULL) def wait(fn,seconds,what): for _ in range(seconds//2): if fn():return time.sleep(2) raise SystemExit(what) +def now():return time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()) roles=('provider','consumer-a','consumer-b') +LOCATION={'apiGroup':'networking.datumapis.com','kind':'Location','name':'local'} +def ipam(d,config): + """Aggregate IPAM into the provider API, as the platform registers it, and + create the boot address class and pool inside the provider project.""" + apply(d/'bootstrap.json',{'apiVersion':'apiregistration.k8s.io/v1','kind':'APIService','metadata':{'name':'v1alpha1.ipam.miloapis.com'}, + 'spec':{'group':'ipam.miloapis.com','version':'v1alpha1','service':{'namespace':'ipam-system','name':'ipam-apiserver','port':443}, + 'caBundle':base64.b64encode((root/'ipam'/'tls.crt').read_bytes()).decode(),'groupPriorityMinimum':1000,'versionPriority':15}}) + # Milo's controller-manager marks a remote APIService Available; the lab + # runs none, so bootstrap does, once Flux reported IPAM's apiserver Ready. + kubectl(d/'bootstrap.json','patch','apiservice','v1alpha1.ipam.miloapis.com','--subresource=status','--type=merge','-p',json.dumps({'status':{'conditions':[ + {'type':'Available','status':'True','reason':'Remote','message':'IPAM apiserver Ready in the platform cluster','lastTransitionTime':now()}]}}),stdout=subprocess.DEVNULL) + wait(lambda:subprocess.run(['kubectl','--kubeconfig',str(config),'--request-timeout=10s','get','ipclasses.ipam.miloapis.com'],capture_output=True).returncode==0,300,'IPAM is not served through the provider project') + # Kea's base subnet is 192.168.77.0/24 and the bridge is .1: the pool + # withholds .0-.99 and .200-.255, so IPAM hands out only .100-.199. + apply(config,{'apiVersion':'ipam.miloapis.com/v1alpha1','kind':'IPClass','metadata':{'name':'lab-provisioning'}, + 'spec':{'ipFamily':'IPv4','addressScope':'Private','allowedPrefixLengths':{'min':32,'max':32},'defaultPrefixLength':32,'reclaimPolicy':'Delete'}}) + apply(config,{'apiVersion':'ipam.miloapis.com/v1alpha1','kind':'IPPool','metadata':{'name':'lab-provisioning'}, + 'spec':{'cidr':'192.168.77.0/24','ipFamily':'IPv4','classNames':['lab-provisioning'],'scope':{'location':LOCATION}, + 'allocation':{'minPrefixLength':32,'maxPrefixLength':32,'strategy':'FirstFit'},'reservations':{'leading':100,'trailing':56,'unitPrefixLength':32}}}) + get=lambda *a:json.loads(kubectl(config,'get',*a,'-o','json',capture_output=True).stdout) + wait(lambda:get('ippool','lab-provisioning').get('status',{}).get('phase')=='Ready',120,'the lab IPAM pool did not become Ready') + pod=next(x for x in json.loads(kubectl(platform,'-n','ipam-system','get','pods','-l','app=ipam-apiserver','-o','json',capture_output=True).stdout)['items'] if not x['metadata'].get('deletionTimestamp')) + db=json.loads(kubectl(platform,'-n','ipam-system','get','statefulset','ipam-postgres','-o','json',capture_output=True).stdout) + api=json.loads(kubectl(d/'bootstrap.json','get','apiservice','v1alpha1.ipam.miloapis.com','-o','json',capture_output=True).stdout) + pool=get('ippool','lab-provisioning') + (root/'evidence'/'ipam.json').write_text(json.dumps({'observedAt':now(),'service':'milo-os/ipam v0.6.0','image':pod['spec']['containers'][0]['image'], + 'imageID':pod['status']['containerStatuses'][0]['imageID'],'storage':db['spec']['template']['spec']['containers'][0]['image'], + 'quota':'off (ENABLE_QUOTA=false): the lab Milo serves no quota API','authn':'TokenReview and SubjectAccessReview delegated to the provider Milo API', + 'apiService':{'name':api['metadata']['name'],'service':api['spec']['service'],'conditions':[{k:c.get(k) for k in ('type','status','reason')} for c in api['status'].get('conditions',[])]}, + 'class':get('ipclass','lab-provisioning')['spec'],'pool':{'spec':pool['spec'],'status':{k:pool['status'].get(k) for k in ('phase','allocatedCIDR','capacity')}}},indent=2,sort_keys=True)+'\n') + print('ipam: milo-os/ipam v0.6.0 aggregated by the provider Milo API; class lab-provisioning, pool 192.168.77.0/24 allocating .100-.199',flush=True) # 1. Credential enrollment into the Flux-created namespaces. for role in roles: d=root/role;ns='milo-'+role if not d.exists(): d.mkdir(mode=0o700) - who=('bootstrap','management','customer')+(('coordinator','release','discovery','staff','projector','plan-author','plan-approver','operator','capacity-operator') if role=='provider' else ()) + # IPAM delegates TokenReview and SubjectAccessReview to the provider API + # as system:masters, as the platform's IPAM client identity does. + who=('bootstrap','management','customer')+(('coordinator','release','discovery','staff','projector','plan-author','plan-approver','operator','capacity-operator','ipam') if role=='provider' else ()) tokens={r:secrets.token_hex(32) for r in who} - (d/'tokens.csv').write_text('\n'.join(f'{v},{k},{k},'+('system:masters' if k=='bootstrap' else 'fleet-local') for k,v in tokens.items())+'\n') + (d/'tokens.csv').write_text('\n'.join(f'{v},{k},{k},'+('system:masters' if k in ('bootstrap','ipam') else 'fleet-local') for k,v in tokens.items())+'\n') run('openssl','req','-x509','-newkey','rsa:2048','-nodes','-keyout',str(d/'tls.key'),'-out',str(d/'tls.crt'),'-days','2','-subj','/CN=fleet-local','-addext',f'subjectAltName=DNS:milo-apiserver.{ns}.svc,IP:127.0.0.1',stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) - for f in ('tokens.csv','tls.key','tls.crt'):(d/f).chmod(0o600) + if role=='provider': + # The aggregation layer's front proxy: a CA the aggregated APIs trust for + # X-Remote-* identity headers, and the client key Milo proxies with. + run('openssl','req','-x509','-newkey','rsa:2048','-nodes','-keyout',str(d/'front-proxy-ca.key'),'-out',str(d/'front-proxy-ca.crt'),'-days','2','-subj','/CN=fleet-front-proxy-ca', + '-addext','basicConstraints=critical,CA:TRUE','-addext','keyUsage=critical,keyCertSign,cRLSign',stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) + run('openssl','req','-new','-newkey','rsa:2048','-nodes','-keyout',str(d/'front-proxy-client.key'),'-out',str(d/'front-proxy-client.csr'),'-subj','/CN=fleet-front-proxy-client',stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) + (d/'front-proxy-client.ext').write_text('extendedKeyUsage=clientAuth\n') + run('openssl','x509','-req','-in',str(d/'front-proxy-client.csr'),'-CA',str(d/'front-proxy-ca.crt'),'-CAkey',str(d/'front-proxy-ca.key'),'-set_serial','1','-days','2', + '-extfile',str(d/'front-proxy-client.ext'),'-out',str(d/'front-proxy-client.crt'),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) + for f in d.iterdir():f.chmod(0o600) wait(lambda:subprocess.run(['kubectl','--kubeconfig',str(platform),'get','namespace',ns],capture_output=True).returncode==0,300,f'Flux did not create namespace {ns}') - secret=kubectl(platform,'-n',ns,'create','secret','generic','milo-apiserver-private',f'--from-file=tokens.csv={d/"tokens.csv"}',f'--from-file=tls.crt={d/"tls.crt"}',f'--from-file=tls.key={d/"tls.key"}','--dry-run=client','-o','json',capture_output=True).stdout - kubectl(platform,'apply','--server-side','--field-manager=fleet-credential-enrollment','-f','-',input=secret,stdout=subprocess.DEVNULL) + files=('tokens.csv','tls.crt','tls.key')+(('front-proxy-ca.crt','front-proxy-client.crt','front-proxy-client.key') if role=='provider' else ()) + enroll(ns,'secret','generic','milo-apiserver-private',*(f'--from-file={f}={d/f}' for f in files)) print(role+': credential Secret enrolled (not in the source)',flush=True) -# 2. Flux must report each Milo Kustomization Ready (Deployment and etcd healthy). -for role in roles: - kubectl(platform,'-n','flux-system','annotate','--overwrite','kustomization','milo-'+role,'reconcile.fluxcd.io/requestedAt='+str(time.time()),stdout=subprocess.DEVNULL) -for role in roles: - kubectl(platform,'-n','flux-system','wait','--for=condition=Ready','kustomization/milo-'+role,'--timeout=600s',stdout=subprocess.DEVNULL) +# IPAM's credentials, in the namespace its Flux layer creates: the database +# password and the DSN IPAM reads, its serving key (whose certificate is the +# APIService caBundle), its kubeconfig for the provider Milo API, and Milo's +# front-proxy CA in the control-plane-ca ConfigMap IPAM's manifests mount. +if synced: + i=root/'ipam';pd=root/'provider' + if not i.exists(): + i.mkdir(mode=0o700) + # The .token suffix enrolls the password in the harness secret scan. + (i/'postgres-password.token').write_text(secrets.token_hex(32)) + run('openssl','req','-x509','-newkey','rsa:2048','-nodes','-keyout',str(i/'tls.key'),'-out',str(i/'tls.crt'),'-days','2','-subj','/CN=ipam-apiserver.ipam-system.svc', + '-addext','subjectAltName=DNS:ipam-apiserver.ipam-system.svc',stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) + token=next(l.split(',')[0] for l in (pd/'tokens.csv').read_text().splitlines() if l.split(',')[1]=='ipam') + kube(i/'kubeconfig','https://milo-apiserver.milo-provider.svc:6443',token,(pd/'tls.crt').read_bytes()) + (i/'dsn').write_text('postgres://ipam:%s@ipam-postgres-0.ipam-postgres.ipam-system.svc:5432/ipam?sslmode=disable'%(i/'postgres-password.token').read_text()) + for f in i.iterdir():f.chmod(0o600) + wait(lambda:subprocess.run(['kubectl','--kubeconfig',str(platform),'get','namespace','ipam-system'],capture_output=True).returncode==0,300,'Flux did not create namespace ipam-system') + enroll('ipam-system','secret','generic','postgres-credentials',f'--from-file=password={i/"postgres-password.token"}',f'--from-file=dsn={i/"dsn"}') + enroll('ipam-system','secret','generic','ipam-apiserver-tls',f'--from-file=tls.crt={i/"tls.crt"}',f'--from-file=tls.key={i/"tls.key"}') + enroll('ipam-system','secret','generic','ipam-milo-credentials',f'--from-file=kubeconfig={i/"kubeconfig"}') + enroll('ipam-system','configmap','control-plane-ca',f'--from-file=ca.crt={pd/"front-proxy-ca.crt"}') + print('ipam: credentials enrolled (not in the source)',flush=True) +# 2. Flux must report each Milo Kustomization Ready (Deployment and etcd +# healthy), and in synced mode IPAM's: PostgreSQL, then the apiserver, which is +# Ready only once its delegated authentication has read the provider API. +layers=['milo-'+r for r in roles]+(['ipam-system','ipam-apiserver'] if synced else []) +for layer in layers: + kubectl(platform,'-n','flux-system','annotate','--overwrite','kustomization',layer,'reconcile.fluxcd.io/requestedAt='+str(time.time()),stdout=subprocess.DEVNULL) +for layer in layers: + kubectl(platform,'-n','flux-system','wait','--for=condition=Ready','kustomization/'+layer,'--timeout=600s',stdout=subprocess.DEVNULL) # 3. Tenant fixture bootstrap through each project API. for role in roles: d=root/role @@ -80,11 +157,7 @@ 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': - # 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 ()): + for crds in ('config/components/inventory/crds/fleet.datumapis.com.yaml','config/components/device-operations/crds/fleet.datumapis.com.yaml'): 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 @@ -97,9 +170,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, and reads - # allocations to confirm a release; the release controller reads custody - # to keep a held operation's claim. + # Synchronized lab DHCP claims boot addresses from IPAM, which asks this + # API to authorize each request. Each requester claims and releases its + # own boot addresses, and reads allocations to confirm a release; the + # release controller reads custody to keep a held operation's claim. claims={'apiGroups':['ipam.miloapis.com'],'resources':['ipclaims'],'verbs':['get','list','create','delete']} allocations={'apiGroups':['ipam.miloapis.com'],'resources':['ipallocations'],'verbs':['get','list']} if synced:rules+=[claims,allocations] @@ -129,6 +203,7 @@ def wait(fn,seconds,what): for who,component in components.items(): apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRole','metadata':{'name':'fleet-'+who},'rules':component}) apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRoleBinding','metadata':{'name':'fleet-'+who},'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'ClusterRole','name':'fleet-'+who},'subjects':[{'kind':'User','name':who}]}) + if synced:ipam(d,config) if role!='provider':rules += [{'apiGroups':['metal.datumapis.com'],'resources':['machines'],'verbs':['update']},{'apiGroups':['metal.datumapis.com'],'resources':['machines/status','installations/status'],'verbs':['update','patch']}] apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRole','metadata':{'name':'fleet-management'},'rules':rules}) apply(d/'bootstrap.json',{'apiVersion':'rbac.authorization.k8s.io/v1','kind':'ClusterRoleBinding','metadata':{'name':'fleet-management'},'roleRef':{'apiGroup':'rbac.authorization.k8s.io','kind':'ClusterRole','name':'fleet-management'},'subjects':[{'kind':'User','name':'management'}]}) diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index 94c24df7..b805fbeb 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -16,10 +16,17 @@ the replacement observed the target instead of repeating it bmc-interrupt delete the BMC Pod mid-installer; the guest keeps running isolation target B untouched, target A disk verifiably zeroed + ipam-watch synced DHCP only, in the background for the whole run: + sample IPAM's claims and allocations in the provider + project, so dhcp-synced can show what IPAM held during + each boot after the claims are gone + dhcp-synced synced DHCP: boot addresses, reservations, Kea leases + and IPAM's allocations agree, and nothing remains held """ import datetime import hashlib import json +import os import pathlib import secrets import socket @@ -460,7 +467,99 @@ def commission_audit(s): return audit(s)[json.loads((s / 'redfish' / 'commission.json').read_text())['auditEntries']:] +# What the lab IPAM pool can allocate: 192.168.77.0/24 less 100 leading and +# 56 trailing reserved addresses (milo.py). LAB_IPAM_FIRST, LAB_IPAM_LAST = '192.168.77.100', '192.168.77.199' +LAB_POOL = {'total': '256', 'allocated': '156', 'available': '100'} +IPAM_KINDS = 'ipclaims.ipam.miloapis.com,ipallocations.ipam.miloapis.com' + + +def ipam_sample(s): + """One read, through the provider project, of IPAM's boot address claims + and the allocations it holds for them.""" + try: + r = subprocess.run(['kubectl', '--kubeconfig', str(s / 'provider' / 'bootstrap-project.json'), '--request-timeout=10s', '-n', 'fleet-provider', + 'get', IPAM_KINDS, '-o', 'json'], text=True, capture_output=True, timeout=30) + except subprocess.TimeoutExpired: + return {'error': 'timed out'} + if r.returncode: + return {'error': r.stderr.strip()[-200:]} + items = json.loads(r.stdout)['items'] + status = lambda i: i.get('status') or {} + return {'claims': sorted(({'name': i['metadata']['name'], 'phase': status(i).get('phase'), 'address': status(i).get('address'), + 'allocation': (status(i).get('boundAllocationRef') or {}).get('name')} for i in items if i['kind'] == 'IPClaim'), key=lambda c: c['name']), + 'allocations': sorted(({'name': i['metadata']['name'], 'claim': ((i.get('spec') or {}).get('claimRef') or {}).get('name'), 'cidr': status(i).get('allocatedCIDR'), + 'phase': status(i).get('phase')} for i in items if i['kind'] == 'IPAllocation'), key=lambda a: a['name'])} + + +def ipam_watch(s): + """Sample IPAM every two seconds until the acceptance script that started + this exits. Consecutive equal samples collapse into one state that held + from its first to its last sample.""" + parent, path, states = os.getppid(), s / 'redfish' / 'ipam-observations.json', [] + while os.getppid() == parent: + at_ = now() + try: + sample = ipam_sample(s) + except Exception as e: # recorded, never fatal: a gap is visible as an error sample + sample = {'error': repr(e)[-200:]} + if states and states[-1]['sample'] == sample: + states[-1]['to'] = at_ + else: + states.append({'from': at_, 'to': at_, 'sample': sample}) + try: + part = path.with_suffix('.part') + part.write_text(json.dumps(states)) + part.replace(path) + except OSError: + pass # the next write carries every state; dhcp-synced checks freshness + time.sleep(2) + + +def ipam_held(sample, claim, address): + """The allocation name if the sample shows the claim bound to address and + an allocation that names the claim back and holds exactly address/32.""" + c = next((c for c in sample.get('claims', []) if c['name'] == claim), None) + if not c or c['phase'] != 'Bound' or c['address'] != address or not c['allocation']: + return None + a = next((a for a in sample['allocations'] if a['name'] == c['allocation']), None) + return a['name'] if a and a['claim'] == claim and a['cidr'] == address + '/32' else None + + +def ipam_record(states, claim, address, start, end): + """IPAM's record of the claim bound to address, and of the allocation that + claim names, held over start..end (epoch seconds). Either a sample inside + the window shows it, or, when IPAM could not be read inside the window, + samples just before and just after it show the same allocation with only + failed reads between: a claim is immutable and its allocation goes only + with it. None without one.""" + def record(allocation, first, last): + return {'claim': claim, 'address': address, 'allocation': allocation, 'allocationClaimRef': claim, 'allocatedCIDR': address + '/32', + 'observedFrom': first['from'], 'observedTo': last['to']} + before = None + for state in states: + sample, began, ended = state['sample'], at(state['from']).timestamp(), at(state['to']).timestamp() + held = ipam_held(sample, claim, address) if 'claims' in sample else None + if ended < start: + before = (held, state) if held else (None if 'claims' in sample else before) + continue + if began > end: + if held and before and before[0] == held: + return record(held, before[1], state) + return None + if held: + return record(held, state, state) + if 'claims' in sample: + # IPAM answered inside the window without the allocation. + before = None + return None + + +def lease_owners(granted, windows): + """For each lease Kea granted (address, MAC, grant time), the operations + whose boot window contains it at that address. windows maps an operation + name to (address, start, end).""" + return [(lease, [n for n, (address, start, end) in windows.items() if address == lease[0] and start <= lease[2] <= end]) for lease in granted] def at(text): @@ -478,7 +577,8 @@ 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.""" + address, IPAM held it for that operation's claim meanwhile, 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' @@ -515,6 +615,22 @@ def provider(*args): leftover = provider('get', 'ipclaims') if leftover: die('boot address claims remain after every release: %s' % [c['metadata']['name'] for c in leftover]) + held = provider('get', 'ipallocations') + if held: + die('IPAM still holds allocations after every release: %s' % [(a['metadata']['name'], (a.get('spec', {}).get('claimRef') or {}).get('name')) for a in held]) + # Only the pool's own reservations hold addresses now: no release leaked. + r = subprocess.run(['kubectl', '--kubeconfig', str(bootstrap), '--request-timeout=30s', 'get', 'ippool', 'lab-provisioning', '-o', 'json'], text=True, capture_output=True, timeout=60) + if r.returncode: + die('IPAM pool read failed: %s' % r.stderr.strip()[-300:]) + capacity = (json.loads(r.stdout).get('status') or {}).get('capacity') or {} + if capacity != LAB_POOL: + die('the lab IPAM pool reports %s, want %s: only its reservations should hold addresses' % (capacity, LAB_POOL)) + states = json.loads((s / 'redfish' / 'ipam-observations.json').read_text()) if (s / 'redfish' / 'ipam-observations.json').exists() else [] + if not any('claims' in st['sample'] for st in states): + die('no IPAM sample was recorded during the run') + # The sampler ran to the end: its last state is recent. + if time.time() - at(states[-1]['to']).timestamp() > 60: + die('the IPAM sampler stopped at %s; its last sample was %s' % (states[-1]['to'], states[-1]['sample'])) def run(*command, container='libvirt'): return kubectl(s, '-n', SITE, 'exec', 'deploy/fleet-site-runtime', '-c', container, '--', *command, check=False, timeout=120) @@ -534,7 +650,11 @@ def serves(report, address): 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] + # A row with no lifetime records a released or deleted lease. Its grant + # time is unknown, so it is only counted among the answers; the row that + # granted the lease carries the grant time. + granted = [(r['address'], r['hwaddr'].lower(), int(r['expire']) - int(r['valid_lifetime'])) for r in rows if int(r['valid_lifetime'])] + windows = {} # 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'])} @@ -566,8 +686,14 @@ def serves(report, address): # 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] + # IPAM allocated the address to this operation's own claim while its + # boot was open, as sampled by ipam-watch. + ipam = ipam_record(states, o['claim'], o['address'], start, end) + if not ipam: + die('%s %s: IPAM recorded no allocation of %s to claim %s during its boot' % (o['kind'], o['name'], o['address'], o['claim'])) + windows[o['name']] = (o['address'], start, end) 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)) + bootScriptDelivered='admitted boot.ipxe' in delivered, keaLeasesInWindow=len(leased), ipam=ipam) 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']: @@ -575,6 +701,11 @@ def serves(report, address): record['operations'].append(entry) if applied[-1]['feed']['reservations']: die('Kea still serves a reservation after the last operation ended') + # Every lease Kea granted falls in the boot window of an operation whose + # claim IPAM held that address for, so Kea served only IPAM's allocations. + for (address, hwaddr, grant), owners in lease_owners(granted, windows): + if not owners: + die('Kea leased %s to %s at %d outside every operation boot window with an IPAM allocation of it' % (address, hwaddr, grant)) 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]) @@ -585,11 +716,13 @@ def serves(report, address): 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 '/dev/null +# Synchronized lab DHCP adds IPAM and its PostgreSQL beside the Milo APIs. +platform_memory=2300m +[[ ${FLEET_LAB_DHCP:-static} != synced ]] || platform_memory=2800m +docker update --memory "$platform_memory" --memory-swap "$platform_memory" --cpus 2 "$prefix-platform-control-plane" >/dev/null cat > "$state/hub-kind.yaml.template" <<'YAML' kind: Cluster diff --git a/internal/multiplane/ipam.go b/internal/multiplane/ipam.go deleted file mode 100644 index 646bd737..00000000 --- a/internal/multiplane/ipam.go +++ /dev/null @@ -1,72 +0,0 @@ -package multiplane - -import ( - "context" - "fmt" - "net/netip" - "sort" - - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "sigs.k8s.io/controller-runtime/pkg/client" - - "go.datum.net/fleet/internal/bootaddress" -) - -// StandInIPAM binds boot address claims in IPAM's place. The lab has no IPAM -// service: the provider project serves IPAM's claim kind from a CRD, and this -// stand-in, with the bootstrap identity, gives each unbound claim the lowest -// free address in its range, as IPAM would when it creates the claim. Fleet's -// own code claims, checks and releases the addresses exactly as it would -// against IPAM. -type StandInIPAM struct { - Client client.Client - Namespace string - First, Last netip.Addr -} - -// Bind binds every unbound claim, oldest first, and returns how many it -// bound. -func (p StandInIPAM) Bind(ctx context.Context) (int, error) { - list := &unstructured.UnstructuredList{} - list.SetGroupVersionKind(bootaddress.GVK.GroupVersion().WithKind(bootaddress.GVK.Kind + "List")) - if err := p.Client.List(ctx, list, client.InNamespace(p.Namespace)); err != nil { - return 0, err - } - used := map[netip.Addr]bool{} - var unbound []*unstructured.Unstructured - for i := range list.Items { - claim := &list.Items[i] - phase, _, _ := unstructured.NestedString(claim.Object, "status", "phase") - text, _, _ := unstructured.NestedString(claim.Object, "status", "address") - if address, err := netip.ParseAddr(text); err == nil { - used[address] = true - } - if phase != "Bound" && claim.GetDeletionTimestamp() == nil { - unbound = append(unbound, claim) - } - } - sort.Slice(unbound, func(i, j int) bool { - a, b := unbound[i].GetCreationTimestamp(), unbound[j].GetCreationTimestamp() - if !a.Equal(&b) { - return a.Before(&b) - } - return unbound[i].GetName() < unbound[j].GetName() - }) - bound := 0 - next := p.First - for _, claim := range unbound { - for used[next] && next.Compare(p.Last) <= 0 { - next = next.Next() - } - if next.Compare(p.Last) > 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 deleted file mode 100644 index d78c105e..00000000 --- a/internal/multiplane/ipam_test.go +++ /dev/null @@ -1,68 +0,0 @@ -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 a3ef4b13..73eb6f03 100644 --- a/internal/multiplane/runner.go +++ b/internal/multiplane/runner.go @@ -9,7 +9,6 @@ import ( "encoding/json" "errors" "fmt" - "net/netip" "os" "path/filepath" "strings" @@ -85,9 +84,6 @@ 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 { @@ -268,14 +264,10 @@ func New(ctx context.Context, c Config) (*Runner, error) { BootInterface: "primary", TargetDisks: []string{"disk-0"}, } if c.BootAddressClass != "" { + // IPAM, aggregated by the provider project's Milo API, binds each claim + // from the lab pool, which allocates only 192.168.77.100-199: the + // static leases sit below .100, so a boot address is never one. 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 fbd5d724b5238cb344ad4584fe95ffb827213251 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 19:56:41 -0600 Subject: [PATCH 2/4] test(multiplane): Drop a stale IPAM sample before a boot Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/test-redfish.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/hack/multiplane/test-redfish.py b/hack/multiplane/test-redfish.py index 530fbb18..61de0fd5 100644 --- a/hack/multiplane/test-redfish.py +++ b/hack/multiplane/test-redfish.py @@ -210,6 +210,9 @@ def build(path): check('an answer inside the window without the allocation breaks the bracket', redfish_steps.ipam_record([outage[0], state('2026-11-20T10:00:00Z', '2026-11-20T10:00:20Z', [], []), failed('2026-11-20T10:00:22Z', '2026-11-20T10:01:00Z'), state('2026-11-20T10:01:02Z', '2026-11-20T10:05:00Z', [claim], [allocation])], 'op-a-boot', '192.168.77.100', t0 + 10, t0 + 50) is None) +check('an answer before the window without the allocation clears the sample before it', + redfish_steps.ipam_record([outage[0], state('2026-11-20T09:59:59Z', '2026-11-20T09:59:59Z', [], []), failed('2026-11-20T10:00:00Z', '2026-11-20T10:01:00Z'), + state('2026-11-20T10:01:02Z', '2026-11-20T10:05:00Z', [claim], [allocation])], 'op-a-boot', '192.168.77.100', t0 + 10, t0 + 50) is None) owners = redfish_steps.lease_owners([('192.168.77.100', 'm', t0 + 30), ('192.168.77.100', 'm', t0 + 300), ('192.168.77.101', 'm', t0 + 30)], {'op-a': ('192.168.77.100', t0, t0 + 60), 'op-b': ('192.168.77.100', t0 + 200, t0 + 400)}) check('each Kea lease belongs to the boot window holding its address', [o for _, o in owners] == [['op-a'], ['op-b'], []], str(owners)) From b0757e00fc38df1c73fde473daef5115d4934f32 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 19:34:25 -0600 Subject: [PATCH 3/4] fix(multiplane): Give IPAM's lab token only to synced runs The provider Milo in every lab run held a cluster-admin token for IPAM, which only synchronized DHCP runs. It now exists only there, and IPAM's sampler starts only for the scenario groups that release a target. The synchronized DHCP evidence also counts a Kea row that renews a live lease as that lease, reads a claim's address from its single-host CIDR when IPAM sets no address, and keys each boot window by its admission. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/acceptance-redfish.sh | 2 +- hack/multiplane/milo.py | 3 ++- hack/multiplane/redfish_steps.py | 22 +++++++++++++++++++--- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/hack/multiplane/acceptance-redfish.sh b/hack/multiplane/acceptance-redfish.sh index d8b04135..b1c3ad5e 100755 --- a/hack/multiplane/acceptance-redfish.sh +++ b/hack/multiplane/acceptance-redfish.sh @@ -20,7 +20,7 @@ runs() { [[ $group == all || $group == "$1" ]]; } # Synchronized lab DHCP: sample IPAM's claims and allocations for the whole # run, so dhcp-synced can show what IPAM held during each boot. The sampler # stops when this script exits. -if [[ ${FLEET_LAB_DHCP:-static} == synced ]]; then +if [[ ${FLEET_LAB_DHCP:-static} == synced ]] && runs release; then python3 hack/multiplane/redfish_steps.py ipam-watch "$state" >/dev/null 2>&1 & watcher=$! trap 'kill "$watcher" 2>/dev/null || true' EXIT diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py index ad4aa613..e092338b 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -82,7 +82,8 @@ def ipam(d,config): d.mkdir(mode=0o700) # IPAM delegates TokenReview and SubjectAccessReview to the provider API # as system:masters, as the platform's IPAM client identity does. - who=('bootstrap','management','customer')+(('coordinator','release','discovery','staff','projector','plan-author','plan-approver','operator','capacity-operator','ipam') if role=='provider' else ()) + # Only synchronized DHCP runs IPAM, so only it gets IPAM's token. + who=('bootstrap','management','customer')+(('coordinator','release','discovery','staff','projector','plan-author','plan-approver','operator','capacity-operator')+(('ipam',) if synced else ()) if role=='provider' else ()) tokens={r:secrets.token_hex(32) for r in who} (d/'tokens.csv').write_text('\n'.join(f'{v},{k},{k},'+('system:masters' if k in ('bootstrap','ipam') else 'fleet-local') for k,v in tokens.items())+'\n') run('openssl','req','-x509','-newkey','rsa:2048','-nodes','-keyout',str(d/'tls.key'),'-out',str(d/'tls.crt'),'-days','2','-subj','/CN=fleet-local','-addext',f'subjectAltName=DNS:milo-apiserver.{ns}.svc,IP:127.0.0.1',stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index b805fbeb..363cb857 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -486,7 +486,12 @@ def ipam_sample(s): return {'error': r.stderr.strip()[-200:]} items = json.loads(r.stdout)['items'] status = lambda i: i.get('status') or {} - return {'claims': sorted(({'name': i['metadata']['name'], 'phase': status(i).get('phase'), 'address': status(i).get('address'), + def address(i): + # The bound address, or the single host the allocated CIDR names, as + # bootaddress reads a claim. + cidr = status(i).get('allocatedCIDR') or '' + return status(i).get('address') or (cidr[:-3] if cidr.endswith('/32') else None) + return {'claims': sorted(({'name': i['metadata']['name'], 'phase': status(i).get('phase'), 'address': address(i), 'allocation': (status(i).get('boundAllocationRef') or {}).get('name')} for i in items if i['kind'] == 'IPClaim'), key=lambda c: c['name']), 'allocations': sorted(({'name': i['metadata']['name'], 'claim': ((i.get('spec') or {}).get('claimRef') or {}).get('name'), 'cidr': status(i).get('allocatedCIDR'), 'phase': status(i).get('phase')} for i in items if i['kind'] == 'IPAllocation'), key=lambda a: a['name'])} @@ -653,7 +658,18 @@ def serves(report, address): # A row with no lifetime records a released or deleted lease. Its grant # time is unknown, so it is only counted among the answers; the row that # granted the lease carries the grant time. - granted = [(r['address'], r['hwaddr'].lower(), int(r['expire']) - int(r['valid_lifetime'])) for r in rows if int(r['valid_lifetime'])] + # A row that renews a lease still live for the same address and MAC is + # that lease, not a new grant. + granted, live = [], {} + for r in rows: + if not int(r['valid_lifetime']): + continue + lease, grant, expire = (r['address'], r['hwaddr'].lower()), int(r['expire']) - int(r['valid_lifetime']), int(r['expire']) + if lease in live and grant <= live[lease]: + live[lease] = max(live[lease], expire) + continue + live[lease] = expire + granted.append((*lease, grant)) windows = {} # An operation asked for a network boot once its power-on was journaled, # whether or not the boot server then served it. @@ -691,7 +707,7 @@ def serves(report, address): ipam = ipam_record(states, o['claim'], o['address'], start, end) if not ipam: die('%s %s: IPAM recorded no allocation of %s to claim %s during its boot' % (o['kind'], o['name'], o['address'], o['claim'])) - windows[o['name']] = (o['address'], start, end) + windows[o['key']] = (o['address'], start, end) 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), ipam=ipam) if entry['networkBoot'] and not leased: From f0be8dd4aba5acb06225cd1e0578e69d64ee5fdf Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 20:14:07 -0600 Subject: [PATCH 4/4] fix(multiplane): End a Kea lease when it is released A released lease no longer counts as live, so a later grant of the same address and MAC is a new grant, not a renewal. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/redfish_steps.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index 363cb857..47949d57 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -662,9 +662,12 @@ def serves(report, address): # that lease, not a new grant. granted, live = [], {} for r in rows: + lease = (r['address'], r['hwaddr'].lower()) if not int(r['valid_lifetime']): + # A released lease ends: the next grant is a new one. + live.pop(lease, None) continue - lease, grant, expire = (r['address'], r['hwaddr'].lower()), int(r['expire']) - int(r['valid_lifetime']), int(r['expire']) + grant, expire = int(r['expire']) - int(r['valid_lifetime']), int(r['expire']) if lease in live and grant <= live[lease]: live[lease] = max(live[lease], expire) continue