diff --git a/config/base/crd/metal.datumapis.com.yaml b/config/base/crd/metal.datumapis.com.yaml index f4386862..6b544a20 100644 --- a/config/base/crd/metal.datumapis.com.yaml +++ b/config/base/crd/metal.datumapis.com.yaml @@ -458,6 +458,22 @@ spec: properties: name: {type: string, minLength: 1} step: {type: integer, format: int32, minimum: 1} + bootClaims: + type: array + maxItems: 64 + items: + type: object + required: [operationKind, operation, claim] + properties: + operationKind: {type: string, enum: [DeviceInstallation, DeviceWipe]} + operation: {type: string, minLength: 1, maxLength: 253} + claim: + type: object + required: [apiGroup, kind, name] + properties: + apiGroup: {type: string, minLength: 1, maxLength: 253} + kind: {type: string, minLength: 1, maxLength: 63} + name: {type: string, minLength: 1, maxLength: 253} conditions: type: array items: {type: object, x-kubernetes-preserve-unknown-fields: true} diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index 4158e12e..3947d9b6 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -521,11 +521,21 @@ spec: addressClaim: type: object properties: + apiGroup: + type: string + minLength: 1 + maxLength: 253 + kind: + type: string + minLength: 1 + maxLength: 63 name: type: string minLength: 1 maxLength: 253 required: + - apiGroup + - kind - name address: type: string @@ -749,11 +759,21 @@ spec: addressClaim: type: object properties: + apiGroup: + type: string + minLength: 1 + maxLength: 253 + kind: + type: string + minLength: 1 + maxLength: 63 name: type: string minLength: 1 maxLength: 253 required: + - apiGroup + - kind - name address: type: string diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index 439f15cb..e21498a5 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -46,24 +46,36 @@ 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 and -address into the operation's `spec.bootNetwork`. The spec holds no UID: +IPAM binds it when it is created. The requester copies a typed reference to +the claim, its API group, kind and name, and the address into the operation's +`spec.bootNetwork`. The spec holds no UID: ```yaml spec: bootInterface: primary bootNetwork: - addressClaim: {name: alloc-3b9d61c2-install-1-boot} + addressClaim: + apiGroup: ipam.miloapis.com + kind: IPClaim + 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, 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. +Admission picks its check by the claim's API group and kind. IPAM's `IPClaim` +is the only kind with a check by default. A claim of any other kind can never +be checked, so the operation fails at once with `UnsupportedBootAddressClaim`, +naming the kind, and is never retried. + +For an `IPClaim`, admission fails the operation with +`BootAddressClaimMismatch` unless that claim 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. Only a claim that cannot be read leaves the +operation `Pending` with `BootAddressUnavailable`; see [IPAM's claim +contract](#ipams-claim-contract). Admission refuses the operation 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: @@ -115,7 +127,152 @@ Fleet follows the contract IPAM implements, not only its documentation: the coordinator checks it again. This holds for every creator: a staff operation waits the same way and is cancelled only by staff expiry, so a brief IPAM outage fails no installation or wipe. A missing, rebound or - recreated claim fails the operation. + recreated claim fails the operation with `BootAddressClaimMismatch`. + +### The address source seam + +Each requester reaches its boot address through one source with five steps: +attach the boot NIC to the boot network, claim the address, release the +address, detach the boot NIC, and list an allocation's claims. The requester +attaches, waits until the boot NIC is on the boot network, then claims the +address and creates the operation. At release it releases the address, then +detaches the boot NIC, under the rules above, and a claim counts as gone only +when both are verified. IPAM's claimer is the default source. Its attach and +detach steps do nothing, because today's sites attach boot NICs to the +provisioning network themselves. + +Admission is the second seam: one check per claim kind. A new source brings a +new claim kind and its check. The coordinator must gain the check before any +requester uses the new source, or it fails the new kind's operations with +`UnsupportedBootAddressClaim`. + +Switching a requester to another source changes only where new claims go. +Each claim an operation already holds is released, listed and verified +through the source of its own claim kind: the configured source, the sources +it replaced, which stay configured as previous sources until no operation +names their kind, and IPAM's claimer, which always takes part as the default. +An IPAM claim made before the switch is still released only once IPAM's +claim is gone and no `IPAllocation` names it, and release does not finish +while it remains. Each source touches only its own kind's claims. A provider +API that does not serve IPAM's kinds, as its API reports when asked for +them, has no IPAM claims, so the default claimer has nothing to release +there. A failed or partial discovery is not that answer and keeps the +release open, and a source someone configured, current or previous, still +reports every error. + +### The NSO boot attachment source + +A second source attaches the boot NIC through NSO and takes the address from +NSO. It is off by default, and no deployment wires it on purpose: nothing +configures it, the coordinator has no check for its claim kind unless one is +registered, and the synchronized lab keeps IPAM's claimer. The check refuses +to be made for an admission reader that cannot read NSO's claims, which +would otherwise leave every operation `Pending`. The source is tested only +against NSO's real types with a test realizer that stands in for the NSO +behavior below. + +For each installation and wipe, the requester creates one NSO +`NetworkInterfaceClaim` named `-boot`, in the namespace Fleet +controls in the provider's NSO API, on a boot network the provider owns. The +claim uses the `Physical` attachment mode, names the boot NIC's MAC and the +switch and port from inventory's cable records, and carries the allocation, +operation and operation kind labels. The requester waits until NSO reports +the claim `Programmed`, then reads the claim's IPv4 address and copies a +reference to the claim, kind `networking.datumapis.com/NetworkInterfaceClaim`, +and the address into the operation. While NSO cannot be read or has not +programmed the port, no address is read and no operation is created. When +NSO reports that IPAM refused the address, such as a full pool, the requester +reports it as for an IPAM claim and creates no operation. A failure NSO does +not classify and retries itself, `AllocationFailed`, keeps the request +waiting with NSO's reason and message. + +Admission checks the claim with the same rules as an IPAM claim: the +operation's own name and labels, created no later than the operation, not +being deleted, `Programmed` on the boot network, and holding exactly the +address. An unreadable claim leaves the operation `Pending` with +`BootAddressUnavailable`; any other problem fails it with +`BootAddressClaimMismatch`. + +Release follows the same rules as for an IPAM claim, so a held operation +keeps its claim, and its port stays on the boot network, until the hold is +settled. The requester deletes the claim. The release counts only once a read +finds NSO's claim gone and IPAM holds no allocation for the address NSO +claimed for it. NSO may remove its claim before IPAM removes that address, so +the release is checked from the allocation's own record rather than from the +claims that remain. The record is only for a source whose address can outlive +its claim, such as NSO's. IPAM removes a claim and its address together, so +IPAM's claims are never recorded and are verified from the claims that +remain, as before. Before it creates an NSO boot claim, the requester records +the operation's kind and name and the claim's kind and name in the +allocation's status, and it removes the record only once the claim's release +is verified. Every release pass removes the entries it verified, including +the hand-over step, so entries do not wait for the final release. An entry +with neither a claim nor an operation, such as one whose attach failed before +any claim was made, is only read, never deleted: it is removed once its claim +is still absent and IPAM holds nothing for its address, and a claim its +requester has made by then is kept, with its entry. The record holds +at most 64 claims. When it is full, the next installation or wipe is refused +with `ErrBootClaimsFull` and makes no claim, until earlier entries are +verified released; no entry is ever dropped or overwritten first. The check +therefore still runs after the claim is gone, after custody retention +removed the operation, and for an operation that was never created. While +an allocation is active, a hand-over step +releases the claims of ended, unheld operations under the same rules, so NSO +can hand a shared boot NIC to the customer. + +A requester makes a boot attachment claim only for an operation custody can +admit next: while custody holds the Device for that allocation and runs no +other operation. A held operation runs nothing, so the operation that +settles it may attach. Otherwise the requester waits with `ErrBootNICBusy` +and claims nothing, so a queued reinstall or wipe never moves the port while +another operation owns the server. + +Fleet writes only claims and never a switch port. Fleet's own guarantees are +the order of release, which closes the `Network` gate after the customer's +claims are gone and before it creates the wipe and its boot attachment +claim, and keeping a held operation's claim until the hold is settled. That +a port is on the boot network only while a boot attachment claim names it, +that the customer's claims for it stay unprogrammed meanwhile, and that NSO +moves the port to the customer's networks in one step are assumption 4 +below, proven only against the test realizer. + +The allocator has a check that reports whether a boot attachment claim of +any known source holds a boot NIC that also carries the Machine's networks, +and the `NetworkReady=False` condition for it, with reason +`BootNetworkAttached`, or `RecoveryHold` while its operation is held. +Nothing calls it yet: the Machine's customer network attachment must call it +and the hand-over step once it lands. The tests stand in for that +attachment's claims. + +#### Assumed NSO contract + +The source relies on NSO behavior that NSO does not have yet. Tenant +isolation rests on assumptions 3 and 4: Fleet checks the network, mode, +labels, Device incarnation and cable record, but cannot isolate one +server's boot traffic from another's. Enabling the source needs NSO's +isolation proven first. Fleet keeps the +list in one place in its code: + +1. A `Physical` attachment mode for an interface with no node, container or + hypervisor. +2. The attachment point as claim annotations: + `networking.datumapis.com/attachment-mac`, + `networking.datumapis.com/attachment-switch` and + `networking.datumapis.com/attachment-port`. Customer claims for a physical + server carry them too. +3. A provider-owned boot network, addressed at each site from the + provisioning class, untagged on an attached port and isolated between + servers. +4. Port membership derived from claims, as above, with `Programmed` on a boot + attachment claim meaning its port is on the boot network. +5. The provisioning address as the claim's IPv4 interface address. +6. A `Physical` claim kept until its port left the claim's network, then its + addresses released. +7. NSO's IPAM claim for that address made under one of two names in the + project's IPAM namespace: `-f-ipv4`, or the same suffixed with + `-l` and eight hex digits of a hash of the location. This mirrors NSO's + code today, not a documented contract. NSO labels neither, so Fleet + checks both names. ## Enrollment @@ -441,6 +598,8 @@ exhaustion through IPAM. See [IPAM in the lab](redfish-lab.md#ipam-in-the-lab). | --- | --- | | Boot addresses claimed from IPAM per operation, checked at admission, and released only after the operation ended unheld | Implemented; tested against a real API server with a stand-in for IPAM's claim API. The synced Redfish lab claims from real IPAM, but no synced run has passed yet | | Boot NIC from Device inventory through the admission snapshot; enrollment without MACs or addresses | Implemented; unit tested | +| Boot address source seam and admission checks by claim kind | Implemented; tested against a real API server | +| NSO boot attachment source, off by default | Implemented against NSO's real types and an assumed contract; tested with a fake client and with a test realizer on a real API server. NSO does not implement the contract yet | | Reservation feed, authenticated applied reports, served and withdrawn gates over every reservation of the Device | Implemented; unit tested with a fake BMC and synchronizer | | Reports bound to feeds the feed served, and refreshed reports of an unchanged feed | Implemented; unit tested, including a forged issue time, another instance's feed, a feed restart and an instance that never fetched the reservation | | Expected DHCP instance set in the enrollment: the feed refuses other instances, withdrawal needs every expected instance's report of a feed issued after the admission, and retirement only by shrinking the set | Implemented; unit tested, including an instance that never reported and one that stopped after fetching the reservation. Restarting the workers and the feed after a change is an operator step | diff --git a/hack/multiplane/redfish_steps.py b/hack/multiplane/redfish_steps.py index 47949d57..6dfc472d 100644 --- a/hack/multiplane/redfish_steps.py +++ b/hack/multiplane/redfish_steps.py @@ -600,7 +600,10 @@ def provider(*args): network = o['spec'].get('bootNetwork') if not network: die('%s %s carries no boot address' % (o['kind'], o['metadata']['name'])) - if network['addressClaim']['name'] != o['metadata']['name'] + '-boot': + claim = network['addressClaim'] + if claim.get('apiGroup') != 'ipam.miloapis.com' or claim.get('kind') != 'IPClaim': + die('%s %s names a %s/%s boot address claim, not an IPAM IPClaim' % (o['kind'], o['metadata']['name'], claim.get('apiGroup'), claim.get('kind'))) + if claim['name'] != o['metadata']['name'] + '-boot': die('%s %s names a claim other than its own' % (o['kind'], o['metadata']['name'])) if not first <= tuple(int(x) for x in network['address'].split('.')) <= last: die('%s %s boot address %s is outside the lab IPAM range' % (o['kind'], o['metadata']['name'], network['address'])) diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go index b6a43c64..304bd612 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -21,8 +21,10 @@ import ( "strings" apierrors "k8s.io/apimachinery/pkg/api/errors" + apiMeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" @@ -50,8 +52,15 @@ var ( // ErrUnsupported means a request Fleet does not implement, such as a // bootstrap payload. ErrUnsupported = errors.New("unsupported request") + // ErrBootClaimsFull means the allocation's boot claim record is full: + // no new boot claim is made until earlier ones are verified released. + ErrBootClaimsFull = errors.New("the allocation's boot claims are not yet verified released, so no new boot claim is made") ) +// MaxBootClaims is how many boot claims an allocation's status records at +// once. It matches the CRD's limit on status.bootClaims. +const MaxBootClaims = 64 + // Machine names one Machine incarnation in one consumer incarnation. type Machine struct { // Consumer is the consumer's typed reference, as recorded in the @@ -143,11 +152,20 @@ 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 + // BootAddresses attaches each installation's and wipe's boot NIC and + // claims its provisioning address when the site's DHCP is synchronized. + // IPAM's bootaddress.Claimer is the default source. Each requester uses + // it with its own client. Nil means the site's DHCP is configured + // independently of Fleet. New claims go through it; claims an operation + // already holds are released through the source of their claim kind, so + // after a switch to another source IPAM's claims are still released by + // IPAM's verified release. + BootAddresses bootaddress.Source + // PreviousBootAddresses are sources the requesters used before + // BootAddresses. Their claims are still released, listed and checked + // through them, by claim kind, until no operation names their kind. + // IPAM's claimer always takes part as the default. + PreviousBootAddresses []bootaddress.Source } // Get returns the Machine's allocation, or nil. @@ -499,7 +517,7 @@ func (a *Allocator) Install(ctx context.Context, allocation *fleetv1.MachineAllo } else if !apierrors.IsNotFound(err) { return nil, err } - network, err := a.bootNetwork(ctx, a.installClaims(), allocation, operation.Name) + network, err := a.bootNetwork(ctx, a.installClaims(), allocation, "DeviceInstallation", operation.Name) if err != nil { return nil, err } @@ -507,33 +525,160 @@ func (a *Allocator) Install(ctx context.Context, allocation *fleetv1.MachineAllo return operation, a.createOnce(ctx, a.Provider, operation, &ops.DeviceInstallation{}) } -// installClaims and wipeClaims are each requester's boot address claimer, +// installClaims and wipeClaims are each requester's boot address source, // with the requester's own client. They are nil when the site's DHCP is not // synchronized. -func (a *Allocator) installClaims() *bootaddress.Claimer { +func (a *Allocator) installClaims() bootaddress.Source { return a.claims(a.Provider, "DeviceInstallation") } -func (a *Allocator) wipeClaims() *bootaddress.Claimer { +func (a *Allocator) wipeClaims() bootaddress.Source { return a.claims(a.Releaser, "DeviceWipe") } -func (a *Allocator) claims(api client.Client, kind string) *bootaddress.Claimer { +func (a *Allocator) claims(api client.Client, kind string) bootaddress.Source { + if a.BootAddresses == nil { + return nil + } + return a.BootAddresses.Requester(api, a.Namespace, kind) +} + +// knownSource is one source a requester's claims may belong to. Implicit is +// IPAM's default claimer when no one configured it: a provider API without +// IPAM's kinds has no IPAM claims for it to release. +type knownSource struct { + source bootaddress.Source + implicit bool +} + +// releaseSources returns, by claim kind, every source whose claims a +// requester may still hold: the configured source, the previous ones, and +// IPAM's claimer, which is the default and so holds the claims made before a +// switch. Each is the requester's own. It is empty when the site's DHCP is +// not synchronized. +func (a *Allocator) releaseSources(api client.Client, kind string) []knownSource { if a.BootAddresses == nil { return nil } - claimer := *a.BootAddresses - claimer.Client, claimer.Namespace, claimer.Kind = api, a.Namespace, kind - return &claimer + byKind := map[schema.GroupKind]knownSource{bootaddress.GVK.GroupKind(): {bootaddress.Claimer{}, true}} + for _, previous := range a.PreviousBootAddresses { + byKind[previous.ClaimKind()] = knownSource{previous, false} + } + byKind[a.BootAddresses.ClaimKind()] = knownSource{a.BootAddresses, false} + kinds := make([]schema.GroupKind, 0, len(byKind)) + for claimKind := range byKind { + kinds = append(kinds, claimKind) + } + sort.Slice(kinds, func(i, j int) bool { return kinds[i].String() < kinds[j].String() }) + sources := make([]knownSource, 0, len(kinds)) + for _, claimKind := range kinds { + known := byKind[claimKind] + sources = append(sources, knownSource{known.source.Requester(api, a.Namespace, kind), known.implicit}) + } + return sources +} + +// absentAPI reports whether an error means the API does not serve the kind. +// A failed or partial discovery is not absence: it may hide a real claim. +func absentAPI(err error) bool { + return apiMeta.IsNoMatchError(err) +} + +// recordBootClaim records, in the allocation's status, the boot claim the +// requester is about to make for an operation, so its release is verified +// from the record even after the claim and the operation are gone. Only a +// source whose address can outlive its claim needs the record; IPAM's +// claims are verified from the claims that remain, as before. +func (a *Allocator) recordBootClaim(ctx context.Context, allocation *fleetv1.MachineAllocation, source bootaddress.Source, kind, operation string) error { + if _, ok := source.(bootaddress.Lingering); !ok { + return nil + } + claimKind := source.ClaimKind() + record := fleetv1.BootClaimRecord{OperationKind: kind, Operation: operation, + Claim: fleetv1.TypedReference{APIGroup: claimKind.Group, Kind: claimKind.Kind, Name: bootaddress.ClaimName(operation)}} + if slices.Contains(allocation.Status.BootClaims, record) { + return nil + } + // A full record fails closed: no entry is ever dropped or overwritten + // before its release is verified. + if len(allocation.Status.BootClaims) >= MaxBootClaims { + return fmt.Errorf("%w: %d recorded", ErrBootClaimsFull, len(allocation.Status.BootClaims)) + } + allocation.Status.BootClaims = append(allocation.Status.BootClaims, record) + return a.Provider.Status().Update(ctx, allocation) +} + +// recordedBootClaims returns the operations of one kind whose recorded boot +// claim is of the claim kind. +func recordedBootClaims(allocation *fleetv1.MachineAllocation, kind string, claimKind schema.GroupKind) []string { + var operations []string + for _, record := range allocation.Status.BootClaims { + if record.OperationKind == kind && (schema.GroupKind{Group: record.Claim.APIGroup, Kind: record.Claim.Kind}) == claimKind { + operations = append(operations, record.Operation) + } + } + return operations } -// 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 { +// bootNetwork records the operation's boot claim in the allocation's status, +// attaches the operation's boot NIC, then claims its boot address, before +// the operation exists. No address is claimed until the boot NIC is on the +// boot network. It returns nil when the site's DHCP is not synchronized. +func (a *Allocator) bootNetwork(ctx context.Context, source bootaddress.Source, allocation *fleetv1.MachineAllocation, kind, operation string) (*ops.BootNetworkInput, error) { + if source == nil { return nil, nil } - return claimer.Claim(ctx, allocation.Name, operation) + if _, moves := source.(attaches); moves { + if err := a.mayAttach(ctx, allocation, kind, operation); err != nil { + return nil, err + } + } + if err := a.recordBootClaim(ctx, allocation, source, kind, operation); err != nil { + return nil, err + } + if err := source.Attach(ctx, allocation, operation); err != nil { + return nil, err + } + // A release pass may have found no claim and cleared the record while + // the claim was being made, so the record is written again from the + // stored allocation before any address is handed out. + if _, ok := source.(bootaddress.Lingering); ok { + stored := &fleetv1.MachineAllocation{} + if err := a.Provider.Get(ctx, client.ObjectKeyFromObject(allocation), stored); err != nil { + return nil, err + } + if err := a.recordBootClaim(ctx, stored, source, kind, operation); err != nil { + return nil, err + } + *allocation = *stored.DeepCopyObject().(*fleetv1.MachineAllocation) + } + return source.Claim(ctx, allocation.Name, operation) +} + +// ErrBootNICBusy means custody does not yet let this operation move the +// Device's boot NIC: another holder has the Device, or another operation is +// running on it. The requester tries again later. +var ErrBootNICBusy = errors.New("allocation: the boot NIC waits until custody can admit this operation") + +// mayAttach lets a source that moves the boot NIC move it only for an +// operation custody can admit next: while custody holds the Device for this +// allocation and runs no other operation. Otherwise the port could leave +// the customer's networks, or join the boot network, while another +// operation or holder owns the server. A held operation runs nothing, so +// the operation that settles it may attach. +func (a *Allocator) mayAttach(ctx context.Context, allocation *fleetv1.MachineAllocation, kind, operation string) error { + state := &ops.DeviceCustody{} + if err := a.Provider.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: allocation.Spec.DeviceRef.Name}, state); err != nil { + return err + } + holder := state.Spec.Holder + if holder.AllocationRef == nil || holder.AllocationRef.Name != allocation.Name || state.Labels[ops.LabelDeviceUID] != allocation.Labels[fleetv1.LabelDeviceUID] { + return fmt.Errorf("%w: custody does not hold the Device for allocation %s", ErrBootNICBusy, allocation.Name) + } + if active := state.Spec.ActiveOperation; active != nil && (active.Kind != kind || active.Name != operation) { + return fmt.Errorf("%w: %s %s is running", ErrBootNICBusy, active.Kind, active.Name) + } + return nil } func (a *Allocator) envelope(allocation *fleetv1.MachineAllocation, creator ops.Creator) ops.OperationEnvelope { diff --git a/internal/allocation/bootaddress_test.go b/internal/allocation/bootaddress_test.go index 0a6b4eb7..8b650742 100644 --- a/internal/allocation/bootaddress_test.go +++ b/internal/allocation/bootaddress_test.go @@ -21,6 +21,7 @@ import ( "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/site" "go.datum.net/fleet/internal/site/simwork" + networkingv1 "go.datum.net/network-services-operator/api/v1alpha" ) // ipam binds each IPAM claim as it is created, as IPAM's API does, and @@ -98,10 +99,11 @@ func (k syncedSite) Run(ctx context.Context, work *site.Work) (any, error) { } // 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. +// default: an allocator with no boot address source installs and releases +// with no boot network input, and never creates an IPAM claim or an NSO boot +// attachment claim. func TestTheDefaultAllocatorClaimsNoBootAddress(t *testing.T) { - e := startEnv(t) + e := startEnvWith(t, nsoCRDs(t)...) if e.allocator.BootAddresses != nil { t.Fatal("the test allocator has a boot address claimer") } @@ -142,6 +144,11 @@ func TestTheDefaultAllocatorClaimsNoBootAddress(t *testing.T) { 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) } + // Nor does it attach a boot NIC through NSO. + var attachments networkingv1.NetworkInterfaceClaimList + if err := e.admin.List(e.ctx, &attachments); err != nil || len(attachments.Items) != 0 { + t.Fatalf("NSO interface claims = %d, %v, want none", len(attachments.Items), err) + } } // TestBootAddressesFollowTheirOperations claims each installation's and @@ -243,7 +250,7 @@ func TestBootAddressesFollowTheirOperations(t *testing.T) { 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()} { + for _, claimer := range []bootaddress.Source{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) } diff --git a/internal/allocation/bootclaims_test.go b/internal/allocation/bootclaims_test.go new file mode 100644 index 00000000..52705bd0 --- /dev/null +++ b/internal/allocation/bootclaims_test.go @@ -0,0 +1,271 @@ +package allocation + +import ( + "context" + "errors" + "fmt" + "slices" + "sync" + "testing" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + networkingv1 "go.datum.net/network-services-operator/api/v1alpha" + + 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/custody" + "go.datum.net/fleet/internal/network/nso" +) + +// TestAFullBootClaimRecordRefusesTheNextClaim fills the allocation's boot +// claim record with NSO claims, the source that records. The next +// installation is refused with ErrBootClaimsFull, no claim is made for it, +// and every recorded entry is kept. +func TestAFullBootClaimRecordRefusesTheNextClaim(t *testing.T) { + e, _ := nsoEnv(t) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + for i := range MaxBootClaims { + operation := fmt.Sprintf("%s-install-held-%d", allocation.Name, i) + allocation.Status.BootClaims = append(allocation.Status.BootClaims, fleetv1.BootClaimRecord{ + OperationKind: "DeviceInstallation", Operation: operation, Claim: nso.BootReference(bootaddress.ClaimName(operation)), + }) + } + if err := e.admin.Status().Update(e.ctx, allocation); err != nil { + t.Fatal(err) + } + full := slices.Clone(allocation.Status.BootClaims) + + installation := e.installation(1, "debian-12", "") + if _, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: installation}); !errors.Is(err, ErrBootClaimsFull) { + t.Fatalf("install with a full record: %v", err) + } + name := custody.InstallationName(allocation.Name, string(installation.UID)) + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: e.allocator.Namespace, Name: bootaddress.ClaimName(name)}, &networkingv1.NetworkInterfaceClaim{}); !apierrors.IsNotFound(err) { + t.Fatalf("a boot claim was made with a full record: %v", err) + } + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: e.allocator.Namespace, Name: name}, &ops.DeviceInstallation{}); !apierrors.IsNotFound(err) { + t.Fatalf("an installation was created with a full record: %v", err) + } + stored := &fleetv1.MachineAllocation{} + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(allocation), stored); err != nil { + t.Fatal(err) + } + if !slices.Equal(stored.Status.BootClaims, full) { + t.Fatalf("the record changed: %d entries, want the %d unverified ones", len(stored.Status.BootClaims), len(full)) + } +} + +// noStatus fails every status write, as a crash before the write would. +type noStatus struct{ client.Client } + +func (c noStatus) Status() client.SubResourceWriter { return failingStatus{c.Client.Status()} } + +type failingStatus struct{ client.SubResourceWriter } + +func (failingStatus) Update(context.Context, client.Object, ...client.SubResourceUpdateOption) error { + return errors.New("the status write did not happen") +} + +// TestTheRecordIsWrittenBeforeTheClaim makes no boot claim when the record +// cannot be written, so a crash between the two never leaves a claim the +// record does not name. +func TestTheRecordIsWrittenBeforeTheClaim(t *testing.T) { + e, _ := nsoEnv(t) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + e.allocator.Provider = noStatus{e.admin} + installation := e.installation(1, "debian-12", "") + if _, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: installation}); err == nil { + t.Fatal("installed without recording its boot claim") + } + name := custody.InstallationName(allocation.Name, string(installation.UID)) + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: e.allocator.Namespace, Name: bootaddress.ClaimName(name)}, &networkingv1.NetworkInterfaceClaim{}); !apierrors.IsNotFound(err) { + t.Fatalf("a boot claim was made before its record: %v", err) + } +} + +// TestIPAMClaimsAreNotRecorded runs installations on one allocation through +// IPAM with the record already full of other entries. IPAM removes a claim +// and its address together, so its claims are never recorded, the record +// never refuses IPAM's work, and it is left as it was. +func TestIPAMClaimsAreNotRecorded(t *testing.T) { + e, _ := nsoEnv(t) + e.allocator.Provider = &ipam{Client: e.admin} + e.allocator.BootAddresses = bootaddress.Claimer{Class: "provisioning"} + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + for i := range MaxBootClaims { + operation := fmt.Sprintf("%s-install-other-%d", allocation.Name, i) + allocation.Status.BootClaims = append(allocation.Status.BootClaims, fleetv1.BootClaimRecord{ + OperationKind: "DeviceInstallation", Operation: operation, Claim: nso.BootReference(bootaddress.ClaimName(operation)), + }) + } + if err := e.admin.Status().Update(e.ctx, allocation); err != nil { + t.Fatal(err) + } + full := slices.Clone(allocation.Status.BootClaims) + previous := "" + for n, name := range []string{"debian-12", "debian-12-second", "debian-12-third"} { + request := Installation{Installation: e.installation(n+1, name, previous), Current: previous} + operation := e.installed(allocation, request) + if claim := operation.Spec.BootNetwork.AddressClaim; claim.Kind != bootaddress.GVK.Kind { + t.Fatalf("installation %d claimed %+v, want IPAM's", n, claim) + } + previous = name + } + stored := &fleetv1.MachineAllocation{} + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(allocation), stored); err != nil { + t.Fatal(err) + } + if !slices.Equal(stored.Status.BootClaims, full) { + t.Fatalf("IPAM installs changed the record: %d entries, want %d", len(stored.Status.BootClaims), len(full)) + } +} + +// TestARecordWithNoClaimIsCleared records an NSO boot claim whose attach +// fails before any claim is made, here because inventory has no cable for +// the boot NIC. With neither a claim nor an operation, the record is +// verified and cleared by the next release pass instead of keeping it open. +func TestARecordWithNoClaimIsCleared(t *testing.T) { + e, _ := nsoEnv(t) + if err := e.admin.Delete(e.ctx, &inventory.Cable{ObjectMeta: metav1.ObjectMeta{Name: "cable-example-1", Namespace: namespace}}); err != nil { + t.Fatal(err) + } + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + if _, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: e.installation(1, "debian-12", "")}); !errors.Is(err, nso.ErrAttachmentUnknown) { + t.Fatalf("install without a cable record: %v", err) + } + if len(allocation.Status.BootClaims) != 1 { + t.Fatalf("record = %+v, want the failed attach recorded", allocation.Status.BootClaims) + } + if none, err := e.allocator.HandOver(e.ctx, allocation); err != nil || !none || len(allocation.Status.BootClaims) != 0 { + t.Fatalf("hand over = none %v, %v, record %+v; want the empty record cleared", none, err, allocation.Status.BootClaims) + } +} + +// claimAfterList creates a requester's claim right after the first list of +// NSO claims returns, as a requester that recorded its claim and is still +// attaching would. +type claimAfterList struct { + client.Client + once *sync.Once + create func() +} + +func (c claimAfterList) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error { + err := c.Client.List(ctx, list, opts...) + if _, ok := list.(*networkingv1.NetworkInterfaceClaimList); ok && err == nil { + c.once.Do(c.create) + } + return err +} + +// TestARecordOnlyCheckNeverDeletesAClaimBeingMade records an NSO claim with +// no claim and no operation yet, then makes the claim right after the +// release pass listed claims. The check of a record with neither only +// reads: the claim is kept, and so is the record, and the pass is not done. +func TestARecordOnlyCheckNeverDeletesAClaimBeingMade(t *testing.T) { + e, _ := nsoEnv(t) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + name := allocation.Name + "-install-attaching" + source := e.allocator.installClaims() + if err := e.allocator.recordBootClaim(e.ctx, allocation, source, "DeviceInstallation", name); err != nil { + t.Fatal(err) + } + healthy := e.allocator.Provider + e.allocator.Provider = claimAfterList{Client: healthy, once: &sync.Once{}, create: func() { + if err := source.Attach(e.ctx, allocation, name); !errors.Is(err, bootaddress.ErrPending) { + t.Errorf("attach in the hook: %v", err) + } + }} + none, err := e.allocator.HandOver(e.ctx, allocation) + e.allocator.Provider = healthy + if err != nil || none { + t.Fatalf("hand over while the claim was being made: none=%v %v", none, err) + } + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: bootaddress.ClaimName(name)}, &networkingv1.NetworkInterfaceClaim{}); err != nil { + t.Fatalf("the claim being made was deleted: %v", err) + } + if len(allocation.Status.BootClaims) != 1 || allocation.Status.BootClaims[0].Operation != name { + t.Fatalf("record = %+v, want the entry kept", allocation.Status.BootClaims) + } +} + +// clearBeforeClaim clears the allocation's boot claim record right before +// the first NSO claim is created, as a release pass that found no claim yet +// would. +type clearBeforeClaim struct { + client.Client + once *sync.Once + clear func() +} + +func (c clearBeforeClaim) Create(ctx context.Context, object client.Object, opts ...client.CreateOption) error { + if _, ok := object.(*networkingv1.NetworkInterfaceClaim); ok { + c.once.Do(c.clear) + } + return c.Client.Create(ctx, object, opts...) +} + +// TestTheRecordIsRestoredBeforeTheAddress clears the record between the +// requester's first record and its claim's creation. The requester records +// the claim again once it is attached, before it reads the address, so an +// address is handed out only for a recorded claim. +func TestTheRecordIsRestoredBeforeTheAddress(t *testing.T) { + e, _ := nsoEnv(t) + r := newRealizer(e.admin) + go r.run(e.ctx) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + name := allocation.Name + "-install-raced" + healthy := e.allocator.Provider + e.allocator.Provider = clearBeforeClaim{Client: healthy, once: &sync.Once{}, clear: func() { + stored := &fleetv1.MachineAllocation{} + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(allocation), stored); err != nil { + t.Error(err) + return + } + stored.Status.BootClaims = nil + if err := e.admin.Status().Update(e.ctx, stored); err != nil { + t.Error(err) + } + }} + recorded := func() bool { + t.Helper() + stored := &fleetv1.MachineAllocation{} + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(allocation), stored); err != nil { + t.Fatal(err) + } + return slices.ContainsFunc(stored.Status.BootClaims, func(record fleetv1.BootClaimRecord) bool { return record.Operation == name }) + } + e.until("the boot address is handed out", func() bool { + input, err := e.allocator.bootNetwork(e.ctx, e.allocator.installClaims(), allocation, "DeviceInstallation", name) + if err != nil && !errors.Is(err, bootaddress.ErrPending) { + t.Fatal(err) + } + if input != nil && !recorded() { + t.Fatalf("an address was handed out for a claim the record does not name") + } + return input != nil + }) +} diff --git a/internal/allocation/bootnic.go b/internal/allocation/bootnic.go new file mode 100644 index 00000000..1944f836 --- /dev/null +++ b/internal/allocation/bootnic.go @@ -0,0 +1,97 @@ +package allocation + +import ( + "context" + "errors" + "fmt" + "slices" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/bootaddress" +) + +var ( + // ErrBootAttached means a boot attachment claim holds a boot NIC that + // also carries the Machine's networks, so the network owner keeps the + // port on the boot network and off the customer's networks. + ErrBootAttached = errors.New("the boot NIC is on the boot network for an installation or wipe") + // ErrBootAttachmentHeld means the claim holding the boot NIC belongs to + // an operation custody holds, so it stays until the hold is settled. + ErrBootAttachmentHeld = errors.New("the boot NIC stays on the boot network while its operation is held") +) + +// attaches is a boot address source that moves boot NICs onto the boot +// network itself. Only such a source takes a shared port off the customer's +// networks. +type attaches interface { + bootaddress.Source + AttachesBootNIC() +} + +// HandOver releases the boot claims of the allocation's ended, unheld +// operations while the allocation is active, under the same rules as +// release, so the network owner can move a shared boot NIC to the +// customer's networks. Fleet writes only claims; the network owner moves the +// port in one step once the boot attachment claim is gone. It reports +// whether no boot claim remains. +func (a *Allocator) HandOver(ctx context.Context, allocation *fleetv1.MachineAllocation) (bool, error) { + if allocation.Status.Phase != fleetv1.AllocationActive { + return false, ErrReleased + } + return a.releaseBootAddresses(ctx, allocation, false) +} + +// BootNIC reports whether a boot attachment claim of any known source holds +// the allocation's boot NIC while it is one of the Machine's interfaces, so a +// claim left by a source used before a switch still counts. It returns +// ErrBootAttached or ErrBootAttachmentHeld while one does, and nil +// otherwise, including for sources that do not attach boot NICs and for a +// dedicated boot NIC. Fleet's customer network attachment must call it. +func (a *Allocator) BootNIC(ctx context.Context, allocation *fleetv1.MachineAllocation, interfaces []string) error { + if a.BootAddresses == nil || !slices.Contains(interfaces, allocation.Spec.BootInterface) { + return nil + } + var holding error + var sources []bootaddress.Source + for _, known := range append(a.releaseSources(a.Provider, "DeviceInstallation"), a.releaseSources(a.Releaser, "DeviceWipe")...) { + if _, ok := known.source.(attaches); ok { + sources = append(sources, known.source) + } + } + for _, source := range sources { + operations, err := source.Operations(ctx, allocation.Name) + if err != nil { + return err + } + for _, operation := range operations { + held, err := a.held(ctx, allocation, operation) + if err != nil { + return err + } + if held { + return fmt.Errorf("%w: %s", ErrBootAttachmentHeld, operation) + } + holding = fmt.Errorf("%w: %s", ErrBootAttached, operation) + } + } + return holding +} + +// BootNICCondition is the Machine's NetworkReady condition while BootNIC +// reports a boot attachment, or nil when it reports none. +func BootNICCondition(machine *fleetv1.Machine, err error) *metav1.Condition { + condition := &metav1.Condition{Type: "NetworkReady", Status: metav1.ConditionFalse, ObservedGeneration: machine.Generation, LastTransitionTime: metav1.Now()} + switch { + case err == nil: + return nil + case errors.Is(err, ErrBootAttachmentHeld): + condition.Reason, condition.Message = "RecoveryHold", "An installation or wipe with an unknown outcome is held, so its boot NIC stays on the boot network until the hold is settled." + case errors.Is(err, ErrBootAttached): + condition.Reason, condition.Message = "BootNetworkAttached", "The boot NIC is on the boot network for an installation or wipe." + default: + condition.Status, condition.Reason, condition.Message = metav1.ConditionUnknown, "NetworkUnavailable", "The boot attachment could not be read." + } + return condition +} diff --git a/internal/allocation/harness_test.go b/internal/allocation/harness_test.go index b57de3a3..f560d347 100644 --- a/internal/allocation/harness_test.go +++ b/internal/allocation/harness_test.go @@ -13,6 +13,7 @@ import ( "github.com/go-logr/logr" corev1 "k8s.io/api/core/v1" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" @@ -20,6 +21,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/envtest" ctrllog "sigs.k8s.io/controller-runtime/pkg/log" + networkingv1 "go.datum.net/network-services-operator/api/v1alpha" + 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" @@ -64,7 +67,7 @@ type env struct { func scheme(t *testing.T) *runtime.Scheme { s := runtime.NewScheme() - for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, inventory.AddToScheme, fleetv1.AddToScheme, ops.AddToScheme} { + for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, inventory.AddToScheme, fleetv1.AddToScheme, ops.AddToScheme, networkingv1.AddToScheme} { if err := add(s); err != nil { t.Fatal(err) } @@ -73,6 +76,12 @@ func scheme(t *testing.T) *runtime.Scheme { } func startEnv(t *testing.T) *env { + t.Helper() + return startEnvWith(t) +} + +// startEnvWith starts the environment with extra CRDs, such as NSO's. +func startEnvWith(t *testing.T, crds ...*apiextensionsv1.CustomResourceDefinition) *env { t.Helper() if os.Getenv("KUBEBUILDER_ASSETS") == "" { t.Skip("KUBEBUILDER_ASSETS required") @@ -84,7 +93,7 @@ func startEnv(t *testing.T) *env { filepath.Join(root, "config", "components", "inventory", "crds"), filepath.Join(root, "config", "components", "device-operations", "crds"), filepath.Join(root, "internal", "bootaddress", "testdata"), - }, ErrorIfCRDPathMissing: true} + }, CRDs: crds, ErrorIfCRDPathMissing: true} config, err := environment.Start() if err != nil { t.Fatal(err) diff --git a/internal/allocation/nsoboot_test.go b/internal/allocation/nsoboot_test.go new file mode 100644 index 00000000..684708e5 --- /dev/null +++ b/internal/allocation/nsoboot_test.go @@ -0,0 +1,660 @@ +package allocation + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "sort" + "strings" + "sync" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + apiMeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/util/yaml" + "sigs.k8s.io/controller-runtime/pkg/client" + + networkingv1 "go.datum.net/network-services-operator/api/v1alpha" + + 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/network/nso" + "go.datum.net/fleet/internal/site/simwork" +) + +const ( + bootNetworkName = "boot" + ipamNamespace = "ipam-provider" + customerNetwork = "customer-a" + detachFinalizer = "networking.datumapis.com/physical-detach" + sharedPort = "switch-example-a/ethernet7" + siteLocation = "location-example-a" +) + +// nsoModule is the pinned NSO module. +const nsoModule = "go.datum.net/network-services-operator" + +// nsoModuleDir finds the NSO module pinned in Fleet's go.mod in the module +// cache, without running the go command. It skips the test when the module's +// sources are not in the cache. +func nsoModuleDir(t *testing.T) string { + t.Helper() + data, err := os.ReadFile(filepath.Join("..", "..", "go.mod")) + if err != nil { + t.Fatal(err) + } + version := "" + for _, line := range strings.Split(string(data), "\n") { + if fields := strings.Fields(strings.TrimPrefix(strings.TrimSpace(line), "require ")); len(fields) >= 2 && fields[0] == nsoModule { + version = fields[1] + } + } + cache := os.Getenv("GOMODCACHE") + if cache == "" { + gopath := os.Getenv("GOPATH") + if gopath == "" { + home, err := os.UserHomeDir() + if err != nil { + t.Skip("no module cache to find the NSO module") + } + gopath = filepath.Join(home, "go") + } + cache = filepath.Join(filepath.SplitList(gopath)[0], "pkg", "mod") + } + // The module path is lower case, so it needs no case escaping. + dir := filepath.Join(cache, filepath.FromSlash(nsoModule)+"@"+version) + if _, err := os.Stat(filepath.Join(dir, "config", "crd", "bases")); version == "" || err != nil { + t.Skipf("NSO module %s@%s is not in the module cache", nsoModule, version) + } + return dir +} + +// nsoCRDs loads NSO's Network, NetworkInterfaceClaim and NetworkInterface +// CRDs from the pinned module, with the assumed Physical attachment mode +// added. +func nsoCRDs(t *testing.T) []*apiextensionsv1.CustomResourceDefinition { + t.Helper() + dir := filepath.Join(nsoModuleDir(t), "config", "crd", "bases") + var crds []*apiextensionsv1.CustomResourceDefinition + for _, name := range []string{"networks", "networkinterfaceclaims", "networkinterfaces"} { + data, err := os.ReadFile(filepath.Join(dir, "networking.datumapis.com_"+name+".yaml")) + if err != nil { + t.Fatal(err) + } + crd := &apiextensionsv1.CustomResourceDefinition{} + if err := yaml.Unmarshal(data, crd); err != nil { + t.Fatal(err) + } + for _, version := range crd.Spec.Versions { + if spec, ok := version.Schema.OpenAPIV3Schema.Properties["spec"]; ok { + if mode, ok := spec.Properties["attachmentMode"]; ok { + mode.Enum = append(mode.Enum, apiextensionsv1.JSON{Raw: []byte(`"` + string(nso.PhysicalMode) + `"`)}) + spec.Properties["attachmentMode"] = mode + version.Schema.OpenAPIV3Schema.Properties["spec"] = spec + } + } + } + crds = append(crds, crd) + } + return crds +} + +// realizer stands in for NSO's physical realizer as Fleet assumes it (see +// nso/assumed.go). It derives each port's membership from the claims that +// name it: the boot network only while a live boot attachment claim names +// the port, otherwise the networks of the live claims that name it. Each +// change is one assignment, recorded in history. It reports what is lost +// before what is gained, keeps a deleting claim until its port left the +// claim's network, and holds one IPAM allocation per boot address. +type realizer struct { + api client.Client + mu sync.Mutex + ports map[string][]string + history map[string][][]string + next int +} + +func newRealizer(api client.Client) *realizer { + return &realizer{api: api, ports: map[string][]string{}, history: map[string][][]string{}} +} + +func (r *realizer) run(ctx context.Context) { + for { + select { + case <-ctx.Done(): + return + case <-time.After(10 * time.Millisecond): + } + _ = r.pass(ctx) + } +} + +func isBoot(claim *networkingv1.NetworkInterfaceClaim) bool { + return claim.Namespace == namespace && claim.Spec.Network.Name == bootNetworkName +} + +func portOf(claim *networkingv1.NetworkInterfaceClaim) string { + point := nso.AttachmentPointOf(claim) + if point.Switch == "" || point.Port == "" { + return "" + } + return point.Switch + "/" + point.Port +} + +func (r *realizer) membership(port string) []string { + r.mu.Lock() + defer r.mu.Unlock() + return slices.Clone(r.ports[port]) +} + +func (r *realizer) changes(port string) [][]string { + r.mu.Lock() + defer r.mu.Unlock() + return slices.Clone(r.history[port]) +} + +func (r *realizer) pass(ctx context.Context) error { + var claims networkingv1.NetworkInterfaceClaimList + if err := r.api.List(ctx, &claims); err != nil { + return err + } + boot, customer := map[string]bool{}, map[string][]string{} + for i := range claims.Items { + claim := &claims.Items[i] + port := portOf(claim) + if port == "" || claim.DeletionTimestamp != nil { + continue + } + if isBoot(claim) { + boot[port] = true + } else if !slices.Contains(customer[port], claim.Spec.Network.Name) { + customer[port] = append(customer[port], claim.Spec.Network.Name) + } + } + r.mu.Lock() + seen := map[string]bool{} + for port := range r.ports { + seen[port] = true + } + for port := range boot { + seen[port] = true + } + for port := range customer { + seen[port] = true + } + for port := range seen { + var want []string + switch { + case boot[port]: + want = []string{bootNetworkName} + default: + want = slices.Clone(customer[port]) + sort.Strings(want) + } + if current := r.ports[port]; !slices.Equal(current, want) { + r.ports[port] = want + r.history[port] = append(r.history[port], want) + } + } + r.mu.Unlock() + // Report losses before gains, so no reader sees a port on both. + for _, gains := range []bool{false, true} { + for i := range claims.Items { + if err := r.report(ctx, &claims.Items[i], gains); err != nil && !apierrors.IsNotFound(err) && !apierrors.IsConflict(err) { + return err + } + } + } + return nil +} + +// report updates one claim: on the first pass only claims that left their +// port's network, on the second the rest. +func (r *realizer) report(ctx context.Context, claim *networkingv1.NetworkInterfaceClaim, gains bool) error { + port := portOf(claim) + if port == "" { + return nil + } + on := slices.Contains(r.membership(port), claim.Spec.Network.Name) + if claim.DeletionTimestamp != nil { + if gains || on { + return nil + } + // Detached: release the boot address, then let the claim go. + if isBoot(claim) { + if err := r.dropAllocation(ctx, claim.Name); err != nil { + return err + } + } + claim.Finalizers = slices.DeleteFunc(claim.Finalizers, func(f string) bool { return f == detachFinalizer }) + return r.api.Update(ctx, claim) + } + if !slices.Contains(claim.Finalizers, detachFinalizer) { + claim.Finalizers = append(claim.Finalizers, detachFinalizer) + return r.api.Update(ctx, claim) + } + programmed := apiMeta.IsStatusConditionTrue(claim.Status.Conditions, networkingv1.NetworkInterfaceClaimProgrammed) + if gains != on || (programmed == on && len(claim.Status.Conditions) > 0) { + return nil + } + if isBoot(claim) && len(claim.Status.Addresses) == 0 { + r.mu.Lock() + r.next++ + address := fmt.Sprintf("198.51.100.%d", 50+r.next) + r.mu.Unlock() + allocation := &unstructured.Unstructured{} + allocation.SetGroupVersionKind(bootaddress.AllocationGVK) + allocation.SetNamespace(ipamNamespace) + allocation.SetName("alloc-" + strings.ReplaceAll(address, ".", "-")) + allocation.Object["spec"] = map[string]any{"claimRef": map[string]any{"name": nso.BootAddressIPClaim(claim.Name)}, "address": address} + if err := r.api.Create(ctx, allocation); err != nil && !apierrors.IsAlreadyExists(err) { + return err + } + claim.Status.Addresses = []networkingv1.NetworkInterfaceAddress{{Family: networkingv1.IPv4Protocol, Address: address + "/24", Gateway: "198.51.100.1", Primary: true}} + } + status := map[bool]metav1.ConditionStatus{true: metav1.ConditionTrue, false: metav1.ConditionFalse} + for kind, value := range map[string]bool{networkingv1.NetworkInterfaceClaimAllocated: true, networkingv1.NetworkInterfaceClaimPrepared: true, networkingv1.NetworkInterfaceClaimProgrammed: on} { + apiMeta.SetStatusCondition(&claim.Status.Conditions, metav1.Condition{Type: kind, Status: status[value], Reason: "TestRealizer", ObservedGeneration: claim.Generation}) + } + return r.api.Status().Update(ctx, claim) +} + +func (r *realizer) dropAllocation(ctx context.Context, claim string) error { + list := &unstructured.UnstructuredList{} + list.SetGroupVersionKind(bootaddress.AllocationGVK.GroupVersion().WithKind("IPAllocationList")) + if err := r.api.List(ctx, list, client.InNamespace(ipamNamespace)); err != nil { + return err + } + for i := range list.Items { + if name, _, _ := unstructured.NestedString(list.Items[i].Object, "spec", "claimRef", "name"); name == nso.BootAddressIPClaim(claim) { + if err := r.api.Delete(ctx, &list.Items[i]); err != nil && !apierrors.IsNotFound(err) { + return err + } + } + } + return nil +} + +// sampler reads every claim naming the shared port, as any reader of NSO +// would, and records a violation when a boot attachment and a customer +// attachment are both programmed on it. +type sampler struct { + mu sync.Mutex + violations []string + samples int +} + +func (s *sampler) run(ctx context.Context, api client.Client) { + for { + select { + case <-ctx.Done(): + return + case <-time.After(5 * time.Millisecond): + } + var claims networkingv1.NetworkInterfaceClaimList + if api.List(ctx, &claims) != nil { + continue + } + var boot, customer []string + for i := range claims.Items { + claim := &claims.Items[i] + if portOf(claim) != sharedPort || !apiMeta.IsStatusConditionTrue(claim.Status.Conditions, networkingv1.NetworkInterfaceClaimProgrammed) { + continue + } + if isBoot(claim) { + boot = append(boot, claim.Name) + } else { + customer = append(customer, claim.Name) + } + } + s.mu.Lock() + s.samples++ + if len(boot) > 0 && len(customer) > 0 { + s.violations = append(s.violations, fmt.Sprintf("boot %v and customer %v", boot, customer)) + } + s.mu.Unlock() + } +} + +// nsoEnv is the environment with NSO's CRDs, the NSO boot source, NSO's +// admission check, a cabled server, and synchronized sites. +func nsoEnv(t *testing.T) (*env, *inventory.Device) { + t.Helper() + e := startEnvWith(t, nsoCRDs(t)...) + e.create(&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: ipamNamespace}}) + e.runner.Kinds["DeviceInstallation"] = syncedSite{simwork.Installation{}} + e.runner.Kinds["DeviceWipe"] = syncedSite{simwork.Wipe{}} + check, err := nso.NewBootAttachmentCheck(e.admin.Scheme(), "", bootNetworkName) + if err != nil { + t.Fatal(err) + } + if err := e.loop.Coordinator.Registry.RegisterBootAddressClaim(nso.BootClaimGroup, nso.BootClaimKind, check.Verify); err != nil { + t.Fatal(err) + } + e.allocator.BootAddresses = nso.BootAttachments{Network: bootNetworkName, IPAM: e.admin, IPAMNamespace: ipamNamespace, Location: siteLocation} + device := e.server(1) + e.create(&inventory.Cable{ObjectMeta: metav1.ObjectMeta{Name: "cable-example-1", Namespace: namespace}, Spec: inventory.CableSpec{ + PhysicalMetadata: inventory.PhysicalMetadata{DisplayName: "Example"}, Medium: "Copper", + Lanes: []inventory.CableLane{{ID: "one", A: inventory.CableEndpoint{DeviceRef: &inventory.LocalReference{Name: device.Name}, ComponentID: "primary", Position: 1}, B: inventory.CableEndpoint{DeviceRef: &inventory.LocalReference{Name: "switch-example-a"}, ComponentID: "ethernet7", Position: 1}}}, + }}) + return e, device +} + +// nsoDown answers every NSO claim read and write as an outage. +type nsoDown struct{ client.Client } + +func (c nsoDown) Get(ctx context.Context, key client.ObjectKey, object client.Object, opts ...client.GetOption) error { + if _, ok := object.(*networkingv1.NetworkInterfaceClaim); ok { + return apierrors.NewServiceUnavailable("nso is down") + } + return c.Client.Get(ctx, key, object, opts...) +} + +func (c nsoDown) Create(ctx context.Context, object client.Object, opts ...client.CreateOption) error { + if _, ok := object.(*networkingv1.NetworkInterfaceClaim); ok { + return apierrors.NewServiceUnavailable("nso is down") + } + return c.Client.Create(ctx, object, opts...) +} + +// TestNSOBootWaitsForTheAttachment creates no installation and binds no +// address while NSO is unavailable or has not programmed the port, and +// creates it once NSO has. +func TestNSOBootWaitsForTheAttachment(t *testing.T) { + e, _ := nsoEnv(t) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + installations := func() int { + t.Helper() + var list ops.DeviceInstallationList + if err := e.admin.List(e.ctx, &list, client.InNamespace(namespace)); err != nil { + t.Fatal(err) + } + return len(list.Items) + } + request := Installation{Installation: e.installation(1, "debian-12", "")} + healthy := e.allocator.Provider + e.allocator.Provider = nsoDown{healthy} + if _, err := e.allocator.Install(e.ctx, allocation, request); err == nil || errors.Is(err, bootaddress.ErrPending) || installations() != 0 { + t.Fatalf("install while NSO is down: %v, %d installations", err, installations()) + } + e.allocator.Provider = healthy + // NSO is up, but its realizer has not programmed the port. + if _, err := e.allocator.Install(e.ctx, allocation, request); !errors.Is(err, bootaddress.ErrPending) || installations() != 0 { + t.Fatalf("install before the port is programmed: %v, %d installations", err, installations()) + } + r := newRealizer(e.admin) + go r.run(e.ctx) + var operation *ops.DeviceInstallation + e.until("the installation is created", func() bool { + operation, err = e.allocator.Install(e.ctx, allocation, request) + if err != nil && !errors.Is(err, bootaddress.ErrPending) { + t.Fatal(err) + } + return err == nil + }) + if operation.Spec.BootNetwork == nil || operation.Spec.BootNetwork.AddressClaim != nso.BootReference(bootaddress.ClaimName(operation.Name)) { + t.Fatalf("boot network = %+v", operation.Spec.BootNetwork) + } +} + +// custodyAs presents the Device's custody changed by set, as though another +// holder or operation had it. +type custodyAs struct { + client.Client + set func(*ops.DeviceCustody) +} + +func (c custodyAs) Get(ctx context.Context, key client.ObjectKey, object client.Object, opts ...client.GetOption) error { + if err := c.Client.Get(ctx, key, object, opts...); err != nil { + return err + } + if state, ok := object.(*ops.DeviceCustody); ok { + c.set(state) + } + return nil +} + +// TestNSOBootNICWaitsForCustody moves no boot NIC, and creates no boot +// attachment claim or installation, while another operation runs on the +// Device or custody holds it for another allocation. Once custody can admit +// the installation, the attachment is made. +func TestNSOBootNICWaitsForCustody(t *testing.T) { + e, _ := nsoEnv(t) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + claims := func() int { + t.Helper() + var list networkingv1.NetworkInterfaceClaimList + if err := e.admin.List(e.ctx, &list); err != nil { + t.Fatal(err) + } + return len(list.Items) + } + request := Installation{Installation: e.installation(1, "debian-12", "")} + healthy := e.allocator.Provider + for name, set := range map[string]func(*ops.DeviceCustody){ + "another operation is running": func(state *ops.DeviceCustody) { + state.Spec.ActiveOperation = &ops.ActiveOperation{OperationReference: ops.OperationReference{Kind: "DeviceWipe", Name: "alloc-other-wipe-1"}} + }, + "custody holds the Device for another allocation": func(state *ops.DeviceCustody) { + state.Spec.Holder.AllocationRef = &ops.LocalReference{Name: "alloc-other"} + }, + } { + e.allocator.Provider = custodyAs{healthy, set} + if _, err := e.allocator.Install(e.ctx, allocation, request); !errors.Is(err, ErrBootNICBusy) || claims() != 0 { + t.Fatalf("%s: %v, %d boot attachment claims", name, err, claims()) + } + } + e.allocator.Provider = healthy + if _, err := e.allocator.Install(e.ctx, allocation, request); !errors.Is(err, bootaddress.ErrPending) || claims() != 1 { + t.Fatalf("once custody can admit it: %v, %d boot attachment claims", err, claims()) + } +} + +// installed creates the installation once its boot NIC is attached and +// waits until it succeeds through NSO's admission check. +func (e *env) installed(allocation *fleetv1.MachineAllocation, request Installation) *ops.DeviceInstallation { + e.t.Helper() + var operation *ops.DeviceInstallation + e.until("the installation is created", func() bool { + var err error + operation, err = e.allocator.Install(e.ctx, allocation, request) + if err != nil && !errors.Is(err, bootaddress.ErrPending) { + e.t.Fatal(err) + } + return err == nil + }) + e.until("the installation succeeds", func() bool { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(operation), operation); err != nil { + e.t.Fatal(err) + } + if operation.Status.Phase.Ended() && operation.Status.Phase != ops.PhaseSucceeded { + e.t.Fatalf("installation ended %s %s: %s", operation.Status.Phase, operation.Status.Reason, operation.Status.Message) + } + return operation.Status.Phase == ops.PhaseSucceeded + }) + return operation +} + +// TestOneWriterPerPortThroughHandover runs a first install, the handover to +// the customer, a held reinstall, its handover, and the release's wipe on a +// boot NIC shared with a customer network. Fleet writes only claims. The +// port is never on the boot network and a customer network at once, each +// move is one step, the Machine is never NetworkReady while a boot +// attachment holds the port, a held operation keeps its claim, and the wipe's +// boot attachment is made only after the customer's claims are gone. +func TestOneWriterPerPortThroughHandover(t *testing.T) { + e, device := nsoEnv(t) + r := newRealizer(e.admin) + go r.run(e.ctx) + s := &sampler{} + go s.run(e.ctx, e.admin) + // The release controller's client records what the customer's claims and + // the release gates were when the wipe's boot attachment claim was made. + var wipeAttach []string + e.allocator.Releaser = recordingCreates{Client: e.admin, onClaim: func(claim *networkingv1.NetworkInterfaceClaim) { + var claims networkingv1.NetworkInterfaceClaimList + _ = e.admin.List(e.ctx, &claims, client.InNamespace("default")) + gates := e.custody(device.Name).Spec.Holder.OpenGates + wipeAttach = append(wipeAttach, fmt.Sprintf("customer claims %d, Network gate open %v", len(claims.Items), slices.Contains(gates, ops.GateNetwork))) + }} + owner := machine(1) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + m := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: owner.Name, Generation: 1}} + interfaces := []string{"primary"} + // networkReady is what the Machine reports: not ready while a boot + // attachment holds its boot NIC, otherwise ready once NSO programmed the + // customer's claim. + var ready []string + networkReady := func() *metav1.Condition { + t.Helper() + err := e.allocator.BootNIC(e.ctx, allocation, interfaces) + if condition := BootNICCondition(m, err); condition != nil { + return condition + } + var claims networkingv1.NetworkInterfaceClaimList + if err := e.admin.List(e.ctx, &claims, client.InNamespace("default")); err != nil { + t.Fatal(err) + } + for _, claim := range claims.Items { + if apiMeta.IsStatusConditionTrue(claim.Status.Conditions, networkingv1.NetworkInterfaceClaimProgrammed) { + ready = append(ready, fmt.Sprintf("membership %v", r.membership(sharedPort))) + return &metav1.Condition{Type: "NetworkReady", Status: metav1.ConditionTrue, Reason: "Programmed"} + } + } + return &metav1.Condition{Type: "NetworkReady", Status: metav1.ConditionFalse, Reason: "NetworkPending"} + } + handedOver := func(what string) { + t.Helper() + e.until(what, func() bool { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(allocation), allocation); err != nil { + t.Fatal(err) + } + if _, err := e.allocator.HandOver(e.ctx, allocation); err != nil { + t.Logf("hand over: %v", err) + } + return networkReady().Status == metav1.ConditionTrue + }) + } + + // First install on the shared boot NIC; the customer's claim, made + // while it runs as #198's attachment would, stays unprogrammed. + first := e.installed(allocation, Installation{Installation: e.installation(1, "debian-12", "")}) + customerClaim := &networkingv1.NetworkInterfaceClaim{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "fleet-customer-primary", Labels: map[string]string{bootaddress.AllocationLabel: allocation.Name}}, + Spec: networkingv1.NetworkInterfaceClaimSpec{Network: networkingv1.LocalNetworkRef{Name: customerNetwork}, InterfaceName: "primary", AttachmentMode: nso.PhysicalMode, IPFamilies: []networkingv1.IPFamily{networkingv1.IPv4Protocol}}} + nso.SetAttachmentPoint(customerClaim, nso.AttachmentPoint{MACAddress: "02:00:00:00:00:01", Switch: "switch-example-a", Port: "ethernet7"}) + e.create(customerClaim) + time.Sleep(200 * time.Millisecond) + if condition := networkReady(); condition.Status != metav1.ConditionFalse || condition.Reason != "BootNetworkAttached" { + t.Fatalf("NetworkReady while the install's boot attachment holds the port = %+v", condition) + } + handedOver("the port is handed to the customer after the first install") + + // A reinstall moves the port back to the boot network for the install. + second := e.installed(allocation, Installation{Installation: e.installation(2, "debian-12-second", "debian-12"), Current: "debian-12"}) + if condition := networkReady(); condition.Status != metav1.ConditionFalse { + t.Fatalf("NetworkReady during the reinstall = %+v", condition) + } + // Held: the claim stays, and so does the port, until the hold is settled. + state := e.custody(device.Name) + state.Spec.RecoveryHold = &ops.RecoveryHold{OperationReference: ops.OperationReference{Kind: "DeviceInstallation", Name: second.Name}, Fence: second.Status.Fence, Since: metav1.Now(), Reason: "Synthetic"} + if err := e.admin.Update(e.ctx, state); err != nil { + t.Fatal(err) + } + for i := 0; i < 5; i++ { + if _, err := e.allocator.HandOver(e.ctx, allocation); err != nil { + t.Fatal(err) + } + time.Sleep(50 * time.Millisecond) + } + if condition := networkReady(); condition.Status != metav1.ConditionFalse || condition.Reason != "RecoveryHold" { + t.Fatalf("NetworkReady while the reinstall is held = %+v", condition) + } + if names, err := e.allocator.installClaims().Operations(e.ctx, allocation.Name); err != nil || !slices.Contains(names, second.Name) { + t.Fatalf("a held operation's boot attachment was released: %v, %v", names, err) + } + state = e.custody(device.Name) + state.Spec.RecoveryHold = nil + if err := e.admin.Update(e.ctx, state); err != nil { + t.Fatal(err) + } + handedOver("the port is handed to the customer after the hold is settled") + + // Release: the customer's claims go first, as the Network gate requires, + // then the wipe attaches the port to the boot network. + if err := e.admin.Delete(e.ctx, customerClaim); err != nil { + t.Fatal(err) + } + e.until("the customer's claim is gone", func() bool { + return apierrors.IsNotFound(e.admin.Get(e.ctx, client.ObjectKeyFromObject(customerClaim), &networkingv1.NetworkInterfaceClaim{})) + }) + e.release(allocation, owner) + if allocation.Status.Wipe == nil { + t.Fatal("release did not wipe") + } + e.until("the wipe's boot attachment is gone", func() bool { return len(r.membership(sharedPort)) == 0 }) + + if len(wipeAttach) != 1 || wipeAttach[0] != "customer claims 0, Network gate open false" { + t.Fatalf("the wipe's boot attachment was made with %v", wipeAttach) + } + want := [][]string{{bootNetworkName}, {customerNetwork}, {bootNetworkName}, {customerNetwork}, nil, {bootNetworkName}, nil} + if got := r.changes(sharedPort); !slices.EqualFunc(got, want, slices.Equal[[]string]) { + t.Fatalf("port membership went %v, want %v: each move one step", got, want) + } + s.mu.Lock() + defer s.mu.Unlock() + if len(s.violations) != 0 || s.samples < 100 { + t.Fatalf("%d of %d samples had both on the port: %v", len(s.violations), s.samples, s.violations) + } + for _, sample := range ready { + if sample != "membership ["+customerNetwork+"]" { + t.Fatalf("NetworkReady was reported with %s", sample) + } + } + for _, operation := range []string{first.Name, second.Name, allocation.Status.Wipe.Name} { + if !strings.HasPrefix(operation, allocation.Name) { + t.Fatalf("operation %s is not the allocation's", operation) + } + } + if allocation.Status.Phase != fleetv1.AllocationReleased { + t.Fatalf("phase = %s", allocation.Status.Phase) + } + var left networkingv1.NetworkInterfaceClaimList + if err := e.admin.List(e.ctx, &left); err != nil || len(left.Items) != 0 { + t.Fatalf("claims left after release: %d, %v", len(left.Items), err) + } + if gone, err := bootaddress.Unallocated(e.ctx, e.admin, ipamNamespace, nso.BootAddressIPClaim(bootaddress.ClaimName(allocation.Status.Wipe.Name))); err != nil || !gone { + t.Fatalf("the wipe's address is still allocated: %v", err) + } +} + +// recordingCreates calls onClaim before each NSO claim it creates. +type recordingCreates struct { + client.Client + onClaim func(*networkingv1.NetworkInterfaceClaim) +} + +func (c recordingCreates) Create(ctx context.Context, object client.Object, opts ...client.CreateOption) error { + if claim, ok := object.(*networkingv1.NetworkInterfaceClaim); ok { + c.onClaim(claim) + } + return c.Client.Create(ctx, object, opts...) +} diff --git a/internal/allocation/release.go b/internal/allocation/release.go index def00d7a..f7f78c6c 100644 --- a/internal/allocation/release.go +++ b/internal/allocation/release.go @@ -97,9 +97,14 @@ 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 +// releaseBootAddresses releases the boot addresses, then detaches the boot +// NICs, of the allocation's ended operations, each with its requester's +// client and through the source of its claim's kind, and reports whether +// none remain of any kind. An operation's claims count as gone only once +// both are verified. The operations come from the claims that remain and +// from the allocation's record of the claims it made, so a release is +// verified again after its claim, or its operation, is gone; a record is +// removed only once its release is verified. A held operation keeps its claim, because a silent DHCP // instance may still serve its address, and so does an operation not yet // 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 @@ -109,48 +114,114 @@ func (a *Allocator) Release(ctx context.Context, allocation *fleetv1.MachineAllo // 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 - 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 { + var verified []fleetv1.BootClaimRecord + type requester struct { + claimer bootaddress.Source + implicit bool + api client.Client + kind string + new func() ops.Operation + } + var pairs []requester + for _, known := range a.releaseSources(a.Provider, "DeviceInstallation") { + pairs = append(pairs, requester{known.source, known.implicit, a.Provider, "DeviceInstallation", func() ops.Operation { return &ops.DeviceInstallation{} }}) + } + for _, known := range a.releaseSources(a.Releaser, "DeviceWipe") { + pairs = append(pairs, requester{known.source, known.implicit, a.Releaser, "DeviceWipe", func() ops.Operation { return &ops.DeviceWipe{} }}) + } + for _, pair := range pairs { + operations, err := pair.claimer.Operations(ctx, allocation.Name) + if pair.implicit && absentAPI(err) { + // No IPAM API, so no IPAM claim to release. continue } - operations, err := pair.claimer.Operations(ctx, allocation.Name) if err != nil { return false, err } + surviving := slices.Clone(operations) + for _, name := range recordedBootClaims(allocation, pair.kind, pair.claimer.ClaimKind()) { + if !slices.Contains(operations, name) { + operations = append(operations, name) + } + } for _, name := range operations { + recordOnly := false if !all { operation := pair.new() - if err := pair.api.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: name}, operation); apierrors.IsNotFound(err) { + err := pair.api.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: name}, operation) + switch { + case apierrors.IsNotFound(err) && slices.Contains(surviving, name): + // A claim whose operation does not exist yet stays: its + // requester may still create the operation. none = false continue - } else if err != nil { + case apierrors.IsNotFound(err): + // A record with neither a claim nor an operation, such as + // one whose attach failed before any claim was made, is + // verified now and cleared once verified. Its requester + // may be creating the claim, so this only reads. + recordOnly = true + case err != nil: return false, err + default: + if !operation.OperationStatus().Phase.Ended() { + none = false + continue + } + held, err := a.held(ctx, allocation, name) + if err != nil { + return false, err + } + if held { + none = false + continue + } } - if !operation.OperationStatus().Phase.Ended() { + } + claimKind := pair.claimer.ClaimKind() + record := fleetv1.BootClaimRecord{OperationKind: pair.kind, Operation: name, + Claim: fleetv1.TypedReference{APIGroup: claimKind.Group, Kind: claimKind.Kind, Name: bootaddress.ClaimName(name)}} + if recordOnly { + lingering, ok := pair.claimer.(bootaddress.Lingering) + if !ok { none = false continue } - held, err := a.held(ctx, allocation, name) + released, err := lingering.Released(ctx, name) if err != nil { return false, err } - if held { + if !released { none = false continue } + verified = append(verified, record) + continue } - gone, err := pair.claimer.Release(ctx, name) + released, err := pair.claimer.Release(ctx, name) if err != nil { return false, err } - none = none && gone + if !released { + none = false + continue + } + detached, err := pair.claimer.Detach(ctx, name) + if err != nil { + return false, err + } + none = none && detached + if detached { + verified = append(verified, record) + } + } + } + if kept := slices.DeleteFunc(slices.Clone(allocation.Status.BootClaims), func(record fleetv1.BootClaimRecord) bool { + return slices.Contains(verified, record) + }); len(kept) != len(allocation.Status.BootClaims) { + allocation.Status.BootClaims = kept + if err := a.Provider.Status().Update(ctx, allocation); err != nil { + return false, err } } return none, nil @@ -271,7 +342,7 @@ func (a *Allocator) wipe(ctx context.Context, allocation *fleetv1.MachineAllocat } else if !apierrors.IsNotFound(err) { return err } - network, err := a.bootNetwork(ctx, a.wipeClaims(), allocation, reference.Name) + network, err := a.bootNetwork(ctx, a.wipeClaims(), allocation, "DeviceWipe", reference.Name) if err != nil { return err } diff --git a/internal/allocation/switch_test.go b/internal/allocation/switch_test.go new file mode 100644 index 00000000..ea8c74e0 --- /dev/null +++ b/internal/allocation/switch_test.go @@ -0,0 +1,88 @@ +package allocation + +import ( + "errors" + "slices" + "testing" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "sigs.k8s.io/controller-runtime/pkg/client" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + "go.datum.net/fleet/internal/bootaddress" +) + +// TestASwitchedSourceStillReleasesItsOldClaims installs through IPAM, then +// switches the allocator to NSO. The installation's IPAM claim is still +// released, by IPAM's verified release, and the release does not report +// done while IPAM holds the address. Each source lists and releases only its +// own claim kind. +func TestASwitchedSourceStillReleasesItsOldClaims(t *testing.T) { + e, _ := nsoEnv(t) + recorder := &ipam{Client: e.admin} + e.allocator.Provider = recorder + nsoSource := e.allocator.BootAddresses + e.allocator.BootAddresses = bootaddress.Claimer{Class: "provisioning"} + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + operation := e.installed(allocation, Installation{Installation: e.installation(1, "debian-12", "")}) + if claim := operation.Spec.BootNetwork.AddressClaim; claim != bootaddress.Reference(bootaddress.ClaimName(operation.Name)) { + t.Fatalf("claim = %+v, want IPAM's", claim) + } + // IPAM records the allocation for the claim. Its delete would remove it + // in the same transaction; the stand-in API does not, so the test does. + ipamAllocation := &unstructured.Unstructured{} + ipamAllocation.SetGroupVersionKind(bootaddress.AllocationGVK) + ipamAllocation.SetNamespace(namespace) + ipamAllocation.SetName("alloc-0123456789abcdef") + ipamAllocation.Object["spec"] = map[string]any{"claimRef": map[string]any{"name": bootaddress.ClaimName(operation.Name)}} + e.create(ipamAllocation) + + // The operator switches the allocator to NSO, and a later operation + // already holds an NSO claim. + e.allocator.BootAddresses = nsoSource + if err := e.allocator.installClaims().Attach(e.ctx, allocation, allocation.Name+"-install-next"); !errors.Is(err, bootaddress.ErrPending) { + t.Fatal(err) + } + ipamClaims := bootaddress.Claimer{}.Requester(e.admin, namespace, "DeviceInstallation") + nsoClaims := e.allocator.installClaims() + if names, err := ipamClaims.Operations(e.ctx, allocation.Name); err != nil || !slices.Equal(names, []string{operation.Name}) { + t.Fatalf("IPAM lists %v, %v; want only the IPAM claim", names, err) + } + if names, err := nsoClaims.Operations(e.ctx, allocation.Name); err != nil || !slices.Equal(names, []string{allocation.Name + "-install-next"}) { + t.Fatalf("NSO lists %v, %v; want only the NSO claim", names, err) + } + + // The IPAM claim is deleted, but IPAM still holds its address: not done. + none, err := e.allocator.HandOver(e.ctx, allocation) + if none || !errors.Is(err, bootaddress.ErrReleaseUnverified) { + t.Fatalf("hand over while IPAM holds the old address: none=%v %v", none, err) + } + claim := &unstructured.Unstructured{} + claim.SetGroupVersionKind(bootaddress.GVK) + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: bootaddress.ClaimName(operation.Name)}, claim); !apierrors.IsNotFound(err) { + t.Fatalf("the old IPAM claim was not deleted: %v", err) + } + if err := e.admin.Delete(e.ctx, ipamAllocation); err != nil { + t.Fatal(err) + } + // Verified: the IPAM claim is gone and no allocation names it. The NSO + // claim's operation was never created, so it stays, and IPAM never + // touched it. + if none, err := e.allocator.HandOver(e.ctx, allocation); err != nil || none { + t.Fatalf("hand over after IPAM released: none=%v %v, want the NSO claim kept", none, err) + } + if names, err := ipamClaims.Operations(e.ctx, allocation.Name); err != nil || len(names) != 0 { + t.Fatalf("IPAM claims left: %v, %v", names, err) + } + if names, err := nsoClaims.Operations(e.ctx, allocation.Name); err != nil || len(names) != 1 { + t.Fatalf("NSO claims = %v, %v; want the uncreated operation's kept", names, err) + } + var installations ops.DeviceInstallationList + if err := e.admin.List(e.ctx, &installations, client.InNamespace(namespace)); err != nil || len(installations.Items) != 1 { + t.Fatalf("installations = %d, %v", len(installations.Items), err) + } +} diff --git a/internal/allocation/verify_test.go b/internal/allocation/verify_test.go new file mode 100644 index 00000000..e7045df1 --- /dev/null +++ b/internal/allocation/verify_test.go @@ -0,0 +1,258 @@ +package allocation + +import ( + "context" + "errors" + "slices" + "testing" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + apiMeta "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/discovery" + "sigs.k8s.io/controller-runtime/pkg/client" + + networkingv1 "go.datum.net/network-services-operator/api/v1alpha" + + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/bootaddress" +) + +// TestAnNSOReleaseIsVerifiedAfterTheClaimIsGone installs through NSO, then +// NSO drops the boot attachment claim while IPAM still holds the address +// NSO claimed for it. The release is checked again from the allocator's own +// record of the operation, and does not finish until IPAM's allocation is +// gone. After a switch back to IPAM, a boot attachment claim NSO still holds +// keeps reporting that it holds the boot NIC. +func TestAnNSOReleaseIsVerifiedAfterTheClaimIsGone(t *testing.T) { + e, _ := nsoEnv(t) + r := newRealizer(e.admin) + ctx, stop := context.WithCancel(e.ctx) + go r.run(ctx) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + operation := e.installed(allocation, Installation{Installation: e.installation(1, "debian-12", "")}) + stop() + claimName := bootaddress.ClaimName(operation.Name) + var allocations unstructured.UnstructuredList + allocations.SetGroupVersionKind(bootaddress.AllocationGVK.GroupVersion().WithKind("IPAllocationList")) + if err := e.admin.List(e.ctx, &allocations, client.InNamespace(ipamNamespace)); err != nil || len(allocations.Items) != 1 { + t.Fatalf("IPAM allocations = %d, %v", len(allocations.Items), err) + } + // NSO's finalizer clears and the claim goes, but IPAM still holds the + // address. + claim := &networkingv1.NetworkInterfaceClaim{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: claimName}, claim); err != nil { + t.Fatal(err) + } + claim.Finalizers = nil + if err := e.admin.Update(e.ctx, claim); err != nil { + t.Fatal(err) + } + if err := e.admin.Delete(e.ctx, claim); err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + if none, err := e.allocator.HandOver(e.ctx, allocation); none || !errors.Is(err, bootaddress.ErrReleaseUnverified) { + t.Fatalf("hand over %d while IPAM holds the address of a claim NSO dropped: none=%v %v", i, none, err) + } + } + if err := e.admin.Delete(e.ctx, &allocations.Items[0]); err != nil { + t.Fatal(err) + } + if none, err := e.allocator.HandOver(e.ctx, allocation); err != nil || !none { + t.Fatalf("hand over once IPAM released: none=%v %v", none, err) + } + // The verified entry is pruned by hand-over, not left for the final + // release. + stored := &fleetv1.MachineAllocation{} + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(allocation), stored); err != nil || len(stored.Status.BootClaims) != 0 { + t.Fatalf("record after a verified hand-over = %+v, %v", stored.Status.BootClaims, err) + } + + // Switch back to IPAM while NSO still holds a boot attachment claim for + // a later operation: the claim still holds the boot NIC. + nsoSource := e.allocator.BootAddresses + if err := e.allocator.installClaims().Attach(e.ctx, allocation, allocation.Name+"-install-next"); !errors.Is(err, bootaddress.ErrPending) { + t.Fatal(err) + } + e.allocator.BootAddresses = bootaddress.Claimer{Class: "provisioning"} + e.allocator.PreviousBootAddresses = []bootaddress.Source{nsoSource} + if err := e.allocator.BootNIC(e.ctx, allocation, []string{"primary"}); !errors.Is(err, ErrBootAttached) { + t.Fatalf("BootNIC after switching back to IPAM = %v, want the NSO claim reported", err) + } +} + +// noIPAM is a provider API that does not serve IPAM's kinds. +type noIPAM struct{ client.Client } + +func (c noIPAM) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error { + if list.GetObjectKind().GroupVersionKind().Group == bootaddress.GVK.Group { + return &apiMeta.NoKindMatchError{GroupKind: schema.GroupKind{Group: bootaddress.GVK.Group, Kind: bootaddress.GVK.Kind}, SearchedVersions: []string{"v1alpha1"}} + } + return c.Client.List(ctx, list, opts...) +} + +// TestNSOReleaseNeedsNoIPAMAPI releases an NSO boot attachment on a provider +// API that does not serve IPAM's claims: IPAM's default claimer has nothing +// to release there. NSO's own IPAM is read through its own reader. +func TestNSOReleaseNeedsNoIPAMAPI(t *testing.T) { + e, _ := nsoEnv(t) + r := newRealizer(e.admin) + go r.run(e.ctx) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + operation := e.installed(allocation, Installation{Installation: e.installation(1, "debian-12", "")}) + e.allocator.Provider, e.allocator.Releaser = noIPAM{e.admin}, noIPAM{e.admin} + var last error + e.until("the NSO boot attachment is released", func() bool { + none, err := e.allocator.HandOver(e.ctx, allocation) + last = err + if apiMeta.IsNoMatchError(err) { + t.Fatalf("hand over without IPAM's API: %v", err) + } + return none && err == nil + }) + if names, err := e.allocator.installClaims().Operations(e.ctx, allocation.Name); err != nil || slices.Contains(names, operation.Name) || last != nil { + t.Fatalf("NSO claims = %v, %v, %v", names, err, last) + } + + // A failed discovery is not an absent API: it may hide a real IPAM claim. + e.allocator.Provider, e.allocator.Releaser = discoveryDown{e.admin}, discoveryDown{e.admin} + if none, err := e.allocator.HandOver(e.ctx, allocation); none || !discovery.IsGroupDiscoveryFailedError(err) { + t.Fatalf("hand over while discovery failed: none=%v %v", none, err) + } + // A source someone configured, here IPAM's claimer as a previous source, + // still reports that its API is absent. + e.allocator.Provider, e.allocator.Releaser = noIPAM{e.admin}, noIPAM{e.admin} + e.allocator.PreviousBootAddresses = []bootaddress.Source{bootaddress.Claimer{}} + if none, err := e.allocator.HandOver(e.ctx, allocation); none || !apiMeta.IsNoMatchError(err) { + t.Fatalf("hand over with a configured source's API absent: none=%v %v", none, err) + } +} + +// discoveryDown fails discovery for IPAM's group. +type discoveryDown struct{ client.Client } + +func (c discoveryDown) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error { + if gvk := list.GetObjectKind().GroupVersionKind(); gvk.Group == bootaddress.GVK.Group { + return &discovery.ErrGroupDiscoveryFailed{Groups: map[schema.GroupVersion]error{gvk.GroupVersion(): errors.New("the server is currently unable to handle the request")}} + } + return c.Client.List(ctx, list, opts...) +} + +// dropBootClaim is NSO removing a boot attachment claim while IPAM still +// holds the address it claimed for it. +func (e *env) dropBootClaim(operation string) { + e.t.Helper() + claim := &networkingv1.NetworkInterfaceClaim{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: bootaddress.ClaimName(operation)}, claim); err != nil { + e.t.Fatal(err) + } + claim.Finalizers = nil + if err := e.admin.Update(e.ctx, claim); err != nil { + e.t.Fatal(err) + } + if err := e.admin.Delete(e.ctx, claim); err != nil { + e.t.Fatal(err) + } +} + +// ipamAllocations lists IPAM's allocations in NSO's IPAM namespace. +func (e *env) ipamAllocations() []unstructured.Unstructured { + e.t.Helper() + var list unstructured.UnstructuredList + list.SetGroupVersionKind(bootaddress.AllocationGVK.GroupVersion().WithKind("IPAllocationList")) + if err := e.admin.List(e.ctx, &list, client.InNamespace(ipamNamespace)); err != nil { + e.t.Fatal(err) + } + return list.Items +} + +// TestARetainedAwayOperationsReleaseIsStillVerified removes an ended +// operation, as custody retention does, after NSO dropped its claim and +// while IPAM still holds the address. The allocation's record of the claim +// keeps the release open until IPAM's allocation is gone. +func TestARetainedAwayOperationsReleaseIsStillVerified(t *testing.T) { + e, _ := nsoEnv(t) + r := newRealizer(e.admin) + ctx, stop := context.WithCancel(e.ctx) + go r.run(ctx) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + operation := e.installed(allocation, Installation{Installation: e.installation(1, "debian-12", "")}) + stop() + held := e.ipamAllocations() + if len(held) != 1 || len(allocation.Status.BootClaims) != 1 { + t.Fatalf("IPAM allocations %d, recorded claims %+v", len(held), allocation.Status.BootClaims) + } + e.dropBootClaim(operation.Name) + operation.Finalizers = nil + if err := e.admin.Update(e.ctx, operation); err != nil && !apierrors.IsNotFound(err) { + t.Fatal(err) + } + if err := e.admin.Delete(e.ctx, operation); err != nil { + t.Fatal(err) + } + e.until("retention removed the installation", func() bool { + return apierrors.IsNotFound(e.admin.Get(e.ctx, client.ObjectKeyFromObject(operation), &ops.DeviceInstallation{})) + }) + if none, _ := e.allocator.releaseBootAddresses(e.ctx, allocation, false); none { + t.Fatal("hand over finished while IPAM holds the address of a removed operation's claim") + } + if none, err := e.allocator.releaseBootAddresses(e.ctx, allocation, true); none || !errors.Is(err, bootaddress.ErrReleaseUnverified) { + t.Fatalf("release while IPAM holds the address: none=%v %v", none, err) + } + if err := e.admin.Delete(e.ctx, &held[0]); err != nil { + t.Fatal(err) + } + if none, err := e.allocator.releaseBootAddresses(e.ctx, allocation, true); err != nil || !none || len(allocation.Status.BootClaims) != 0 { + t.Fatalf("release once IPAM released: none=%v %v, record %+v", none, err, allocation.Status.BootClaims) + } +} + +// TestANeverCreatedOperationsReleaseIsStillVerified attaches and claims an +// address for an operation that is never created, then NSO drops the claim +// while IPAM still holds the address. Release does not finish until IPAM's +// allocation is gone. +func TestANeverCreatedOperationsReleaseIsStillVerified(t *testing.T) { + e, _ := nsoEnv(t) + r := newRealizer(e.admin) + ctx, stop := context.WithCancel(e.ctx) + go r.run(ctx) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + name := allocation.Name + "-install-never" + e.until("the boot address is claimed", func() bool { + input, err := e.allocator.bootNetwork(e.ctx, e.allocator.installClaims(), allocation, "DeviceInstallation", name) + if err != nil && !errors.Is(err, bootaddress.ErrPending) { + t.Fatal(err) + } + return input != nil + }) + stop() + held := e.ipamAllocations() + if len(held) != 1 { + t.Fatalf("IPAM allocations = %d", len(held)) + } + e.dropBootClaim(name) + if none, err := e.allocator.releaseBootAddresses(e.ctx, allocation, true); none || !errors.Is(err, bootaddress.ErrReleaseUnverified) { + t.Fatalf("release while IPAM holds a never-created operation's address: none=%v %v", none, err) + } + if err := e.admin.Delete(e.ctx, &held[0]); err != nil { + t.Fatal(err) + } + if none, err := e.allocator.releaseBootAddresses(e.ctx, allocation, true); err != nil || !none || len(allocation.Status.BootClaims) != 0 { + t.Fatalf("release once IPAM released: none=%v %v, record %+v", none, err, allocation.Status.BootClaims) + } +} diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index 5cc5c6ff..62ebff54 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -17,6 +17,8 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" + + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" ) var GroupVersion = schema.GroupVersion{Group: "fleet.datumapis.com", Version: "v1alpha1"} @@ -309,16 +311,17 @@ type DeviceInstallationSpec struct { 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. +// BootNetworkInput is the provisioning address the boot address source +// 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 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"` + // AddressClaim is the operation's own address claim, by API group, kind + // and its only name. Admission picks its check by the group and kind. + // The claim's incarnation is pinned by that name, its labels, and its + // creation no later than the operation's; no UID is held in spec. + AddressClaim fleetv1.TypedReference `json:"addressClaim"` // Address is the bound host address, without a prefix length. Address string `json:"address"` } diff --git a/internal/api/v1alpha1/types.go b/internal/api/v1alpha1/types.go index ac4bc000..f353be18 100644 --- a/internal/api/v1alpha1/types.go +++ b/internal/api/v1alpha1/types.go @@ -437,10 +437,23 @@ const ( type MachineAllocationStatus struct { Phase string `json:"phase,omitempty"` // Wipe is the latest DeviceWipe the release created. - Wipe *WipeReference `json:"wipe,omitempty"` + Wipe *WipeReference `json:"wipe,omitempty"` + // BootClaims are the boot claims the allocator made for its + // operations, each recorded before the claim is created and removed + // only once its release is verified. + BootClaims []BootClaimRecord `json:"bootClaims,omitempty"` Conditions []metav1.Condition `json:"conditions,omitempty"` } +// BootClaimRecord is one boot claim an allocation's requester made for an +// operation, by the operation's kind and name and the claim's typed +// reference. +type BootClaimRecord struct { + OperationKind string `json:"operationKind"` + Operation string `json:"operation"` + Claim TypedReference `json:"claim"` +} + // WipeReference names a release's DeviceWipe and its step. type WipeReference struct { Name string `json:"name"` diff --git a/internal/bootaddress/bootaddress.go b/internal/bootaddress/bootaddress.go index c8925637..95d76314 100644 --- a/internal/bootaddress/bootaddress.go +++ b/internal/bootaddress/bootaddress.go @@ -1,6 +1,11 @@ // Package bootaddress claims a provisioning address from IPAM for one // network-booting operation, and checks a claimed address at admission. // +// Source is the seam a requester uses for an operation's boot attachment and +// address. Claimer, IPAM's implementation, is the default: today's sites +// attach boot NICs to the provisioning network statically, so its attach and +// detach steps do nothing. +// // 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 @@ -30,6 +35,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" ) // GVK is IPAM's address claim. @@ -114,6 +120,59 @@ func claimExists(err error) bool { // ClaimName is the only name an operation's boot address claim may have. func ClaimName(operation string) string { return operation + "-boot" } +// Reference is the typed reference an operation carries to its IPAM claim. +func Reference(name string) fleetv1.TypedReference { + return fleetv1.TypedReference{APIGroup: GVK.Group, Kind: GVK.Kind, Name: name} +} + +// Source attaches an operation's boot NIC to the boot network and claims its +// provisioning address, for one requester and one operation kind. The +// requester calls Attach, then Claim, then creates the operation with the +// claimed input. It releases with Release, then Detach, under the +// allocator's rules for ended and held operations; the release counts only +// once both report it verified. Every claim is named from the operation, so +// a requester that crashes and runs again finds it. +type Source interface { + // Requester returns the source for one requester: its own client, the + // operations' namespace, and the operation kind it creates. + Requester(api client.Client, namespace, kind string) Source + // Attach puts the operation's boot NIC on the boot network. It returns + // nil once the network owner reports the port there, ErrPending until + // then, and ErrExhausted or ErrRefused when the owner refused it. + Attach(ctx context.Context, allocation *fleetv1.MachineAllocation, operation string) error + // Claim returns the operation's bound boot address. It returns + // ErrPending until the address is bound, and ErrExhausted or ErrRefused + // when none can be. + Claim(ctx context.Context, allocation, operation string) (*ops.BootNetworkInput, error) + // Release returns true only once the operation's address is verified + // released. + Release(ctx context.Context, operation string) (bool, error) + // Detach returns true only once the operation's boot NIC is verified off + // the boot network. + Detach(ctx context.Context, operation string) (bool, error) + // Operations returns the operations of the source's kind in an + // allocation that still hold a claim. + Operations(ctx context.Context, allocation string) ([]string, error) + // ClaimKind is the API group and kind of the claims the source makes, + // as an operation's boot network input names them. + ClaimKind() schema.GroupKind +} + +var _ Source = Claimer{} + +// Lingering is a Source whose address can outlive its claim, so the +// allocator records each claim it makes and verifies its release from that +// record, even after the claim is gone. IPAM's claimer is not: IPAM removes +// a claim and its allocation in one transaction, so its surviving claims are +// the whole record. +type Lingering interface { + Source + AddressOutlivesClaim() + // Released reports, without deleting anything, whether the operation's + // claim is absent and its address no longer allocated. + Released(ctx context.Context, operation string) (bool, error) +} + // ScopeRef is one IPAM scope reference, such as the site's location. type ScopeRef struct { APIGroup string @@ -137,6 +196,24 @@ type Claimer struct { Scope map[string]ScopeRef } +// Requester returns the claimer with the requester's client, namespace and +// kind. +func (c Claimer) Requester(api client.Client, namespace, kind string) Source { + c.Client, c.Namespace, c.Kind = api, namespace, kind + return c +} + +// Attach does nothing: the site attaches boot NICs to its provisioning +// network itself. +func (c Claimer) Attach(context.Context, *fleetv1.MachineAllocation, string) error { return nil } + +// ClaimKind is IPAM's IPClaim. +func (Claimer) ClaimKind() schema.GroupKind { return GVK.GroupKind() } + +// Detach does nothing, and reports the boot NIC detached, for the same +// reason. +func (c Claimer) Detach(context.Context, string) (bool, error) { return true, nil } + func (c Claimer) desired(allocation, operation string) *unstructured.Unstructured { claim := &unstructured.Unstructured{} claim.SetGroupVersionKind(GVK) @@ -180,7 +257,7 @@ func (c Claimer) Claim(ctx context.Context, allocation, operation string) (*ops. if err != nil { return nil, err } - return &ops.BootNetworkInput{AddressClaim: ops.LocalReference{Name: claim.GetName()}, Address: address}, nil + return &ops.BootNetworkInput{AddressClaim: Reference(claim.GetName()), Address: address}, nil } // Release deletes the operation's claim. It returns true only once the @@ -194,7 +271,7 @@ func (c Claimer) Claim(ctx context.Context, allocation, operation string) (*ops. func (c Claimer) Release(ctx context.Context, operation string) (bool, error) { claim, err := c.get(ctx, ClaimName(operation)) if apierrors.IsNotFound(err) { - return c.unallocated(ctx, ClaimName(operation)) + return Unallocated(ctx, c.Client, c.Namespace, ClaimName(operation)) } if err != nil { return false, err @@ -208,14 +285,15 @@ func (c Claimer) Release(ctx context.Context, operation string) (bool, error) { if _, err := c.get(ctx, claim.GetName()); !apierrors.IsNotFound(err) { return false, err } - return c.unallocated(ctx, claim.GetName()) + return Unallocated(ctx, c.Client, c.Namespace, claim.GetName()) } -// unallocated reports whether no IPAM allocation names the claim. -func (c Claimer) unallocated(ctx context.Context, claim string) (bool, error) { +// Unallocated reports whether no IPAM allocation in the namespace names the +// IPAM claim. It returns ErrReleaseUnverified when one does. +func Unallocated(ctx context.Context, reader client.Reader, namespace, claim string) (bool, error) { list := &unstructured.UnstructuredList{} list.SetGroupVersionKind(AllocationGVK.GroupVersion().WithKind(AllocationGVK.Kind + "List")) - if err := c.Client.List(ctx, list, client.InNamespace(c.Namespace)); err != nil { + if err := reader.List(ctx, list, client.InNamespace(namespace)); err != nil { return false, err } for _, allocation := range list.Items { @@ -261,7 +339,7 @@ func Verify(ctx context.Context, reader client.Reader, operation ops.Operation, return ErrUnavailable } namespace := operation.GetNamespace() - if input.AddressClaim.Name != ClaimName(operation.GetName()) { + if input.AddressClaim != Reference(ClaimName(operation.GetName())) { return fmt.Errorf("%w: the claim is not the operation's own", ErrUnavailable) } claim := &unstructured.Unstructured{} diff --git a/internal/bootaddress/bootaddress_test.go b/internal/bootaddress/bootaddress_test.go index 142a20dd..dd507d97 100644 --- a/internal/bootaddress/bootaddress_test.go +++ b/internal/bootaddress/bootaddress_test.go @@ -116,7 +116,7 @@ func TestVerifyRequiresTheExactBoundIncarnation(t *testing.T) { } } stamp(created) - good := ops.BootNetworkInput{AddressClaim: ops.LocalReference{Name: claim.GetName()}, Address: "198.51.100.10"} + good := ops.BootNetworkInput{AddressClaim: Reference(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)) @@ -133,7 +133,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.LocalReference{Name: "other-boot"}, Address: good.Address}, + "other name": {AddressClaim: Reference("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"}, } { @@ -338,7 +338,7 @@ func TestVerifyWaitsWhenIPAMCannotBeRead(t *testing.T) { operation := &ops.DeviceInstallation{} operation.Name, operation.Namespace = "alloc-a-install-1", namespace operation.CreationTimestamp = metav1.NewTime(time.Now().Add(time.Hour)) - input := ops.BootNetworkInput{AddressClaim: ops.LocalReference{Name: ClaimName(operation.Name)}, Address: "198.51.100.10"} + input := ops.BootNetworkInput{AddressClaim: Reference(ClaimName(operation.Name)), Address: "198.51.100.10"} if err := Verify(ctx, api, operation, "DeviceInstallation", input); !errors.Is(err, ErrUnavailable) || errors.Is(err, ErrUnreachable) { t.Fatalf("a missing claim: %v", err) } @@ -389,7 +389,7 @@ func TestARetainingClaimIsNeverUsed(t *testing.T) { operation := &ops.DeviceInstallation{} operation.Name, operation.Namespace = "alloc-a-install-1", namespace operation.CreationTimestamp = metav1.NewTime(created.Add(time.Second)) - input := ops.BootNetworkInput{AddressClaim: ops.LocalReference{Name: claim.GetName()}, Address: "198.51.100.10"} + input := ops.BootNetworkInput{AddressClaim: Reference(claim.GetName()), Address: "198.51.100.10"} if err := Verify(ctx, api, operation, "DeviceInstallation", input); err != nil { t.Fatal(err) } diff --git a/internal/custody/admission_test.go b/internal/custody/admission_test.go index 11fb76f9..aedb3016 100644 --- a/internal/custody/admission_test.go +++ b/internal/custody/admission_test.go @@ -4,11 +4,13 @@ import ( "context" "fmt" "reflect" + "strings" "testing" "time" 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" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -294,7 +296,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.LocalReference{Name: created.GetName()}, Address: address} + return &ops.BootNetworkInput{AddressClaim: bootaddress.Reference(created.GetName()), Address: address} } withAddress := func(request string, input *ops.BootNetworkInput) *ops.DeviceInstallation { operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: name(request), Namespace: "default", Labels: map[string]string{ops.LabelInstallationUID: request}}, Spec: ops.DeviceInstallationSpec{ @@ -327,13 +329,13 @@ func TestAdmissionPreconditions(t *testing.T) { recreatedOperation, withAddress("other-address", otherAddress), withAddress("unbound", claim("unbound", "Pending", "198.51.100.12")), - withAddress("missing", &ops.BootNetworkInput{AddressClaim: ops.LocalReference{Name: bootaddress.ClaimName(name("missing"))}, Address: good.Address}), + withAddress("missing", &ops.BootNetworkInput{AddressClaim: bootaddress.Reference(bootaddress.ClaimName(name("missing"))), 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.requirePhase(operation, ops.PhaseFailed, ReasonBootAddressMismatch) } e.requireUntouched(device.Name, fence) admitted := withAddress("bound", good) @@ -367,6 +369,33 @@ func TestAdmissionPreconditions(t *testing.T) { e.requireUntouched(releasing.Name, wipeFence) }) + t.Run("a boot address claim of a kind with no check fails for good", func(t *testing.T) { + e := e.sub(t) + device := fresh() + if err := e.coord.Claim(e.ctx, device.Name, device.UID, "alloc-kind"); err != nil { + t.Fatal(err) + } + fence := e.custody(device.Name).Spec.Fence + name := InstallationName("alloc-kind", "request-1") + // A claim of the unknown kind exists with the operation's labels and + // address; no check can read it, so it never counts. + e.ipClaim(bootaddress.ClaimName(name), name, "DeviceInstallation", "Bound", "198.51.100.20") + operation := &ops.DeviceInstallation{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default", Labels: map[string]string{ops.LabelInstallationUID: "request-1"}}, Spec: ops.DeviceInstallationSpec{ + OperationEnvelope: envelope(device, providerUser, allocated("alloc-kind")), + Image: ops.ImageInput{Name: "debian-12", Digest: imageDigest}, BootInterface: "primary", TargetDisks: []string{"disk-0"}, + BootNetwork: &ops.BootNetworkInput{AddressClaim: fleetv1.TypedReference{APIGroup: "networking.example.com", Kind: "AddressLease", Name: bootaddress.ClaimName(name)}, Address: "198.51.100.20"}, + }} + e.create(operation) + if outcome := e.settle(device.Name); outcome.RequeueAfter != 0 { + t.Fatalf("an unsupported claim kind asked to be checked again: %+v", outcome) + } + status := e.requirePhase(operation, ops.PhaseFailed, ReasonBootAddressUnsupported) + if !strings.Contains(status.Message, "networking.example.com/AddressLease") { + t.Fatalf("message = %q, want the claim's group and kind", status.Message) + } + e.requireUntouched(device.Name, fence) + }) + 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/kinds.go b/internal/custody/kinds.go index 09bdc60c..5ada5456 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -38,7 +38,15 @@ const ( ReasonRetryAuthorized = "RetryAlreadyAuthorized" ReasonDisposalRequired = "DisposalRequired" ReasonInvalidResolve = "InvalidResolve" - ReasonBootAddress = "BootAddressUnavailable" + // ReasonBootAddress means the boot address claim's source could not be + // read. The operation waits and is checked again. + ReasonBootAddress = "BootAddressUnavailable" + // ReasonBootAddressMismatch means the boot address claim is not the + // operation's own, or does not hold its address. The operation fails. + ReasonBootAddressMismatch = "BootAddressClaimMismatch" + // ReasonBootAddressUnsupported means no check is registered for the + // boot address claim's kind, so it can never be checked. + ReasonBootAddressUnsupported = "UnsupportedBootAddressClaim" // Reasons every site's install and wipe workers raise. ReasonTargetUnsupported = "TargetUnsupported" ReasonTargetDisks = "TargetDisksUnknown" @@ -65,11 +73,13 @@ func NoBootNetwork(network *ops.BootNetworkInput) *Refusal { // networkBootReasons are the coordinator's reasons for a network boot's // inputs. -var networkBootReasons = []Reason{{Name: ReasonBootInterfaceUnknown, RaisedBy: RaisedByCoordinator}, {Name: ReasonBootAddress, RaisedBy: RaisedByCoordinator}} +var networkBootReasons = []Reason{{Name: ReasonBootInterfaceUnknown, RaisedBy: RaisedByCoordinator}, {Name: ReasonBootAddress, RaisedBy: RaisedByCoordinator}, + {Name: ReasonBootAddressMismatch, RaisedBy: RaisedByCoordinator}, {Name: ReasonBootAddressUnsupported, 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. +// operation's claim. The check is the one registered for the claim's kind; +// a kind with none is refused for good. func checkNetworkBoot(ctx context.Context, admission *Admission, kind, bootInterface string, network *ops.BootNetworkInput) *Refusal { found := false for _, iface := range admission.Device.Spec.Interfaces { @@ -83,13 +93,18 @@ func checkNetworkBoot(ctx context.Context, admission *Admission, kind, bootInter if network == nil { return nil } - if err := bootaddress.Verify(ctx, admission.Reader, admission.Operation, kind, *network); errors.Is(err, bootaddress.ErrUnreachable) { + claim := network.AddressClaim + check := admission.Registry.BootAddressClaim(claim.APIGroup, claim.Kind) + if check == nil { + return refuse(ReasonBootAddressUnsupported, "boot address claims of kind %s/%s cannot be checked", claim.APIGroup, claim.Kind) + } + if err := check(ctx, admission.Reader, admission.Operation, kind, *network); errors.Is(err, bootaddress.ErrUnreachable) { // Fail closed without deciding: the claim may still hold the address. - refusal := refuse(ReasonBootAddress, "waiting: IPAM could not be read to check the boot address claim %s: %v", network.AddressClaim.Name, err) + refusal := refuse(ReasonBootAddress, "waiting: the boot address claim %s could not be read: %v", claim.Name, err) refusal.Retry = true return refusal } else if err != nil { - return refuse(ReasonBootAddress, "the boot address claim %s does not hold %s", network.AddressClaim.Name, network.Address) + return refuse(ReasonBootAddressMismatch, "the boot address claim %s does not hold %s: %v", claim.Name, network.Address, err) } return nil } @@ -386,6 +401,10 @@ func DefaultRegistry() (*Registry, error) { return nil, err } } + // IPAM's claim is the only boot address claim kind built in. + if err := registry.RegisterBootAddressClaim(bootaddress.GVK.Group, bootaddress.GVK.Kind, bootaddress.Verify); err != nil { + return nil, err + } return registry, nil } diff --git a/internal/custody/registry.go b/internal/custody/registry.go index da6e5526..2e7d6418 100644 --- a/internal/custody/registry.go +++ b/internal/custody/registry.go @@ -289,14 +289,45 @@ var sharedReasons = []string{ReasonUnsupportedKind, ReasonInputMismatch, ReasonC var reasonPattern = regexp.MustCompile(`^[A-Z][A-Za-z0-9]{0,62}$`) -// Registry holds the operation kinds and the admission rules. +// Registry holds the operation kinds, the admission rules, and the checks +// for each kind of boot address claim. type Registry struct { - kinds map[string]*Kind - order []string - rules []Rule + kinds map[string]*Kind + order []string + rules []Rule + bootClaims map[schema.GroupKind]BootAddressCheck } -func NewRegistry() *Registry { return &Registry{kinds: map[string]*Kind{}} } +func NewRegistry() *Registry { + return &Registry{kinds: map[string]*Kind{}, bootClaims: map[schema.GroupKind]BootAddressCheck{}} +} + +// BootAddressCheck checks at admission that an operation's boot address +// claim is the operation's own and holds exactly the input's address. kind +// is the operation's kind. It must not write. It returns an error wrapping +// bootaddress.ErrUnreachable when the claim's source cannot be read, so the +// operation waits, and any other error when the claim does not hold the +// address, so the operation fails. +type BootAddressCheck func(ctx context.Context, reader client.Reader, operation ops.Operation, kind string, input ops.BootNetworkInput) error + +// RegisterBootAddressClaim adds the check for one kind of boot address +// claim. Registering a claim kind twice is an error. +func (r *Registry) RegisterBootAddressClaim(apiGroup, kind string, check BootAddressCheck) error { + key := schema.GroupKind{Group: apiGroup, Kind: kind} + if apiGroup == "" || kind == "" || check == nil { + return errors.New("a boot address claim check needs an API group, a kind and a check") + } + if _, ok := r.bootClaims[key]; ok { + return fmt.Errorf("boot address claim %s/%s is already registered", apiGroup, kind) + } + r.bootClaims[key] = check + return nil +} + +// BootAddressClaim returns the check for a boot address claim kind, or nil. +func (r *Registry) BootAddressClaim(apiGroup, kind string) BootAddressCheck { + return r.bootClaims[schema.GroupKind{Group: apiGroup, Kind: kind}] +} // Register adds a kind. Registering a kind twice is an error. func (r *Registry) Register(kind Kind) error { diff --git a/internal/network/nso/assumed.go b/internal/network/nso/assumed.go new file mode 100644 index 00000000..a8b9993f --- /dev/null +++ b/internal/network/nso/assumed.go @@ -0,0 +1,105 @@ +package nso + +// This file is the one place Fleet writes down what it assumes of NSO for a +// physical server: assumed NSO contract, not in NSO yet. Everything else in +// this package uses NSO's real types and reasons. Each assumption is listed +// once, with the test realizer that stands in for it. +// +// 1. Physical attachment mode. A NetworkInterfaceClaim with attachmentMode +// Physical is an interface with no node, container or hypervisor. +// 2. Attachment point. NSO has no field for it, so Fleet sets the host +// interface's MAC and the switch and port it is cabled to as the +// annotations below on every Physical claim. A customer interface claim +// for a physical server carries the same annotations. +// 3. Provider-owned boot network. A Network in the namespace Fleet controls +// in the provider's NSO API, addressed at each site from the +// provisioning IPAM class, untagged on a port while attached and +// isolated between servers. +// 4. Membership from claims. While a boot attachment claim, one on the boot +// network, names a port, the port is on the boot network only, and every +// other claim naming it reports Prepared but not Programmed. Otherwise +// the port carries the networks of the claims that name it. Each change +// is one step: releasing the boot attachment claim moves the port to the +// customer's networks directly. A boot attachment claim reports +// Programmed once its port is on the boot network. +// 5. Boot address. A boot attachment claim's IPv4 interface address, in +// status.addresses, is the operation's provisioning address. +// 6. Detach before delete. NSO keeps a Physical claim until its port is off +// the claim's network, then releases its addresses. +// 7. Verified release. NSO makes the IPAM claim for a claim's IPv4 address +// under one of the names BootAddressIPClaims returns, in the IPAM +// namespace of the claim's project: the plain name, or one suffixed with +// a hash of the location. This mirrors NSO's code today (ipClaimNames in +// its interface claim controller), not a documented contract; NSO puts +// no labels on those IPAM claims, so the names are the only link. + +import ( + "crypto/sha256" + "encoding/hex" + "strings" + + "k8s.io/apimachinery/pkg/util/validation" + + networkingv1 "go.datum.net/network-services-operator/api/v1alpha" +) + +// PhysicalMode is the assumed attachment mode for a physical server. +const PhysicalMode networkingv1.NetworkInterfaceAttachmentMode = "Physical" + +// AttachmentPoint is where a host interface meets the network: its MAC, and +// the switch and port at the other end of its cable. +type AttachmentPoint struct { + MACAddress string + Switch string + Port string +} + +// Assumed annotations naming a Physical claim's attachment point. +const ( + AttachmentMACAnnotation = "networking.datumapis.com/attachment-mac" + AttachmentSwitchAnnotation = "networking.datumapis.com/attachment-switch" + AttachmentPortAnnotation = "networking.datumapis.com/attachment-port" +) + +// SetAttachmentPoint writes the attachment point onto a claim. +func SetAttachmentPoint(claim *networkingv1.NetworkInterfaceClaim, point AttachmentPoint) { + if claim.Annotations == nil { + claim.Annotations = map[string]string{} + } + claim.Annotations[AttachmentMACAnnotation] = point.MACAddress + claim.Annotations[AttachmentSwitchAnnotation] = point.Switch + claim.Annotations[AttachmentPortAnnotation] = point.Port +} + +// AttachmentPointOf reads a claim's attachment point. +func AttachmentPointOf(claim *networkingv1.NetworkInterfaceClaim) AttachmentPoint { + return AttachmentPoint{MACAddress: claim.Annotations[AttachmentMACAnnotation], Switch: claim.Annotations[AttachmentSwitchAnnotation], Port: claim.Annotations[AttachmentPortAnnotation]} +} + +// BootAddressIPClaims are the names NSO may make the IPAM claim for a claim's +// IPv4 interface address under at a location: the plain name, then the name +// suffixed with the first eight hex digits of the location name's SHA-256. +func BootAddressIPClaims(claim, location string) []string { + sum := sha256.Sum256([]byte(location)) + return []string{BootAddressIPClaim(claim), ipClaimName(claim, "f-ipv4-l"+hex.EncodeToString(sum[:])[:8])} +} + +// BootAddressIPClaim is the plain name of the IPAM claim NSO makes for a +// claim's IPv4 interface address. +func BootAddressIPClaim(claim string) string { return ipClaimName(claim, "f-ipv4") } + +// ipClaimName is the claim's name and the discriminator, hashed when the +// result would not be a valid name. +func ipClaimName(claim, discriminator string) string { + const maxName, hashLen = 253, 12 + candidate := claim + "-" + discriminator + if len(candidate) <= maxName && len(validation.IsDNS1123Subdomain(candidate)) == 0 { + return candidate + } + sum := sha256.Sum256([]byte(claim + "\x00" + discriminator)) + prefix := claim + if limit := maxName - 1 - hashLen; len(prefix) > limit { + prefix = prefix[:limit] + } + return strings.TrimRight(prefix, "-.") + "-" + hex.EncodeToString(sum[:])[:hashLen] +} diff --git a/internal/network/nso/boot.go b/internal/network/nso/boot.go new file mode 100644 index 00000000..e8ac3c65 --- /dev/null +++ b/internal/network/nso/boot.go @@ -0,0 +1,458 @@ +package nso + +import ( + "context" + "errors" + "fmt" + "net/netip" + "strings" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + apiMeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/client" + + networkingv1 "go.datum.net/network-services-operator/api/v1alpha" + + 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/bootnet" + "go.datum.net/fleet/internal/custody" +) + +// BootClaimGroup and BootClaimKind name NSO's claim in an operation's boot +// network input. +const ( + BootClaimGroup = "networking.datumapis.com" + BootClaimKind = "NetworkInterfaceClaim" +) + +// NSO's reasons on Allocated when IPAM refused an address. +const ( + reasonExhausted = "AddressPoolExhausted" + reasonRetainedConflict = "RetainedAddressConflict" + reasonRejected = "AddressAllocationRejected" + // reasonFailed is NSO's catch-all for an IPAM error it does not + // classify. NSO keeps the claim and retries it, so Fleet waits. + reasonFailed = "AllocationFailed" +) + +// BootReference is the typed reference an operation carries to its boot +// attachment claim. +func BootReference(name string) fleetv1.TypedReference { + return fleetv1.TypedReference{APIGroup: BootClaimGroup, Kind: BootClaimKind, Name: name} +} + +// BootAttachments is the NSO boot address source. For each installation and +// wipe it creates one Physical boot attachment claim on the provider's boot +// network, for the boot NIC's attachment point, named from the operation. +// NSO moves the port onto the boot network and binds its provisioning +// address; the requester claims the address only once NSO reports the port +// Programmed. Nothing configures it by default; IPAM's claimer stays the +// default source. It relies on the contract in assumed.go. +type BootAttachments struct { + // Client reaches the provider's NSO API and Device inventory. Each + // requester uses its own. + Client client.Client + // Namespace holds the boot attachment claims and the boot network. + // Empty means the operations' namespace. + Namespace string + // Kind is the operation kind the requester creates. + Kind string + // Network is the provider-owned boot network. + Network string + // IPAM reads the namespace where NSO makes its IPAM claims, IPAMNamespace, + // to verify that a released claim's address is no longer allocated. + IPAM client.Reader + IPAMNamespace string + // Location is the site's location, which NSO's IPAM claim names may + // carry. + Location string +} + +var _ bootaddress.Source = BootAttachments{} + +// Requester returns the source with the requester's client and kind. +func (b BootAttachments) Requester(api client.Client, namespace, kind string) bootaddress.Source { + b.Client, b.Kind = api, kind + if b.Namespace == "" { + b.Namespace = namespace + } + return b +} + +// ClaimKind is NSO's NetworkInterfaceClaim. +func (BootAttachments) ClaimKind() schema.GroupKind { + return schema.GroupKind{Group: BootClaimGroup, Kind: BootClaimKind} +} + +// AddressOutlivesClaim marks the source as bootaddress.Lingering: NSO may +// remove its claim before IPAM removes the address it claimed for it. +func (BootAttachments) AddressOutlivesClaim() {} + +// AttachesBootNIC marks the source as the one that moves boot NICs. +func (BootAttachments) AttachesBootNIC() {} + +func (b BootAttachments) valid() error { + if b.Client == nil || b.Namespace == "" || b.Kind == "" || b.Network == "" { + return errors.New("nso: a client, namespace, kind and boot network are required") + } + return nil +} + +func (b BootAttachments) get(ctx context.Context, name string) (*networkingv1.NetworkInterfaceClaim, error) { + claim := &networkingv1.NetworkInterfaceClaim{} + return claim, b.Client.Get(ctx, client.ObjectKey{Namespace: b.Namespace, Name: name}, claim) +} + +// Attach creates the operation's boot attachment claim once and returns nil +// once NSO reports the port on the boot network, ErrPending until then, and +// ErrExhausted or ErrRefused when NSO reports IPAM refused its address. +func (b BootAttachments) Attach(ctx context.Context, allocation *fleetv1.MachineAllocation, operation string) error { + if err := b.valid(); err != nil { + return err + } + name := bootaddress.ClaimName(operation) + claim, err := b.get(ctx, name) + if apierrors.IsNotFound(err) { + device := &inventory.Device{} + if err := b.Client.Get(ctx, client.ObjectKey{Namespace: allocation.Namespace, Name: allocation.Spec.DeviceRef.Name}, device); err != nil { + return err + } + if string(device.UID) != allocation.Labels[fleetv1.LabelDeviceUID] { + return fmt.Errorf("%w: the Device is another incarnation", bootaddress.ErrConflict) + } + point, locateErr := LocateBootNIC(ctx, b.Client, device, allocation.Spec.BootInterface) + if locateErr != nil { + return locateErr + } + if err := b.Client.Create(ctx, b.desired(allocation, operation, point)); err != nil && !apierrors.IsAlreadyExists(err) { + return err + } + claim, err = b.get(ctx, name) + } + if err != nil { + return err + } + if err := b.owned(claim, allocation.Name, operation); err != nil { + return err + } + if err := refused(claim); err != nil { + return err + } + if !programmed(claim) { + return fmt.Errorf("%w: the boot NIC is not on the boot network yet", bootaddress.ErrPending) + } + return nil +} + +func (b BootAttachments) desired(allocation *fleetv1.MachineAllocation, operation string, point AttachmentPoint) *networkingv1.NetworkInterfaceClaim { + claim := &networkingv1.NetworkInterfaceClaim{ + ObjectMeta: metav1.ObjectMeta{Name: bootaddress.ClaimName(operation), Namespace: b.Namespace, Labels: map[string]string{ + bootaddress.AllocationLabel: allocation.Name, bootaddress.OperationLabel: operation, bootaddress.KindLabel: b.Kind, + }}, + Spec: networkingv1.NetworkInterfaceClaimSpec{ + Network: networkingv1.LocalNetworkRef{Name: b.Network}, + InterfaceName: allocation.Spec.BootInterface, + AttachmentMode: PhysicalMode, + IPFamilies: []networkingv1.IPFamily{networkingv1.IPv4Protocol}, + ReclaimPolicy: networkingv1.NetworkInterfaceReclaimPolicyDelete, + }, + } + SetAttachmentPoint(claim, point) + return claim +} + +// ErrAttachmentUnknown means inventory cannot say where the boot NIC is +// cabled. +var ErrAttachmentUnknown = errors.New("the boot NIC's attachment point is unknown") + +// LocateBootNIC returns where a Device interface meets the network: its MAC +// from Device inventory, and the switch and port at the other end of the one +// cable record that lands on it. Cable endpoints name the interface as the +// Device's component. +func LocateBootNIC(ctx context.Context, reader client.Reader, device *inventory.Device, iface string) (AttachmentPoint, error) { + var mac string + for _, candidate := range device.Spec.Interfaces { + if candidate.Name == iface { + mac = candidate.MACAddress + } + } + normalized, ok := bootnet.NormalizeMAC(strings.ReplaceAll(mac, "-", ":")) + if !ok { + return AttachmentPoint{}, fmt.Errorf("%w: the Device records no MAC for %q", ErrAttachmentUnknown, iface) + } + var cables inventory.CableList + if err := reader.List(ctx, &cables, client.InNamespace(device.Namespace)); err != nil { + return AttachmentPoint{}, err + } + var found []AttachmentPoint + for _, cable := range cables.Items { + for _, lane := range cable.Spec.Lanes { + for _, ends := range [][2]inventory.CableEndpoint{{lane.A, lane.B}, {lane.B, lane.A}} { + here, there := ends[0], ends[1] + if here.DeviceRef != nil && here.DeviceRef.Name == device.Name && here.ComponentID == iface && there.DeviceRef != nil && there.ComponentID != "" { + found = append(found, AttachmentPoint{MACAddress: normalized, Switch: there.DeviceRef.Name, Port: there.ComponentID}) + } + } + } + } + if len(found) != 1 { + return AttachmentPoint{}, fmt.Errorf("%w: %d cable records land on %q", ErrAttachmentUnknown, len(found), iface) + } + return found[0], nil +} + +// owned requires the claim to be this requester's boot attachment for the +// operation, on the boot network, and not being deleted. +func (b BootAttachments) owned(claim *networkingv1.NetworkInterfaceClaim, allocation, operation string) error { + labels := claim.Labels + if labels[bootaddress.AllocationLabel] != allocation || labels[bootaddress.OperationLabel] != operation || labels[bootaddress.KindLabel] != b.Kind || + claim.Spec.Network.Name != b.Network || claim.Spec.AttachmentMode != PhysicalMode || claim.Spec.ReclaimPolicy != networkingv1.NetworkInterfaceReclaimPolicyDelete || + AttachmentPointOf(claim).Port == "" || claim.DeletionTimestamp != nil { + return fmt.Errorf("%w: %s", bootaddress.ErrConflict, claim.Name) + } + return nil +} + +// Claim returns the operation's provisioning address, which NSO bound to its +// boot attachment claim. It reads no address while the port is not on the +// boot network. +func (b BootAttachments) Claim(ctx context.Context, allocation, operation string) (*ops.BootNetworkInput, error) { + if err := b.valid(); err != nil { + return nil, err + } + claim, err := b.get(ctx, bootaddress.ClaimName(operation)) + if apierrors.IsNotFound(err) { + return nil, fmt.Errorf("%w: the boot NIC is not attached", bootaddress.ErrPending) + } + if err != nil { + return nil, err + } + if err := b.owned(claim, allocation, operation); err != nil { + return nil, err + } + if err := refused(claim); err != nil { + return nil, err + } + if !programmed(claim) { + return nil, fmt.Errorf("%w: the boot NIC is not on the boot network yet", bootaddress.ErrPending) + } + address, err := bootAddress(claim) + if err != nil { + return nil, err + } + return &ops.BootNetworkInput{AddressClaim: BootReference(claim.Name), Address: address}, nil +} + +// Release deletes the operation's claim and returns true only once a read +// finds it gone and IPAM holds no allocation for the address NSO claimed for +// it. NSO keeps the claim until the port is off the boot network, so a +// delete that failed or is still in progress keeps it held. +func (b BootAttachments) Release(ctx context.Context, operation string) (bool, error) { + gone, err := b.remove(ctx, operation) + if err != nil || !gone { + return false, err + } + return b.unallocated(ctx, operation) +} + +// Released reports whether the operation's claim is absent and IPAM holds +// no allocation for the address NSO claimed for it. It deletes nothing, so a +// claim its requester is still creating is never removed. +func (b BootAttachments) Released(ctx context.Context, operation string) (bool, error) { + if err := b.valid(); err != nil { + return false, err + } + if _, err := b.get(ctx, bootaddress.ClaimName(operation)); err == nil { + return false, nil + } else if !apierrors.IsNotFound(err) { + return false, err + } + return b.unallocated(ctx, operation) +} + +// unallocated reports whether IPAM holds no allocation under either name NSO +// may claim the operation's address under. +func (b BootAttachments) unallocated(ctx context.Context, operation string) (bool, error) { + if b.IPAM == nil || b.IPAMNamespace == "" || b.Location == "" { + return false, errors.New("nso: no IPAM reader, namespace and location to verify the boot address release") + } + for _, name := range BootAddressIPClaims(bootaddress.ClaimName(operation), b.Location) { + if free, err := bootaddress.Unallocated(ctx, b.IPAM, b.IPAMNamespace, name); err != nil || !free { + return false, err + } + } + return true, nil +} + +// Detach returns true once the operation's claim is gone, which NSO allows +// only after the port left the boot network. +func (b BootAttachments) Detach(ctx context.Context, operation string) (bool, error) { + return b.remove(ctx, operation) +} + +func (b BootAttachments) remove(ctx context.Context, operation string) (bool, error) { + if err := b.valid(); err != nil { + return false, err + } + claim, err := b.get(ctx, bootaddress.ClaimName(operation)) + if apierrors.IsNotFound(err) { + return true, nil + } + if err != nil { + return false, err + } + if claim.Labels[bootaddress.OperationLabel] != operation || claim.Labels[bootaddress.KindLabel] != b.Kind { + return false, fmt.Errorf("%w: %s", bootaddress.ErrConflict, claim.Name) + } + if claim.DeletionTimestamp == nil { + uid := claim.UID + if err := b.Client.Delete(ctx, claim, client.Preconditions{UID: &uid}); err != nil && !apierrors.IsNotFound(err) { + return false, err + } + } + if _, err := b.get(ctx, claim.Name); !apierrors.IsNotFound(err) { + return false, err + } + return true, nil +} + +// Operations returns the operations of the requester's kind in an +// allocation that still have a boot attachment claim. +func (b BootAttachments) Operations(ctx context.Context, allocation string) ([]string, error) { + if err := b.valid(); err != nil { + return nil, err + } + var list networkingv1.NetworkInterfaceClaimList + if err := b.Client.List(ctx, &list, client.InNamespace(b.Namespace), client.MatchingLabels{bootaddress.AllocationLabel: allocation, bootaddress.KindLabel: b.Kind}); err != nil { + return nil, err + } + var operations []string + for _, claim := range list.Items { + if operation := claim.Labels[bootaddress.OperationLabel]; operation != "" && claim.Name == bootaddress.ClaimName(operation) { + operations = append(operations, operation) + } + } + return operations, nil +} + +// BootAttachmentCheck is admission's check for NSO's boot attachment claim. +// Only NewBootAttachmentCheck makes a usable one. +type BootAttachmentCheck struct { + namespace string + network string +} + +var _ custody.BootAddressCheck = BootAttachmentCheck{}.Verify + +// NewBootAttachmentCheck returns the check for claims in namespace, empty for +// the operation's own, on the boot network. It fails when the admission +// reader's scheme does not know NSO's claim, because every read would then +// fail and leave operations Pending forever. +func NewBootAttachmentCheck(scheme *runtime.Scheme, namespace, network string) (BootAttachmentCheck, error) { + if network == "" { + return BootAttachmentCheck{}, errors.New("nso: the boot network is required") + } + if scheme == nil || !scheme.Recognizes(networkingv1.GroupVersion.WithKind(BootClaimKind)) { + return BootAttachmentCheck{}, fmt.Errorf("nso: the admission reader's scheme does not know %s/%s", BootClaimGroup, BootClaimKind) + } + return BootAttachmentCheck{namespace: namespace, network: network}, nil +} + +// Verify requires the input to name the operation's own boot attachment +// claim, by its only name and its labels, created no later than the +// operation, not being deleted, Programmed on the boot network, and bound to +// exactly the input's address. It returns bootaddress.ErrUnreachable when +// NSO cannot be read for any reason but the claim's absence, and +// bootaddress.ErrUnavailable otherwise. +func (c BootAttachmentCheck) Verify(ctx context.Context, reader client.Reader, operation ops.Operation, kind string, input ops.BootNetworkInput) error { + if reader == nil || c.network == "" { + return fmt.Errorf("%w: the check was not made by NewBootAttachmentCheck", bootaddress.ErrUnavailable) + } + name := bootaddress.ClaimName(operation.GetName()) + if input.AddressClaim != BootReference(name) { + return fmt.Errorf("%w: the claim is not the operation's own", bootaddress.ErrUnavailable) + } + namespace := c.namespace + if namespace == "" { + namespace = operation.GetNamespace() + } + claim := &networkingv1.NetworkInterfaceClaim{} + if err := reader.Get(ctx, client.ObjectKey{Namespace: namespace, Name: name}, claim); apierrors.IsNotFound(err) { + return fmt.Errorf("%w: %v", bootaddress.ErrUnavailable, err) + } else if err != nil { + return fmt.Errorf("%w: %v", bootaddress.ErrUnreachable, err) + } + created, opened := claim.CreationTimestamp, operation.GetCreationTimestamp() + if claim.DeletionTimestamp != nil || created.IsZero() || opened.IsZero() || created.After(opened.Time) { + return fmt.Errorf("%w: the claim was recreated after its operation or is being deleted", bootaddress.ErrUnavailable) + } + if claim.Labels[bootaddress.OperationLabel] != operation.GetName() || claim.Labels[bootaddress.KindLabel] != kind { + return fmt.Errorf("%w: the claim belongs to another operation", bootaddress.ErrUnavailable) + } + if claim.Spec.Network.Name != c.network || claim.Spec.AttachmentMode != PhysicalMode || !programmed(claim) { + return fmt.Errorf("%w: the boot NIC is not on the boot network", bootaddress.ErrUnavailable) + } + address, err := bootAddress(claim) + if err != nil { + return fmt.Errorf("%w: %v", bootaddress.ErrUnavailable, err) + } + if want, err := netip.ParseAddr(input.Address); err != nil || want.String() != address { + return fmt.Errorf("%w: the claim holds another address", bootaddress.ErrUnavailable) + } + return nil +} + +// programmed reports whether NSO reports the claim Programmed at its +// generation. +func programmed(claim *networkingv1.NetworkInterfaceClaim) bool { + condition := apiMeta.FindStatusCondition(claim.Status.Conditions, networkingv1.NetworkInterfaceClaimProgrammed) + return condition != nil && condition.Status == metav1.ConditionTrue && condition.ObservedGeneration == claim.Generation +} + +// refused maps NSO's report that IPAM refused the claim's address. A +// failure NSO retries is ErrPending with NSO's reason and message, so the +// wait says why. +func refused(claim *networkingv1.NetworkInterfaceClaim) error { + condition := apiMeta.FindStatusCondition(claim.Status.Conditions, networkingv1.NetworkInterfaceClaimAllocated) + if condition == nil || condition.Status != metav1.ConditionFalse || condition.ObservedGeneration != claim.Generation { + return nil + } + switch condition.Reason { + case reasonExhausted: + return fmt.Errorf("%w: %s", bootaddress.ErrExhausted, condition.Message) + case reasonRetainedConflict, reasonRejected: + return fmt.Errorf("%w: %s", bootaddress.ErrRefused, condition.Message) + case reasonFailed: + return fmt.Errorf("%w: NSO retries the address: %s: %s", bootaddress.ErrPending, condition.Reason, condition.Message) + } + return nil +} + +// bootAddress returns the claim's one IPv4 interface address, without its +// prefix length. +func bootAddress(claim *networkingv1.NetworkInterfaceClaim) (string, error) { + var found []string + for _, address := range claim.Status.Addresses { + if address.Family != networkingv1.IPv4Protocol { + continue + } + prefix, err := netip.ParsePrefix(address.Address) + if err != nil || !prefix.Addr().Is4() { + return "", errors.New("the claim's IPv4 address is not one host address") + } + found = append(found, prefix.Addr().String()) + } + switch len(found) { + case 0: + return "", fmt.Errorf("%w: NSO has not bound an address", bootaddress.ErrPending) + case 1: + return found[0], nil + } + return "", errors.New("the claim holds more than one IPv4 address") +} diff --git a/internal/network/nso/boot_test.go b/internal/network/nso/boot_test.go new file mode 100644 index 00000000..a2233c06 --- /dev/null +++ b/internal/network/nso/boot_test.go @@ -0,0 +1,428 @@ +package nso + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "strings" + "testing" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + apiMeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + + networkingv1 "go.datum.net/network-services-operator/api/v1alpha" + + 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" +) + +const ( + bootNamespace = "fleet-provider" + ipamNamespace = "ipam-provider" + bootNetwork = "boot" + location = "location-example-a" +) + +// bootFixture is the provider's NSO API with one cabled Device, and an +// allocation of it whose boot NIC is primary. +func bootFixture(t *testing.T, funcs interceptor.Funcs) (BootAttachments, client.Client, *fleetv1.MachineAllocation) { + t.Helper() + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{networkingv1.AddToScheme, inventory.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + scheme.AddKnownTypeWithName(bootaddress.AllocationGVK, &unstructured.Unstructured{}) + scheme.AddKnownTypeWithName(bootaddress.AllocationGVK.GroupVersion().WithKind("IPAllocationList"), &unstructured.UnstructuredList{}) + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "server-example-001", Namespace: bootNamespace, UID: "00000000-0000-4000-8000-000000000101"}, + Spec: inventory.DeviceSpec{Interfaces: []inventory.Interface{{Name: "primary", MACAddress: "02:00:00:00:00:01"}}}} + cable := &inventory.Cable{ObjectMeta: metav1.ObjectMeta{Name: "cable-example-1", Namespace: bootNamespace}, Spec: inventory.CableSpec{Lanes: []inventory.CableLane{{ID: "one", + A: inventory.CableEndpoint{DeviceRef: &inventory.LocalReference{Name: device.Name}, ComponentID: "primary"}, + B: inventory.CableEndpoint{DeviceRef: &inventory.LocalReference{Name: "switch-example-a"}, ComponentID: "ethernet7"}}}}} + api := fake.NewClientBuilder().WithScheme(scheme).WithObjects(device, cable).WithStatusSubresource(&networkingv1.NetworkInterfaceClaim{}).WithInterceptorFuncs(funcs).Build() + allocation := &fleetv1.MachineAllocation{ObjectMeta: metav1.ObjectMeta{Name: "alloc-example", Namespace: bootNamespace, Labels: map[string]string{fleetv1.LabelDeviceUID: string(device.UID)}}, + Spec: fleetv1.MachineAllocationSpec{DeviceRef: fleetv1.AllocatedDeviceReference{Name: device.Name}, BootInterface: "primary"}} + source := BootAttachments{Network: bootNetwork, IPAM: api, IPAMNamespace: ipamNamespace, Location: location} + return source.Requester(api, bootNamespace, "DeviceInstallation").(BootAttachments), api, allocation +} + +func bootClaim(t *testing.T, api client.Client, operation string) *networkingv1.NetworkInterfaceClaim { + t.Helper() + claim := &networkingv1.NetworkInterfaceClaim{} + if err := api.Get(context.Background(), client.ObjectKey{Namespace: bootNamespace, Name: bootaddress.ClaimName(operation)}, claim); err != nil { + t.Fatal(err) + } + return claim +} + +// report writes what NSO reports for a claim: its addresses and conditions. +func report(t *testing.T, api client.Client, claim *networkingv1.NetworkInterfaceClaim, address string, conditions map[string]metav1.Condition) { + t.Helper() + if err := api.Get(context.Background(), client.ObjectKeyFromObject(claim), claim); err != nil { + t.Fatal(err) + } + claim.Status.Addresses = nil + if address != "" { + claim.Status.Addresses = []networkingv1.NetworkInterfaceAddress{{Family: networkingv1.IPv4Protocol, Address: address, Gateway: "198.51.100.1", Primary: true}} + } + for kind, condition := range conditions { + condition.Type, condition.ObservedGeneration = kind, claim.Generation + if condition.Reason == "" { + condition.Reason = "Test" + } + apiMeta.SetStatusCondition(&claim.Status.Conditions, condition) + } + if err := api.Status().Update(context.Background(), claim); err != nil { + t.Fatal(err) + } +} + +var programmedTrue = map[string]metav1.Condition{ + networkingv1.NetworkInterfaceClaimAllocated: {Status: metav1.ConditionTrue}, + networkingv1.NetworkInterfaceClaimPrepared: {Status: metav1.ConditionTrue}, + networkingv1.NetworkInterfaceClaimProgrammed: {Status: metav1.ConditionTrue}, +} + +// TestBootAttachmentIsTheOperationsOwnClaim creates one Physical claim per +// operation on the boot network, named from the operation, for the boot +// NIC's attachment point from inventory, and waits until NSO programs it. +func TestBootAttachmentIsTheOperationsOwnClaim(t *testing.T) { + ctx := context.Background() + source, api, allocation := bootFixture(t, interceptor.Funcs{}) + if err := source.Attach(ctx, allocation, "alloc-example-install-1"); !errors.Is(err, bootaddress.ErrPending) { + t.Fatalf("attach before NSO programs the port: %v", err) + } + claim := bootClaim(t, api, "alloc-example-install-1") + want := AttachmentPoint{MACAddress: "02:00:00:00:00:01", Switch: "switch-example-a", Port: "ethernet7"} + if claim.Spec.AttachmentMode != PhysicalMode || claim.Spec.Network.Name != bootNetwork || AttachmentPointOf(claim) != want || + claim.Labels[bootaddress.AllocationLabel] != allocation.Name || claim.Labels[bootaddress.OperationLabel] != "alloc-example-install-1" || claim.Labels[bootaddress.KindLabel] != "DeviceInstallation" { + t.Fatalf("claim = %+v", claim) + } + report(t, api, claim, "198.51.100.10/24", programmedTrue) + if err := source.Attach(ctx, allocation, "alloc-example-install-1"); err != nil { + t.Fatalf("attach once programmed: %v", err) + } + // Another operation, such as a retry, has its own claim. + if err := source.Attach(ctx, allocation, "alloc-example-install-1-retry-1"); !errors.Is(err, bootaddress.ErrPending) { + t.Fatal(err) + } + if names, err := source.Operations(ctx, allocation.Name); err != nil || len(names) != 2 || names[0] == names[1] { + t.Fatalf("operations = %v, %v", names, err) + } + // Another requester's claim under the name is a conflict, not its own. + wipes := source.Requester(api, bootNamespace, "DeviceWipe") + if err := wipes.Attach(ctx, allocation, "alloc-example-install-1"); !errors.Is(err, bootaddress.ErrConflict) { + t.Fatalf("a requester adopted another's claim: %v", err) + } + if _, err := wipes.Release(ctx, "alloc-example-install-1"); !errors.Is(err, bootaddress.ErrConflict) { + t.Fatalf("a requester released another's claim: %v", err) + } +} + +// TestNoAddressIsClaimedBeforeTheBootNICIsProgrammed reads no address while +// the port is not on the boot network, even one NSO already bound. +func TestNoAddressIsClaimedBeforeTheBootNICIsProgrammed(t *testing.T) { + ctx := context.Background() + source, api, allocation := bootFixture(t, interceptor.Funcs{}) + if _, err := source.Claim(ctx, allocation.Name, "alloc-example-install-1"); !errors.Is(err, bootaddress.ErrPending) { + t.Fatalf("claim before attach: %v", err) + } + if err := source.Attach(ctx, allocation, "alloc-example-install-1"); !errors.Is(err, bootaddress.ErrPending) { + t.Fatal(err) + } + claim := bootClaim(t, api, "alloc-example-install-1") + report(t, api, claim, "198.51.100.10/24", map[string]metav1.Condition{networkingv1.NetworkInterfaceClaimAllocated: {Status: metav1.ConditionTrue}}) + if input, err := source.Claim(ctx, allocation.Name, "alloc-example-install-1"); !errors.Is(err, bootaddress.ErrPending) { + t.Fatalf("an address was claimed before the port was programmed: %+v, %v", input, err) + } + report(t, api, claim, "198.51.100.10/24", programmedTrue) + input, err := source.Claim(ctx, allocation.Name, "alloc-example-install-1") + if err != nil || input.Address != "198.51.100.10" || input.AddressClaim != BootReference(claim.Name) { + t.Fatalf("input = %+v, %v", input, err) + } + if input.AddressClaim.APIGroup != networkingv1.GroupVersion.Group { + t.Fatalf("reference group %q is not NSO's", input.AddressClaim.APIGroup) + } +} + +// TestNSORefusalsAreReported maps NSO's report that IPAM refused the address +// to the same errors IPAM's refusals give, so no operation is created, and +// waits out a failure NSO retries. +func TestNSORefusalsAreReported(t *testing.T) { + ctx := context.Background() + for reason, want := range map[string]error{ + "AddressPoolExhausted": bootaddress.ErrExhausted, + "RetainedAddressConflict": bootaddress.ErrRefused, + "AddressAllocationRejected": bootaddress.ErrRefused, + "AllocationFailed": bootaddress.ErrPending, + "SomethingNSOAddsLater": bootaddress.ErrPending, + } { + source, api, allocation := bootFixture(t, interceptor.Funcs{}) + _ = source.Attach(ctx, allocation, "alloc-example-install-1") + report(t, api, bootClaim(t, api, "alloc-example-install-1"), "", map[string]metav1.Condition{ + networkingv1.NetworkInterfaceClaimAllocated: {Status: metav1.ConditionFalse, Reason: reason, Message: `IPPool "lab-provisioning" is exhausted`}, + }) + if err := source.Attach(ctx, allocation, "alloc-example-install-1"); !errors.Is(err, want) { + t.Errorf("%s: attach = %v, want %v", reason, err, want) + } + _, err := source.Claim(ctx, allocation.Name, "alloc-example-install-1") + if !errors.Is(err, want) { + t.Errorf("%s: claim = %v, want %v", reason, err, want) + } + // NSO retries a failure it does not classify; the wait says why. + if reason == "AllocationFailed" && (!strings.Contains(err.Error(), "AllocationFailed") || !strings.Contains(err.Error(), "lab-provisioning")) { + t.Errorf("AllocationFailed: %v, want NSO's reason and message", err) + } + } +} + +// TestBootAttachmentCheckNeedsNSOsTypes refuses to make the check for an +// admission reader whose scheme does not know NSO's claim, which would leave +// every operation Pending, and a check not made by its constructor fails +// closed. +func TestBootAttachmentCheckNeedsNSOsTypes(t *testing.T) { + if _, err := NewBootAttachmentCheck(runtime.NewScheme(), "", bootNetwork); err == nil { + t.Fatal("a check was made for a reader that cannot read NSO's claims") + } + if _, err := NewBootAttachmentCheck(nil, "", bootNetwork); err == nil { + t.Fatal("a check was made with no scheme") + } + scheme := runtime.NewScheme() + if err := networkingv1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + if _, err := NewBootAttachmentCheck(scheme, "", ""); err == nil { + t.Fatal("a check was made with no boot network") + } + if _, err := NewBootAttachmentCheck(scheme, "", bootNetwork); err != nil { + t.Fatal(err) + } + operation := &ops.DeviceInstallation{} + operation.Name, operation.Namespace = "alloc-example-install-1", bootNamespace + _, api, _ := bootFixture(t, interceptor.Funcs{}) + if err := (BootAttachmentCheck{}).Verify(context.Background(), api, operation, "DeviceInstallation", ops.BootNetworkInput{}); !errors.Is(err, bootaddress.ErrUnavailable) { + t.Fatalf("a zero check: %v", err) + } +} + +// TestNSOUnavailableAttachesNothing returns NSO's outage, never a pending +// attachment or an address, and creates nothing. +func TestNSOUnavailableAttachesNothing(t *testing.T) { + ctx := context.Background() + down := func(object client.Object) bool { _, ok := object.(*networkingv1.NetworkInterfaceClaim); return ok } + source, api, allocation := bootFixture(t, interceptor.Funcs{ + Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, object client.Object, opts ...client.GetOption) error { + if down(object) { + return apierrors.NewServiceUnavailable("nso is down") + } + return c.Get(ctx, key, object, opts...) + }, + }) + err := source.Attach(ctx, allocation, "alloc-example-install-1") + if err == nil || errors.Is(err, bootaddress.ErrPending) || !apierrors.IsServiceUnavailable(err) { + t.Fatalf("attach while NSO is down: %v", err) + } + if _, err := source.Claim(ctx, allocation.Name, "alloc-example-install-1"); err == nil || errors.Is(err, bootaddress.ErrPending) { + t.Fatalf("claim while NSO is down: %v", err) + } + var claims networkingv1.NetworkInterfaceClaimList + if err := api.List(ctx, &claims); err != nil || len(claims.Items) != 0 { + t.Fatalf("claims = %d, %v", len(claims.Items), err) + } +} + +// TestBootAttachmentCheckRequiresTheExactProgrammedClaim admits only the +// operation's own claim, created no later than the operation, programmed on +// the boot network and bound to the input's address; waits while NSO cannot +// be read; and refuses everything else. +func TestBootAttachmentCheckRequiresTheExactProgrammedClaim(t *testing.T) { + ctx := context.Background() + down := false + source, api, allocation := bootFixture(t, interceptor.Funcs{ + Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, object client.Object, opts ...client.GetOption) error { + if _, ok := object.(*networkingv1.NetworkInterfaceClaim); ok && down { + return apierrors.NewServiceUnavailable("nso is down") + } + return c.Get(ctx, key, object, opts...) + }, + }) + check, err := NewBootAttachmentCheck(api.Scheme(), "", bootNetwork) + if err != nil { + t.Fatal(err) + } + _ = source.Attach(ctx, allocation, "alloc-example-install-1") + claim := bootClaim(t, api, "alloc-example-install-1") + created := time.Date(2026, 11, 25, 12, 0, 0, 0, time.UTC) + claim.CreationTimestamp = metav1.NewTime(created) + if err := api.Update(ctx, claim); err != nil { + t.Fatal(err) + } + report(t, api, claim, "198.51.100.10/24", programmedTrue) + operation := &ops.DeviceInstallation{} + operation.Name, operation.Namespace = "alloc-example-install-1", bootNamespace + operation.CreationTimestamp = metav1.NewTime(created.Add(time.Second)) + good := ops.BootNetworkInput{AddressClaim: BootReference(claim.Name), Address: "198.51.100.10"} + if err := check.Verify(ctx, api, operation, "DeviceInstallation", good); err != nil { + t.Fatal(err) + } + refused := func(what string, operation ops.Operation, kind string, input ops.BootNetworkInput) { + t.Helper() + if err := check.Verify(ctx, api, operation, kind, input); !errors.Is(err, bootaddress.ErrUnavailable) || errors.Is(err, bootaddress.ErrUnreachable) { + t.Errorf("%s: %v", what, err) + } + } + other := &ops.DeviceInstallation{ObjectMeta: *operation.ObjectMeta.DeepCopy()} + other.Name = "alloc-example-install-2" + refused("another operation", other, "DeviceInstallation", good) + refused("another kind", operation, "DeviceWipe", good) + refused("another address", operation, "DeviceInstallation", ops.BootNetworkInput{AddressClaim: good.AddressClaim, Address: "198.51.100.11"}) + refused("IPAM's kind", operation, "DeviceInstallation", ops.BootNetworkInput{AddressClaim: bootaddress.Reference(claim.Name), Address: good.Address}) + if other, _ := NewBootAttachmentCheck(api.Scheme(), "", "customer-a"); !errors.Is(other.Verify(ctx, api, operation, "DeviceInstallation", good), bootaddress.ErrUnavailable) { + t.Errorf("a claim on another network verified: %v", err) + } + // Recreated after the operation, even with the same address. + claim.CreationTimestamp = metav1.NewTime(created.Add(2 * time.Second)) + if err := api.Update(ctx, claim); err != nil { + t.Fatal(err) + } + refused("recreated", operation, "DeviceInstallation", good) + claim.CreationTimestamp = metav1.NewTime(created) + if err := api.Update(ctx, claim); err != nil { + t.Fatal(err) + } + // Not programmed: the port is not on the boot network. + report(t, api, claim, "198.51.100.10/24", map[string]metav1.Condition{networkingv1.NetworkInterfaceClaimProgrammed: {Status: metav1.ConditionFalse}}) + refused("not programmed", operation, "DeviceInstallation", good) + report(t, api, claim, "198.51.100.10/24", programmedTrue) + if err := check.Verify(ctx, api, operation, "DeviceInstallation", good); err != nil { + t.Fatal(err) + } + down = true + if err := check.Verify(ctx, api, operation, "DeviceInstallation", good); !errors.Is(err, bootaddress.ErrUnreachable) || errors.Is(err, bootaddress.ErrUnavailable) { + t.Fatalf("an outage: %v", err) + } + down = false + // Being deleted, and then missing. + claim.Finalizers = []string{"networking.datumapis.com/physical-detach"} + if err := api.Update(ctx, claim); err != nil { + t.Fatal(err) + } + if err := api.Delete(ctx, claim); err != nil { + t.Fatal(err) + } + refused("being deleted", operation, "DeviceInstallation", good) + claim = bootClaim(t, api, "alloc-example-install-1") + claim.Finalizers = nil + if err := api.Update(ctx, claim); err != nil { + t.Fatal(err) + } + refused("missing", operation, "DeviceInstallation", good) +} + +// TestBootReleaseIsVerifiedInNSOAndIPAM counts a release only once NSO's +// claim is gone and IPAM holds no allocation for the address NSO claimed. A +// failed delete, or a claim NSO still keeps, stays held. +func TestBootReleaseIsVerifiedInNSOAndIPAM(t *testing.T) { + ctx := context.Background() + failing := false + source, api, allocation := bootFixture(t, interceptor.Funcs{ + Delete: func(ctx context.Context, c client.WithWatch, object client.Object, opts ...client.DeleteOption) error { + if failing { + return apierrors.NewInternalError(errors.New("nso could not delete")) + } + return c.Delete(ctx, object, opts...) + }, + }) + _ = source.Attach(ctx, allocation, "alloc-example-install-1") + claim := bootClaim(t, api, "alloc-example-install-1") + claim.Finalizers = []string{"networking.datumapis.com/physical-detach"} + if err := api.Update(ctx, claim); err != nil { + t.Fatal(err) + } + ipamAllocation := &unstructured.Unstructured{} + ipamAllocation.SetGroupVersionKind(bootaddress.AllocationGVK) + ipamAllocation.SetNamespace(ipamNamespace) + ipamAllocation.SetName("alloc-0123456789abcdef") + ipamAllocation.Object["spec"] = map[string]any{"claimRef": map[string]any{"name": BootAddressIPClaim(claim.Name)}} + if err := api.Create(ctx, ipamAllocation); err != nil { + t.Fatal(err) + } + + failing = true + if gone, err := source.Release(ctx, "alloc-example-install-1"); err == nil || gone { + t.Fatalf("a failed delete released: %v, %v", gone, err) + } + failing = false + // NSO keeps the claim until the port is off the boot network. + if gone, err := source.Release(ctx, "alloc-example-install-1"); err != nil || gone { + t.Fatalf("a claim NSO keeps released: %v, %v", gone, err) + } + if detached, err := source.Detach(ctx, "alloc-example-install-1"); err != nil || detached { + t.Fatalf("a claim NSO keeps detached: %v, %v", detached, err) + } + claim = bootClaim(t, api, "alloc-example-install-1") + claim.Finalizers = nil + if err := api.Update(ctx, claim); err != nil { + t.Fatal(err) + } + // The claim is gone, but IPAM still holds the address NSO claimed. + if gone, err := source.Release(ctx, "alloc-example-install-1"); !errors.Is(err, bootaddress.ErrReleaseUnverified) || gone { + t.Fatalf("a release with a remaining IPAM allocation: %v, %v", gone, err) + } + if err := api.Delete(ctx, ipamAllocation); err != nil { + t.Fatal(err) + } + // NSO may have claimed the address under the name for the location. + located := ipamAllocation.DeepCopy() + located.SetResourceVersion("") + located.SetName("alloc-fedcba9876543210") + located.Object["spec"] = map[string]any{"claimRef": map[string]any{"name": BootAddressIPClaims(claim.Name, location)[1]}} + if err := api.Create(ctx, located); err != nil { + t.Fatal(err) + } + if gone, err := source.Release(ctx, "alloc-example-install-1"); !errors.Is(err, bootaddress.ErrReleaseUnverified) || gone { + t.Fatalf("a release with an allocation under the location's name: %v, %v", gone, err) + } + if err := api.Delete(ctx, located); err != nil { + t.Fatal(err) + } + if gone, err := source.Release(ctx, "alloc-example-install-1"); err != nil || !gone { + t.Fatalf("release = %v, %v", gone, err) + } + if detached, err := source.Detach(ctx, "alloc-example-install-1"); err != nil || !detached { + t.Fatalf("detach = %v, %v", detached, err) + } + if _, err := (BootAttachments{Client: api, Namespace: bootNamespace, Kind: "DeviceInstallation", Network: bootNetwork}).Release(ctx, "alloc-example-install-1"); err == nil { + t.Fatal("a release without an IPAM reader was verified") + } +} + +func TestBootAddressIPClaimFollowsNSOsNaming(t *testing.T) { + if got := BootAddressIPClaim("alloc-example-install-1-boot"); got != "alloc-example-install-1-boot-f-ipv4" { + t.Fatalf("name = %q", got) + } + if long := BootAddressIPClaim(strings.Repeat("b", 260)); len(long) > 253 { + t.Fatalf("hashed name is %d characters", len(long)) + } + // NSO's location name: the first eight hex digits of SHA-256("location-example-a"). + names := BootAddressIPClaims("alloc-example-install-1-boot", location) + if len(names) != 2 || names[0] != "alloc-example-install-1-boot-f-ipv4" || names[1] != "alloc-example-install-1-boot-f-ipv4-l"+locationHash(location) { + t.Fatalf("names = %v", names) + } +} + +func locationHash(name string) string { + sum := sha256.Sum256([]byte(name)) + return hex.EncodeToString(sum[:])[:8] +} diff --git a/internal/site/redfishwork/dhcp_test.go b/internal/site/redfishwork/dhcp_test.go index 240031da..66304836 100644 --- a/internal/site/redfishwork/dhcp_test.go +++ b/internal/site/redfishwork/dhcp_test.go @@ -13,6 +13,7 @@ import ( "time" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/bootnet" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/site" @@ -32,7 +33,7 @@ func newRequest(method, url, body string) (*http.Request, error) { } func bootNetwork() *ops.BootNetworkInput { - return &ops.BootNetworkInput{AddressClaim: ops.LocalReference{Name: "alloc-example-install-boot"}, Address: address} + return &ops.BootNetworkInput{AddressClaim: fleetv1.TypedReference{APIGroup: "ipam.miloapis.com", Kind: "IPClaim", Name: "alloc-example-install-boot"}, Address: address} } // synchronizer stands in for one Kea instance and its synchronizer: each