From 54c643ea9b132c91e0f6ea0489777ad66b9a960b Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 09:54:50 -0600 Subject: [PATCH 1/9] feat: Take boot addresses from IPAM and boot NICs from inventory Each requester claims an IPAM address before it creates an installation or wipe and carries it in the operation's boot network input. Admission refuses an address its claim no longer holds. The site publishes the admitted snapshot's boot MAC at that address only while the boot is open, records publishing as a sent step, and succeeds only when no DHCP instance still serves any reservation of the Device. Claims are released only after their operation ended unheld. Site enrollment no longer names MACs or provisioning addresses. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-multiplane/main.go | 6 +- cmd/fleet-multiplane/site.go | 8 +- .../crds/fleet.datumapis.com.yaml | 59 ++++ .../device-operations/roles/coordinator.yaml | 1 + .../roles/installation-requester.yaml | 6 +- .../roles/wipe-requester.yaml | 6 +- config/site/redfish/graph/kustomization.yaml | 9 +- docs/development/device-custody.md | 1 + docs/operations/README.md | 2 +- docs/operations/boot-network.md | 189 ++++++++----- docs/operations/redfish-lab.md | 5 +- hack/multiplane/evidence.py | 7 +- hack/multiplane/redfish_steps.py | 5 +- hack/multiplane/test-redfish.py | 4 +- internal/allocation/allocator.go | 51 +++- internal/allocation/bootaddress_test.go | 166 +++++++++++ internal/allocation/harness_test.go | 3 + internal/allocation/release.go | 69 +++++ .../api/operations/v1alpha1/config_test.go | 11 +- internal/api/operations/v1alpha1/types.go | 23 ++ internal/bootaddress/bootaddress.go | 209 ++++++++++++++ internal/bootaddress/bootaddress_test.go | 109 ++++++++ internal/bootaddress/testdata/ipclaims.yaml | 22 ++ internal/bootnet/feed.go | 51 ++-- internal/bootnet/feed_test.go | 24 +- internal/custody/admission_test.go | 53 +++- internal/custody/harness_test.go | 25 +- internal/custody/kinds.go | 69 ++++- internal/dhcpsync/sync.go | 26 +- internal/dhcpsync/sync_test.go | 20 +- internal/redfish/enrollment.go | 75 ++--- internal/redfish/enrollment_test.go | 7 +- internal/site/access.go | 2 +- internal/site/redfishwork/boot.go | 6 +- internal/site/redfishwork/dhcp.go | 100 +++++-- internal/site/redfishwork/dhcp_test.go | 261 ++++++++++++++---- internal/site/redfishwork/kinds.go | 64 ++++- internal/site/redfishwork/kinds_test.go | 4 +- internal/site/runner_test.go | 6 +- internal/site/simwork/kinds.go | 6 + internal/site/vmwork/kinds.go | 6 + internal/site/vmwork/kinds_test.go | 2 +- 42 files changed, 1454 insertions(+), 324 deletions(-) create mode 100644 internal/allocation/bootaddress_test.go create mode 100644 internal/bootaddress/bootaddress.go create mode 100644 internal/bootaddress/bootaddress_test.go create mode 100644 internal/bootaddress/testdata/ipclaims.yaml diff --git a/cmd/fleet-multiplane/main.go b/cmd/fleet-multiplane/main.go index c33dbcfd..aec50164 100644 --- a/cmd/fleet-multiplane/main.go +++ b/cmd/fleet-multiplane/main.go @@ -21,6 +21,7 @@ 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() { @@ -32,7 +33,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|redfish-probe| [flags]") + 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]") } fs := flag.NewFlagSet(os.Args[1], flag.ContinueOnError) once := fs.Bool("once", false, "one attempt, for fault injection") @@ -52,6 +53,7 @@ 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)") if err := fs.Parse(os.Args[2:]); err != nil { return err } @@ -82,6 +84,8 @@ func run() error { return boot(os.Args[1], *origin, *extraMAC, *syncToken) 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 3c4c1f6c..828781ee 100644 --- a/cmd/fleet-multiplane/site.go +++ b/cmd/fleet-multiplane/site.go @@ -253,13 +253,7 @@ func boot(command, origin, extraMAC, syncToken string) error { return err } if command == "dhcp-feed" { - // Reservations name each Device's provisioning attachment, which - // only the enrollment records. - enrollment, err := redfish.ParseEnrollment([]byte(os.Getenv("FLEET_REDFISH_ENROLLMENT"))) - if err != nil { - return err - } - server.Enrollment = enrollment + // 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) diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index c5ca1033..7e1b595f 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -515,6 +515,33 @@ spec: minLength: 1 maxLength: 63 x-kubernetes-list-type: set + bootNetwork: + type: object + properties: + addressClaim: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + uid: + type: string + minLength: 1 + maxLength: 64 + required: + - name + - uid + address: + type: string + minLength: 2 + maxLength: 45 + x-kubernetes-validations: + - rule: isIP(self) + message: address must be one IP address without a prefix length + required: + - addressClaim + - address required: - creator - deviceRef @@ -714,6 +741,37 @@ spec: minLength: 1 maxLength: 63 x-kubernetes-list-type: set + bootInterface: + type: string + minLength: 1 + maxLength: 63 + bootNetwork: + type: object + properties: + addressClaim: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + uid: + type: string + minLength: 1 + maxLength: 64 + required: + - name + - uid + address: + type: string + minLength: 2 + maxLength: 45 + x-kubernetes-validations: + - rule: isIP(self) + message: address must be one IP address without a prefix length + required: + - addressClaim + - address required: - creator - deviceRef @@ -721,6 +779,7 @@ spec: - step - cleaningPolicyDigest - targetDisks + - bootInterface x-kubernetes-validations: - rule: self == oldSelf message: an operation spec is immutable after create diff --git a/config/components/device-operations/roles/coordinator.yaml b/config/components/device-operations/roles/coordinator.yaml index 77b5c27b..afc75e3f 100644 --- a/config/components/device-operations/roles/coordinator.yaml +++ b/config/components/device-operations/roles/coordinator.yaml @@ -53,3 +53,4 @@ spec: - metal.datumapis.com/machinecapacities.get - metal.datumapis.com/machinecapacities.list - metal.datumapis.com/machinecapacities.watch + - ipam.miloapis.com/ipclaims.get diff --git a/config/components/device-operations/roles/installation-requester.yaml b/config/components/device-operations/roles/installation-requester.yaml index 0c78eeeb..d9ca470c 100644 --- a/config/components/device-operations/roles/installation-requester.yaml +++ b/config/components/device-operations/roles/installation-requester.yaml @@ -4,7 +4,7 @@ metadata: name: fleet.datumapis.com-device-installation-requester annotations: kubernetes.io/display-name: Fleet Device Installation Requester - kubernetes.io/description: The Fleet provider for Metal. Creates DeviceInstallations from Installations, and reads custody and the commissioning evidence it evaluates capacity from. + kubernetes.io/description: The Fleet provider for Metal. Creates DeviceInstallations from Installations, claims and releases their boot addresses, and reads custody and the commissioning evidence it evaluates capacity from. spec: launchStage: Alpha includedPermissions: @@ -27,3 +27,7 @@ spec: - fleet.datumapis.com/devicecommissioningplanapprovals.get - fleet.datumapis.com/devicecommissioningplanapprovals.list - fleet.datumapis.com/devicecommissioningplanapprovals.watch + - ipam.miloapis.com/ipclaims.create + - ipam.miloapis.com/ipclaims.get + - ipam.miloapis.com/ipclaims.list + - ipam.miloapis.com/ipclaims.delete diff --git a/config/components/device-operations/roles/wipe-requester.yaml b/config/components/device-operations/roles/wipe-requester.yaml index ff7dce80..0a445933 100644 --- a/config/components/device-operations/roles/wipe-requester.yaml +++ b/config/components/device-operations/roles/wipe-requester.yaml @@ -4,7 +4,7 @@ metadata: name: fleet.datumapis.com-device-wipe-requester annotations: kubernetes.io/display-name: Fleet Device Wipe Requester - kubernetes.io/description: The release controller. Creates DeviceWipes during release and reads custody. + kubernetes.io/description: The release controller. Creates DeviceWipes during release, claims and releases their boot addresses, and reads custody. spec: launchStage: Alpha includedPermissions: @@ -15,3 +15,7 @@ spec: - fleet.datumapis.com/devicecustodies.get - fleet.datumapis.com/devicecustodies.list - fleet.datumapis.com/devicecustodies.watch + - ipam.miloapis.com/ipclaims.create + - ipam.miloapis.com/ipclaims.get + - ipam.miloapis.com/ipclaims.list + - ipam.miloapis.com/ipclaims.delete diff --git a/config/site/redfish/graph/kustomization.yaml b/config/site/redfish/graph/kustomization.yaml index b6d20b16..324ce59c 100644 --- a/config/site/redfish/graph/kustomization.yaml +++ b/config/site/redfish/graph/kustomization.yaml @@ -25,12 +25,13 @@ patches: - {name: FLEET_SITE_CREDENTIALS_NAMESPACE, value: fleet-site-credentials} - {name: FLEET_SITE_PROJECT, value: provider} # Explicit site enrollment: each Device maps to exactly one BMC - # endpoint, Redfish System (Id and UUID), NIC and console capture. - # The lab's dnsmasq hands out static leases, so DHCP is "static" and - # targets carry no provisioning attachment. Only target A is + # endpoint, Redfish System (Id and UUID) and console capture. The + # boot NIC comes from Device inventory. The lab's dnsmasq hands out + # static leases, so DHCP is "static" and an operation carries no + # boot address. Only target A is # published as capacity; target B is enrolled to prove isolation. - name: FLEET_REDFISH_ENROLLMENT - value: '{"dhcp":"static","targets":[{"device":"fleet-provider/synthetic-device-central-01","endpoint":"https://10.96.0.81:8443","systemID":"System-1","systemUUID":"7f3d0c2e-1a5b-4c6d-8e9f-0a1b2c3d4e0a","mac":"52:54:00:77:01:0a","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","mac":"52:54:00:77:01:0b","diskBytes":2147483648,"console":"target-b.log"}]}' + value: '{"dhcp":"static","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"}]}' - {name: HOME, value: /tmp} - op: replace path: /spec/resources/9/template/spec/template/spec/containers/0/volumeMounts diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index c3355627..9cb5aad8 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -171,6 +171,7 @@ them. | Synthetic staging mode | **Implemented.** The manager's flag handling is unit tested, and no run exercises the mode | | Power projector | **Implemented and verified** by the standalone smoke | | Synchronized DHCP feed on the site store | **Implemented and verified** by a unit test. Not exercised at a site | +| Boot addresses from IPAM as installation and wipe inputs | **Implemented and verified** by tests against a real API server with a stand-in for IPAM's claim API. See [Boot network](../operations/boot-network.md) | ### MachineAllocation diff --git a/docs/operations/README.md b/docs/operations/README.md index faa1907b..e86069d7 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -16,7 +16,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Understand the local VM site that the multi-plane run drives | [Local VM site](local-vm.md) | The workers that install a real OS over firmware PXE into a disposable libvirt domain, boot it from disk, and wipe it; the single-plane harness is retired; not KVM or hardware qualification | | Exercise Milo, Karmada and cell-local PXE end to end with one command | [Multi-plane acceptance](multiplane.md) (`task multiplane:acceptance`) | Native project routing, the custody coordinator, federation delivery/reflection, partition, [Kubernetes site execution](site-execution.md) (Flux-owned shared services, kro-created per-operation Jobs) with worker Pod/Job interruption, delivery and reflection faults, wrong location, release with a wipe and reuse; the run on the custody path passes every phase; every service [installed by per-cluster Flux](gitops.md) from a source built from the checkout; production authority unqualified | | Drive the same pipeline through Redfish instead of libvirt | [Redfish-mode acceptance](redfish-lab.md) (`task multiplane:redfish-acceptance`) | Redfish site workers: per-Device credentials over a pinned TLS key, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; the run on custody passes every phase; not physical BMC or hardware qualification | -| Publish physical-side DHCP reservations for network boot | [Boot network](boot-network.md) | Per-Device BMC endpoints and provisioning attachments, a reservation feed read from the site store that exists only while a boot is admitted, served and withdrawn evidence from the DHCP owner's Kea synchronizer; unit tested, not exercised at a site | +| Publish DHCP reservations for network boot | [Boot network](boot-network.md) | Boot addresses claimed from IPAM per installation and wipe, boot NICs from Device inventory, a reservation feed read from the site store that exists only while a boot is admitted, served and withdrawn evidence from the Kea synchronizer; tested against a real API server and unit tested, not exercised at a site | | Plan a rack slot and register the server bound to it | [Planning and registering physical devices](physical-inventory.md) | Operator-written `DeviceClaim` and `Device` records in the provider project in Milo, with immutable identity and binding, shown read-only in the staff portal; no capacity or hardware effect; unit tested | | Record what each Device's BMC reports | [BMC discovery](bmc-discovery.md) | Read-only Redfish discovery into Device status, with TLS public-key pinning approved per BMC and identity compared with spec; unit and TLS end-to-end tested, not qualified on vendor hardware | | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index 5a12bc7a..c8e4953a 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -1,38 +1,74 @@ -# Boot network: physical addresses and DHCP reservations - -A physical host has addresses that belong to the asset, separate from the -addresses a consumer's Machine receives. Fleet records the physical ones in the -site enrollment and, for network boot, publishes a DHCP reservation only while an -operation's boot is admitted at the Device's stored fence. The network owner's DHCP applies it and reports -back; those reports are the evidence that the boot was reachable and that -provisioning networking was later revoked. - -This page describes the implemented contract. The design and its alternatives -are in the [boot network enhancement](../enhancements/boot-network/README.md). -What is still proposed is listed under -[Implemented versus proposed](#implemented-versus-proposed). +# Boot network: boot addresses and DHCP reservations + +A server that network-boots needs a provisioning address while Fleet installs +or wipes it, and none afterwards. Fleet claims that address from IPAM for each +installation and wipe, and carries it in the operation. The boot NIC comes from +Device inventory. At a site whose DHCP Fleet synchronizes, the site publishes a +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. + +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 +is still proposed is listed under [Implemented versus +proposed](#implemented-versus-proposed). ## Two kinds of address | | Address | Belongs to | Lifetime | Owner | | --- | --- | --- | --- | --- | | Physical | BMC endpoint | Physical asset | The hardware's life | Networking/IPAM (out-of-band) | -| | Provisioning attachment (address and gateway) | Physical asset, during an admitted network boot | The boot window | Networking/IPAM allocates; Fleet publishes | +| | Boot address | One installation or wipe | Until no DHCP instance can still serve it | IPAM assigns; Fleet claims and publishes | | | Underlay (loopback, routing peers) | Physical host on the fabric | The host's life on the site | Galactic and IPAM | | Consumer | Machine interfaces (`Machine.spec.networkInterfaces`) | Allocation | Allocation to release | Networking/IPAM, through the Machine | -A provisioning address must not be a consumer address. Release fences -provisioning networking, so Fleet must be able to withdraw the provisioning -address without touching anything a tenant uses. A site whose firmware boots on -the same untagged network and address as the running OS cannot meet that, and -needs a dedicated provisioning network on the install NIC. +A boot address must not be a consumer address. A site whose firmware boots on +the same untagged network and address as the running OS cannot withdraw one +without the other, and needs a dedicated provisioning network on the boot NIC. + +## Boot address claims + +When the allocator is configured with a provisioning IPAM class, each requester +claims a boot address before it creates its operation: + +- the Metal provider, for a `DeviceInstallation`; and +- the release controller, for a `DeviceWipe`. + +The claim is an IPAM `IPClaim` in the provider project named +`-boot`, labeled with the allocation, the operation and the +operation kind. It asks for one IPv4 host address and `reclaimPolicy: Delete`. +IPAM binds it when it is created. The requester copies the claim's name, UID +and address into the operation's `spec.bootNetwork`: + +```yaml +spec: + bootInterface: primary + bootNetwork: + addressClaim: {name: alloc-3b9d61c2-install-1-boot, uid: 1d2f7a9e-0b3c-4e5f-8a6b-7c8d9e0f1a2b} + address: 198.51.100.10 +``` + +Admission refuses the operation with `BootAddressUnavailable` unless that claim +incarnation exists, is `Bound`, and holds that address. It refuses it with +`BootInterfaceUnknown` unless the Device records the boot interface with a MAC. +The admission snapshot records that MAC. + +Each requester deletes only its own kind's claims, during release: + +- a claim whose operation ended and is not the recovery hold; and +- every remaining claim once the allocation is released. + +A claim whose operation does not exist yet stays, so a requester that crashed +between the claim and the operation still finds it. The roles grant each +requester `create`, `get`, `list` and `delete` on `ipclaims`, and the +coordinator `get`. ## Enrollment The site enrollment (`FLEET_REDFISH_ENROLLMENT`) is the explicit mapping of the -Devices a Redfish site serves. It sets a site DHCP mode and, per target, the BMC -endpoint, the Redfish System, the boot NIC and, in synchronized mode, the -provisioning attachment: +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: ```json { @@ -42,8 +78,6 @@ provisioning attachment: "endpoint": "https://192.0.2.20:443", "systemID": "Self", "systemUUID": "00000000-0000-4000-8000-000000000001", - "mac": "00:00:5e:00:53:01", - "provisioning": {"address": "198.51.100.10/24", "gateway": "198.51.100.1"}, "diskBytes": 960197124096, "console": "example-01.log" }] @@ -55,47 +89,52 @@ provisioning attachment: the same Id (`Self`), so a System is identified by its endpoint plus Id, and by its UUID. - **`dhcp: static`** means the site's DHCP is configured independently of Fleet. - Targets must not carry a provisioning attachment. The Redfish lab uses this - mode: its dnsmasq hands out fixed leases. -- **`dhcp: synced`** requires a provisioning attachment on every target: a host - address in prefix form and a different host in the same prefix as gateway. - Provisioning addresses are unique within the enrollment. + The site refuses an operation with a boot address + (`BootNetworkUnsupported`). The Redfish lab uses this mode: its dnsmasq hands + 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`). -Before it sends anything, the site worker checks the enrollment against the -operation's admitted snapshot: the BMC endpoint, the system UUID and the boot -MAC. A mismatch ends the operation without an effect. +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. ## Reservation lifecycle -In synchronized mode the site serves a reservation feed derived only from the -site store. A target's boot NIC holds its provisioning address while its -operation's boot admission: +At a synchronized site, the site serves a reservation feed derived only from +the site store. A boot admission publishes the snapshot's boot MAC at the +operation's boot address while it: - is at the Device's stored fence, so a superseded operation holds none; - has a window that has not expired; and - has not been closed. -That window opens at admission, before power-on, so DHCP is ready when firmware -asks. The boot handler's narrower rule still decides which scripts and artifacts -are served. +The worker journals a `boot-reservation` step before it stores the admission, +so an operation that published a reservation can end `Succeeded` or +`OutcomeUnknown`, never `Failed`. That keeps its address claimed until +withdrawal is proven. The worker gates its effects on reports: -1. **Before arming a network boot** it waits, with no effect, until some DHCP - instance reports a feed that serves the boot NIC at its exact provisioning - address, accepted after this operation's boot admission was created. A report - from an earlier operation is not evidence. If the boot window expires first, - the worker stops before it arms the boot, and nothing is sent. -2. **Before reporting success** it waits until every DHCP instance that served - the reservation during this operation reports a later feed without it, for up to ten - minutes. A silent instance may still be serving, so the worker does not - report success. Completion therefore includes verified withdrawal. - -Report times are the boot service's clock and admission times the worker's, so -both roles must run on synchronized clocks. +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 + 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 at the site retires it: + +```sh +FLEET_BOOT_EVIDENCE=/var/lib/fleet-boot fleet-multiplane dhcp-retire -instance dhcp-a +``` -A reservation carries an address and gateway only. It does not tell firmware -what to boot; see the boot-program row below. +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. ## Feed and reports @@ -106,16 +145,17 @@ 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", "gateway", "expires"}]}`. - Reservations are sorted by MAC; the revision is the SHA-256 of their canonical - JSON, so a feed is self-verifying. + `{"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 and instance names. It holds -no token, receipt or boot capability. An unreadable line is treated as -corruption, never as evidence. +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. ## Kea synchronizer @@ -124,28 +164,29 @@ with a stable instance name such as a StatefulSet pod name. Each cycle it: 1. fetches and verifies the feed over HTTPS; 2. reads Kea's PID with `status-get`; -3. when the revision changed or Kea restarted, adds each reservation to the base - configuration's subnet with exactly its prefix, sets the gateway as the - host's `routers` option, and sends `config-set` over Kea's control socket; +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. -A reservation with no matching base subnet fails the cycle; it is never -dropped. A restarted Kea loses its reservations and fails closed until the next -cycle re-applies them. An instance that disappears after serving never reports -withdrawal, which keeps that operation Unknown until an operator resolves it, -so instance names must survive restarts. Before scaling down, drain the -instance being removed until it reports an empty feed. +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. ## Implemented versus proposed | Behavior | Status | | --- | --- | -| Per-target BMC endpoints, endpoint-scoped System identity, static and synced DHCP modes, validated provisioning attachments | Implemented; unit tested | -| Reservation feed, authenticated applied reports, served and withdrawn gates, multi-instance withdrawal | Implemented; unit tested with a fake BMC and synchronizer, including a silent instance | -| Kea synchronizer: exact-subnet placement, restart re-apply, report only after Kea accepted | Implemented; unit tested against a fake Kea control socket | -| Provisioning attachments allocated by Networking/IPAM instead of enrollment values | Proposed | -| NIC MACs and BMC endpoints recorded as Fleet inventory observations | Proposed; the enrollment is the only record | -| Deployment of `dhcp-feed` and the synchronizer, TLS to the feed, relay and provisioning VLAN at a site | Proposed; not exercised end to end | +| 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 | +| 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 | +| 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 rejects it | +| 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 | + +[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 a52cf661..1597ae52 100644 --- a/docs/operations/redfish-lab.md +++ b/docs/operations/redfish-lab.md @@ -143,8 +143,9 @@ ownership audit covers the BMC Deployment, Service and ServiceAccount. The disks, domain UUIDs and MACs exist before any allocation. Each installation or cleanup reuses target A's single persistent disk. The site enrollment is an explicit Device-to-System mapping in the worker template, with each target's BMC -endpoint, System Id, UUID, MAC, disk size and console capture name. The lab sets -`"dhcp": "static"` because its dnsmasq leases are fixed; see +endpoint, System Id, UUID, disk size and console capture name. Target A's boot +NIC MAC is a Device inventory fact, seeded from the lab's VM definitions. The +lab sets `"dhcp": "static"` because its dnsmasq leases are fixed; see [Boot network](boot-network.md) for synchronized DHCP. Before any request, the worker checks the enrollment against the admitted snapshot. diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index 68ce85a4..7cd5439a 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -154,6 +154,11 @@ def site_operations(raw): return store, ops, provider, held +def lab_mac(system): + """The boot NIC of a lab target, as the lab's VM definitions record it.""" + return next(t['mac'] for t in json.loads(pathlib.Path('hack/redfish-lab/targets.json').read_text()) if t['system'] == system).lower() + + def check_sequence(ops, held, interrupt): """Consumer A's allocation holds the interrupted install; the other is B's, whose installation was held at its deadline.""" @@ -315,7 +320,7 @@ def redfish_provider(): expected, receipts = [], [] for o in ops: boot = boot_record(raw, 'boot', o['operation']) - if not boot.get('closed') or boot.get('phase') or boot.get('fence') != o['fence'] or boot.get('mac') != a['mac'].lower(): + if not boot.get('closed') or boot.get('phase') or boot.get('fence') != o['fence'] or boot.get('mac') != lab_mac(a['systemID']): fail('an operation did not keep a closed boot admission for target A at its fence') want = ['FLEET-INSTALLED:' + boot['receipt'], 'FLEET-DISK-BOOT:' + boot['receipt']] if o['kind'] == 'DeviceInstallation' else ['FLEET-WIPED:%s:%d' % (boot['receipt'], a['diskBytes'])] for line in want: diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index 9cde2d8e..40491d2a 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -158,6 +158,9 @@ def enroll(s): 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 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())} fixture = {} for target in enrollment['targets']: namespace, name = target['device'].split('/') @@ -172,7 +175,7 @@ def enroll(s): # from one BMC with one TLS key, and custody refuses a key that # another active Device also records. if target['device'] == 'fleet-provider/synthetic-device-central-01': - fixture[target['device']] = {'bmcEndpoint': target['endpoint'], 'systemUUID': target['systemUUID'], 'bootMACAddress': target['mac'], 'bmcPublicKeySHA256': pin, 'disks': ['disk-0']} + fixture[target['device']] = {'bmcEndpoint': target['endpoint'], 'systemUUID': target['systemUUID'], 'bootMACAddress': lab_macs[target['systemID']], 'bmcPublicKeySHA256': pin, 'disks': ['disk-0']} write(d / 'fixture-enrollment.json', fixture) write(s / 'evidence' / 'redfish-enrollment.json', { 'observedAt': now(), 'credentialSecrets': [CREDENTIALS + '/' + credential_name(t['device']) for t in enrollment['targets']], 'username': 'fleet-lab-operator', diff --git a/hack/multiplane/test-redfish.py b/hack/multiplane/test-redfish.py index d4f7494f..0812d6bf 100644 --- a/hack/multiplane/test-redfish.py +++ b/hack/multiplane/test-redfish.py @@ -80,9 +80,9 @@ def build(path): targets = json.loads((root / 'hack/redfish-lab/targets.json').read_text()) 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: no provisioning attachment published', enrollment.get('dhcp') == 'static' and not any('provisioning' in t for t in enrollment.get('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('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']]['mac'] == t['mac'] + 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]) check('only target A is the published capacity Device', [t.get('device') for t in enrollment.get('targets', [])][:1] == ['fleet-provider/synthetic-device-central-01'] and enrollment['targets'][0].get('systemID') == 'System-1') diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go index 46d809b0..7c071432 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -29,6 +29,7 @@ import ( inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/bootaddress" "go.datum.net/fleet/internal/capacity" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/tenancy" @@ -142,6 +143,11 @@ type Allocator struct { // BootInterface and TargetDisks are pinned on each allocation. BootInterface string TargetDisks []string + // BootAddresses claims each installation's and wipe's provisioning + // address from IPAM when the site's DHCP is synchronized. Its client is + // replaced by the requester's own. Nil means the site's DHCP is + // configured independently of Fleet. + BootAddresses *bootaddress.Claimer } // Get returns the Machine's allocation, or nil. @@ -473,20 +479,63 @@ func (a *Allocator) Install(ctx context.Context, allocation *fleetv1.MachineAllo if err != nil { return nil, err } + name := custody.InstallationName(allocation.Name, string(installation.UID)) + // An existing installation keeps the inputs it was created with; its + // boot address may already be released. + existing := &ops.DeviceInstallation{} + if err := a.Provider.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: name}, existing); err == nil { + return existing, nil + } else if !apierrors.IsNotFound(err) { + return nil, err + } + network, err := a.bootNetwork(ctx, a.installClaims(), allocation, name) + if err != nil { + return nil, err + } labels := operationLabels(allocation) labels[ops.LabelInstallationUID] = string(installation.UID) operation := &ops.DeviceInstallation{ - ObjectMeta: metav1.ObjectMeta{Name: custody.InstallationName(allocation.Name, string(installation.UID)), Namespace: a.Namespace, Labels: labels}, + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: a.Namespace, Labels: labels}, Spec: ops.DeviceInstallationSpec{ OperationEnvelope: a.envelope(allocation, a.ProviderCreator), Image: image, BootInterface: allocation.Spec.BootInterface, TargetDisks: slices.Clone(allocation.Spec.TargetDisks), + BootNetwork: network, }, } return operation, a.createOnce(ctx, a.Provider, operation, &ops.DeviceInstallation{}) } +// installClaims and wipeClaims are each requester's boot address claimer, +// with the requester's own client. They are nil when the site's DHCP is not +// synchronized. +func (a *Allocator) installClaims() *bootaddress.Claimer { + return a.claims(a.Provider, "DeviceInstallation") +} + +func (a *Allocator) wipeClaims() *bootaddress.Claimer { + return a.claims(a.Releaser, "DeviceWipe") +} + +func (a *Allocator) claims(api client.Client, kind string) *bootaddress.Claimer { + if a.BootAddresses == nil { + return nil + } + claimer := *a.BootAddresses + claimer.Client, claimer.Namespace, claimer.Kind = api, a.Namespace, kind + return &claimer +} + +// bootNetwork claims the operation's boot address before the operation +// exists. It returns nil when the site's DHCP is not synchronized. +func (a *Allocator) bootNetwork(ctx context.Context, claimer *bootaddress.Claimer, allocation *fleetv1.MachineAllocation, operation string) (*ops.BootNetworkInput, error) { + if claimer == nil { + return nil, nil + } + return claimer.Claim(ctx, allocation.Name, operation) +} + func (a *Allocator) envelope(allocation *fleetv1.MachineAllocation, creator ops.Creator) ops.OperationEnvelope { return ops.OperationEnvelope{ Creator: creator, diff --git a/internal/allocation/bootaddress_test.go b/internal/allocation/bootaddress_test.go new file mode 100644 index 00000000..22d339a7 --- /dev/null +++ b/internal/allocation/bootaddress_test.go @@ -0,0 +1,166 @@ +package allocation + +import ( + "context" + "encoding/json" + "fmt" + "sync" + "testing" + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "sigs.k8s.io/controller-runtime/pkg/client" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/bootaddress" + "go.datum.net/fleet/internal/custody" + "go.datum.net/fleet/internal/site" + "go.datum.net/fleet/internal/site/simwork" +) + +// ipam binds each IPAM claim as it is created, as IPAM's API does, and +// records the names created, in order. +type ipam struct { + client.Client + mu sync.Mutex + next int + creates []string +} + +func (c *ipam) Create(ctx context.Context, object client.Object, options ...client.CreateOption) error { + if err := c.Client.Create(ctx, object, options...); err != nil { + return err + } + c.mu.Lock() + c.creates = append(c.creates, object.GetName()) + c.next++ + n := c.next + c.mu.Unlock() + claim, ok := object.(*unstructured.Unstructured) + if !ok || claim.GroupVersionKind() != bootaddress.GVK { + return nil + } + claim.Object["status"] = map[string]any{"phase": "Bound", "address": fmt.Sprintf("198.51.100.%d", 10+n)} + return c.Client.Status().Update(ctx, claim) +} + +func (c *ipam) created() []string { + c.mu.Lock() + defer c.mu.Unlock() + return append([]string(nil), c.creates...) +} + +// syncedSite is a simulated site whose DHCP Fleet synchronizes: it requires +// a boot address, then runs the simulator's worker on the rest. +type syncedSite struct{ inner site.Kind } + +func (k syncedSite) strip(work *site.Work) (*site.Work, bool) { + var inputs map[string]json.RawMessage + if json.Unmarshal(work.Inputs, &inputs) != nil || inputs["bootNetwork"] == nil { + return nil, false + } + delete(inputs, "bootNetwork") + copied := *work + copied.Inputs, _ = json.Marshal(inputs) + return &copied, true +} + +func (k syncedSite) Check(ctx context.Context, work *site.Work) *custody.Refusal { + stripped, ok := k.strip(work) + if !ok { + return &custody.Refusal{Reason: custody.ReasonBootNetworkRequired, Message: "a synchronized site needs a boot address"} + } + return k.inner.Check(ctx, stripped) +} + +func (k syncedSite) Run(ctx context.Context, work *site.Work) (any, error) { + stripped, _ := k.strip(work) + return k.inner.Run(ctx, stripped) +} + +// TestBootAddressesFollowTheirOperations claims each installation's and +// wipe's boot address before the operation exists, carries it into the +// admitted inputs, and releases a claim only once its operation ended and +// is not held. +func TestBootAddressesFollowTheirOperations(t *testing.T) { + e := startEnv(t) + e.runner.Kinds["DeviceInstallation"] = syncedSite{simwork.Installation{}} + e.runner.Kinds["DeviceWipe"] = syncedSite{simwork.Wipe{}} + recorder := &ipam{Client: e.admin} + e.allocator.Provider, e.allocator.Releaser = recorder, recorder + e.allocator.BootAddresses = &bootaddress.Claimer{Class: "provisioning"} + device := e.server(1) + + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + operation, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: e.installation(1, "debian-12", "")}) + if err != nil { + t.Fatal(err) + } + network := operation.Spec.BootNetwork + if network == nil || network.AddressClaim.Name != bootaddress.ClaimName(operation.Name) || network.AddressClaim.UID == "" || network.Address == "" { + t.Fatalf("boot network = %+v", network) + } + creates := recorder.created() + if len(creates) != 3 || creates[0] != allocation.Name || creates[1] != network.AddressClaim.Name || creates[2] != operation.Name { + t.Fatalf("creates = %v, want the claim before the operation", creates) + } + e.until("the installation succeeds", func() bool { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(operation), operation); err != nil { + t.Fatal(err) + } + if operation.Status.Phase.Ended() && operation.Status.Phase != ops.PhaseSucceeded { + t.Fatalf("installation ended %s: %s", operation.Status.Phase, operation.Status.Message) + } + return operation.Status.Phase == ops.PhaseSucceeded + }) + if state := e.custody(device.Name); state.Spec.LastResult == nil || state.Spec.LastResult.Name != operation.Name { + t.Fatalf("custody = %+v", state.Spec) + } + // Asking again returns the existing operation and claims nothing new. + if _, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: e.installation(1, "debian-12", "")}); err != nil || len(recorder.created()) != 3 { + t.Fatalf("repeat install: %v, creates %v", err, recorder.created()) + } + + claims := e.allocator.installClaims() + held := &ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: "DeviceInstallation", Name: operation.Name}} + // A claim for an operation not yet created stays: its requester may + // still create the operation. + if _, err := claims.Claim(e.ctx, allocation.Name, allocation.Name+"-install-pending"); err != nil { + t.Fatal(err) + } + if none, err := e.allocator.releaseBootAddresses(e.ctx, allocation, held, false); err != nil || none { + t.Fatalf("release under a hold: none=%v %v", none, err) + } + if remaining, _ := claims.Operations(e.ctx, allocation.Name); len(remaining) != 2 { + t.Fatalf("a held or uncreated operation lost its claim: %v", remaining) + } + if none, err := e.allocator.releaseBootAddresses(e.ctx, allocation, nil, false); err != nil || none { + t.Fatalf("release without a hold: none=%v %v", none, err) + } + if remaining, _ := claims.Operations(e.ctx, allocation.Name); len(remaining) != 1 || remaining[0] != allocation.Name+"-install-pending" { + t.Fatalf("remaining = %v, want only the uncreated operation's claim", remaining) + } + + e.release(allocation, machine(1)) + if allocation.Status.Wipe == nil { + t.Fatal("release did not wipe") + } + wipe := &ops.DeviceWipe{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: allocation.Status.Wipe.Name}, wipe); err != nil { + t.Fatal(err) + } + if wipe.Spec.BootNetwork == nil || wipe.Spec.BootInterface != "primary" || wipe.Spec.BootNetwork.Address == network.Address { + t.Fatalf("wipe boot network = %+v on %q, want its own address", wipe.Spec.BootNetwork, wipe.Spec.BootInterface) + } + for _, claimer := range []*bootaddress.Claimer{claims, e.allocator.wipeClaims()} { + if remaining, err := claimer.Operations(e.ctx, allocation.Name); err != nil || len(remaining) != 0 { + t.Fatalf("claims left after release: %v, %v", remaining, err) + } + } + if allocation.Status.Phase != fleetv1.AllocationReleased { + t.Fatalf("phase = %s", allocation.Status.Phase) + } +} diff --git a/internal/allocation/harness_test.go b/internal/allocation/harness_test.go index 7d662aea..b57de3a3 100644 --- a/internal/allocation/harness_test.go +++ b/internal/allocation/harness_test.go @@ -54,6 +54,7 @@ type env struct { allocator *Allocator loop *delivery.Loop store *site.Store + runner *site.Runner enrollment fixture.Enrollment class *fleetv1.MachineClass profile *fleetv1.MachineProfile @@ -82,6 +83,7 @@ func startEnv(t *testing.T) *env { filepath.Join(root, "config", "base", "crd"), filepath.Join(root, "config", "components", "inventory", "crds"), filepath.Join(root, "config", "components", "device-operations", "crds"), + filepath.Join(root, "internal", "bootaddress", "testdata"), }, ErrorIfCRDPathMissing: true} config, err := environment.Start() if err != nil { @@ -107,6 +109,7 @@ func startEnv(t *testing.T) *env { } runner := &site.Runner{Site: siteName, Store: e.store, Results: site.NewResults(e.store), Access: fixture.Access{Enrollment: e.enrollment}, Kinds: map[string]site.Kind{"DeviceInstallation": simwork.Installation{}, "DeviceWipe": simwork.Wipe{}, "DeviceCommissioning": simwork.Commissioning{}}, Poll: 20 * time.Millisecond} + e.runner = runner dispatcher := &siteapi.Dispatcher{Runner: runner, Context: ctx} server := httptest.NewServer(siteapi.Handler(dispatcher, e.store, runner.Results, func() (string, error) { return siteToken, nil })) t.Cleanup(func() { cancel(); server.Close(); dispatcher.Wait() }) diff --git a/internal/allocation/release.go b/internal/allocation/release.go index 7b60b25f..b501d033 100644 --- a/internal/allocation/release.go +++ b/internal/allocation/release.go @@ -12,6 +12,7 @@ import ( ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/bootaddress" "go.datum.net/fleet/internal/custody" ) @@ -52,8 +53,14 @@ func (a *Allocator) Release(ctx context.Context, allocation *fleetv1.MachineAllo if err := a.releaseQuota(ctx, allocation, machine); err != nil { return false, err } + if gone, err := a.releaseBootAddresses(ctx, allocation, nil, true); err != nil || !gone { + return false, err + } return true, a.setPhase(ctx, allocation, fleetv1.AllocationReleased) } + if _, err := a.releaseBootAddresses(ctx, allocation, state.Spec.RecoveryHold, false); err != nil { + return false, err + } if err := a.setPhase(ctx, allocation, fleetv1.AllocationReleasing); err != nil { return false, err } @@ -90,6 +97,57 @@ func (a *Allocator) Release(ctx context.Context, allocation *fleetv1.MachineAllo return false, nil } +// releaseBootAddresses deletes the boot address claims of the allocation's +// ended operations, each with its requester's client, and reports whether +// none remain. A held operation keeps its claim, because a silent DHCP +// instance may still serve its address, and so does an operation not yet +// created. With all, it deletes every claim: the Device left the allocation, +// so no operation of it is held or can still be created. +func (a *Allocator) releaseBootAddresses(ctx context.Context, allocation *fleetv1.MachineAllocation, hold *ops.RecoveryHold, all bool) (bool, error) { + none := true + for _, pair := range []struct { + claimer *bootaddress.Claimer + api client.Client + new func() ops.Operation + }{ + {a.installClaims(), a.Provider, func() ops.Operation { return &ops.DeviceInstallation{} }}, + {a.wipeClaims(), a.Releaser, func() ops.Operation { return &ops.DeviceWipe{} }}, + } { + if pair.claimer == nil { + continue + } + operations, err := pair.claimer.Operations(ctx, allocation.Name) + if err != nil { + return false, err + } + for _, name := range operations { + if !all { + if hold != nil && hold.Name == name { + none = false + continue + } + operation := pair.new() + if err := pair.api.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: name}, operation); apierrors.IsNotFound(err) { + none = false + continue + } else if err != nil { + return false, err + } + if !operation.OperationStatus().Phase.Ended() { + none = false + continue + } + } + gone, err := pair.claimer.Release(ctx, name) + if err != nil { + return false, err + } + none = none && gone + } + } + return none, nil +} + func (a *Allocator) releaseQuota(ctx context.Context, _ *fleetv1.MachineAllocation, machine Machine) error { if a.Quota == nil { return nil @@ -175,6 +233,15 @@ func (a *Allocator) wipe(ctx context.Context, allocation *fleetv1.MachineAllocat return err } } + if err := a.Releaser.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: reference.Name}, &ops.DeviceWipe{}); err == nil { + return nil + } else if !apierrors.IsNotFound(err) { + return err + } + network, err := a.bootNetwork(ctx, a.wipeClaims(), allocation, reference.Name) + if err != nil { + return err + } wipe := &ops.DeviceWipe{ ObjectMeta: metav1.ObjectMeta{Name: reference.Name, Namespace: a.Namespace, Labels: operationLabels(allocation)}, Spec: ops.DeviceWipeSpec{ @@ -182,6 +249,8 @@ func (a *Allocator) wipe(ctx context.Context, allocation *fleetv1.MachineAllocat Step: reference.Step, CleaningPolicyDigest: allocation.Spec.CleaningPolicyDigest, TargetDisks: slices.Clone(allocation.Spec.TargetDisks), + BootInterface: allocation.Spec.BootInterface, + BootNetwork: network, }, } return a.createOnce(ctx, a.Releaser, wipe, &ops.DeviceWipe{}) diff --git a/internal/api/operations/v1alpha1/config_test.go b/internal/api/operations/v1alpha1/config_test.go index 5d33b255..60587b01 100644 --- a/internal/api/operations/v1alpha1/config_test.go +++ b/internal/api/operations/v1alpha1/config_test.go @@ -180,6 +180,11 @@ func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { declared(t, filepath.Join(componentRoot, "protected-resources"), permissions) declared(t, filepath.Join(configRoot, "components", "inventory", "protected-resources"), permissions) declared(t, filepath.Join(configRoot, "components", "iam", "protected-resources"), permissions) + // IPAM declares its own ProtectedResources. The requesters claim boot + // addresses, and the coordinator reads them at admission. + for _, verb := range []string{"create", "get", "list", "delete"} { + permissions["ipam.miloapis.com/ipclaims."+verb] = true + } roles := map[string]role{} for _, r := range decodeDir[role](t, filepath.Join(componentRoot, "roles")) { roles[r.Metadata.Name] = r @@ -206,12 +211,12 @@ func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { "fleet.datumapis.com-device-commissioning-plan-approver": p(group+"devicecommissioningplanapprovals", "create", "delete"), "fleet.datumapis.com-device-recovery-operator": slices.Concat(p(group+"devicerecoveries", "create"), p("metal.datumapis.com/machineallocations", read...)), "fleet.datumapis.com-device-installation-requester": slices.Concat(p(group+"deviceinstallations", "create", "get", "list", "watch"), p(group+"devicecustodies", read...), - p(group+"devices", read...), p(group+"devicecommissionings", read...), p(group+"devicecommissioningplans", read...), p(group+"devicecommissioningplanapprovals", read...)), + p(group+"devices", read...), p(group+"devicecommissionings", read...), p(group+"devicecommissioningplans", read...), p(group+"devicecommissioningplanapprovals", read...), p("ipam.miloapis.com/ipclaims", "create", "get", "list", "delete")), "fleet.datumapis.com-capacity-projector": slices.Concat(p("metal.datumapis.com/machinecapacities", "get", "list", "watch", "updateStatus"), p(group+"devices", read...), p(group+"devicecustodies", read...), p(group+"devicecommissionings", read...), p(group+"devicecommissioningplans", read...), p(group+"devicecommissioningplanapprovals", read...)), - "fleet.datumapis.com-device-wipe-requester": slices.Concat(p(group+"devicewipes", "create", "get", "list", "watch"), p(group+"devicecustodies", read...)), + "fleet.datumapis.com-device-wipe-requester": slices.Concat(p(group+"devicewipes", "create", "get", "list", "watch"), p(group+"devicecustodies", read...), p("ipam.miloapis.com/ipclaims", "create", "get", "list", "delete")), } - coordinator := slices.Concat(p(group+"devicecustodies", "get", "list", "watch", "create", "update", "delete"), p(group+"devices", read...), p("metal.datumapis.com/machineallocations", read...), p("metal.datumapis.com/machinecapacities", read...)) + coordinator := slices.Concat(p(group+"devicecustodies", "get", "list", "watch", "create", "update", "delete"), p(group+"devices", read...), p("metal.datumapis.com/machineallocations", read...), p("metal.datumapis.com/machinecapacities", read...), p("ipam.miloapis.com/ipclaims", "get")) for _, plural := range []string{"deviceinstallations", "devicewipes", "devicerecoveries", "devicecommissionings"} { coordinator = slices.Concat(coordinator, p(group+plural, "get", "list", "watch", "delete", "updateStatus"), []string{group + plural + "/status.update"}) } diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index a5aaa47d..aecd97a5 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -304,6 +304,26 @@ type DeviceInstallationSpec struct { Bootstrap *SealedInput `json:"bootstrap,omitempty"` BootInterface string `json:"bootInterface"` TargetDisks []string `json:"targetDisks"` + // BootNetwork is the provisioning address for the network boot. It is + // required at a site whose DHCP is synchronized and refused elsewhere. + BootNetwork *BootNetworkInput `json:"bootNetwork,omitempty"` +} + +// BootNetworkInput is the provisioning address IPAM assigned to one +// operation. The site answers DHCP for the boot NIC with Address only while +// the operation runs. The requester claims the address before it creates the +// operation and releases the claim when the operation can no longer reach +// DHCP. +type BootNetworkInput struct { + AddressClaim ClaimReference `json:"addressClaim"` + // Address is the bound host address, without a prefix length. + Address string `json:"address"` +} + +// ClaimReference names one IPAM claim incarnation in the provider project. +type ClaimReference struct { + Name string `json:"name"` + UID string `json:"uid"` } type ImageInput struct { @@ -347,6 +367,9 @@ type DeviceWipeSpec struct { // pinned at allocation. CleaningPolicyDigest string `json:"cleaningPolicyDigest"` TargetDisks []string `json:"targetDisks"` + // BootInterface names the Device interface the wipe network-boots. + BootInterface string `json:"bootInterface"` + BootNetwork *BootNetworkInput `json:"bootNetwork,omitempty"` } // WipeEvidence is the result evidence of a DeviceWipe. diff --git a/internal/bootaddress/bootaddress.go b/internal/bootaddress/bootaddress.go new file mode 100644 index 00000000..8bf823a3 --- /dev/null +++ b/internal/bootaddress/bootaddress.go @@ -0,0 +1,209 @@ +// Package bootaddress claims a provisioning address from IPAM for one +// network-booting operation, and checks a claimed address at admission. +// +// The requester of an installation or wipe claims the address before it +// creates the operation, under a name derived from the operation, so a retry +// finds the same claim. It releases the claim once the operation can no +// longer reach DHCP: after the operation ends, or, for an unknown outcome, +// after its recovery hold is settled. Fleet reads only the claim's bound +// address; the gateway and prefix stay in the DHCP owner's base +// configuration. +package bootaddress + +import ( + "context" + "errors" + "fmt" + "net/netip" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/client" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" +) + +// GVK is IPAM's address claim. +var GVK = schema.GroupVersionKind{Group: "ipam.miloapis.com", Version: "v1alpha1", Kind: "IPClaim"} + +// Labels name the allocation and operation a claim belongs to. +const ( + AllocationLabel = "fleet.datumapis.com/allocation" + OperationLabel = "fleet.datumapis.com/operation" + KindLabel = "fleet.datumapis.com/operation-kind" +) + +var ( + // ErrPending means IPAM has not bound the claim yet. + ErrPending = errors.New("the boot address claim is not bound yet") + // ErrUnavailable means the claim is missing, another incarnation, or + // bound to another address. + ErrUnavailable = errors.New("the boot address claim does not hold the admitted address") + // ErrConflict means a claim with the operation's name has other inputs. + ErrConflict = errors.New("the boot address claim has other inputs") +) + +// ClaimName is the only name an operation's boot address claim may have. +func ClaimName(operation string) string { return operation + "-boot" } + +// ScopeRef is one IPAM scope reference, such as the site's location. +type ScopeRef struct { + APIGroup string + Kind string + Name string +} + +// Claimer claims and releases boot addresses in the provider project, for +// one requester and one operation kind. Each requester releases only the +// claims it made. +type Claimer struct { + // Kind is the operation kind the requester creates. + Kind string + // Client must read through to the API server. + Client client.Client + // Namespace is the operations' namespace. + Namespace string + // Class is the network owner's provisioning IPAM class. + Class string + // Scope is passed to IPAM as the claim's scope. + Scope map[string]ScopeRef +} + +func (c Claimer) desired(allocation, operation string) *unstructured.Unstructured { + claim := &unstructured.Unstructured{} + claim.SetGroupVersionKind(GVK) + claim.SetNamespace(c.Namespace) + claim.SetName(ClaimName(operation)) + claim.SetLabels(map[string]string{AllocationLabel: allocation, OperationLabel: operation, KindLabel: c.Kind}) + spec := map[string]any{"className": c.Class, "ipFamily": "IPv4", "prefixLength": int64(32), "reclaimPolicy": "Delete"} + if len(c.Scope) > 0 { + scope := map[string]any{} + for role, ref := range c.Scope { + scope[role] = map[string]any{"apiGroup": ref.APIGroup, "kind": ref.Kind, "name": ref.Name} + } + spec["scope"] = scope + } + claim.Object["spec"] = spec + return claim +} + +// Claim returns the operation's bound boot address, creating its claim once. +// It returns ErrPending until IPAM binds the claim. +func (c Claimer) Claim(ctx context.Context, allocation, operation string) (*ops.BootNetworkInput, error) { + if c.Client == nil || c.Namespace == "" || c.Class == "" || c.Kind == "" || allocation == "" || operation == "" { + return nil, errors.New("bootaddress: a client, namespace, class, kind, allocation and operation are required") + } + desired := c.desired(allocation, operation) + claim, err := c.get(ctx, desired.GetName()) + if apierrors.IsNotFound(err) { + if err := c.Client.Create(ctx, desired); err != nil && !apierrors.IsAlreadyExists(err) { + return nil, err + } + claim, err = c.get(ctx, desired.GetName()) + } + if err != nil { + return nil, err + } + if labels := claim.GetLabels(); labels[OperationLabel] != operation || labels[AllocationLabel] != allocation || labels[KindLabel] != c.Kind || stringAt(claim, "spec", "className") != c.Class { + return nil, fmt.Errorf("%w: %s", ErrConflict, claim.GetName()) + } + address, err := bound(claim) + if err != nil { + return nil, err + } + return &ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: claim.GetName(), UID: string(claim.GetUID())}, Address: address}, nil +} + +// Release deletes the operation's claim. It returns true once the claim is +// gone. +func (c Claimer) Release(ctx context.Context, operation string) (bool, error) { + claim, err := c.get(ctx, ClaimName(operation)) + if apierrors.IsNotFound(err) { + return true, nil + } + if err != nil { + return false, err + } + if claim.GetLabels()[OperationLabel] != operation || claim.GetLabels()[KindLabel] != c.Kind { + return false, fmt.Errorf("%w: %s", ErrConflict, claim.GetName()) + } + if claim.GetDeletionTimestamp() == nil { + uid := claim.GetUID() + if err := c.Client.Delete(ctx, claim, client.Preconditions{UID: &uid}); err != nil && !apierrors.IsNotFound(err) { + return false, err + } + } + return false, nil +} + +// Operations returns the operations of the claimer's kind in an allocation +// that still have a boot address claim. +func (c Claimer) Operations(ctx context.Context, allocation string) ([]string, error) { + list := &unstructured.UnstructuredList{} + list.SetGroupVersionKind(GVK.GroupVersion().WithKind(GVK.Kind + "List")) + if err := c.Client.List(ctx, list, client.InNamespace(c.Namespace), client.MatchingLabels{AllocationLabel: allocation, KindLabel: c.Kind}); err != nil { + return nil, err + } + var operations []string + for _, claim := range list.Items { + if operation := claim.GetLabels()[OperationLabel]; operation != "" && claim.GetName() == ClaimName(operation) { + operations = append(operations, operation) + } + } + return operations, nil +} + +func (c Claimer) get(ctx context.Context, name string) (*unstructured.Unstructured, error) { + claim := &unstructured.Unstructured{} + claim.SetGroupVersionKind(GVK) + return claim, c.Client.Get(ctx, client.ObjectKey{Namespace: c.Namespace, Name: name}, claim) +} + +// Verify requires the named claim incarnation to be bound to exactly the +// input's address. Admission calls it with the provider project's reader. +func Verify(ctx context.Context, reader client.Reader, namespace string, input ops.BootNetworkInput) error { + if reader == nil { + return ErrUnavailable + } + claim := &unstructured.Unstructured{} + claim.SetGroupVersionKind(GVK) + if err := reader.Get(ctx, client.ObjectKey{Namespace: namespace, Name: input.AddressClaim.Name}, claim); err != nil { + return fmt.Errorf("%w: %v", ErrUnavailable, err) + } + if string(claim.GetUID()) != input.AddressClaim.UID || claim.GetDeletionTimestamp() != nil { + return fmt.Errorf("%w: the claim is another incarnation or is being deleted", ErrUnavailable) + } + address, err := bound(claim) + if err != nil { + return fmt.Errorf("%w: %v", ErrUnavailable, err) + } + want, err := netip.ParseAddr(input.Address) + if err != nil || want.String() != address { + return fmt.Errorf("%w: the claim holds another address", ErrUnavailable) + } + return nil +} + +// bound returns a bound claim's IPv4 host address in canonical form. +func bound(claim *unstructured.Unstructured) (string, error) { + if stringAt(claim, "status", "phase") != "Bound" { + return "", ErrPending + } + text := stringAt(claim, "status", "address") + if text == "" { + if prefix, err := netip.ParsePrefix(stringAt(claim, "status", "allocatedCIDR")); err == nil && prefix.IsSingleIP() { + text = prefix.Addr().String() + } + } + address, err := netip.ParseAddr(text) + if err != nil || !address.Is4() || address.Zone() != "" { + return "", errors.New("the claim is not bound to one IPv4 host address") + } + return address.String(), nil +} + +func stringAt(object *unstructured.Unstructured, fields ...string) string { + value, _, _ := unstructured.NestedString(object.Object, fields...) + return value +} diff --git a/internal/bootaddress/bootaddress_test.go b/internal/bootaddress/bootaddress_test.go new file mode 100644 index 00000000..818bf957 --- /dev/null +++ b/internal/bootaddress/bootaddress_test.go @@ -0,0 +1,109 @@ +package bootaddress + +import ( + "context" + "errors" + "testing" + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" +) + +const namespace = "fleet-provider" + +func claimer(t *testing.T, objects ...client.Object) (Claimer, client.Client) { + t.Helper() + scheme := runtime.NewScheme() + scheme.AddKnownTypeWithName(GVK, &unstructured.Unstructured{}) + scheme.AddKnownTypeWithName(GVK.GroupVersion().WithKind("IPClaimList"), &unstructured.UnstructuredList{}) + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objects...).Build() + return Claimer{Client: c, Namespace: namespace, Class: "provisioning", Kind: "DeviceInstallation"}, c +} + +func bind(t *testing.T, c client.Client, name, phase, address string) *unstructured.Unstructured { + t.Helper() + claim := &unstructured.Unstructured{} + claim.SetGroupVersionKind(GVK) + if err := c.Get(context.Background(), client.ObjectKey{Namespace: namespace, Name: name}, claim); err != nil { + t.Fatal(err) + } + claim.Object["status"] = map[string]any{"phase": phase, "address": address} + if err := c.Update(context.Background(), claim); err != nil { + t.Fatal(err) + } + return claim +} + +// TestClaimIsCreatedOnceAndBoundBeforeUse creates one claim per operation +// and returns its address only once IPAM bound it to one IPv4 host. +func TestClaimIsCreatedOnceAndBoundBeforeUse(t *testing.T) { + ctx := context.Background() + c, api := claimer(t) + if _, err := c.Claim(ctx, "alloc-a", "alloc-a-install-1"); !errors.Is(err, ErrPending) { + t.Fatalf("unbound claim: %v", err) + } + claim := bind(t, api, "alloc-a-install-1-boot", "Bound", "198.51.100.10") + input, err := c.Claim(ctx, "alloc-a", "alloc-a-install-1") + if err != nil || input.Address != "198.51.100.10" || input.AddressClaim.Name != "alloc-a-install-1-boot" || input.AddressClaim.UID != string(claim.GetUID()) { + t.Fatalf("input = %+v, %v", input, err) + } + if spec, _, _ := unstructured.NestedMap(claim.Object, "spec"); spec["className"] != "provisioning" || spec["ipFamily"] != "IPv4" || spec["reclaimPolicy"] != "Delete" { + t.Fatalf("spec = %v", spec) + } + bind(t, api, "alloc-a-install-1-boot", "Bound", "2001:db8::10") + if _, err := c.Claim(ctx, "alloc-a", "alloc-a-install-1"); err == nil { + t.Fatal("an IPv6 boot address was accepted for DHCPv4") + } + // Another requester's claim under the same name is a conflict. + wipes := c + wipes.Kind = "DeviceWipe" + if _, err := wipes.Claim(ctx, "alloc-a", "alloc-a-install-1"); !errors.Is(err, ErrConflict) { + t.Fatalf("foreign claim: %v", err) + } + if _, err := wipes.Release(ctx, "alloc-a-install-1"); !errors.Is(err, ErrConflict) { + t.Fatalf("a requester released another's claim: %v", err) + } +} + +// TestVerifyRequiresTheExactBoundIncarnation refuses a missing claim, +// another incarnation, another address, and an unbound or deleting claim. +func TestVerifyRequiresTheExactBoundIncarnation(t *testing.T) { + ctx := context.Background() + c, api := claimer(t) + if _, err := c.Claim(ctx, "alloc-a", "alloc-a-install-1"); !errors.Is(err, ErrPending) { + t.Fatal(err) + } + claim := bind(t, api, "alloc-a-install-1-boot", "Bound", "198.51.100.10") + good := ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: claim.GetName(), UID: string(claim.GetUID())}, Address: "198.51.100.10"} + if err := Verify(ctx, api, namespace, good); err != nil { + t.Fatal(err) + } + for name, input := range map[string]ops.BootNetworkInput{ + "missing": {AddressClaim: ops.ClaimReference{Name: "other-boot", UID: good.AddressClaim.UID}, Address: good.Address}, + "other UID": {AddressClaim: ops.ClaimReference{Name: good.AddressClaim.Name, UID: string(types.UID("other"))}, Address: good.Address}, + "other address": {AddressClaim: good.AddressClaim, Address: "198.51.100.11"}, + "not an address": {AddressClaim: good.AddressClaim, Address: "198.51.100.10/24"}, + } { + if err := Verify(ctx, api, namespace, input); !errors.Is(err, ErrUnavailable) { + t.Errorf("%s: %v", name, err) + } + } + bind(t, api, claim.GetName(), "Releasing", "198.51.100.10") + if err := Verify(ctx, api, namespace, good); !errors.Is(err, ErrUnavailable) { + t.Fatalf("unbound claim verified: %v", err) + } + if err := Verify(ctx, nil, namespace, good); !errors.Is(err, ErrUnavailable) { + t.Fatal("no reader verified") + } + if gone, err := c.Release(ctx, "alloc-a-install-1"); err != nil || gone { + t.Fatalf("release = %v, %v", gone, err) + } + if gone, err := c.Release(ctx, "alloc-a-install-1"); err != nil || !gone { + t.Fatalf("second release = %v, %v", gone, err) + } +} diff --git a/internal/bootaddress/testdata/ipclaims.yaml b/internal/bootaddress/testdata/ipclaims.yaml new file mode 100644 index 00000000..561f8905 --- /dev/null +++ b/internal/bootaddress/testdata/ipclaims.yaml @@ -0,0 +1,22 @@ +# 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. +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: ipclaims.ipam.miloapis.com +spec: + group: ipam.miloapis.com + names: {kind: IPClaim, listKind: IPClaimList, plural: ipclaims, singular: ipclaim} + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: {status: {}} + schema: + openAPIV3Schema: + type: object + properties: + spec: {type: object, x-kubernetes-preserve-unknown-fields: true} + status: {type: object, x-kubernetes-preserve-unknown-fields: true} diff --git a/internal/bootnet/feed.go b/internal/bootnet/feed.go index 02b4e285..349d5873 100644 --- a/internal/bootnet/feed.go +++ b/internal/bootnet/feed.go @@ -1,8 +1,9 @@ // Package bootnet is the boot-reservation contract between a site's boot -// service and the DHCP owner's synchronizer. A reservation maps one enrolled -// boot NIC to the provisioning address the network owner assigned to that -// physical asset, and exists only while an operation's network boot is -// admitted. The synchronizer reports what each DHCP instance applied; those +// service and the DHCP synchronizer. A reservation maps one boot NIC, as +// Device inventory records it, to the provisioning address IPAM assigned to +// one operation, and exists only while that operation's network boot is +// admitted. The DHCP base configuration supplies each subnet's prefix and +// gateway. The synchronizer reports what each DHCP instance applied; those // reports are the evidence that a reservation was served and later withdrawn. package bootnet @@ -18,12 +19,11 @@ import ( "time" ) -// Reservation is one boot NIC's provisioning address. Address is in prefix -// form (address/prefix length) so the DHCP side never infers the subnet. +// Reservation is one boot NIC's provisioning address: one host address, +// without a prefix length. type Reservation struct { MAC string `json:"mac"` Address string `json:"address"` - Gateway string `json:"gateway"` Expires time.Time `json:"expires"` } @@ -51,18 +51,14 @@ func NormalizeMAC(v string) (string, bool) { return hw.String(), true } -// ValidAttachment checks a provisioning address and its gateway: the address -// is a host in its prefix and the gateway is a different host in the same one. -func ValidAttachment(address, gateway string) error { - p, err := netip.ParsePrefix(address) - if err != nil || p.Addr().Zone() != "" || p.Addr() == p.Masked().Addr() || p.Bits() == p.Addr().BitLen() { - return errors.New("provisioning address must be a host address in prefix form") +// HostAddress returns the canonical form of one IP host address, refusing a +// prefix, a zone, and the unspecified address. +func HostAddress(v string) (string, error) { + address, err := netip.ParseAddr(v) + if err != nil || address.Zone() != "" || address.IsUnspecified() || address.Is4In6() { + return "", errors.New("a provisioning address must be one IP host address") } - g, err := netip.ParseAddr(gateway) - if err != nil || g.Zone() != "" || g == p.Addr() || g == p.Masked().Addr() || !p.Masked().Contains(g) { - return errors.New("provisioning gateway must be another host in the address prefix") - } - return nil + return address.String(), nil } func canonical(r Reservation) (Reservation, error) { @@ -70,12 +66,11 @@ func canonical(r Reservation) (Reservation, error) { if !ok || r.Expires.IsZero() { return Reservation{}, errors.New("invalid reservation") } - if err := ValidAttachment(r.Address, r.Gateway); err != nil { + address, err := HostAddress(r.Address) + if err != nil { return Reservation{}, err } - p, _ := netip.ParsePrefix(r.Address) - g, _ := netip.ParseAddr(r.Gateway) - return Reservation{MAC: mac, Address: p.String(), Gateway: g.String(), Expires: r.Expires.UTC().Truncate(time.Second)}, nil + return Reservation{MAC: mac, Address: address, Expires: r.Expires.UTC().Truncate(time.Second)}, nil } func revision(rs []Reservation) string { @@ -98,11 +93,10 @@ func NewFeed(rs []Reservation) (Feed, error) { sort.Slice(out, func(i, j int) bool { return out[i].MAC < out[j].MAC }) addresses := map[string]bool{} for i, r := range out { - a, _ := netip.ParsePrefix(r.Address) - if (i > 0 && out[i-1].MAC == r.MAC) || addresses[a.Addr().String()] { + if (i > 0 && out[i-1].MAC == r.MAC) || addresses[r.Address] { return Feed{}, errors.New("duplicate reservation") } - addresses[a.Addr().String()] = true + addresses[r.Address] = true } return Feed{Revision: revision(out), Reservations: out}, nil } @@ -139,10 +133,11 @@ func (f Feed) Has(mac, address string) bool { return false } -// Serves reports whether the feed serves mac at any address. -func (f Feed) Serves(mac string) bool { +// Serves reports whether the feed serves mac at any address, or address to +// any MAC. +func (f Feed) Serves(mac, address string) bool { for _, r := range f.Reservations { - if r.MAC == mac { + if r.MAC == mac || r.Address == address { return true } } diff --git a/internal/bootnet/feed_test.go b/internal/bootnet/feed_test.go index 985483a4..efb206b6 100644 --- a/internal/bootnet/feed_test.go +++ b/internal/bootnet/feed_test.go @@ -7,8 +7,8 @@ import ( func TestFeedIsCanonicalAndSelfVerifying(t *testing.T) { exp := time.Date(2030, 1, 2, 3, 4, 5, 999, time.FixedZone("x", 3600)) - a := Reservation{MAC: "52-54-00-77-01-0B", Address: "192.0.2.11/24", Gateway: "192.0.2.1", Expires: exp} - b := Reservation{MAC: "52:54:00:77:01:0a", Address: "192.0.2.10/24", Gateway: "192.0.2.1", Expires: exp} + a := Reservation{MAC: "52-54-00-77-01-0B", Address: "192.0.2.11", Expires: exp} + b := Reservation{MAC: "52:54:00:77:01:0a", Address: "192.0.2.10", Expires: exp} f1, err := NewFeed([]Reservation{a, b}) if err != nil { t.Fatal(err) @@ -20,7 +20,7 @@ func TestFeedIsCanonicalAndSelfVerifying(t *testing.T) { if err := f1.Verify(); err != nil { t.Fatal(err) } - if !f1.Has("52:54:00:77:01:0a", "192.0.2.10/24") || f1.Has("52:54:00:77:01:0a", "192.0.2.11/24") || !f1.Serves("52:54:00:77:01:0b") || f1.Serves("52:54:00:77:01:0c") { + if !f1.Has("52:54:00:77:01:0a", "192.0.2.10") || f1.Has("52:54:00:77:01:0a", "192.0.2.11") || !f1.Serves("52:54:00:77:01:0b", "") || !f1.Serves("", "192.0.2.11") || f1.Serves("52:54:00:77:01:0c", "192.0.2.12") { t.Fatal("membership is not exact") } empty, _ := NewFeed(nil) @@ -34,20 +34,20 @@ func TestFeedIsCanonicalAndSelfVerifying(t *testing.T) { } } for name, rs := range map[string][]Reservation{ - "duplicate MAC": {b, {MAC: b.MAC, Address: "192.0.2.12/24", Gateway: "192.0.2.1", Expires: exp}}, - "duplicate address": {b, {MAC: "52:54:00:77:01:0c", Address: "192.0.2.10/25", Gateway: "192.0.2.1", Expires: exp}}, - "no expiry": {{MAC: b.MAC, Address: b.Address, Gateway: b.Gateway}}, - "bare address": {{MAC: b.MAC, Address: "192.0.2.10", Gateway: b.Gateway, Expires: exp}}, - "gateway is host": {{MAC: b.MAC, Address: b.Address, Gateway: "192.0.2.10", Expires: exp}}, - "host route": {{MAC: b.MAC, Address: "192.0.2.10/32", Gateway: "192.0.2.1", Expires: exp}}, - "long MAC": {{MAC: "02:00:5e:10:00:00:00:01", Address: b.Address, Gateway: b.Gateway, Expires: exp}}, + "duplicate MAC": {b, {MAC: b.MAC, Address: "192.0.2.12", Expires: exp}}, + "duplicate address": {b, {MAC: "52:54:00:77:01:0c", Address: "192.0.2.10", Expires: exp}}, + "no expiry": {{MAC: b.MAC, Address: b.Address}}, + "prefix form": {{MAC: b.MAC, Address: "192.0.2.10/24", Expires: exp}}, + "unspecified": {{MAC: b.MAC, Address: "0.0.0.0", Expires: exp}}, + "mapped": {{MAC: b.MAC, Address: "::ffff:192.0.2.10", Expires: exp}}, + "long MAC": {{MAC: "02:00:5e:10:00:00:00:01", Address: b.Address, Expires: exp}}, } { if _, err := NewFeed(rs); err == nil { t.Errorf("%s: accepted", name) } } - if _, err := NewFeed([]Reservation{{MAC: b.MAC, Address: "2001:db8::10/64", Gateway: "2001:db8::1", Expires: exp}}); err != nil { - t.Fatalf("IPv6 attachment: %v", err) + if _, err := NewFeed([]Reservation{{MAC: b.MAC, Address: "2001:db8::10", Expires: exp}}); err != nil { + t.Fatalf("IPv6 address: %v", err) } if (Applied{Instance: "kea-0", Feed: empty}).Verify() != nil || (Applied{Instance: "-kea", Feed: empty}).Verify() == nil { t.Fatal("instance names not checked") diff --git a/internal/custody/admission_test.go b/internal/custody/admission_test.go index 827721dc..3fe0395b 100644 --- a/internal/custody/admission_test.go +++ b/internal/custody/admission_test.go @@ -83,7 +83,7 @@ func TestAdmissionPreconditions(t *testing.T) { named := &DeviceTestStaffOperation{ObjectMeta: metav1.ObjectMeta{GenerateName: "named-", Namespace: "default"}, Spec: testSpec{OperationEnvelope: envelope(device, staffUser, allocated("alloc-x")), Input: "a"}} e.create(named) // Staff cannot create the release kind either. - wipe := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: WipeName("alloc-x", 1), Namespace: "default"}, Spec: ops.DeviceWipeSpec{OperationEnvelope: envelope(device, staffUser, allocated("alloc-x")), Step: 1, CleaningPolicyDigest: policyDigest, TargetDisks: []string{"disk-0"}}} + wipe := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: WipeName("alloc-x", 1), Namespace: "default"}, Spec: ops.DeviceWipeSpec{OperationEnvelope: envelope(device, staffUser, allocated("alloc-x")), Step: 1, CleaningPolicyDigest: policyDigest, TargetDisks: []string{"disk-0"}, BootInterface: "primary"}} e.create(wipe) e.settle(device.Name) for _, operation := range []ops.Operation{spoof, service, named, wipe} { @@ -268,6 +268,57 @@ func TestAdmissionPreconditions(t *testing.T) { e.requireUntouched(device.Name, fence) }) + t.Run("a boot address must still be bound to its claim", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, "alloc-net"); err != nil { + t.Fatal(err) + } + fence := e.custody(device.Name).Spec.Fence + bound := e.ipClaim("alloc-net-boot-a", "Bound", "198.51.100.10") + pending := e.ipClaim("alloc-net-boot-b", "Pending", "") + withAddress := func(request string, input *ops.BootNetworkInput) *ops.DeviceInstallation { + operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName("alloc-net", request), Namespace: "default"}, Spec: ops.DeviceInstallationSpec{ + OperationEnvelope: envelope(device, providerUser, allocated("alloc-net")), RequestUID: request, + Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, BootNetwork: input, + }} + e.create(operation) + return operation + } + refused := []*ops.DeviceInstallation{ + withAddress("other-uid", &ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: bound.GetName(), UID: "00000000-0000-4000-8000-0000000009ff"}, Address: "198.51.100.10"}), + withAddress("other-address", &ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: bound.GetName(), UID: string(bound.GetUID())}, Address: "198.51.100.11"}), + withAddress("unbound", &ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: pending.GetName(), UID: string(pending.GetUID())}, Address: "198.51.100.12"}), + withAddress("missing", &ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: "alloc-net-boot-missing", UID: string(bound.GetUID())}, Address: "198.51.100.10"}), + } + e.settle(device.Name) + for _, operation := range refused { + e.requirePhase(operation, ops.PhaseFailed, ReasonBootAddress) + } + e.requireUntouched(device.Name, fence) + // A wipe network-boots too, so its boot interface must have a MAC. + releasing := fresh() + if err := e.coord.Claim(e.ctx, releasing.Name, "alloc-net-wipe"); err != nil { + t.Fatal(err) + } + if err := e.coord.BeginRelease(e.ctx, releasing.Name, "alloc-net-wipe"); err != nil { + t.Fatal(err) + } + wipeFence := e.custody(releasing.Name).Spec.Fence + wipe := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: WipeName("alloc-net-wipe", 1), Namespace: "default"}, Spec: ops.DeviceWipeSpec{ + OperationEnvelope: envelope(releasing, releaseUser, allocated("alloc-net-wipe")), Step: 1, CleaningPolicyDigest: policyDigest, TargetDisks: []string{"disk-0"}, BootInterface: "absent", + }} + e.create(wipe) + e.settle(releasing.Name) + e.requirePhase(wipe, ops.PhaseFailed, ReasonBootInterfaceUnknown) + e.requireUntouched(releasing.Name, wipeFence) + admitted := withAddress("bound", &ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: bound.GetName(), UID: string(bound.GetUID())}, Address: "198.51.100.10"}) + e.settle(device.Name) + if active := e.custody(device.Name).Spec.ActiveOperation; active == nil || active.Name != admitted.Name || active.Snapshot.BootMACAddress == "" { + t.Fatalf("active = %+v, want the bound installation with the boot MAC from inventory", active) + } + }) + t.Run("a staff operation not admitted within five minutes expires", func(t *testing.T) { e := e.sub(t) device := fresh() diff --git a/internal/custody/harness_test.go b/internal/custody/harness_test.go index 8b01531a..d2b8bb52 100644 --- a/internal/custody/harness_test.go +++ b/internal/custody/harness_test.go @@ -14,10 +14,12 @@ import ( inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" metal "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/bootaddress" admissionregistrationv1 "k8s.io/api/admissionregistration/v1" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/rest" @@ -153,6 +155,7 @@ func startEnv(t *testing.T) *env { filepath.Join(root, "config", "components", "inventory", "crds"), filepath.Join(root, "config", "components", "device-operations", "crds"), filepath.Join("testdata", "crds"), + filepath.Join(root, "internal", "bootaddress", "testdata"), }, ErrorIfCRDPathMissing: true} config, err := environment.Start() if err != nil { @@ -349,17 +352,35 @@ func (e *env) installation(device *inventory.Device, allocation, request string) func (e *env) wipe(device *inventory.Device, allocation string, step int32) *ops.DeviceWipe { e.t.Helper() operation := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: WipeName(allocation, step), Namespace: "default"}, Spec: ops.DeviceWipeSpec{ - OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, CleaningPolicyDigest: policyDigest, TargetDisks: []string{"disk-0"}, + OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, CleaningPolicyDigest: policyDigest, TargetDisks: []string{"disk-0"}, BootInterface: "primary", }} e.create(operation) return operation } +// ipClaim creates a stand-in IPAM claim with the given phase and address. +func (e *env) ipClaim(name, phase, address string) *unstructured.Unstructured { + e.t.Helper() + claim := &unstructured.Unstructured{} + claim.SetGroupVersionKind(bootaddress.GVK) + claim.SetNamespace("default") + claim.SetName(name) + claim.Object["spec"] = map[string]any{"className": "provisioning"} + if err := e.admin.Create(e.ctx, claim); err != nil { + e.t.Fatal(err) + } + claim.Object["status"] = map[string]any{"phase": phase, "address": address} + if err := e.admin.Status().Update(e.ctx, claim); err != nil { + e.t.Fatal(err) + } + return claim +} + // namedWipe creates a wipe with an explicit name, such as a retry's. func (e *env) namedWipe(device *inventory.Device, allocation, name string, step int32) *ops.DeviceWipe { e.t.Helper() operation := &ops.DeviceWipe{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, Spec: ops.DeviceWipeSpec{ - OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, CleaningPolicyDigest: policyDigest, TargetDisks: []string{"disk-0"}, + OperationEnvelope: envelope(device, releaseUser, allocated(allocation)), Step: step, CleaningPolicyDigest: policyDigest, TargetDisks: []string{"disk-0"}, BootInterface: "primary", }} e.create(operation) return operation diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index 36aa7aa0..2d6eb229 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -9,8 +9,10 @@ import ( "strconv" "time" - ops "go.datum.net/fleet/internal/api/operations/v1alpha1" "sigs.k8s.io/controller-runtime/pkg/client" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/bootaddress" ) // Per-kind deadlines. The site worker stops at the deadline exactly; the @@ -36,15 +38,56 @@ const ( ReasonRetryAuthorized = "RetryAlreadyAuthorized" ReasonDisposalRequired = "DisposalRequired" ReasonInvalidResolve = "InvalidResolve" + ReasonBootAddress = "BootAddressUnavailable" // Reasons every site's install and wipe workers raise. ReasonTargetUnsupported = "TargetUnsupported" ReasonTargetDisks = "TargetDisksUnknown" ReasonInputsUnreadable = "InputsUnreadable" + // Reasons a site raises when an operation's boot network input does not + // fit the site's DHCP. + ReasonBootNetworkRequired = "BootNetworkRequired" + ReasonBootNetworkUnsupported = "BootNetworkUnsupported" ) // workerReasons are the reasons every site's install and wipe workers // raise before sending anything. -var workerReasons = []Reason{{Name: ReasonTargetUnsupported, RaisedBy: RaisedByWorker}, {Name: ReasonTargetDisks, RaisedBy: RaisedByWorker}, {Name: ReasonInputsUnreadable, RaisedBy: RaisedByWorker}} +var workerReasons = []Reason{{Name: ReasonTargetUnsupported, RaisedBy: RaisedByWorker}, {Name: ReasonTargetDisks, RaisedBy: RaisedByWorker}, {Name: ReasonInputsUnreadable, RaisedBy: RaisedByWorker}, + {Name: ReasonBootNetworkRequired, RaisedBy: RaisedByWorker}, {Name: ReasonBootNetworkUnsupported, RaisedBy: RaisedByWorker}} + +// NoBootNetwork refuses a boot address at a site whose DHCP Fleet does not +// synchronize. Every such site's install and wipe workers call it. +func NoBootNetwork(network *ops.BootNetworkInput) *Refusal { + if network != nil { + return refuse(ReasonBootNetworkUnsupported, "this site's DHCP is not synchronized, so it cannot serve a boot address") + } + return nil +} + +// networkBootReasons are the coordinator's reasons for a network boot's +// inputs. +var networkBootReasons = []Reason{{Name: ReasonBootInterfaceUnknown, RaisedBy: RaisedByCoordinator}, {Name: ReasonBootAddress, RaisedBy: RaisedByCoordinator}} + +// checkNetworkBoot requires the boot interface to have a MAC in Device +// inventory and a boot address, when given, to still be bound to the +// operation's claim. +func checkNetworkBoot(ctx context.Context, admission *Admission, bootInterface string, network *ops.BootNetworkInput) *Refusal { + found := false + for _, iface := range admission.Device.Spec.Interfaces { + if iface.Name == bootInterface && iface.MACAddress != "" { + found = true + } + } + if !found { + return refuse(ReasonBootInterfaceUnknown, "the Device records no interface %q with a MAC address", bootInterface) + } + if network == nil { + return nil + } + if err := bootaddress.Verify(ctx, admission.Reader, admission.Operation.GetNamespace(), *network); err != nil { + return refuse(ReasonBootAddress, "the boot address claim %s does not hold %s", network.AddressClaim.Name, network.Address) + } + return nil +} const evidenceLimit = 4096 @@ -100,21 +143,16 @@ func DeviceInstallationKind() Kind { Deadline: InstallationDeadline, Effectful: true, BootInterface: func(operation ops.Operation) string { return operation.(*ops.DeviceInstallation).Spec.BootInterface }, - Check: func(_ context.Context, admission *Admission) *Refusal { + Check: func(ctx context.Context, admission *Admission) *Refusal { installation := admission.Operation.(*ops.DeviceInstallation) // Bootstrap stays refused until the sealed store exists. if installation.Spec.Bootstrap != nil { return refuse(ReasonBootstrapUnsupported, "bootstrap payloads need the sealed store, which is not implemented") } - for _, iface := range admission.Device.Spec.Interfaces { - if iface.Name == installation.Spec.BootInterface && iface.MACAddress != "" { - return nil - } - } - return refuse(ReasonBootInterfaceUnknown, "the Device records no interface %q with a MAC address", installation.Spec.BootInterface) + return checkNetworkBoot(ctx, admission, installation.Spec.BootInterface, installation.Spec.BootNetwork) }, Settles: []SettleRule{{Held: "DeviceInstallation"}}, - Reasons: append([]Reason{{Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}, {Name: ReasonBootInterfaceUnknown, RaisedBy: RaisedByCoordinator}}, workerReasons...), + Reasons: append(append([]Reason{{Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}}, networkBootReasons...), workerReasons...), Evidence: StrictEvidence(evidenceLimit, func(_ ops.Operation, evidence *ops.InstallationEvidence) error { return validateSteps(evidence.Steps) }), @@ -137,13 +175,18 @@ func DeviceWipeKind() Kind { Name: func(operation ops.Operation) string { return WipeName(allocationName(operation), operation.(*ops.DeviceWipe).Spec.Step) }, - Deadline: WipeDeadline, - Effectful: true, + Deadline: WipeDeadline, + Effectful: true, + BootInterface: func(operation ops.Operation) string { return operation.(*ops.DeviceWipe).Spec.BootInterface }, + Check: func(ctx context.Context, admission *Admission) *Refusal { + wipe := admission.Operation.(*ops.DeviceWipe) + return checkNetworkBoot(ctx, admission, wipe.Spec.BootInterface, wipe.Spec.BootNetwork) + }, // A wipe after release settles an installation hold. A held wipe is // settled by a later wipe only after a DeviceRecovery with Retry. Settles: []SettleRule{{Held: "DeviceInstallation"}, {Held: "DeviceWipe", RequiresRetry: true}}, Retryable: true, - Reasons: workerReasons, + Reasons: append(append([]Reason{}, networkBootReasons...), workerReasons...), Evidence: StrictEvidence(evidenceLimit, func(_ ops.Operation, evidence *ops.WipeEvidence) error { if len(evidence.WipedDisks) > 16 { return errors.New("evidence records at most 16 disks") diff --git a/internal/dhcpsync/sync.go b/internal/dhcpsync/sync.go index 15f0c596..68a5c092 100644 --- a/internal/dhcpsync/sync.go +++ b/internal/dhcpsync/sync.go @@ -110,8 +110,10 @@ func (s *Syncer) report(ctx context.Context, feed bootnet.Feed) error { return nil } -// config adds each reservation to the base subnet with exactly its prefix. -// A reservation with no such subnet is an error: it is never dropped silently. +// config adds each reservation to the one base subnet that contains its +// address. The base subnet supplies the prefix, gateway and boot options. A +// reservation with no such subnet, or with two, is an error: it is never +// dropped silently. func (s *Syncer) config(feed bootnet.Feed) (map[string]any, error) { b, err := os.ReadFile(s.Base) if err != nil { @@ -127,26 +129,28 @@ func (s *Syncer) config(feed bootnet.Feed) (map[string]any, error) { return nil, errors.New("base Kea configuration has no Dhcp4 subnet4 list") } for _, r := range feed.Reservations { - p := netip.MustParsePrefix(r.Address) - if !p.Addr().Is4() { + address := netip.MustParseAddr(r.Address) + if !address.Is4() { return nil, fmt.Errorf("reservation %s is not IPv4", r.MAC) } var subnet map[string]any for _, v := range subnets { m, _ := v.(map[string]any) text, _ := m["subnet"].(string) - if sp, err := netip.ParsePrefix(text); err == nil && sp == p.Masked() { - subnet = m + sp, err := netip.ParsePrefix(text) + if err != nil || !sp.Contains(address) { + continue } + if subnet != nil { + return nil, fmt.Errorf("two base subnets contain reservation %s", r.MAC) + } + subnet = m } if subnet == nil { - return nil, fmt.Errorf("no base subnet %s for reservation %s", p.Masked(), r.MAC) + return nil, fmt.Errorf("no base subnet contains reservation %s", r.MAC) } hosts, _ := subnet["reservations"].([]any) - subnet["reservations"] = append(hosts, map[string]any{ - "hw-address": r.MAC, "ip-address": p.Addr().String(), - "option-data": []any{map[string]any{"name": "routers", "data": r.Gateway}}, - }) + subnet["reservations"] = append(hosts, map[string]any{"hw-address": r.MAC, "ip-address": address.String()}) } return cfg, nil } diff --git a/internal/dhcpsync/sync_test.go b/internal/dhcpsync/sync_test.go index 3121a534..1206463a 100644 --- a/internal/dhcpsync/sync_test.go +++ b/internal/dhcpsync/sync_test.go @@ -131,9 +131,9 @@ func newSyncer(t *testing.T) (*Syncer, *fakeKea, *fakeSite) { return &Syncer{Feed: srv.URL, Token: token, Instance: "kea-0", Socket: kea.serve(t), Base: base, HTTP: srv.Client()}, kea, site } -var reservation = bootnet.Reservation{MAC: "52:54:00:77:01:0a", Address: "192.0.2.10/24", Gateway: "192.0.2.1", Expires: time.Now().Add(time.Hour)} +var reservation = bootnet.Reservation{MAC: "52:54:00:77:01:0a", Address: "192.0.2.10", Expires: time.Now().Add(time.Hour)} -func TestAppliesReservationIntoItsExactSubnetThenReports(t *testing.T) { +func TestAppliesReservationIntoItsContainingSubnetThenReports(t *testing.T) { s, kea, site := newSyncer(t) ctx := context.Background() if err := s.Cycle(ctx); err != nil || kea.applied() != 1 || len(site.reported()) != 1 { @@ -147,7 +147,7 @@ func TestAppliesReservationIntoItsExactSubnetThenReports(t *testing.T) { subnets := kea.configs[1]["Dhcp4"].(map[string]any)["subnet4"].([]any) kea.mu.Unlock() hosts, _ := json.Marshal(subnets[0].(map[string]any)["reservations"]) - if string(hosts) != `[{"hw-address":"52:54:00:77:01:0a","ip-address":"192.0.2.10","option-data":[{"data":"192.0.2.1","name":"routers"}]}]` || subnets[1].(map[string]any)["reservations"] != nil { + if string(hosts) != `[{"hw-address":"52:54:00:77:01:0a","ip-address":"192.0.2.10"}]` || subnets[1].(map[string]any)["reservations"] != nil { t.Fatalf("reservation not placed in exactly its subnet: %s", hosts) } reports := site.reported() @@ -166,7 +166,7 @@ func TestAppliesReservationIntoItsExactSubnetThenReports(t *testing.T) { t.Fatalf("restarted Kea not re-applied: %v", err) } site.set(t) - if err := s.Cycle(ctx); err != nil || len(site.reported()) != 3 || site.reported()[2].Feed.Serves(reservation.MAC) { + if err := s.Cycle(ctx); err != nil || len(site.reported()) != 3 || site.reported()[2].Feed.Serves(reservation.MAC, reservation.Address) { t.Fatalf("withdrawal not applied and reported: %v", err) } } @@ -184,10 +184,18 @@ func TestNothingIsReportedThatKeaDidNotAccept(t *testing.T) { kea.mu.Lock() kea.fail = false kea.mu.Unlock() - site.set(t, bootnet.Reservation{MAC: reservation.MAC, Address: "203.0.113.10/24", Gateway: "203.0.113.1", Expires: reservation.Expires}) + site.set(t, bootnet.Reservation{MAC: reservation.MAC, Address: "203.0.113.10", Expires: reservation.Expires}) if err := s.Cycle(ctx); err == nil || kea.applied() != 0 || len(site.reported()) != 0 { t.Fatal("a reservation without a base subnet was dropped or applied") } + // Two base subnets containing one address are ambiguous: refused. + overlap := filepath.Join(t.TempDir(), "overlap.conf") + os.WriteFile(overlap, []byte(`{"Dhcp4":{"subnet4":[{"id":1,"subnet":"192.0.2.0/24"},{"id":2,"subnet":"192.0.2.0/25"}]}}`), 0600) + s.Base = overlap + site.set(t, reservation) + if err := s.Cycle(ctx); err == nil || kea.applied() != 0 || len(site.reported()) != 0 { + t.Fatal("a reservation in two base subnets was applied") + } s.Token = "wrong-token-wrong-token-wrong-token-0000" if err := s.Cycle(ctx); err == nil { t.Fatal("an unauthenticated feed was accepted") @@ -198,7 +206,7 @@ func TestForgedFeedIsRejectedBeforeKea(t *testing.T) { s, kea, site := newSyncer(t) site.set(t, reservation) site.mu.Lock() - site.feed.Reservations[0].Address = "192.0.2.99/24" + site.feed.Reservations[0].Address = "192.0.2.99" site.mu.Unlock() if err := s.Cycle(context.Background()); err == nil || kea.applied() != 0 { t.Fatal("a feed whose revision does not match its reservations was applied") diff --git a/internal/redfish/enrollment.go b/internal/redfish/enrollment.go index 4f9ddfd7..bf6ff560 100644 --- a/internal/redfish/enrollment.go +++ b/internal/redfish/enrollment.go @@ -12,40 +12,29 @@ import ( "path/filepath" "strconv" "strings" - "time" - - "go.datum.net/fleet/internal/bootnet" ) -// Target is one enrolled server: the Device it is, its BMC endpoint, its -// exact Redfish System, its boot NIC and, when the site's DHCP is -// synchronized, the provisioning attachment the network owner assigned to -// it. Console names the serial-console capture file for the target (a lab -// seam; see the operations guide). Enrollment is site configuration and is -// never inferred. +// Target is one enrolled server: the Device it is, its BMC endpoint and its +// exact Redfish System. Console names the serial-console capture file for the +// target (a lab seam; see the operations guide). The boot NIC comes from +// Device inventory through the admission snapshot, and the boot address from +// IPAM through the operation's inputs. Enrollment is site configuration and +// is never inferred. type Target struct { // Device is "/" in the provider project. - Device string `json:"device"` - Endpoint string `json:"endpoint"` - SystemID string `json:"systemID"` - SystemUUID string `json:"systemUUID"` - MAC string `json:"mac"` - Provisioning Provisioning `json:"provisioning,omitzero"` - DiskBytes int64 `json:"diskBytes"` - Console string `json:"console"` -} - -// Provisioning is the asset's address on the provisioning network, in prefix -// form, and that network's gateway. Networking/IPAM allocates it; Fleet only -// publishes it while the asset's network boot is admitted. -type Provisioning struct { - Address string `json:"address"` - Gateway string `json:"gateway"` + Device string `json:"device"` + Endpoint string `json:"endpoint"` + SystemID string `json:"systemID"` + SystemUUID string `json:"systemUUID"` + DiskBytes int64 `json:"diskBytes"` + Console string `json:"console"` } -// DHCP modes. Static: the site's DHCP is configured independently of Fleet. -// Synced: Fleet publishes boot reservations and a network boot requires -// evidence that DHCP applied the reservation and later withdrew it. +// DHCP modes. Static: the site's DHCP is configured independently of Fleet, +// and an operation with a boot address is refused. Synced: Fleet publishes +// each operation's boot reservation, an operation without a boot address is +// refused, and a network boot requires evidence that DHCP applied the +// reservation and later withdrew it. const ( DHCPStatic = "static" DHCPSynced = "synced" @@ -67,10 +56,6 @@ func (e Enrollment) Target(device string) (Target, bool) { return Target{}, false } -func normalizeMAC(v string) (string, bool) { - return bootnet.NormalizeMAC(strings.ReplaceAll(v, "-", ":")) -} - func ParseEnrollment(b []byte) (Enrollment, error) { var e Enrollment d := json.NewDecoder(strings.NewReader(string(b))) @@ -80,33 +65,15 @@ func ParseEnrollment(b []byte) (Enrollment, error) { } seen := map[string]bool{} for i, t := range e.Targets { - mac, ok := normalizeMAC(t.MAC) endpoint, err := ParseEndpoint(t.Endpoint) // A Redfish System ID is unique only within its BMC. system := "s" + endpoint + " " + t.SystemID - if !ok || err != nil || !validDevice(t.Device) || t.SystemID == "" || len(t.SystemUUID) != 36 || t.DiskBytes <= 0 || t.Console == "" || filepath.Base(t.Console) != t.Console || - seen["a"+t.Device] || seen[system] || seen["u"+strings.ToLower(t.SystemUUID)] || seen["m"+mac] { + if err != nil || !validDevice(t.Device) || t.SystemID == "" || len(t.SystemUUID) != 36 || t.DiskBytes <= 0 || t.Console == "" || filepath.Base(t.Console) != t.Console || + seen["a"+t.Device] || seen[system] || seen["u"+strings.ToLower(t.SystemUUID)] { return Enrollment{}, errors.New("invalid or duplicate Redfish enrollment target") } - seen["a"+t.Device], seen[system], seen["u"+strings.ToLower(t.SystemUUID)], seen["m"+mac] = true, true, true, true - e.Targets[i].MAC, e.Targets[i].Endpoint = mac, endpoint - if e.DHCP == DHCPStatic { - if t.Provisioning != (Provisioning{}) { - return Enrollment{}, errors.New("a static-DHCP enrollment carries no provisioning attachment") - } - continue - } - feed, err := bootnet.NewFeed([]bootnet.Reservation{{MAC: mac, Address: t.Provisioning.Address, Gateway: t.Provisioning.Gateway, Expires: time.Unix(1, 0)}}) - if err != nil { - return Enrollment{}, errors.New("invalid provisioning attachment for enrolled target " + t.Device) - } - r := feed.Reservations[0] - address := "p" + strings.SplitN(r.Address, "/", 2)[0] - if seen[address] { - return Enrollment{}, errors.New("duplicate provisioning address") - } - seen[address] = true - e.Targets[i].Provisioning = Provisioning{Address: r.Address, Gateway: r.Gateway} + seen["a"+t.Device], seen[system], seen["u"+strings.ToLower(t.SystemUUID)] = true, true, true + e.Targets[i].Endpoint = endpoint } return e, nil } diff --git a/internal/redfish/enrollment_test.go b/internal/redfish/enrollment_test.go index 69d77cb1..2f6dbe33 100644 --- a/internal/redfish/enrollment_test.go +++ b/internal/redfish/enrollment_test.go @@ -14,7 +14,7 @@ func enrollment(targets string) string { return `{"dhcp":"static","targets":[` + targets + `]}` } -const targetA = `{"device":"fleet-provider/server-example-001","endpoint":"https://192.0.2.10:8443","systemID":"System-1","systemUUID":"` + uuidA + `","mac":"52:54:00:77:01:0a","diskBytes":2147483648,"console":"target-a.log"}` +const targetA = `{"device":"fleet-provider/server-example-001","endpoint":"https://192.0.2.10:8443","systemID":"System-1","systemUUID":"` + uuidA + `","diskBytes":2147483648,"console":"target-a.log"}` // TestEnrollmentNamesEachDeviceOnce accepts an explicit Device to BMC // mapping and refuses a target without a Device, a duplicate, or another @@ -33,8 +33,9 @@ func TestEnrollmentNamesEachDeviceOnce(t *testing.T) { for name, body := range map[string]string{ "no device": strings.Replace(targetA, `"device":"fleet-provider/server-example-001",`, "", 1), "device name only": strings.Replace(targetA, "fleet-provider/server-example-001", "server-example-001", 1), - "duplicate device": targetA + "," + strings.NewReplacer(uuidA, uuidB, "System-1", "System-2", "01:0a", "01:0b").Replace(targetA), - "duplicate system": targetA + "," + strings.NewReplacer("server-example-001", "server-example-002", "01:0a", "01:0b").Replace(targetA), + "duplicate device": targetA + "," + strings.NewReplacer(uuidA, uuidB, "System-1", "System-2").Replace(targetA), + "duplicate system": targetA + "," + strings.NewReplacer("server-example-001", "server-example-002").Replace(targetA), + "enrolled MAC": strings.Replace(targetA, `"console"`, `"mac":"52:54:00:77:01:0a","console"`, 1), "no console": strings.Replace(targetA, `"target-a.log"`, `""`, 1), "no disk": strings.Replace(targetA, `2147483648`, `0`, 1), "unknown field": strings.Replace(targetA, `"console"`, `"extra":1,"console"`, 1), diff --git a/internal/site/access.go b/internal/site/access.go index c3c44793..2e0ad2cc 100644 --- a/internal/site/access.go +++ b/internal/site/access.go @@ -72,7 +72,7 @@ func (a RedfishAccess) Prepare(ctx context.Context, assignment Assignment) (any, return nil, &custody.Refusal{Reason: ReasonNotEnrolled, Message: "this site does not serve the Device"} } snapshot := assignment.Snapshot - if !strings.EqualFold(target.SystemUUID, snapshot.SystemUUID) || target.Endpoint != snapshot.BMCEndpoint || (snapshot.BootMACAddress != "" && !strings.EqualFold(target.MAC, snapshot.BootMACAddress)) { + if !strings.EqualFold(target.SystemUUID, snapshot.SystemUUID) || target.Endpoint != snapshot.BMCEndpoint { return nil, &custody.Refusal{Reason: custody.ReasonDeviceIdentityMismatch, Message: "the site's enrollment does not match the admitted snapshot"} } credential, found, err := a.Credentials.Lookup(ctx, assignment.Device) diff --git a/internal/site/redfishwork/boot.go b/internal/site/redfishwork/boot.go index 9581587d..9b3d84c3 100644 --- a/internal/site/redfishwork/boot.go +++ b/internal/site/redfishwork/boot.go @@ -15,7 +15,6 @@ import ( "time" "go.datum.net/fleet/internal/bootnet" - "go.datum.net/fleet/internal/redfish" "go.datum.net/fleet/internal/site" ) @@ -38,10 +37,7 @@ type BootServer struct { // BootRoot holds the per-operation delivery evidence and the retained // DHCP reports the workers read. BootRoot string - // Enrollment names each Device's provisioning attachment when the - // site's DHCP is synchronized. - Enrollment redfish.Enrollment - Now func() time.Time + 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 6f64e616..f76d2397 100644 --- a/internal/site/redfishwork/dhcp.go +++ b/internal/site/redfishwork/dhcp.go @@ -14,7 +14,6 @@ import ( "time" "go.datum.net/fleet/internal/bootnet" - "go.datum.net/fleet/internal/redfish" "go.datum.net/fleet/internal/site" ) @@ -27,16 +26,21 @@ 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. +// 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. type report struct { At time.Time `json:"at"` Instance string `json:"instance"` Feed bootnet.Feed `json:"feed"` + Retired bool `json:"retired,omitempty"` } // Reservations is the complete desired reservation set: each boot NIC whose -// admission is not closed, unexpired and at the Device's stored fence holds -// its provisioning address. It is empty when no network boot is admitted. +// admission carries a boot address and is not closed, unexpired and at the +// Device's stored fence holds that address. The MAC comes from the admission +// snapshot and the address from the operation's inputs. It is empty when no +// network boot is admitted. func (b BootServer) Reservations() (bootnet.Feed, error) { records, err := b.Store.Records(bootRecords) if err != nil { @@ -45,17 +49,13 @@ func (b BootServer) Reservations() (bootnet.Feed, error) { reservations := []bootnet.Reservation{} for _, record := range records { var boot Boot - if json.Unmarshal(record.Data, &boot) != nil || boot.Closed || !b.now().Before(boot.Expires) { - continue - } - target, ok := b.Enrollment.Target(record.Device) - if !ok || target.Provisioning == (redfish.Provisioning{}) { + if json.Unmarshal(record.Data, &boot) != nil || boot.Address == "" || boot.Closed || !b.now().Before(boot.Expires) { continue } if fence, _, err := b.Store.Peek(record.Device); err != nil || fence != boot.Fence { continue } - reservations = append(reservations, bootnet.Reservation{MAC: target.MAC, Address: target.Provisioning.Address, Gateway: target.Provisioning.Gateway, Expires: boot.Expires}) + reservations = append(reservations, bootnet.Reservation{MAC: boot.MAC, Address: boot.Address, Expires: boot.Expires}) } return bootnet.NewFeed(reservations) } @@ -121,6 +121,21 @@ 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. func reports(root string) ([]report, error) { @@ -146,18 +161,17 @@ func reports(root string) ([]report, error) { } // awaitReservation waits, without any effect, until some DHCP instance -// reports serving the target's exact provisioning address since this +// 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, work *site.Work, boot Boot) error { +func (c Config) awaitReservation(ctx context.Context, boot Boot) error { poll, _, _, _ := c.durations() - target := conn(work).Target for { retained, err := reports(c.BootRoot) if err != nil { return err } for _, r := range retained { - if r.At.After(boot.Created) && r.Feed.Has(target.MAC, target.Provisioning.Address) { + if !r.Retired && r.At.After(boot.Created) && r.Feed.Has(boot.MAC, boot.Address) { return nil } } @@ -170,32 +184,41 @@ func (c Config) awaitReservation(ctx context.Context, work *site.Work, boot Boot } } -// awaitWithdrawal requires every DHCP instance that served the boot NIC -// during this operation to now report a feed without it. A silent instance -// keeps the outcome unknown: its reservation may still be served. -func (c Config) awaitWithdrawal(ctx context.Context, work *site.Work, 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. +func (c Config) awaitWithdrawal(ctx context.Context, store *site.Store, device string, boot Boot) error { poll, _, _, _ := c.durations() - mac := conn(work).Target.MAC deadline := c.now().Add(withdrawalWindow) for { + published, err := publishedFor(store, device) + if err != nil { + return err + } retained, err := reports(c.BootRoot) if err != nil { return err } - served, latest := map[string]bool{}, map[string]bootnet.Feed{} + served, latest := false, map[string]bootnet.Feed{} for _, r := range retained { - if !r.At.After(boot.Created) { + if r.Retired { + delete(latest, r.Instance) continue } - if r.Feed.Serves(mac) { - served[r.Instance] = true + if r.At.After(boot.Created) && r.Feed.Has(boot.MAC, boot.Address) { + served = true } latest[r.Instance] = r.Feed } - withdrawn := len(served) > 0 - for instance := range served { - if latest[instance].Serves(mac) { - withdrawn = false + withdrawn := served + for _, feed := range latest { + for _, p := range published { + if feed.Serves(p.MAC, p.Address) { + withdrawn = false + } } } if withdrawn { @@ -209,3 +232,26 @@ func (c Config) awaitWithdrawal(ctx context.Context, work *site.Work, boot Boot) } } } + +// publishedFor returns every boot admission of the Device that carried a +// boot address, whatever its fence or state. +func publishedFor(store *site.Store, device string) ([]Boot, error) { + records, err := store.Records(bootRecords) + if err != nil { + return nil, err + } + var out []Boot + for _, record := range records { + var boot Boot + if record.Device != device { + continue + } + if err := json.Unmarshal(record.Data, &boot); err != nil { + return nil, errors.New("an unreadable boot admission") + } + if boot.Address != "" { + out = append(out, boot) + } + } + return out, nil +} diff --git a/internal/site/redfishwork/dhcp_test.go b/internal/site/redfishwork/dhcp_test.go index 139952c4..e5a03147 100644 --- a/internal/site/redfishwork/dhcp_test.go +++ b/internal/site/redfishwork/dhcp_test.go @@ -8,21 +8,169 @@ import ( "os" "path/filepath" "strings" + "sync" "testing" "time" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" "go.datum.net/fleet/internal/bootnet" - "go.datum.net/fleet/internal/redfish" + "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/site" ) -const syncToken = "synthetic-dhcp-synchronizer-token-0123456789" +const ( + syncToken = "synthetic-dhcp-synchronizer-token-0123456789" + address = "192.0.2.20" +) + +func newRequest(method, url, body string) (*http.Request, error) { + request, err := http.NewRequest(method, url, strings.NewReader(body)) + if err == nil { + request.Header.Set("Authorization", "Bearer "+syncToken) + } + return request, err +} + +func bootNetwork() *ops.BootNetworkInput { + return &ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: "alloc-example-install-boot", UID: "00000000-0000-4000-8000-000000000501"}, Address: address} +} + +// synchronizer stands in for one Kea instance and its synchronizer: each +// tick it applies the site's current feed and reports it. +type synchronizer struct { + server BootServer + instance string + mu sync.Mutex + paused bool +} + +func (s *synchronizer) run(ctx context.Context, t *testing.T) { + handler, err := s.server.DHCPHandler(syncToken) + if err != nil { + t.Error(err) + return + } + for ctx.Err() == nil { + s.mu.Lock() + paused := s.paused + s.mu.Unlock() + if !paused { + feed, err := s.server.Reservations() + if err == nil { + data, _ := json.Marshal(bootnet.Applied{Instance: s.instance, Feed: feed}) + request, _ := newRequest("POST", "/dhcp/v1/applied", string(data)) + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + if recorder.Code != http.StatusNoContent { + t.Errorf("applied report = %d", recorder.Code) + } + } + } + time.Sleep(5 * time.Millisecond) + } +} -// TestSyncedDHCPFollowsTheOpenAdmission serves a reservation only for an -// open admission at the Device's stored fence, retains the DHCP owner's -// applied reports, and makes a worker wait for the reservation before a -// network boot and for its withdrawal before it reports. -func TestSyncedDHCPFollowsTheOpenAdmission(t *testing.T) { +// TestASyncedInstallServesItsAddressOnlyWhileItRuns runs an installation at +// a synchronized site. The reservation carries the snapshot's boot MAC and +// the admitted address, DHCP serves it before the network boot, and the +// install succeeds only after DHCP withdrew it. +func TestASyncedInstallServesItsAddressOnlyWhileItRuns(t *testing.T) { + l := newLab(t) + r := runner(t, l) + synced(r) + server := BootServer{Store: r.Store, BootRoot: l.bootRoot} + seen := make(chan bootnet.Feed, 1) + l.onHook = func() { + feed, _ := server.Reservations() + select { + case seen <- feed: + default: + } + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go (&synchronizer{server: server, instance: "dhcp-a"}).run(ctx, t) + spec := installSpec() + spec.BootNetwork = bootNetwork() + result, err := r.Run(context.Background(), assignment(l, "DeviceInstallation", "op-synced", 1, spec)) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseSucceeded || l.onCount() != 2 { + t.Fatalf("result = %+v, %d power-ons", result, l.onCount()) + } + if feed := <-seen; !feed.Has(mac, address) || len(feed.Reservations) != 1 { + t.Fatalf("feed at power-on = %+v, want the snapshot MAC at the admitted address", feed) + } + if feed, _ := server.Reservations(); len(feed.Reservations) != 0 { + t.Fatalf("reservation outlived its operation: %+v", feed) + } +} + +func synced(r *site.Runner) { + for name, kind := range r.Kinds { + switch k := kind.(type) { + case Installation: + k.Synced = true + r.Kinds[name] = k + case Wipe: + k.Synced = true + r.Kinds[name] = k + } + } +} + +// TestABootAddressMustFitTheSiteDHCP refuses, with nothing sent, a network +// boot without a boot address at a synchronized site and one with a boot +// address elsewhere. +func TestABootAddressMustFitTheSiteDHCP(t *testing.T) { + l := newLab(t) + r := runner(t, l) + spec := installSpec() + spec.BootNetwork = bootNetwork() + result, _ := r.Run(context.Background(), assignment(l, "DeviceInstallation", "op-static", 1, spec)) + if result.Phase != ops.PhaseFailed || result.Reason != custody.ReasonBootNetworkUnsupported || l.onCount() != 0 { + t.Fatalf("static site: %+v", result) + } + m := newLab(t) + s := runner(t, m) + synced(s) + wipe := ops.DeviceWipeSpec{Step: 1, CleaningPolicyDigest: "sha256:" + strings.Repeat("b", 64), TargetDisks: []string{"disk-0"}, BootInterface: "primary"} + result, _ = s.Run(context.Background(), assignment(m, "DeviceWipe", "op-no-address", 1, wipe)) + if result.Phase != ops.PhaseFailed || result.Reason != custody.ReasonBootNetworkRequired || m.onCount() != 0 { + t.Fatalf("synced site without an address: %+v", result) + } + if feed, _ := (BootServer{Store: s.Store}).Reservations(); len(feed.Reservations) != 0 { + t.Fatalf("a refused operation published %+v", feed) + } +} + +// TestAPublishedReservationNeverEndsFailed lets DHCP never apply the +// reservation. The worker stops before any power-on, but the reservation +// was published, so the outcome is unknown and the address stays claimed. +func TestAPublishedReservationNeverEndsFailed(t *testing.T) { + l := newLab(t) + r := runner(t, l) + synced(r) + installation := r.Kinds["DeviceInstallation"].(Installation) + installation.BootWindow = 200 * time.Millisecond + r.Kinds["DeviceInstallation"] = installation + spec := installSpec() + spec.BootNetwork = bootNetwork() + result, err := r.Run(context.Background(), assignment(l, "DeviceInstallation", "op-unapplied", 1, spec)) + if err != nil { + t.Fatal(err) + } + if result.Phase != ops.PhaseOutcomeUnknown || l.onCount() != 0 { + t.Fatalf("result = %+v, %d power-ons", result, l.onCount()) + } +} + +// 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) { root := t.TempDir() for _, dir := range []string{"store", "boot"} { if err := os.Mkdir(filepath.Join(root, dir), 0o700); err != nil { @@ -33,65 +181,84 @@ func TestSyncedDHCPFollowsTheOpenAdmission(t *testing.T) { if err != nil { t.Fatal(err) } - const device = "fleet-provider/server-example-001" - target := redfish.Target{Device: device, MAC: "52:54:00:77:01:0a", Provisioning: redfish.Provisioning{Address: "192.0.2.20/24", Gateway: "192.0.2.1"}} now := time.Now().UTC().Truncate(time.Second) clock := func() time.Time { return now } - if err := store.Raise(device, 3); err != nil { - t.Fatal(err) - } - boot := Boot{Operation: "00000000-0000-4000-8000-000000000301", Fence: 3, MAC: target.MAC, 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) - } - server := BootServer{Store: store, BootRoot: filepath.Join(root, "boot"), Enrollment: redfish.Enrollment{DHCP: redfish.DHCPSynced, Targets: []redfish.Target{target}}, Now: clock} - feed, err := server.Reservations() - if err != nil || !feed.Has(target.MAC, target.Provisioning.Address) { - t.Fatalf("feed = %+v, %v", feed, err) - } + server := BootServer{Store: store, BootRoot: filepath.Join(root, "boot"), Now: clock} handler, err := server.DHCPHandler(syncToken) if err != nil { t.Fatal(err) } - feedServer := httptest.NewServer(handler) - defer feedServer.Close() - post := func(applied bootnet.Applied) { + post := func(instance string, rs ...bootnet.Reservation) { t.Helper() - data, _ := json.Marshal(applied) - request, _ := newRequest("POST", feedServer.URL+"/dhcp/v1/applied", string(data)) - response, err := feedServer.Client().Do(request) - if err != nil || response.StatusCode != 204 { - t.Fatalf("applied report = %v, %v", response, err) + 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) } - response.Body.Close() } - request, _ := newRequest("GET", feedServer.URL+"/dhcp/v1/reservations", "") + request, _ := newRequest("GET", "/dhcp/v1/reservations", "") request.Header.Del("Authorization") - if response, err := feedServer.Client().Do(request); err != nil || response.StatusCode != 401 { - t.Fatalf("unauthenticated feed = %v, %v", response, err) + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + if recorder.Code != http.StatusUnauthorized { + t.Fatalf("unauthenticated feed = %d", recorder.Code) } + // 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) + } + if err := store.PutRecord(device, 2, bootRecords, held.Operation, held); err != nil { + t.Fatal(err) + } + 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 { + 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) + } + 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) + } config := Config{BootRoot: server.BootRoot, Poll: 5 * time.Millisecond, Now: clock, Synced: true} - work := &site.Work{Connection: &site.RedfishConnection{Target: target}} short := func() context.Context { ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) t.Cleanup(cancel) return ctx } - if err := config.awaitReservation(short(), work, boot); err == nil { + if err := config.awaitReservation(short(), boot); err == nil { t.Fatal("a worker booted before DHCP applied the reservation") } - post(bootnet.Applied{Instance: "dhcp-a", Feed: feed}) - if err := config.awaitReservation(short(), work, boot); err != nil { + post("dhcp-a", feed.Reservations...) + if err := config.awaitReservation(short(), boot); err != nil { t.Fatalf("applied reservation not seen: %v", err) } - if err := config.awaitWithdrawal(short(), work, boot); err == nil { - t.Fatal("a reservation still served counted as withdrawn") + 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") + } + if err := RetireInstance(server.BootRoot, "dhcp-b"); err != nil { + t.Fatal(err) } - empty, _ := bootnet.NewFeed(nil) - post(bootnet.Applied{Instance: "dhcp-a", Feed: empty}) - if err := config.awaitWithdrawal(short(), work, boot); err != nil { - t.Fatalf("withdrawal not seen: %v", err) + if err := config.awaitWithdrawal(short(), store, device, boot); err != nil { + t.Fatalf("withdrawal after retiring the silent instance: %v", 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") } // A newer fence supersedes the admission: its reservation goes. if err := store.Raise(device, 4); err != nil { @@ -101,11 +268,3 @@ func TestSyncedDHCPFollowsTheOpenAdmission(t *testing.T) { t.Fatalf("feed after a newer fence = %+v, %v", feed, err) } } - -func newRequest(method, url, body string) (*http.Request, error) { - request, err := http.NewRequest(method, url, strings.NewReader(body)) - if err == nil { - request.Header.Set("Authorization", "Bearer "+syncToken) - } - return request, err -} diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index 04f8f494..9f1b27ec 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -25,6 +25,7 @@ import ( "time" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/bootnet" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/redfish" "go.datum.net/fleet/internal/site" @@ -126,6 +127,9 @@ func (k Installation) Check(_ context.Context, work *site.Work) *custody.Refusal if spec.Bootstrap != nil { return &custody.Refusal{Reason: custody.ReasonBootstrapUnsupported, Message: "bootstrap payloads need the sealed store, which is not implemented"} } + if refusal := k.checkBootNetwork(work, spec.BootNetwork); refusal != nil { + return refusal + } return checkTarget(work, spec.TargetDisks, installPhases) } @@ -140,9 +144,47 @@ func (k Wipe) Check(_ context.Context, work *site.Work) *custody.Refusal { if conn(work).Target.DiskBytes <= 0 { return &custody.Refusal{Reason: ReasonTargetDisks, Message: "the site's enrollment records no disk size to verify the wipe against"} } + if refusal := k.checkBootNetwork(work, spec.BootNetwork); refusal != nil { + return refusal + } return checkTarget(work, spec.TargetDisks, wipePhases) } +// checkBootNetwork requires a boot address exactly at a synchronized site, +// and the boot NIC's MAC from Device inventory, which the admission snapshot +// carries. +func (c Config) checkBootNetwork(work *site.Work, network *ops.BootNetworkInput) *custody.Refusal { + switch { + case c.Synced && network == nil: + return &custody.Refusal{Reason: custody.ReasonBootNetworkRequired, Message: "this site's DHCP is synchronized, so a network boot needs a boot address"} + case !c.Synced: + if refusal := custody.NoBootNetwork(network); refusal != nil { + return refusal + } + } + if _, ok := bootnet.NormalizeMAC(work.Snapshot.BootMACAddress); !ok { + return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "the admission snapshot records no boot NIC MAC"} + } + if network != nil { + if _, err := bootnet.HostAddress(network.Address); err != nil { + return &custody.Refusal{Reason: ReasonInputs, Message: "the boot address is not one IPv4 host address"} + } + } + return nil +} + +// bootAddress is the admitted boot address, or empty. +func bootAddress(work *site.Work) string { + var inputs struct { + BootNetwork *ops.BootNetworkInput `json:"bootNetwork"` + } + if json.Unmarshal(work.Inputs, &inputs) != nil || inputs.BootNetwork == nil { + return "" + } + address, _ := bootnet.HostAddress(inputs.BootNetwork.Address) + return address +} + // checkTarget requires the one enrolled disk and every capability the phases // use. Target disks stay a site-local enrollment fact: the site enrolls one // disk per server, named disk-0. @@ -207,8 +249,11 @@ type Boot struct { Fence int64 `json:"fence"` Mode string `json:"mode"` MAC string `json:"mac"` - Receipt string `json:"receipt"` - Token string `json:"token"` + // Address is the admitted boot address at a synchronized site. The + // reservation feed publishes MAC and Address while the boot is open. + Address string `json:"address,omitempty"` + Receipt string `json:"receipt"` + Token string `json:"token"` // Created is when the admission was created; DHCP reports before it // are not this operation's. Created time.Time `json:"created"` @@ -239,7 +284,16 @@ func (c Config) boot(ctx context.Context, work *site.Work, mode string) (Boot, e return boot, err } _, _, _, window := c.durations() - boot = Boot{Operation: work.Key(), Fence: work.Fence, Mode: mode, MAC: strings.ToLower(conn(work).Target.MAC), Receipt: hex.EncodeToString(receipt), Token: hex.EncodeToString(token), Created: c.now().UTC(), Expires: c.now().Add(window).UTC()} + mac, _ := bootnet.NormalizeMAC(work.Snapshot.BootMACAddress) + boot = Boot{Operation: work.Key(), Fence: work.Fence, Mode: mode, MAC: mac, Address: bootAddress(work), Receipt: hex.EncodeToString(receipt), Token: hex.EncodeToString(token), Created: c.now().UTC(), Expires: c.now().Add(window).UTC()} + if boot.Address != "" { + // Publishing the reservation is an effect: from here on the + // operation can no longer end Failed, so its boot address is kept + // until withdrawal is proven. + if err := work.Step(ctx, site.Step{Name: "boot-reservation", Send: func(context.Context) error { return nil }, Idempotent: true}); err != nil { + return boot, err + } + } return boot, store.PutRecord(work.Device, work.Fence, bootRecords, work.Key(), boot) } @@ -292,7 +346,7 @@ func (c Config) run(ctx context.Context, work *site.Work, phases []phase) ([]ops } } if ph.mode != "" && c.Synced && !requested { - if err := c.awaitReservation(ctx, work, boot); err != nil { + if err := c.awaitReservation(ctx, boot); err != nil { return nil, err } } @@ -323,7 +377,7 @@ func (c Config) run(ctx context.Context, work *site.Work, phases []phase) ([]ops evidence = append(evidence, ops.StepEvidence{Name: ph.name, CompletedAt: metaNow(c.now())}) } if c.Synced { - if err := c.awaitWithdrawal(ctx, work, boot); err != nil { + if err := c.awaitWithdrawal(ctx, work.Store(), work.Device, boot); err != nil { return nil, err } } diff --git a/internal/site/redfishwork/kinds_test.go b/internal/site/redfishwork/kinds_test.go index bc51f28a..2249dc17 100644 --- a/internal/site/redfishwork/kinds_test.go +++ b/internal/site/redfishwork/kinds_test.go @@ -317,7 +317,7 @@ func runner(t *testing.T, l *lab) *site.Runner { return &site.Runner{ Site: "site-example-a", Store: store, Results: site.NewResults(store), Access: site.RedfishAccess{Credentials: credentials{pin: l.pin()}, - Targets: site.StaticTargets{device: {Device: "server-example-001", Endpoint: l.server.URL, SystemID: "A", SystemUUID: uuid, MAC: mac, DiskBytes: diskBytes, Console: filepath.Base(l.console)}}}, + Targets: site.StaticTargets{device: {Device: "server-example-001", Endpoint: l.server.URL, SystemID: "A", SystemUUID: uuid, DiskBytes: diskBytes, Console: filepath.Base(l.console)}}}, Kinds: map[string]site.Kind{"DeviceInstallation": Installation{config}, "DeviceWipe": Wipe{config}}, Poll: 10 * time.Millisecond, } @@ -362,7 +362,7 @@ func TestInstallationRunsBothPhasesWithOneOnEach(t *testing.T) { func TestWipeChecksTheEnrolledDisk(t *testing.T) { l := newLab(t) r := runner(t, l) - spec := ops.DeviceWipeSpec{Step: 1, CleaningPolicyDigest: "sha256:" + strings.Repeat("b", 64), TargetDisks: []string{"disk-0"}} + spec := ops.DeviceWipeSpec{Step: 1, CleaningPolicyDigest: "sha256:" + strings.Repeat("b", 64), TargetDisks: []string{"disk-0"}, BootInterface: "primary"} result, err := r.Run(context.Background(), assignment(l, "DeviceWipe", "op-wipe", 1, spec)) if err != nil { t.Fatal(err) diff --git a/internal/site/runner_test.go b/internal/site/runner_test.go index 324fa4eb..5d81b3fa 100644 --- a/internal/site/runner_test.go +++ b/internal/site/runner_test.go @@ -193,7 +193,7 @@ func newFixture(t *testing.T, uuid string) *fixture { Site: "site-example-a", Store: store, Results: NewResults(store), Access: &RedfishAccess{ Credentials: fixedCredentials{credential: bmcdiscovery.Credential{Username: "operator", Password: "synthetic-secret", Pin: b.pin()}, found: true}, - Targets: StaticTargets{testDevice: {Device: "server-example-001", Endpoint: b.server.URL, SystemID: "A", SystemUUID: testUUID, MAC: testMAC}}, + Targets: StaticTargets{testDevice: {Device: "server-example-001", Endpoint: b.server.URL, SystemID: "A", SystemUUID: testUUID}}, }, Kinds: map[string]Kind{"DeviceInstallation": kind}, Poll: 10 * time.Millisecond, @@ -253,7 +253,7 @@ func TestPinMismatchSendsNothing(t *testing.T) { impostor := newBMC(t, testUUID) // Enrollment and the snapshot name the impostor's endpoint, while the // approved pin and the snapshot's key are the real BMC's. - f.access().Targets = StaticTargets{testDevice: {Endpoint: impostor.server.URL, SystemID: "A", SystemUUID: testUUID, MAC: testMAC}} + f.access().Targets = StaticTargets{testDevice: {Endpoint: impostor.server.URL, SystemID: "A", SystemUUID: testUUID}} assignment := f.assignment(1, "op-pin") assignment.Snapshot.BMCEndpoint = impostor.server.URL result, err := f.runner.Run(context.Background(), assignment) @@ -298,7 +298,7 @@ func TestIdentityMismatchSendsNothing(t *testing.T) { // is contacted. g := newFixture(t, testUUID) moved := g.assignment(1, "op-moved") - moved.Snapshot.BootMACAddress = "02:00:00:00:00:99" + moved.Snapshot.BMCEndpoint = "https://192.0.2.99:443" result, _ = g.runner.Run(context.Background(), moved) if result.Phase != ops.PhaseFailed || result.Reason != custody.ReasonDeviceIdentityMismatch || g.bmc.count(any_) != 0 { t.Fatalf("result = %+v, requests %d", result, g.bmc.count(any_)) diff --git a/internal/site/simwork/kinds.go b/internal/site/simwork/kinds.go index 545f12be..8c8ad306 100644 --- a/internal/site/simwork/kinds.go +++ b/internal/site/simwork/kinds.go @@ -91,6 +91,9 @@ func (Installation) Check(_ context.Context, work *site.Work) *custody.Refusal { if spec.Bootstrap != nil { return &custody.Refusal{Reason: custody.ReasonBootstrapUnsupported, Message: "bootstrap payloads need the sealed store, which is not implemented"} } + if refusal := custody.NoBootNetwork(spec.BootNetwork); refusal != nil { + return refusal + } return checkDisks(work, spec.TargetDisks) } @@ -162,6 +165,9 @@ func (Wipe) Check(_ context.Context, work *site.Work) *custody.Refusal { if refusal != nil { return refusal } + if refusal := custody.NoBootNetwork(spec.BootNetwork); refusal != nil { + return refusal + } return checkDisks(work, spec.TargetDisks) } diff --git a/internal/site/vmwork/kinds.go b/internal/site/vmwork/kinds.go index a8d3c6c0..89e883c6 100644 --- a/internal/site/vmwork/kinds.go +++ b/internal/site/vmwork/kinds.go @@ -159,6 +159,9 @@ func (k Installation) Check(_ context.Context, work *site.Work) *custody.Refusal if spec.Bootstrap != nil { return &custody.Refusal{Reason: custody.ReasonBootstrapUnsupported, Message: "bootstrap payloads need the sealed store, which is not implemented"} } + if refusal := custody.NoBootNetwork(spec.BootNetwork); refusal != nil { + return refusal + } if spec.Image.Name+"@"+spec.Image.Digest != k.Image { return &custody.Refusal{Reason: custody.ReasonTargetUnsupported, Message: "the site installs only its verified local image"} } @@ -448,6 +451,9 @@ func (k Wipe) Check(_ context.Context, work *site.Work) *custody.Refusal { if refusal != nil { return refusal } + if refusal := custody.NoBootNetwork(spec.BootNetwork); refusal != nil { + return refusal + } return enrolled(work, spec.TargetDisks) } diff --git a/internal/site/vmwork/kinds_test.go b/internal/site/vmwork/kinds_test.go index 7b716135..76f8a285 100644 --- a/internal/site/vmwork/kinds_test.go +++ b/internal/site/vmwork/kinds_test.go @@ -215,7 +215,7 @@ func installSpec() ops.DeviceInstallationSpec { } func wipeSpec() ops.DeviceWipeSpec { - return ops.DeviceWipeSpec{OperationEnvelope: envelope(), Step: 1, CleaningPolicyDigest: "sha256:" + key, TargetDisks: []string{"disk-0"}} + return ops.DeviceWipeSpec{OperationEnvelope: envelope(), Step: 1, CleaningPolicyDigest: "sha256:" + key, TargetDisks: []string{"disk-0"}, BootInterface: "primary"} } // TestInstallThenWipe installs directly, proves each phase by its receipt, From 7a64a76583a28f8a1b4734788d680da1734706e4 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 10:05:46 -0600 Subject: [PATCH 2/9] fix: Keep held retries' boot addresses claimed Read custody after each operation, so a hold written before OutcomeUnknown keeps its claim, and keep the original's claim while a held retry names it. Admit only the operation's own claim, refuse an IPv6 boot address at the site, and let the multi-plane composition set a provisioning class. Co-Authored-By: Claude Opus 5.5 --- docs/development/device-custody.md | 2 +- docs/operations/boot-network.md | 18 +++++--- internal/allocation/bootaddress_test.go | 57 +++++++++++++++++++----- internal/allocation/release.go | 37 +++++++++++---- internal/bootaddress/bootaddress.go | 14 ++++-- internal/bootaddress/bootaddress_test.go | 21 ++++++--- internal/custody/admission_test.go | 37 ++++++++++----- internal/custody/harness_test.go | 6 ++- internal/custody/kinds.go | 8 ++-- internal/multiplane/runner.go | 8 ++++ internal/site/redfishwork/dhcp_test.go | 12 +++++ internal/site/redfishwork/kinds.go | 3 +- 12 files changed, 171 insertions(+), 52 deletions(-) diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 9cb5aad8..f6ad1416 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -171,7 +171,7 @@ them. | Synthetic staging mode | **Implemented.** The manager's flag handling is unit tested, and no run exercises the mode | | Power projector | **Implemented and verified** by the standalone smoke | | Synchronized DHCP feed on the site store | **Implemented and verified** by a unit test. Not exercised at a site | -| Boot addresses from IPAM as installation and wipe inputs | **Implemented and verified** by tests against a real API server with a stand-in for IPAM's claim API. See [Boot network](../operations/boot-network.md) | +| Boot addresses from IPAM as installation and wipe inputs | **Implemented and verified** by tests against a real API server with a stand-in for IPAM's claim API. **Inert** end to end: no run sets a provisioning class. See [Boot network](../operations/boot-network.md) | ### MachineAllocation diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index c8e4953a..5621ab23 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -30,14 +30,17 @@ without the other, and needs a dedicated provisioning network on the boot NIC. ## Boot address claims When the allocator is configured with a provisioning IPAM class, each requester -claims a boot address before it creates its operation: +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: - the Metal provider, for a `DeviceInstallation`; and - the release controller, for a `DeviceWipe`. The claim is an IPAM `IPClaim` in the provider project named `-boot`, labeled with the allocation, the operation and the -operation kind. It asks for one IPv4 host address and `reclaimPolicy: Delete`. +operation kind, and scoped to the site's location. It asks for one IPv4 host +address and `reclaimPolicy: Delete`. IPAM binds it when it is created. The requester copies the claim's name, UID and address into the operation's `spec.bootNetwork`: @@ -50,15 +53,20 @@ spec: ``` Admission refuses the operation with `BootAddressUnavailable` unless that claim -incarnation exists, is `Bound`, and holds that address. It refuses it with +is the operation's own, by name and labels, and that incarnation exists, is +`Bound`, and holds that address. It refuses it with `BootInterfaceUnknown` unless the Device records the boot interface with a MAC. The admission snapshot records that MAC. Each requester deletes only its own kind's claims, during release: -- a claim whose operation ended and is not the recovery hold; and +- a claim whose operation ended and that custody's recovery hold does not + name, either as the held operation or as the original of a held retry; and - every remaining claim once the allocation is released. +The allocator reads custody after it reads the operation, because the +coordinator writes a hold before it copies `OutcomeUnknown` to the operation. + A claim whose operation does not exist yet stays, so a requester that crashed between the claim and the operation still finds it. The roles grant each requester `create`, `get`, `list` and `delete` on `ipclaims`, and the @@ -179,7 +187,7 @@ drain the instance being removed until it reports an empty feed. | 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 | +| 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 | | 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/internal/allocation/bootaddress_test.go b/internal/allocation/bootaddress_test.go index 22d339a7..3233b0f3 100644 --- a/internal/allocation/bootaddress_test.go +++ b/internal/allocation/bootaddress_test.go @@ -7,6 +7,7 @@ import ( "sync" "testing" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "sigs.k8s.io/controller-runtime/pkg/client" @@ -44,6 +45,20 @@ func (c *ipam) Create(ctx context.Context, object client.Object, options ...clie return c.Client.Status().Update(ctx, claim) } +// writer is one requester's client: it may delete only the claims of its +// own operation kind. +type writer struct { + client.Client + kind string +} + +func (w writer) Delete(ctx context.Context, object client.Object, options ...client.DeleteOption) error { + if claim, ok := object.(*unstructured.Unstructured); ok && claim.GroupVersionKind() == bootaddress.GVK && claim.GetLabels()[bootaddress.KindLabel] != w.kind { + return fmt.Errorf("the %s requester deleted a %s claim", w.kind, claim.GetLabels()[bootaddress.KindLabel]) + } + return w.Client.Delete(ctx, object, options...) +} + func (c *ipam) created() []string { c.mu.Lock() defer c.mu.Unlock() @@ -87,7 +102,7 @@ func TestBootAddressesFollowTheirOperations(t *testing.T) { e.runner.Kinds["DeviceInstallation"] = syncedSite{simwork.Installation{}} e.runner.Kinds["DeviceWipe"] = syncedSite{simwork.Wipe{}} recorder := &ipam{Client: e.admin} - e.allocator.Provider, e.allocator.Releaser = recorder, recorder + e.allocator.Provider, e.allocator.Releaser = writer{recorder, "DeviceInstallation"}, writer{recorder, "DeviceWipe"} e.allocator.BootAddresses = &bootaddress.Claimer{Class: "provisioning"} device := e.server(1) @@ -125,23 +140,45 @@ func TestBootAddressesFollowTheirOperations(t *testing.T) { } claims := e.allocator.installClaims() - held := &ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: "DeviceInstallation", Name: operation.Name}} // A claim for an operation not yet created stays: its requester may // still create the operation. if _, err := claims.Claim(e.ctx, allocation.Name, allocation.Name+"-install-pending"); err != nil { t.Fatal(err) } - if none, err := e.allocator.releaseBootAddresses(e.ctx, allocation, held, false); err != nil || none { - t.Fatalf("release under a hold: none=%v %v", none, err) - } - if remaining, _ := claims.Operations(e.ctx, allocation.Name); len(remaining) != 2 { - t.Fatalf("a held or uncreated operation lost its claim: %v", remaining) + hold := func(held *ops.RecoveryHold) { + t.Helper() + state := e.custody(device.Name) + state.Spec.RecoveryHold = held + if err := e.admin.Update(e.ctx, state); err != nil { + t.Fatal(err) + } } - if none, err := e.allocator.releaseBootAddresses(e.ctx, allocation, nil, false); err != nil || none { + remaining := func() []string { + t.Helper() + names, err := claims.Operations(e.ctx, allocation.Name) + if err != nil { + t.Fatal(err) + } + return names + } + held := ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: "DeviceInstallation", Name: operation.Name, UID: string(operation.UID)}, Fence: operation.Status.Fence, Since: metav1.Now(), Reason: "Synthetic"} + hold(&held) + if none, err := e.allocator.releaseBootAddresses(e.ctx, allocation, false); err != nil || none || len(remaining()) != 2 { + t.Fatalf("release under a hold: none=%v %v, remaining %v", none, err, remaining()) + } + // A retry that also ended unknown holds the original as its retry name. + retry := held + retry.Name, retry.RetryName = operation.Name+"-retry-1", operation.Name + hold(&retry) + if none, err := e.allocator.releaseBootAddresses(e.ctx, allocation, false); err != nil || none || len(remaining()) != 2 { + t.Fatalf("release under a retry's hold: none=%v %v, remaining %v", none, err, remaining()) + } + hold(nil) + if none, err := e.allocator.releaseBootAddresses(e.ctx, allocation, false); err != nil || none { t.Fatalf("release without a hold: none=%v %v", none, err) } - if remaining, _ := claims.Operations(e.ctx, allocation.Name); len(remaining) != 1 || remaining[0] != allocation.Name+"-install-pending" { - t.Fatalf("remaining = %v, want only the uncreated operation's claim", remaining) + if names := remaining(); len(names) != 1 || names[0] != allocation.Name+"-install-pending" { + t.Fatalf("remaining = %v, want only the uncreated operation's claim", names) } e.release(allocation, machine(1)) diff --git a/internal/allocation/release.go b/internal/allocation/release.go index b501d033..fce6914d 100644 --- a/internal/allocation/release.go +++ b/internal/allocation/release.go @@ -53,12 +53,12 @@ func (a *Allocator) Release(ctx context.Context, allocation *fleetv1.MachineAllo if err := a.releaseQuota(ctx, allocation, machine); err != nil { return false, err } - if gone, err := a.releaseBootAddresses(ctx, allocation, nil, true); err != nil || !gone { + if gone, err := a.releaseBootAddresses(ctx, allocation, true); err != nil || !gone { return false, err } return true, a.setPhase(ctx, allocation, fleetv1.AllocationReleased) } - if _, err := a.releaseBootAddresses(ctx, allocation, state.Spec.RecoveryHold, false); err != nil { + if _, err := a.releaseBootAddresses(ctx, allocation, false); err != nil { return false, err } if err := a.setPhase(ctx, allocation, fleetv1.AllocationReleasing); err != nil { @@ -101,9 +101,13 @@ func (a *Allocator) Release(ctx context.Context, allocation *fleetv1.MachineAllo // ended operations, each with its requester's client, and reports whether // none remain. A held operation keeps its claim, because a silent DHCP // instance may still serve its address, and so does an operation not yet -// created. With all, it deletes every claim: the Device left the allocation, -// so no operation of it is held or can still be created. -func (a *Allocator) releaseBootAddresses(ctx context.Context, allocation *fleetv1.MachineAllocation, hold *ops.RecoveryHold, all bool) (bool, error) { +// created. The hold names the held operation, and, after a retry that also +// ended unknown, the original operation as its retry name; both keep their +// claims. Custody is read after the operation, because the coordinator writes +// a hold before it copies OutcomeUnknown to the operation. With all, it +// deletes every claim: the Device left the allocation, so no operation of it +// is held or can still be created. +func (a *Allocator) releaseBootAddresses(ctx context.Context, allocation *fleetv1.MachineAllocation, all bool) (bool, error) { none := true for _, pair := range []struct { claimer *bootaddress.Claimer @@ -122,10 +126,6 @@ func (a *Allocator) releaseBootAddresses(ctx context.Context, allocation *fleetv } for _, name := range operations { if !all { - if hold != nil && hold.Name == name { - none = false - continue - } operation := pair.new() if err := pair.api.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: name}, operation); apierrors.IsNotFound(err) { none = false @@ -137,6 +137,14 @@ func (a *Allocator) releaseBootAddresses(ctx context.Context, allocation *fleetv none = false continue } + held, err := a.held(ctx, allocation, name) + if err != nil { + return false, err + } + if held { + none = false + continue + } } gone, err := pair.claimer.Release(ctx, name) if err != nil { @@ -148,6 +156,17 @@ func (a *Allocator) releaseBootAddresses(ctx context.Context, allocation *fleetv return none, nil } +// held reports whether custody's recovery hold names the operation, as the +// held operation or as the original of a held retry. +func (a *Allocator) held(ctx context.Context, allocation *fleetv1.MachineAllocation, operation string) (bool, error) { + state := &ops.DeviceCustody{} + if err := a.Releaser.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: allocation.Spec.DeviceRef.Name}, state); err != nil { + return false, err + } + hold := state.Spec.RecoveryHold + return hold != nil && (hold.Name == operation || hold.RetryName == operation), nil +} + func (a *Allocator) releaseQuota(ctx context.Context, _ *fleetv1.MachineAllocation, machine Machine) error { if a.Quota == nil { return nil diff --git a/internal/bootaddress/bootaddress.go b/internal/bootaddress/bootaddress.go index 8bf823a3..936dfe63 100644 --- a/internal/bootaddress/bootaddress.go +++ b/internal/bootaddress/bootaddress.go @@ -105,7 +105,7 @@ func (c Claimer) Claim(ctx context.Context, allocation, operation string) (*ops. if err != nil { return nil, err } - if labels := claim.GetLabels(); labels[OperationLabel] != operation || labels[AllocationLabel] != allocation || labels[KindLabel] != c.Kind || stringAt(claim, "spec", "className") != c.Class { + if labels := claim.GetLabels(); labels[OperationLabel] != operation || labels[AllocationLabel] != allocation || labels[KindLabel] != c.Kind { return nil, fmt.Errorf("%w: %s", ErrConflict, claim.GetName()) } address, err := bound(claim) @@ -160,12 +160,17 @@ func (c Claimer) get(ctx context.Context, name string) (*unstructured.Unstructur return claim, c.Client.Get(ctx, client.ObjectKey{Namespace: c.Namespace, Name: name}, claim) } -// Verify requires the named claim incarnation to be bound to exactly the +// Verify requires the input to name the operation's own claim, by its only +// name and its labels, and that claim incarnation to be bound to exactly the // input's address. Admission calls it with the provider project's reader. -func Verify(ctx context.Context, reader client.Reader, namespace string, input ops.BootNetworkInput) error { +func Verify(ctx context.Context, reader client.Reader, operation ops.Operation, kind string, input ops.BootNetworkInput) error { if reader == nil { return ErrUnavailable } + namespace := operation.GetNamespace() + if input.AddressClaim.Name != ClaimName(operation.GetName()) { + return fmt.Errorf("%w: the claim is not the operation's own", ErrUnavailable) + } claim := &unstructured.Unstructured{} claim.SetGroupVersionKind(GVK) if err := reader.Get(ctx, client.ObjectKey{Namespace: namespace, Name: input.AddressClaim.Name}, claim); err != nil { @@ -174,6 +179,9 @@ func Verify(ctx context.Context, reader client.Reader, namespace string, input o if string(claim.GetUID()) != input.AddressClaim.UID || claim.GetDeletionTimestamp() != nil { return fmt.Errorf("%w: the claim is another incarnation or is being deleted", ErrUnavailable) } + if labels := claim.GetLabels(); labels[OperationLabel] != operation.GetName() || labels[KindLabel] != kind { + return fmt.Errorf("%w: the claim belongs to another operation", ErrUnavailable) + } address, err := bound(claim) if err != nil { return fmt.Errorf("%w: %v", ErrUnavailable, err) diff --git a/internal/bootaddress/bootaddress_test.go b/internal/bootaddress/bootaddress_test.go index 818bf957..98a3b5b0 100644 --- a/internal/bootaddress/bootaddress_test.go +++ b/internal/bootaddress/bootaddress_test.go @@ -80,24 +80,35 @@ func TestVerifyRequiresTheExactBoundIncarnation(t *testing.T) { } claim := bind(t, api, "alloc-a-install-1-boot", "Bound", "198.51.100.10") good := ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: claim.GetName(), UID: string(claim.GetUID())}, Address: "198.51.100.10"} - if err := Verify(ctx, api, namespace, good); err != nil { + operation := &ops.DeviceInstallation{} + operation.Name, operation.Namespace = "alloc-a-install-1", namespace + if err := Verify(ctx, api, operation, "DeviceInstallation", good); err != nil { t.Fatal(err) } + // The claim must be the operation's own: by name and by its labels. + other := &ops.DeviceInstallation{} + other.Name, other.Namespace = "alloc-a-install-2", namespace + if err := Verify(ctx, api, other, "DeviceInstallation", good); !errors.Is(err, ErrUnavailable) { + t.Fatalf("another operation's claim verified: %v", err) + } + if err := Verify(ctx, api, operation, "DeviceWipe", good); !errors.Is(err, ErrUnavailable) { + t.Fatalf("another kind's claim verified: %v", err) + } for name, input := range map[string]ops.BootNetworkInput{ - "missing": {AddressClaim: ops.ClaimReference{Name: "other-boot", UID: good.AddressClaim.UID}, Address: good.Address}, + "other name": {AddressClaim: ops.ClaimReference{Name: "other-boot", UID: good.AddressClaim.UID}, Address: good.Address}, "other UID": {AddressClaim: ops.ClaimReference{Name: good.AddressClaim.Name, UID: string(types.UID("other"))}, Address: good.Address}, "other address": {AddressClaim: good.AddressClaim, Address: "198.51.100.11"}, "not an address": {AddressClaim: good.AddressClaim, Address: "198.51.100.10/24"}, } { - if err := Verify(ctx, api, namespace, input); !errors.Is(err, ErrUnavailable) { + if err := Verify(ctx, api, operation, "DeviceInstallation", input); !errors.Is(err, ErrUnavailable) { t.Errorf("%s: %v", name, err) } } bind(t, api, claim.GetName(), "Releasing", "198.51.100.10") - if err := Verify(ctx, api, namespace, good); !errors.Is(err, ErrUnavailable) { + if err := Verify(ctx, api, operation, "DeviceInstallation", good); !errors.Is(err, ErrUnavailable) { t.Fatalf("unbound claim verified: %v", err) } - if err := Verify(ctx, nil, namespace, good); !errors.Is(err, ErrUnavailable) { + if err := Verify(ctx, nil, operation, "DeviceInstallation", good); !errors.Is(err, ErrUnavailable) { t.Fatal("no reader verified") } if gone, err := c.Release(ctx, "alloc-a-install-1"); err != nil || gone { diff --git a/internal/custody/admission_test.go b/internal/custody/admission_test.go index 3fe0395b..1dd41ac2 100644 --- a/internal/custody/admission_test.go +++ b/internal/custody/admission_test.go @@ -8,6 +8,7 @@ import ( inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/bootaddress" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" ) @@ -275,27 +276,44 @@ func TestAdmissionPreconditions(t *testing.T) { t.Fatal(err) } fence := e.custody(device.Name).Spec.Fence - bound := e.ipClaim("alloc-net-boot-a", "Bound", "198.51.100.10") - pending := e.ipClaim("alloc-net-boot-b", "Pending", "") + name := func(request string) string { return InstallationName("alloc-net", request) } + // claim creates the operation's own claim and returns the input that + // names it. + claim := func(request, phase, address string) *ops.BootNetworkInput { + created := e.ipClaim(bootaddress.ClaimName(name(request)), name(request), "DeviceInstallation", phase, address) + return &ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: created.GetName(), UID: string(created.GetUID())}, Address: address} + } withAddress := func(request string, input *ops.BootNetworkInput) *ops.DeviceInstallation { - operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: InstallationName("alloc-net", request), Namespace: "default"}, Spec: ops.DeviceInstallationSpec{ + operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: name(request), Namespace: "default"}, Spec: ops.DeviceInstallationSpec{ OperationEnvelope: envelope(device, providerUser, allocated("alloc-net")), RequestUID: request, Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, BootNetwork: input, }} e.create(operation) return operation } + otherUID := claim("other-uid", "Bound", "198.51.100.10") + otherUID.AddressClaim.UID = "00000000-0000-4000-8000-0000000009ff" + otherAddress := claim("other-address", "Bound", "198.51.100.11") + otherAddress.Address = "198.51.100.99" + good := claim("bound", "Bound", "198.51.100.13") refused := []*ops.DeviceInstallation{ - withAddress("other-uid", &ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: bound.GetName(), UID: "00000000-0000-4000-8000-0000000009ff"}, Address: "198.51.100.10"}), - withAddress("other-address", &ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: bound.GetName(), UID: string(bound.GetUID())}, Address: "198.51.100.11"}), - withAddress("unbound", &ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: pending.GetName(), UID: string(pending.GetUID())}, Address: "198.51.100.12"}), - withAddress("missing", &ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: "alloc-net-boot-missing", UID: string(bound.GetUID())}, Address: "198.51.100.10"}), + withAddress("other-uid", otherUID), + withAddress("other-address", otherAddress), + withAddress("unbound", claim("unbound", "Pending", "198.51.100.12")), + withAddress("missing", &ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: bootaddress.ClaimName(name("missing")), UID: good.AddressClaim.UID}, Address: good.Address}), + // Another operation's bound claim is not this operation's. + withAddress("foreign", good), } e.settle(device.Name) for _, operation := range refused { e.requirePhase(operation, ops.PhaseFailed, ReasonBootAddress) } e.requireUntouched(device.Name, fence) + admitted := withAddress("bound", good) + e.settle(device.Name) + if active := e.custody(device.Name).Spec.ActiveOperation; active == nil || active.Name != admitted.Name || active.Snapshot.BootMACAddress == "" { + t.Fatalf("active = %+v, want the bound installation with the boot MAC from inventory", active) + } // A wipe network-boots too, so its boot interface must have a MAC. releasing := fresh() if err := e.coord.Claim(e.ctx, releasing.Name, "alloc-net-wipe"); err != nil { @@ -312,11 +330,6 @@ func TestAdmissionPreconditions(t *testing.T) { e.settle(releasing.Name) e.requirePhase(wipe, ops.PhaseFailed, ReasonBootInterfaceUnknown) e.requireUntouched(releasing.Name, wipeFence) - admitted := withAddress("bound", &ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: bound.GetName(), UID: string(bound.GetUID())}, Address: "198.51.100.10"}) - e.settle(device.Name) - if active := e.custody(device.Name).Spec.ActiveOperation; active == nil || active.Name != admitted.Name || active.Snapshot.BootMACAddress == "" { - t.Fatalf("active = %+v, want the bound installation with the boot MAC from inventory", active) - } }) t.Run("a staff operation not admitted within five minutes expires", func(t *testing.T) { diff --git a/internal/custody/harness_test.go b/internal/custody/harness_test.go index d2b8bb52..7ad36e9e 100644 --- a/internal/custody/harness_test.go +++ b/internal/custody/harness_test.go @@ -358,13 +358,15 @@ func (e *env) wipe(device *inventory.Device, allocation string, step int32) *ops return operation } -// ipClaim creates a stand-in IPAM claim with the given phase and address. -func (e *env) ipClaim(name, phase, address string) *unstructured.Unstructured { +// ipClaim creates a stand-in IPAM claim for an operation, with the given +// phase and address. +func (e *env) ipClaim(name, operation, kind, phase, address string) *unstructured.Unstructured { e.t.Helper() claim := &unstructured.Unstructured{} claim.SetGroupVersionKind(bootaddress.GVK) claim.SetNamespace("default") claim.SetName(name) + claim.SetLabels(map[string]string{bootaddress.OperationLabel: operation, bootaddress.KindLabel: kind}) claim.Object["spec"] = map[string]any{"className": "provisioning"} if err := e.admin.Create(e.ctx, claim); err != nil { e.t.Fatal(err) diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index 2d6eb229..b59ca465 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -70,7 +70,7 @@ var networkBootReasons = []Reason{{Name: ReasonBootInterfaceUnknown, RaisedBy: R // checkNetworkBoot requires the boot interface to have a MAC in Device // inventory and a boot address, when given, to still be bound to the // operation's claim. -func checkNetworkBoot(ctx context.Context, admission *Admission, bootInterface string, network *ops.BootNetworkInput) *Refusal { +func checkNetworkBoot(ctx context.Context, admission *Admission, kind, bootInterface string, network *ops.BootNetworkInput) *Refusal { found := false for _, iface := range admission.Device.Spec.Interfaces { if iface.Name == bootInterface && iface.MACAddress != "" { @@ -83,7 +83,7 @@ func checkNetworkBoot(ctx context.Context, admission *Admission, bootInterface s if network == nil { return nil } - if err := bootaddress.Verify(ctx, admission.Reader, admission.Operation.GetNamespace(), *network); err != nil { + if err := bootaddress.Verify(ctx, admission.Reader, admission.Operation, kind, *network); err != nil { return refuse(ReasonBootAddress, "the boot address claim %s does not hold %s", network.AddressClaim.Name, network.Address) } return nil @@ -149,7 +149,7 @@ func DeviceInstallationKind() Kind { if installation.Spec.Bootstrap != nil { return refuse(ReasonBootstrapUnsupported, "bootstrap payloads need the sealed store, which is not implemented") } - return checkNetworkBoot(ctx, admission, installation.Spec.BootInterface, installation.Spec.BootNetwork) + return checkNetworkBoot(ctx, admission, "DeviceInstallation", installation.Spec.BootInterface, installation.Spec.BootNetwork) }, Settles: []SettleRule{{Held: "DeviceInstallation"}}, Reasons: append(append([]Reason{{Name: ReasonBootstrapUnsupported, RaisedBy: RaisedByBoth}}, networkBootReasons...), workerReasons...), @@ -180,7 +180,7 @@ func DeviceWipeKind() Kind { BootInterface: func(operation ops.Operation) string { return operation.(*ops.DeviceWipe).Spec.BootInterface }, Check: func(ctx context.Context, admission *Admission) *Refusal { wipe := admission.Operation.(*ops.DeviceWipe) - return checkNetworkBoot(ctx, admission, wipe.Spec.BootInterface, wipe.Spec.BootNetwork) + return checkNetworkBoot(ctx, admission, "DeviceWipe", wipe.Spec.BootInterface, wipe.Spec.BootNetwork) }, // A wipe after release settles an installation hold. A held wipe is // settled by a later wipe only after a DeviceRecovery with Retry. diff --git a/internal/multiplane/runner.go b/internal/multiplane/runner.go index 15db2958..321331a2 100644 --- a/internal/multiplane/runner.go +++ b/internal/multiplane/runner.go @@ -29,6 +29,7 @@ import ( inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleet "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/bootaddress" "go.datum.net/fleet/internal/capacity" "go.datum.net/fleet/internal/controller" "go.datum.net/fleet/internal/coordination" @@ -64,6 +65,10 @@ type Config struct { State, HubKubeconfig, Cell, Image string // Enrollment is the cell's fixture enrollment of each Device it serves. Enrollment fixture.Enrollment + // BootAddressClass is the provisioning IPAM class for a site whose DHCP + // Fleet synchronizes. Empty means the site's DHCP is configured + // independently, as in the lab. + BootAddressClass string `json:",omitempty"` } type Project struct { @@ -258,6 +263,9 @@ func New(ctx context.Context, c Config) (*Runner, error) { Capacity: &capacity.Projector{Reader: r.Provider.API, Namespace: DeviceNamespace, Cleaning: cleaningResolver}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, } + 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}}} + } return r, nil } diff --git a/internal/site/redfishwork/dhcp_test.go b/internal/site/redfishwork/dhcp_test.go index e5a03147..726649e6 100644 --- a/internal/site/redfishwork/dhcp_test.go +++ b/internal/site/redfishwork/dhcp_test.go @@ -143,6 +143,18 @@ func TestABootAddressMustFitTheSiteDHCP(t *testing.T) { if feed, _ := (BootServer{Store: s.Store}).Reservations(); len(feed.Reservations) != 0 { t.Fatalf("a refused operation published %+v", feed) } + // Kea DHCPv4 cannot serve an IPv6 boot address, so the site refuses it + // before it can stall the other reservations. + n := newLab(t) + u := runner(t, n) + synced(u) + v6 := installSpec() + v6.BootNetwork = bootNetwork() + v6.BootNetwork.Address = "2001:db8::20" + result, _ = u.Run(context.Background(), assignment(n, "DeviceInstallation", "op-v6", 1, v6)) + if result.Phase != ops.PhaseFailed || result.Reason != ReasonInputs || n.onCount() != 0 { + t.Fatalf("IPv6 boot address: %+v", result) + } } // TestAPublishedReservationNeverEndsFailed lets DHCP never apply the diff --git a/internal/site/redfishwork/kinds.go b/internal/site/redfishwork/kinds.go index 9f1b27ec..cff5ca26 100644 --- a/internal/site/redfishwork/kinds.go +++ b/internal/site/redfishwork/kinds.go @@ -17,6 +17,7 @@ import ( "encoding/json" "errors" "fmt" + "net/netip" "os" "path/filepath" "slices" @@ -166,7 +167,7 @@ func (c Config) checkBootNetwork(work *site.Work, network *ops.BootNetworkInput) return &custody.Refusal{Reason: ReasonUnsupportedTarget, Message: "the admission snapshot records no boot NIC MAC"} } if network != nil { - if _, err := bootnet.HostAddress(network.Address); err != nil { + if address, err := netip.ParseAddr(network.Address); err != nil || !address.Is4() || address.String() != network.Address { return &custody.Refusal{Reason: ReasonInputs, Message: "the boot address is not one IPv4 host address"} } } From 29706e16c55d4552947892417209ea18898e94fa Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 11:13:57 -0600 Subject: [PATCH 3/9] fix(multiplane): Read the lab boot MAC in Redfish evidence The boot order check still read the MAC from the site enrollment, which no longer names one. Read it from the lab's VM definitions, as the boot admission check does. Co-Authored-By: Claude Opus 5.5 --- hack/multiplane/evidence.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index 7cd5439a..5d05dd5d 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -347,7 +347,7 @@ def redfish_provider(): qemu = (raw / 'libvirt-qemu' / 'fleet-lab-target-a.log').read_text(errors='replace') blocks = re.split(r'^\S+ \S+: starting up ', qemu, flags=re.M)[1:] def network(block): - return any(a['mac'] in seg and ('"bootindex":1' in seg or 'bootindex=1' in seg) for seg in re.split(r'\s-device\s', block)) + return any(lab_mac(a['systemID']) in seg and ('"bootindex":1' in seg or 'bootindex=1' in seg) for seg in re.split(r'\s-device\s', block)) order = ['network' if network(b) else 'disk' for b in blocks] starts = {'targetA': order, 'targetB': (raw / 'libvirt-qemu' / 'fleet-lab-target-b.log').read_text(errors='replace').count(': starting up ') if (raw / 'libvirt-qemu' / 'fleet-lab-target-b.log').exists() else 0} From c7c04e36b839a342dfdb4a6db51a1ef06bef2d8b Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 16:32:52 -0600 Subject: [PATCH 4/9] fix: Keep the boot address claim's UID out of operation specs An installation or wipe names its boot address claim by name only. Admission pins the claim by its only name, its operation and kind labels, and a creation time no later than the operation's, so a claim recreated under the name after the operation is refused. Co-Authored-By: Claude Opus 5.5 --- .../crds/fleet.datumapis.com.yaml | 10 ----- docs/operations/boot-network.md | 12 +++--- internal/allocation/bootaddress_test.go | 2 +- internal/api/operations/v1alpha1/types.go | 11 ++---- internal/bootaddress/bootaddress.go | 14 ++++--- internal/bootaddress/bootaddress_test.go | 38 +++++++++++++++---- internal/custody/admission_test.go | 25 +++++++++--- internal/site/redfishwork/dhcp_test.go | 2 +- 8 files changed, 73 insertions(+), 41 deletions(-) diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index 7e1b595f..27dcbf03 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -525,13 +525,8 @@ spec: type: string minLength: 1 maxLength: 253 - uid: - type: string - minLength: 1 - maxLength: 64 required: - name - - uid address: type: string minLength: 2 @@ -755,13 +750,8 @@ spec: type: string minLength: 1 maxLength: 253 - uid: - type: string - minLength: 1 - maxLength: 64 required: - name - - uid address: type: string minLength: 2 diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index 5621ab23..cacde862 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -41,20 +41,22 @@ The claim is an IPAM `IPClaim` in the provider project named `-boot`, labeled with the allocation, the operation and the operation kind, and scoped to the site's location. It asks for one IPv4 host address and `reclaimPolicy: Delete`. -IPAM binds it when it is created. The requester copies the claim's name, UID -and address into the operation's `spec.bootNetwork`: +IPAM binds it when it is created. The requester copies the claim's name and +address into the operation's `spec.bootNetwork`. The spec holds no UID: ```yaml spec: bootInterface: primary bootNetwork: - addressClaim: {name: alloc-3b9d61c2-install-1-boot, uid: 1d2f7a9e-0b3c-4e5f-8a6b-7c8d9e0f1a2b} + addressClaim: {name: alloc-3b9d61c2-install-1-boot} address: 198.51.100.10 ``` Admission refuses the operation with `BootAddressUnavailable` unless that claim -is the operation's own, by name and labels, and that incarnation exists, is -`Bound`, and holds that address. It refuses it with +is the operation's own, by name and labels, exists, is `Bound`, holds that +address, and was created no later than the operation. The requester always +creates the claim first, so a claim deleted and recreated under the name after +the operation is refused even if it holds the same address. It refuses it with `BootInterfaceUnknown` unless the Device records the boot interface with a MAC. The admission snapshot records that MAC. diff --git a/internal/allocation/bootaddress_test.go b/internal/allocation/bootaddress_test.go index 3233b0f3..8ed0638f 100644 --- a/internal/allocation/bootaddress_test.go +++ b/internal/allocation/bootaddress_test.go @@ -115,7 +115,7 @@ func TestBootAddressesFollowTheirOperations(t *testing.T) { t.Fatal(err) } network := operation.Spec.BootNetwork - if network == nil || network.AddressClaim.Name != bootaddress.ClaimName(operation.Name) || network.AddressClaim.UID == "" || network.Address == "" { + if network == nil || network.AddressClaim.Name != bootaddress.ClaimName(operation.Name) || network.Address == "" { t.Fatalf("boot network = %+v", network) } creates := recorder.created() diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index aecd97a5..689c453b 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -315,17 +315,14 @@ type DeviceInstallationSpec struct { // operation and releases the claim when the operation can no longer reach // DHCP. type BootNetworkInput struct { - AddressClaim ClaimReference `json:"addressClaim"` + // AddressClaim is the operation's own IPAM claim, by its only name. Its + // incarnation is pinned by that name, its labels, and its creation no + // later than the operation's; no UID is held in spec. + AddressClaim LocalReference `json:"addressClaim"` // Address is the bound host address, without a prefix length. Address string `json:"address"` } -// ClaimReference names one IPAM claim incarnation in the provider project. -type ClaimReference struct { - Name string `json:"name"` - UID string `json:"uid"` -} - type ImageInput struct { Name string `json:"name"` Digest string `json:"digest"` diff --git a/internal/bootaddress/bootaddress.go b/internal/bootaddress/bootaddress.go index 936dfe63..dc40866c 100644 --- a/internal/bootaddress/bootaddress.go +++ b/internal/bootaddress/bootaddress.go @@ -112,7 +112,7 @@ func (c Claimer) Claim(ctx context.Context, allocation, operation string) (*ops. if err != nil { return nil, err } - return &ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: claim.GetName(), UID: string(claim.GetUID())}, Address: address}, nil + return &ops.BootNetworkInput{AddressClaim: ops.LocalReference{Name: claim.GetName()}, Address: address}, nil } // Release deletes the operation's claim. It returns true once the claim is @@ -161,8 +161,11 @@ func (c Claimer) get(ctx context.Context, name string) (*unstructured.Unstructur } // Verify requires the input to name the operation's own claim, by its only -// name and its labels, and that claim incarnation to be bound to exactly the -// input's address. Admission calls it with the provider project's reader. +// name and its labels, and that claim to be bound to exactly the input's +// address. The requester creates the claim before the operation, so a claim +// created after its operation is a recreation, never the claim the operation +// was built from, and is refused. Admission calls it with the provider +// project's reader. func Verify(ctx context.Context, reader client.Reader, operation ops.Operation, kind string, input ops.BootNetworkInput) error { if reader == nil { return ErrUnavailable @@ -176,8 +179,9 @@ func Verify(ctx context.Context, reader client.Reader, operation ops.Operation, if err := reader.Get(ctx, client.ObjectKey{Namespace: namespace, Name: input.AddressClaim.Name}, claim); err != nil { return fmt.Errorf("%w: %v", ErrUnavailable, err) } - if string(claim.GetUID()) != input.AddressClaim.UID || claim.GetDeletionTimestamp() != nil { - return fmt.Errorf("%w: the claim is another incarnation or is being deleted", ErrUnavailable) + created, opened := claim.GetCreationTimestamp(), operation.GetCreationTimestamp() + if claim.GetDeletionTimestamp() != nil || created.IsZero() || opened.IsZero() || created.After(opened.Time) { + return fmt.Errorf("%w: the claim was recreated after its operation or is being deleted", ErrUnavailable) } if labels := claim.GetLabels(); labels[OperationLabel] != operation.GetName() || labels[KindLabel] != kind { return fmt.Errorf("%w: the claim belongs to another operation", ErrUnavailable) diff --git a/internal/bootaddress/bootaddress_test.go b/internal/bootaddress/bootaddress_test.go index 98a3b5b0..e12eae63 100644 --- a/internal/bootaddress/bootaddress_test.go +++ b/internal/bootaddress/bootaddress_test.go @@ -4,10 +4,11 @@ import ( "context" "errors" "testing" + "time" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" @@ -49,7 +50,7 @@ func TestClaimIsCreatedOnceAndBoundBeforeUse(t *testing.T) { } claim := bind(t, api, "alloc-a-install-1-boot", "Bound", "198.51.100.10") input, err := c.Claim(ctx, "alloc-a", "alloc-a-install-1") - if err != nil || input.Address != "198.51.100.10" || input.AddressClaim.Name != "alloc-a-install-1-boot" || input.AddressClaim.UID != string(claim.GetUID()) { + if err != nil || input.Address != "198.51.100.10" || input.AddressClaim.Name != "alloc-a-install-1-boot" { t.Fatalf("input = %+v, %v", input, err) } if spec, _, _ := unstructured.NestedMap(claim.Object, "spec"); spec["className"] != "provisioning" || spec["ipFamily"] != "IPv4" || spec["reclaimPolicy"] != "Delete" { @@ -71,7 +72,8 @@ func TestClaimIsCreatedOnceAndBoundBeforeUse(t *testing.T) { } // TestVerifyRequiresTheExactBoundIncarnation refuses a missing claim, -// another incarnation, another address, and an unbound or deleting claim. +// a claim recreated after its operation, another address, and an unbound or +// deleting claim. func TestVerifyRequiresTheExactBoundIncarnation(t *testing.T) { ctx := context.Background() c, api := claimer(t) @@ -79,9 +81,19 @@ func TestVerifyRequiresTheExactBoundIncarnation(t *testing.T) { t.Fatal(err) } claim := bind(t, api, "alloc-a-install-1-boot", "Bound", "198.51.100.10") - good := ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: claim.GetName(), UID: string(claim.GetUID())}, Address: "198.51.100.10"} + created := time.Date(2026, 11, 25, 12, 0, 0, 0, time.UTC) + stamp := func(at time.Time) { + t.Helper() + claim.SetCreationTimestamp(metav1.NewTime(at)) + if err := api.Update(ctx, claim); err != nil { + t.Fatal(err) + } + } + stamp(created) + good := ops.BootNetworkInput{AddressClaim: ops.LocalReference{Name: claim.GetName()}, Address: "198.51.100.10"} operation := &ops.DeviceInstallation{} operation.Name, operation.Namespace = "alloc-a-install-1", namespace + operation.CreationTimestamp = metav1.NewTime(created.Add(time.Second)) if err := Verify(ctx, api, operation, "DeviceInstallation", good); err != nil { t.Fatal(err) } @@ -95,8 +107,7 @@ func TestVerifyRequiresTheExactBoundIncarnation(t *testing.T) { t.Fatalf("another kind's claim verified: %v", err) } for name, input := range map[string]ops.BootNetworkInput{ - "other name": {AddressClaim: ops.ClaimReference{Name: "other-boot", UID: good.AddressClaim.UID}, Address: good.Address}, - "other UID": {AddressClaim: ops.ClaimReference{Name: good.AddressClaim.Name, UID: string(types.UID("other"))}, Address: good.Address}, + "other name": {AddressClaim: ops.LocalReference{Name: "other-boot"}, Address: good.Address}, "other address": {AddressClaim: good.AddressClaim, Address: "198.51.100.11"}, "not an address": {AddressClaim: good.AddressClaim, Address: "198.51.100.10/24"}, } { @@ -104,7 +115,20 @@ func TestVerifyRequiresTheExactBoundIncarnation(t *testing.T) { t.Errorf("%s: %v", name, err) } } - bind(t, api, claim.GetName(), "Releasing", "198.51.100.10") + // The claim deleted and recreated under its name after the operation + // was created is not the claim the operation was built from, even with + // the same address. + stamp(created.Add(2 * time.Second)) + if err := Verify(ctx, api, operation, "DeviceInstallation", good); !errors.Is(err, ErrUnavailable) { + t.Fatalf("a claim recreated after its operation verified: %v", err) + } + stamp(created) + unstamped := &ops.DeviceInstallation{} + unstamped.Name, unstamped.Namespace = operation.Name, operation.Namespace + if err := Verify(ctx, api, unstamped, "DeviceInstallation", good); !errors.Is(err, ErrUnavailable) { + t.Fatalf("an operation with no creation time verified: %v", err) + } + claim = bind(t, api, claim.GetName(), "Releasing", "198.51.100.10") if err := Verify(ctx, api, operation, "DeviceInstallation", good); !errors.Is(err, ErrUnavailable) { t.Fatalf("unbound claim verified: %v", err) } diff --git a/internal/custody/admission_test.go b/internal/custody/admission_test.go index 1dd41ac2..c1e3625e 100644 --- a/internal/custody/admission_test.go +++ b/internal/custody/admission_test.go @@ -10,6 +10,7 @@ import ( ops "go.datum.net/fleet/internal/api/operations/v1alpha1" "go.datum.net/fleet/internal/bootaddress" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "sigs.k8s.io/controller-runtime/pkg/client" ) @@ -281,7 +282,7 @@ func TestAdmissionPreconditions(t *testing.T) { // names it. claim := func(request, phase, address string) *ops.BootNetworkInput { created := e.ipClaim(bootaddress.ClaimName(name(request)), name(request), "DeviceInstallation", phase, address) - return &ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: created.GetName(), UID: string(created.GetUID())}, Address: address} + return &ops.BootNetworkInput{AddressClaim: ops.LocalReference{Name: created.GetName()}, Address: address} } withAddress := func(request string, input *ops.BootNetworkInput) *ops.DeviceInstallation { operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: name(request), Namespace: "default"}, Spec: ops.DeviceInstallationSpec{ @@ -291,16 +292,30 @@ func TestAdmissionPreconditions(t *testing.T) { e.create(operation) return operation } - otherUID := claim("other-uid", "Bound", "198.51.100.10") - otherUID.AddressClaim.UID = "00000000-0000-4000-8000-0000000009ff" + // A claim deleted and recreated under its name, with the same labels + // and address, after its operation was created is not the claim the + // operation was built from. + recreated := claim("recreated", "Bound", "198.51.100.10") + recreatedOperation := withAddress("recreated", recreated) + old := &unstructured.Unstructured{} + old.SetGroupVersionKind(bootaddress.GVK) + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: "default", Name: recreated.AddressClaim.Name}, old); err != nil { + t.Fatal(err) + } + if err := e.admin.Delete(e.ctx, old); err != nil { + t.Fatal(err) + } + // Creation times have one-second resolution. + time.Sleep(1100 * time.Millisecond) + claim("recreated", "Bound", "198.51.100.10") otherAddress := claim("other-address", "Bound", "198.51.100.11") otherAddress.Address = "198.51.100.99" good := claim("bound", "Bound", "198.51.100.13") refused := []*ops.DeviceInstallation{ - withAddress("other-uid", otherUID), + recreatedOperation, withAddress("other-address", otherAddress), withAddress("unbound", claim("unbound", "Pending", "198.51.100.12")), - withAddress("missing", &ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: bootaddress.ClaimName(name("missing")), UID: good.AddressClaim.UID}, Address: good.Address}), + withAddress("missing", &ops.BootNetworkInput{AddressClaim: ops.LocalReference{Name: bootaddress.ClaimName(name("missing"))}, Address: good.Address}), // Another operation's bound claim is not this operation's. withAddress("foreign", good), } diff --git a/internal/site/redfishwork/dhcp_test.go b/internal/site/redfishwork/dhcp_test.go index 726649e6..0d248646 100644 --- a/internal/site/redfishwork/dhcp_test.go +++ b/internal/site/redfishwork/dhcp_test.go @@ -32,7 +32,7 @@ func newRequest(method, url, body string) (*http.Request, error) { } func bootNetwork() *ops.BootNetworkInput { - return &ops.BootNetworkInput{AddressClaim: ops.ClaimReference{Name: "alloc-example-install-boot", UID: "00000000-0000-4000-8000-000000000501"}, Address: address} + return &ops.BootNetworkInput{AddressClaim: ops.LocalReference{Name: "alloc-example-install-boot"}, Address: address} } // synchronizer stands in for one Kea instance and its synchronizer: each From 60725ba60a0798f60492fad807e967c2c2a80a0f Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 17:30:44 -0600 Subject: [PATCH 5/9] test(site): Stop the stand-in synchronizer before its test ends The stand-in synchronizer could post one more report after the synced install test returned and its directories were removed, failing the finished test under the race detector. The test now waits for it to stop. Co-Authored-By: Claude Opus 5.5 --- internal/site/redfishwork/dhcp_test.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/internal/site/redfishwork/dhcp_test.go b/internal/site/redfishwork/dhcp_test.go index 0d248646..69712eb4 100644 --- a/internal/site/redfishwork/dhcp_test.go +++ b/internal/site/redfishwork/dhcp_test.go @@ -61,7 +61,7 @@ func (s *synchronizer) run(ctx context.Context, t *testing.T) { request, _ := newRequest("POST", "/dhcp/v1/applied", string(data)) recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, request) - if recorder.Code != http.StatusNoContent { + if recorder.Code != http.StatusNoContent && ctx.Err() == nil { t.Errorf("applied report = %d", recorder.Code) } } @@ -88,8 +88,13 @@ func TestASyncedInstallServesItsAddressOnlyWhileItRuns(t *testing.T) { } } ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - go (&synchronizer{server: server, instance: "dhcp-a"}).run(ctx, t) + stopped := make(chan struct{}) + go func() { + defer close(stopped) + (&synchronizer{server: server, instance: "dhcp-a"}).run(ctx, t) + }() + // The synchronizer stops before the test's directories are removed. + defer func() { cancel(); <-stopped }() spec := installSpec() spec.BootNetwork = bootNetwork() result, err := r.Run(context.Background(), assignment(l, "DeviceInstallation", "op-synced", 1, spec)) From b30485ea1c04ea9ef7de696245e4f97f0b45ccee Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 17:02:24 -0600 Subject: [PATCH 6/9] fix(allocation): Check an existing operation before reusing its address An installation or wipe that already exists keeps the boot address it was created with. Reusing it skipped the spec and incarnation checks that a create conflict runs, so an operation recorded for an earlier Device under the same name was taken for the new one. The existing operation is now compared with the requested one, carrying its own boot address, under the same rule as a create conflict. The boot address tests also follow the no-UID operation fields. Co-Authored-By: Claude Opus 5.5 --- internal/allocation/allocator.go | 36 ++++++++++++++----------- internal/allocation/bootaddress_test.go | 2 +- internal/allocation/release.go | 24 ++++++++++------- internal/custody/admission_test.go | 10 +++---- 4 files changed, 41 insertions(+), 31 deletions(-) diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go index 7c071432..b6a43c64 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -479,31 +479,31 @@ func (a *Allocator) Install(ctx context.Context, allocation *fleetv1.MachineAllo if err != nil { return nil, err } - name := custody.InstallationName(allocation.Name, string(installation.UID)) - // An existing installation keeps the inputs it was created with; its - // boot address may already be released. - existing := &ops.DeviceInstallation{} - if err := a.Provider.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: name}, existing); err == nil { - return existing, nil - } else if !apierrors.IsNotFound(err) { - return nil, err - } - network, err := a.bootNetwork(ctx, a.installClaims(), allocation, name) - if err != nil { - return nil, err - } labels := operationLabels(allocation) labels[ops.LabelInstallationUID] = string(installation.UID) operation := &ops.DeviceInstallation{ - ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: a.Namespace, Labels: labels}, + ObjectMeta: metav1.ObjectMeta{Name: custody.InstallationName(allocation.Name, string(installation.UID)), Namespace: a.Namespace, Labels: labels}, Spec: ops.DeviceInstallationSpec{ OperationEnvelope: a.envelope(allocation, a.ProviderCreator), Image: image, BootInterface: allocation.Spec.BootInterface, TargetDisks: slices.Clone(allocation.Spec.TargetDisks), - BootNetwork: network, }, } + // An existing installation keeps the boot address it was created with, + // which may already be released. + existing := &ops.DeviceInstallation{} + if err := a.Provider.Get(ctx, client.ObjectKeyFromObject(operation), existing); err == nil { + operation.Spec.BootNetwork = existing.Spec.BootNetwork + return operation, matchExisting(operation, existing) + } else if !apierrors.IsNotFound(err) { + return nil, err + } + network, err := a.bootNetwork(ctx, a.installClaims(), allocation, operation.Name) + if err != nil { + return nil, err + } + operation.Spec.BootNetwork = network return operation, a.createOnce(ctx, a.Provider, operation, &ops.DeviceInstallation{}) } @@ -560,6 +560,12 @@ func (a *Allocator) createOnce(ctx context.Context, api client.Client, operation if err := api.Get(ctx, client.ObjectKeyFromObject(operation), existing); err != nil { return err } + return matchExisting(operation, existing) +} + +// matchExisting accepts an existing operation only when it has the same spec +// and was made for the same incarnations, then copies it into operation. +func matchExisting(operation ops.Operation, existing ops.Operation) error { want, err := specDigest(operation) if err != nil { return err diff --git a/internal/allocation/bootaddress_test.go b/internal/allocation/bootaddress_test.go index 8ed0638f..49ed595e 100644 --- a/internal/allocation/bootaddress_test.go +++ b/internal/allocation/bootaddress_test.go @@ -161,7 +161,7 @@ func TestBootAddressesFollowTheirOperations(t *testing.T) { } return names } - held := ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: "DeviceInstallation", Name: operation.Name, UID: string(operation.UID)}, Fence: operation.Status.Fence, Since: metav1.Now(), Reason: "Synthetic"} + held := ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: "DeviceInstallation", Name: operation.Name}, Fence: operation.Status.Fence, Since: metav1.Now(), Reason: "Synthetic"} hold(&held) if none, err := e.allocator.releaseBootAddresses(e.ctx, allocation, false); err != nil || none || len(remaining()) != 2 { t.Fatalf("release under a hold: none=%v %v, remaining %v", none, err, remaining()) diff --git a/internal/allocation/release.go b/internal/allocation/release.go index fce6914d..def00d7a 100644 --- a/internal/allocation/release.go +++ b/internal/allocation/release.go @@ -252,15 +252,6 @@ func (a *Allocator) wipe(ctx context.Context, allocation *fleetv1.MachineAllocat return err } } - if err := a.Releaser.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: reference.Name}, &ops.DeviceWipe{}); err == nil { - return nil - } else if !apierrors.IsNotFound(err) { - return err - } - network, err := a.bootNetwork(ctx, a.wipeClaims(), allocation, reference.Name) - if err != nil { - return err - } wipe := &ops.DeviceWipe{ ObjectMeta: metav1.ObjectMeta{Name: reference.Name, Namespace: a.Namespace, Labels: operationLabels(allocation)}, Spec: ops.DeviceWipeSpec{ @@ -269,8 +260,21 @@ func (a *Allocator) wipe(ctx context.Context, allocation *fleetv1.MachineAllocat CleaningPolicyDigest: allocation.Spec.CleaningPolicyDigest, TargetDisks: slices.Clone(allocation.Spec.TargetDisks), BootInterface: allocation.Spec.BootInterface, - BootNetwork: network, }, } + // An existing wipe keeps the boot address it was created with, which may + // already be released. + existing := &ops.DeviceWipe{} + if err := a.Releaser.Get(ctx, client.ObjectKeyFromObject(wipe), existing); err == nil { + wipe.Spec.BootNetwork = existing.Spec.BootNetwork + return matchExisting(wipe, existing) + } else if !apierrors.IsNotFound(err) { + return err + } + network, err := a.bootNetwork(ctx, a.wipeClaims(), allocation, reference.Name) + if err != nil { + return err + } + wipe.Spec.BootNetwork = network return a.createOnce(ctx, a.Releaser, wipe, &ops.DeviceWipe{}) } diff --git a/internal/custody/admission_test.go b/internal/custody/admission_test.go index c1e3625e..569d692e 100644 --- a/internal/custody/admission_test.go +++ b/internal/custody/admission_test.go @@ -273,7 +273,7 @@ func TestAdmissionPreconditions(t *testing.T) { t.Run("a boot address must still be bound to its claim", func(t *testing.T) { e := e.sub(t) device := fresh() - if err := e.coord.Claim(e.ctx, device.Name, "alloc-net"); err != nil { + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-net"); err != nil { t.Fatal(err) } fence := e.custody(device.Name).Spec.Fence @@ -285,9 +285,9 @@ func TestAdmissionPreconditions(t *testing.T) { return &ops.BootNetworkInput{AddressClaim: ops.LocalReference{Name: created.GetName()}, Address: address} } withAddress := func(request string, input *ops.BootNetworkInput) *ops.DeviceInstallation { - operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: name(request), Namespace: "default"}, Spec: ops.DeviceInstallationSpec{ - OperationEnvelope: envelope(device, providerUser, allocated("alloc-net")), RequestUID: request, - Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, BootNetwork: input, + operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: name(request), Namespace: "default", Labels: map[string]string{ops.LabelInstallationUID: request}}, Spec: ops.DeviceInstallationSpec{ + OperationEnvelope: envelope(device, providerUser, allocated("alloc-net")), + Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, BootNetwork: input, }} e.create(operation) return operation @@ -331,7 +331,7 @@ func TestAdmissionPreconditions(t *testing.T) { } // A wipe network-boots too, so its boot interface must have a MAC. releasing := fresh() - if err := e.coord.Claim(e.ctx, releasing.Name, "alloc-net-wipe"); err != nil { + if err := e.coord.Claim(e.ctx, releasing.Name, releasing.UID, "alloc-net-wipe"); err != nil { t.Fatal(err) } if err := e.coord.BeginRelease(e.ctx, releasing.Name, "alloc-net-wipe"); err != nil { From e95e34c7b5e9b86c873fde544b8c81785ef5cdfa Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 18:28:20 -0600 Subject: [PATCH 7/9] test: Pin boot addresses off by default An allocator with no boot address claimer, the default, installs and releases with no boot network input and creates no IPAM claim. A site whose DHCP Fleet does not synchronize, also the default, boots an install and a wipe without storing an address the reservation feed could publish. Co-Authored-By: Claude Opus 5.5 --- internal/allocation/bootaddress_test.go | 47 +++++++++++++++++++++++++ internal/site/redfishwork/dhcp_test.go | 25 +++++++++++++ 2 files changed, 72 insertions(+) diff --git a/internal/allocation/bootaddress_test.go b/internal/allocation/bootaddress_test.go index 49ed595e..3457a72b 100644 --- a/internal/allocation/bootaddress_test.go +++ b/internal/allocation/bootaddress_test.go @@ -93,6 +93,53 @@ func (k syncedSite) Run(ctx context.Context, work *site.Work) (any, error) { return k.inner.Run(ctx, stripped) } +// TestTheDefaultAllocatorClaimsNoBootAddress keeps boot addresses off by +// default: an allocator with no boot address claimer installs and releases +// with no boot network input and never creates an IPAM claim. +func TestTheDefaultAllocatorClaimsNoBootAddress(t *testing.T) { + e := startEnv(t) + if e.allocator.BootAddresses != nil { + t.Fatal("the test allocator has a boot address claimer") + } + e.server(1) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + operation, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: e.installation(1, "debian-12", "")}) + if err != nil { + t.Fatal(err) + } + if operation.Spec.BootNetwork != nil { + t.Fatalf("installation boot network = %+v, want none", operation.Spec.BootNetwork) + } + e.until("the installation succeeds", func() bool { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(operation), operation); err != nil { + t.Fatal(err) + } + if operation.Status.Phase.Ended() && operation.Status.Phase != ops.PhaseSucceeded { + t.Fatalf("installation ended %s: %s", operation.Status.Phase, operation.Status.Message) + } + return operation.Status.Phase == ops.PhaseSucceeded + }) + e.release(allocation, machine(1)) + if allocation.Status.Wipe == nil { + t.Fatal("release did not wipe") + } + wipe := &ops.DeviceWipe{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: allocation.Status.Wipe.Name}, wipe); err != nil { + t.Fatal(err) + } + if wipe.Spec.BootNetwork != nil { + t.Fatalf("wipe boot network = %+v, want none", wipe.Spec.BootNetwork) + } + claims := &unstructured.UnstructuredList{} + claims.SetGroupVersionKind(bootaddress.GVK.GroupVersion().WithKind(bootaddress.GVK.Kind + "List")) + if err := e.admin.List(e.ctx, claims); err != nil || len(claims.Items) != 0 { + t.Fatalf("IPAM claims = %d, %v, want none", len(claims.Items), err) + } +} + // TestBootAddressesFollowTheirOperations claims each installation's and // wipe's boot address before the operation exists, carries it into the // admitted inputs, and releases a claim only once its operation ended and diff --git a/internal/site/redfishwork/dhcp_test.go b/internal/site/redfishwork/dhcp_test.go index 69712eb4..66d5eb32 100644 --- a/internal/site/redfishwork/dhcp_test.go +++ b/internal/site/redfishwork/dhcp_test.go @@ -125,6 +125,31 @@ func synced(r *site.Runner) { } } +// TestAStaticSiteStoresNoReservation runs an install and a wipe at a site +// whose DHCP Fleet does not synchronize, the default: both boot, and no boot +// record carries an address the reservation feed could publish. +func TestAStaticSiteStoresNoReservation(t *testing.T) { + l := newLab(t) + r := runner(t, l) + if result, err := r.Run(context.Background(), assignment(l, "DeviceInstallation", "op-static-install", 1, installSpec())); err != nil || result.Phase != ops.PhaseSucceeded { + t.Fatalf("install: %+v, %v", result, err) + } + wipe := ops.DeviceWipeSpec{Step: 1, CleaningPolicyDigest: "sha256:" + strings.Repeat("b", 64), TargetDisks: []string{"disk-0"}, BootInterface: "primary"} + if result, err := r.Run(context.Background(), assignment(l, "DeviceWipe", "op-static-wipe", 2, wipe)); err != nil || result.Phase != ops.PhaseSucceeded { + t.Fatalf("wipe: %+v, %v", result, err) + } + records, err := r.Store.Records(bootRecords) + if err != nil || len(records) != 2 { + t.Fatalf("boot records = %d, %v, want one per boot", len(records), err) + } + for _, record := range records { + var boot Boot + if err := json.Unmarshal(record.Data, &boot); err != nil || boot.Address != "" { + t.Fatalf("boot record %s carries address %q, %v", record.Name, boot.Address, err) + } + } +} + // TestABootAddressMustFitTheSiteDHCP refuses, with nothing sent, a network // boot without a boot address at a synchronized site and one with a boot // address elsewhere. From cb457fb9897d663cf165319d673c09e5da967fe5 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 19:27:14 -0600 Subject: [PATCH 8/9] fix(iam): Keep IPAM grants out of the default roles The installation, wipe and coordinator roles every environment applies granted IPAM claim permissions, though no site uses boot addresses. They move to two roles of their own, a boot address requester and checker, in a component no overlay includes. An environment that enables boot addresses includes it and binds them; until then Fleet holds no IPAM permission anywhere. A test keeps IPAM grants out of the default roles and the component out of every kustomization. Co-Authored-By: Claude Opus 5.5 --- .../boot-addresses/boot-address-checker.yaml | 11 ++++ .../boot-address-requester.yaml | 14 +++++ .../boot-addresses/kustomization.yaml | 11 ++++ .../device-operations/roles/coordinator.yaml | 1 - .../roles/installation-requester.yaml | 6 +- .../roles/wipe-requester.yaml | 6 +- docs/operations/boot-network.md | 13 +++- .../api/operations/v1alpha1/config_test.go | 61 ++++++++++++++++--- 8 files changed, 101 insertions(+), 22 deletions(-) create mode 100644 config/components/boot-addresses/boot-address-checker.yaml create mode 100644 config/components/boot-addresses/boot-address-requester.yaml create mode 100644 config/components/boot-addresses/kustomization.yaml diff --git a/config/components/boot-addresses/boot-address-checker.yaml b/config/components/boot-addresses/boot-address-checker.yaml new file mode 100644 index 00000000..3b61a02b --- /dev/null +++ b/config/components/boot-addresses/boot-address-checker.yaml @@ -0,0 +1,11 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-boot-address-checker + annotations: + kubernetes.io/display-name: Fleet Boot Address Checker + kubernetes.io/description: The custody coordinator at a site whose DHCP Fleet synchronizes. Reads an operation's boot address claim at admission. +spec: + launchStage: Alpha + includedPermissions: + - ipam.miloapis.com/ipclaims.get diff --git a/config/components/boot-addresses/boot-address-requester.yaml b/config/components/boot-addresses/boot-address-requester.yaml new file mode 100644 index 00000000..9ac2b3a6 --- /dev/null +++ b/config/components/boot-addresses/boot-address-requester.yaml @@ -0,0 +1,14 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-boot-address-requester + annotations: + kubernetes.io/display-name: Fleet Boot Address Requester + kubernetes.io/description: The Fleet provider for Metal and the release controller at a site whose DHCP Fleet synchronizes. Claims and releases the boot address of each installation and wipe. +spec: + launchStage: Alpha + includedPermissions: + - ipam.miloapis.com/ipclaims.create + - ipam.miloapis.com/ipclaims.get + - ipam.miloapis.com/ipclaims.list + - ipam.miloapis.com/ipclaims.delete diff --git a/config/components/boot-addresses/kustomization.yaml b/config/components/boot-addresses/kustomization.yaml new file mode 100644 index 00000000..8d05313c --- /dev/null +++ b/config/components/boot-addresses/kustomization.yaml @@ -0,0 +1,11 @@ +# Roles for boot address claims, which only a site whose DHCP Fleet +# synchronizes uses (docs/operations/boot-network.md). No overlay includes +# this component, so no environment grants Fleet any IPAM permission until +# it enables boot addresses: it then includes this component and binds the +# requester role to the installation and wipe requesters and the checker +# role to the custody coordinator. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - boot-address-requester.yaml + - boot-address-checker.yaml diff --git a/config/components/device-operations/roles/coordinator.yaml b/config/components/device-operations/roles/coordinator.yaml index afc75e3f..77b5c27b 100644 --- a/config/components/device-operations/roles/coordinator.yaml +++ b/config/components/device-operations/roles/coordinator.yaml @@ -53,4 +53,3 @@ spec: - metal.datumapis.com/machinecapacities.get - metal.datumapis.com/machinecapacities.list - metal.datumapis.com/machinecapacities.watch - - ipam.miloapis.com/ipclaims.get diff --git a/config/components/device-operations/roles/installation-requester.yaml b/config/components/device-operations/roles/installation-requester.yaml index d9ca470c..0c78eeeb 100644 --- a/config/components/device-operations/roles/installation-requester.yaml +++ b/config/components/device-operations/roles/installation-requester.yaml @@ -4,7 +4,7 @@ metadata: name: fleet.datumapis.com-device-installation-requester annotations: kubernetes.io/display-name: Fleet Device Installation Requester - kubernetes.io/description: The Fleet provider for Metal. Creates DeviceInstallations from Installations, claims and releases their boot addresses, and reads custody and the commissioning evidence it evaluates capacity from. + kubernetes.io/description: The Fleet provider for Metal. Creates DeviceInstallations from Installations, and reads custody and the commissioning evidence it evaluates capacity from. spec: launchStage: Alpha includedPermissions: @@ -27,7 +27,3 @@ spec: - fleet.datumapis.com/devicecommissioningplanapprovals.get - fleet.datumapis.com/devicecommissioningplanapprovals.list - fleet.datumapis.com/devicecommissioningplanapprovals.watch - - ipam.miloapis.com/ipclaims.create - - ipam.miloapis.com/ipclaims.get - - ipam.miloapis.com/ipclaims.list - - ipam.miloapis.com/ipclaims.delete diff --git a/config/components/device-operations/roles/wipe-requester.yaml b/config/components/device-operations/roles/wipe-requester.yaml index 0a445933..ff7dce80 100644 --- a/config/components/device-operations/roles/wipe-requester.yaml +++ b/config/components/device-operations/roles/wipe-requester.yaml @@ -4,7 +4,7 @@ metadata: name: fleet.datumapis.com-device-wipe-requester annotations: kubernetes.io/display-name: Fleet Device Wipe Requester - kubernetes.io/description: The release controller. Creates DeviceWipes during release, claims and releases their boot addresses, and reads custody. + kubernetes.io/description: The release controller. Creates DeviceWipes during release and reads custody. spec: launchStage: Alpha includedPermissions: @@ -15,7 +15,3 @@ spec: - fleet.datumapis.com/devicecustodies.get - fleet.datumapis.com/devicecustodies.list - fleet.datumapis.com/devicecustodies.watch - - ipam.miloapis.com/ipclaims.create - - ipam.miloapis.com/ipclaims.get - - ipam.miloapis.com/ipclaims.list - - ipam.miloapis.com/ipclaims.delete diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index cacde862..f41b34fd 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -70,9 +70,16 @@ The allocator reads custody after it reads the operation, because the coordinator writes a hold before it copies `OutcomeUnknown` to the operation. A claim whose operation does not exist yet stays, so a requester that crashed -between the claim and the operation still finds it. The roles grant each -requester `create`, `get`, `list` and `delete` on `ipclaims`, and the -coordinator `get`. +between the claim and the operation still finds it. + +The IPAM permissions are in their own roles, in +`config/components/boot-addresses`, which no overlay includes. The +`boot-address-requester` role grants `create`, `get`, `list` and `delete` on +`ipclaims`, and the `boot-address-checker` role grants `get`. An environment +that enables boot addresses includes that component and binds the requester +role to the installation and wipe requesters and the checker role to the +coordinator. The device operations roles every environment applies grant no +IPAM permission. ## Enrollment diff --git a/internal/api/operations/v1alpha1/config_test.go b/internal/api/operations/v1alpha1/config_test.go index 60587b01..754662e0 100644 --- a/internal/api/operations/v1alpha1/config_test.go +++ b/internal/api/operations/v1alpha1/config_test.go @@ -180,11 +180,6 @@ func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { declared(t, filepath.Join(componentRoot, "protected-resources"), permissions) declared(t, filepath.Join(configRoot, "components", "inventory", "protected-resources"), permissions) declared(t, filepath.Join(configRoot, "components", "iam", "protected-resources"), permissions) - // IPAM declares its own ProtectedResources. The requesters claim boot - // addresses, and the coordinator reads them at admission. - for _, verb := range []string{"create", "get", "list", "delete"} { - permissions["ipam.miloapis.com/ipclaims."+verb] = true - } roles := map[string]role{} for _, r := range decodeDir[role](t, filepath.Join(componentRoot, "roles")) { roles[r.Metadata.Name] = r @@ -211,12 +206,12 @@ func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { "fleet.datumapis.com-device-commissioning-plan-approver": p(group+"devicecommissioningplanapprovals", "create", "delete"), "fleet.datumapis.com-device-recovery-operator": slices.Concat(p(group+"devicerecoveries", "create"), p("metal.datumapis.com/machineallocations", read...)), "fleet.datumapis.com-device-installation-requester": slices.Concat(p(group+"deviceinstallations", "create", "get", "list", "watch"), p(group+"devicecustodies", read...), - p(group+"devices", read...), p(group+"devicecommissionings", read...), p(group+"devicecommissioningplans", read...), p(group+"devicecommissioningplanapprovals", read...), p("ipam.miloapis.com/ipclaims", "create", "get", "list", "delete")), + p(group+"devices", read...), p(group+"devicecommissionings", read...), p(group+"devicecommissioningplans", read...), p(group+"devicecommissioningplanapprovals", read...)), "fleet.datumapis.com-capacity-projector": slices.Concat(p("metal.datumapis.com/machinecapacities", "get", "list", "watch", "updateStatus"), p(group+"devices", read...), p(group+"devicecustodies", read...), p(group+"devicecommissionings", read...), p(group+"devicecommissioningplans", read...), p(group+"devicecommissioningplanapprovals", read...)), - "fleet.datumapis.com-device-wipe-requester": slices.Concat(p(group+"devicewipes", "create", "get", "list", "watch"), p(group+"devicecustodies", read...), p("ipam.miloapis.com/ipclaims", "create", "get", "list", "delete")), + "fleet.datumapis.com-device-wipe-requester": slices.Concat(p(group+"devicewipes", "create", "get", "list", "watch"), p(group+"devicecustodies", read...)), } - coordinator := slices.Concat(p(group+"devicecustodies", "get", "list", "watch", "create", "update", "delete"), p(group+"devices", read...), p("metal.datumapis.com/machineallocations", read...), p("metal.datumapis.com/machinecapacities", read...), p("ipam.miloapis.com/ipclaims", "get")) + coordinator := slices.Concat(p(group+"devicecustodies", "get", "list", "watch", "create", "update", "delete"), p(group+"devices", read...), p("metal.datumapis.com/machineallocations", read...), p("metal.datumapis.com/machinecapacities", read...)) for _, plural := range []string{"deviceinstallations", "devicewipes", "devicerecoveries", "devicecommissionings"} { coordinator = slices.Concat(coordinator, p(group+plural, "get", "list", "watch", "delete", "updateStatus"), []string{group + plural + "/status.update"}) } @@ -457,3 +452,53 @@ func boundToBoth(roles []role, bindings []policyBinding) string { } return "" } + +// TestBootAddressRolesAreOptIn keeps every IPAM permission out of the +// device operations roles, which every environment applies, and in the +// boot address roles, which no overlay includes. An environment grants +// them only when it enables boot addresses. +func TestBootAddressRolesAreOptIn(t *testing.T) { + root := filepath.Join(configRoot, "components", "boot-addresses") + claims := func(verbs ...string) []string { + var out []string + for _, verb := range verbs { + out = append(out, "ipam.miloapis.com/ipclaims."+verb) + } + return out + } + want := map[string][]string{ + "fleet.datumapis.com-boot-address-requester": claims("create", "delete", "get", "list"), + "fleet.datumapis.com-boot-address-checker": claims("get"), + } + roles := decodeDir[role](t, root) + if len(roles) != len(want) { + t.Fatalf("boot address roles = %d, want %d", len(roles), len(want)) + } + for _, r := range roles { + actual := slices.Clone(r.Spec.Included) + slices.Sort(actual) + if !slices.Equal(actual, want[r.Metadata.Name]) || len(r.Spec.Inherited) != 0 { + t.Fatalf("%s = %v, want %v", r.Metadata.Name, actual, want[r.Metadata.Name]) + } + } + for _, r := range decodeDir[role](t, filepath.Join(componentRoot, "roles")) { + for _, permission := range r.Spec.Included { + if strings.HasPrefix(permission, "ipam.miloapis.com/") { + t.Fatalf("%s grants %s, which only the boot address roles may", r.Metadata.Name, permission) + } + } + } + err := filepath.WalkDir(configRoot, func(path string, entry fs.DirEntry, err error) error { + if err != nil || entry.IsDir() || entry.Name() != "kustomization.yaml" || filepath.Dir(path) == root { + return err + } + data, err := os.ReadFile(path) + if err == nil && bytes.Contains(data, []byte("boot-addresses")) { + t.Errorf("%s includes the boot address roles", path) + } + return err + }) + if err != nil { + t.Fatal(err) + } +} From 1328d7e39dd337f300c54d986a3e24b840c912f8 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 19:27:14 -0600 Subject: [PATCH 9/9] fix(custody): Leave a wipe's boot interface optional in its schema DeviceWipe gained a required bootInterface, so a wipe stored before it would fail validation on its next write, including the finalizer removal that retention needs. The schema now leaves it optional. Admission still refuses a wipe whose boot interface the Device does not record with a MAC address. Co-Authored-By: Claude Opus 5.5 --- .../device-operations/crds/fleet.datumapis.com.yaml | 4 +++- internal/api/operations/v1alpha1/types.go | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index 27dcbf03..9032ccc1 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -736,6 +736,9 @@ spec: minLength: 1 maxLength: 63 x-kubernetes-list-type: set + # Optional in the schema so wipes stored before it existed stay + # valid; admission refuses a wipe whose boot interface the + # Device does not record with a MAC address. bootInterface: type: string minLength: 1 @@ -769,7 +772,6 @@ spec: - step - cleaningPolicyDigest - targetDisks - - bootInterface x-kubernetes-validations: - rule: self == oldSelf message: an operation spec is immutable after create diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index 689c453b..f0796275 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -365,7 +365,9 @@ type DeviceWipeSpec struct { CleaningPolicyDigest string `json:"cleaningPolicyDigest"` TargetDisks []string `json:"targetDisks"` // BootInterface names the Device interface the wipe network-boots. - BootInterface string `json:"bootInterface"` + // Admission requires it; the schema leaves it optional so wipes stored + // before it existed stay valid. + BootInterface string `json:"bootInterface,omitempty"` BootNetwork *BootNetworkInput `json:"bootNetwork,omitempty"` }