diff --git a/config/components/boot-addresses/boot-address-requester.yaml b/config/components/boot-addresses/boot-address-requester.yaml index 9ac2b3a6..944a86dd 100644 --- a/config/components/boot-addresses/boot-address-requester.yaml +++ b/config/components/boot-addresses/boot-address-requester.yaml @@ -4,7 +4,7 @@ metadata: name: fleet.datumapis.com-boot-address-requester annotations: kubernetes.io/display-name: Fleet Boot Address Requester - kubernetes.io/description: The Fleet provider for Metal and the release controller at a site whose DHCP Fleet synchronizes. Claims and releases the boot address of each installation and wipe. + kubernetes.io/description: The Fleet provider for Metal and the release controller at a site whose DHCP Fleet synchronizes. Claims and releases the boot address of each installation and wipe, and reads IPAM's allocations to confirm a release. spec: launchStage: Alpha includedPermissions: @@ -12,3 +12,5 @@ spec: - ipam.miloapis.com/ipclaims.get - ipam.miloapis.com/ipclaims.list - ipam.miloapis.com/ipclaims.delete + - ipam.miloapis.com/ipallocations.get + - ipam.miloapis.com/ipallocations.list diff --git a/docs/operations/boot-network.md b/docs/operations/boot-network.md index 54fa0908..4e68bb94 100644 --- a/docs/operations/boot-network.md +++ b/docs/operations/boot-network.md @@ -80,12 +80,43 @@ between the claim and the operation still finds it. The IPAM permissions are in their own roles, in `config/components/boot-addresses`, which no overlay includes. The `boot-address-requester` role grants `create`, `get`, `list` and `delete` on -`ipclaims`, and the `boot-address-checker` role grants `get`. An environment +`ipclaims` and `get` and `list` on `ipallocations`, and the `boot-address-checker` role grants `get`. An environment that enables boot addresses includes that component and binds the requester role to the installation and wipe requesters and the checker role to the coordinator. The device operations roles every environment applies grant no IPAM permission. +### IPAM's claim contract + +Fleet follows the contract IPAM implements, not only its documentation: + +- IPAM binds a claim, or refuses it, in the create response. A second create + under the same name is a `409 Conflict` with a `ClaimExists` cause, so the + requester reads the existing claim instead. +- A full pool is a `507` with an `Exhausted` cause and, when one pool ran out, + its name. The requester reports `IPAM has no free provisioning address` and + creates no operation. A `400` refusal, such as an unknown class, is reported + as `IPAM refused the boot address claim` with IPAM's message, and also + creates no operation. Neither leaves a claim. +- IPAM rewrites the claim's class and family to the resolved class, keeps its + labels, and stamps its owner as the provider project. Fleet reads only the + labels and the bound address. +- Fleet uses a claim only if IPAM stored it with reclaim policy `Delete`, + which overrides the class's. A retaining claim, or a `409` such as + `AllocationRetained`, is refused: its address would outlive the claim. +- A delete releases the address and removes the claim and its allocation in + one transaction. IPAM ignores delete preconditions, so the claim's name and + labels are the guard. A release counts only when a read finds the claim gone + and no `IPAllocation` names it; because the claim deletes its allocation, a + claim found gone after a lost delete response was released. A failed delete + leaves the claim and its address held until a later call. +- A claim read at admission that fails for any reason but its absence leaves + the operation `Pending` with `BootAddressUnavailable`, never admitted, and + 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. + ## Enrollment The site enrollment (`FLEET_REDFISH_ENROLLMENT`) is the explicit mapping of the diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py index 622a0912..4981059f 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -97,10 +97,12 @@ def wait(fn,seconds,what): rules+=[{'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch','create','delete']},{'apiGroups':['metal.datumapis.com'],'resources':['machineallocations/status'],'verbs':['get','update']}, {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations'],'verbs':['get','list','watch','create']}, {'apiGroups':['fleet.datumapis.com'],'resources':['devices','devicecustodies','devicecommissionings','devicecommissioningplans','devicecommissioningplanapprovals'],'verbs':['get','list','watch']}] - # Each requester claims and releases its own boot addresses; the release - # controller reads custody to keep a held operation's claim. + # Each requester claims and releases its own boot addresses, and reads + # allocations to confirm a release; the release controller reads custody + # to keep a held operation's claim. claims={'apiGroups':['ipam.miloapis.com'],'resources':['ipclaims'],'verbs':['get','list','create','delete']} - if synced:rules.append(claims) + allocations={'apiGroups':['ipam.miloapis.com'],'resources':['ipallocations'],'verbs':['get','list']} + if synced:rules+=[claims,allocations] # The coordinator rules mirror config/components/device-operations/roles/ # coordinator.yaml: it lists and settles every registered operation kind. components={ @@ -109,7 +111,7 @@ def wait(fn,seconds,what): {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations/status','devicewipes/status','devicepoweroperations/status','devicerecoveries/status','devicecommissionings/status'],'verbs':['get','update']}, {'apiGroups':['fleet.datumapis.com'],'resources':['devicecommissioningplans','devicecommissioningplanapprovals'],'verbs':['get','list','watch']}, {'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch']}]+([{'apiGroups':['ipam.miloapis.com'],'resources':['ipclaims'],'verbs':['get']}] if synced else []), - 'release':[{'apiGroups':['fleet.datumapis.com'],'resources':['devicewipes'],'verbs':['get','create']}]+([claims,{'apiGroups':['fleet.datumapis.com'],'resources':['devicecustodies'],'verbs':['get']}] if synced else []), + 'release':[{'apiGroups':['fleet.datumapis.com'],'resources':['devicewipes'],'verbs':['get','create']}]+([claims,allocations,{'apiGroups':['fleet.datumapis.com'],'resources':['devicecustodies'],'verbs':['get']}] if synced else []), # The capacity projector is the only writer of capacity status. 'projector':[{'apiGroups':['metal.datumapis.com'],'resources':['machinecapacities'],'verbs':['get','list','watch']},{'apiGroups':['metal.datumapis.com'],'resources':['machinecapacities/status'],'verbs':['get','update']}, {'apiGroups':['fleet.datumapis.com'],'resources':['devices','devicecustodies','devicecommissionings','devicecommissioningplans','devicecommissioningplanapprovals'],'verbs':['get','list','watch']}], diff --git a/internal/allocation/bootaddress_test.go b/internal/allocation/bootaddress_test.go index 3457a72b..0a6b4eb7 100644 --- a/internal/allocation/bootaddress_test.go +++ b/internal/allocation/bootaddress_test.go @@ -3,10 +3,14 @@ package allocation import ( "context" "encoding/json" + "errors" "fmt" + "net/http" + "strings" "sync" "testing" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "sigs.k8s.io/controller-runtime/pkg/client" @@ -248,3 +252,37 @@ func TestBootAddressesFollowTheirOperations(t *testing.T) { t.Fatalf("phase = %s", allocation.Status.Phase) } } + +// exhausted refuses every IPAM claim as IPAM does when its pool is full. +type exhausted struct{ client.Client } + +func (c exhausted) Create(ctx context.Context, object client.Object, options ...client.CreateOption) error { + if claim, ok := object.(*unstructured.Unstructured); ok && claim.GroupVersionKind() == bootaddress.GVK { + return &apierrors.StatusError{ErrStatus: metav1.Status{ + Status: metav1.StatusFailure, Code: http.StatusInsufficientStorage, Reason: "InsufficientStorage", + Details: &metav1.StatusDetails{Name: "lab-provisioning", Causes: []metav1.StatusCause{{Type: "Exhausted"}}}, + }} + } + return c.Client.Create(ctx, object, options...) +} + +// TestAnExhaustedPoolSendsNothing refuses the installation with IPAM's +// reason and creates no operation, so nothing reaches the site. +func TestAnExhaustedPoolSendsNothing(t *testing.T) { + e := startEnv(t) + e.allocator.Provider = exhausted{e.admin} + e.allocator.BootAddresses = &bootaddress.Claimer{Class: "provisioning"} + e.server(1) + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + installation := e.installation(1, "debian-12", "") + if _, err := e.allocator.Install(e.ctx, allocation, Installation{Installation: installation}); !errors.Is(err, bootaddress.ErrExhausted) || !strings.Contains(err.Error(), "lab-provisioning") { + t.Fatalf("install with a full pool: %v", err) + } + operations := &ops.DeviceInstallationList{} + if err := e.admin.List(e.ctx, operations, client.InNamespace(e.allocator.Namespace)); err != nil || len(operations.Items) != 0 { + t.Fatalf("operations = %d, %v", len(operations.Items), err) + } +} diff --git a/internal/api/operations/v1alpha1/config_test.go b/internal/api/operations/v1alpha1/config_test.go index e06a8e84..39401e5a 100644 --- a/internal/api/operations/v1alpha1/config_test.go +++ b/internal/api/operations/v1alpha1/config_test.go @@ -514,7 +514,8 @@ func TestBootAddressRolesAreOptIn(t *testing.T) { return out } want := map[string][]string{ - "fleet.datumapis.com-boot-address-requester": claims("create", "delete", "get", "list"), + // Requesters also read IPAM's allocations to confirm a release. + "fleet.datumapis.com-boot-address-requester": append(claims("create", "delete", "get", "list"), "ipam.miloapis.com/ipallocations.get", "ipam.miloapis.com/ipallocations.list"), "fleet.datumapis.com-boot-address-checker": claims("get"), } roles := decodeDir[role](t, root) @@ -522,9 +523,10 @@ func TestBootAddressRolesAreOptIn(t *testing.T) { t.Fatalf("boot address roles = %d, want %d", len(roles), len(want)) } for _, r := range roles { - actual := slices.Clone(r.Spec.Included) + actual, expected := slices.Clone(r.Spec.Included), slices.Clone(want[r.Metadata.Name]) slices.Sort(actual) - if !slices.Equal(actual, want[r.Metadata.Name]) || len(r.Spec.Inherited) != 0 { + slices.Sort(expected) + if !slices.Equal(actual, expected) || len(r.Spec.Inherited) != 0 { t.Fatalf("%s = %v, want %v", r.Metadata.Name, actual, want[r.Metadata.Name]) } } diff --git a/internal/bootaddress/bootaddress.go b/internal/bootaddress/bootaddress.go index dc40866c..c8925637 100644 --- a/internal/bootaddress/bootaddress.go +++ b/internal/bootaddress/bootaddress.go @@ -8,12 +8,20 @@ // after its recovery hold is settled. Fleet reads only the claim's bound // address; the gateway and prefix stay in the DHCP owner's base // configuration. +// +// It follows IPAM's claim contract: IPAM binds a claim, or refuses it, in the +// create response; a second create under the same name is a conflict; and a +// delete releases the address and removes the claim and its allocation in +// one transaction, ignoring delete preconditions. Fleet uses only claims +// whose stored reclaim policy is Delete, which overrides the class's: a claim +// IPAM retained would leave its address allocated after the claim is gone. package bootaddress import ( "context" "errors" "fmt" + "net/http" "net/netip" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -27,6 +35,9 @@ import ( // GVK is IPAM's address claim. var GVK = schema.GroupVersionKind{Group: "ipam.miloapis.com", Version: "v1alpha1", Kind: "IPClaim"} +// AllocationGVK is IPAM's record of an address held for a claim. +var AllocationGVK = schema.GroupVersionKind{Group: "ipam.miloapis.com", Version: "v1alpha1", Kind: "IPAllocation"} + // Labels name the allocation and operation a claim belongs to. const ( AllocationLabel = "fleet.datumapis.com/allocation" @@ -42,8 +53,64 @@ var ( ErrUnavailable = errors.New("the boot address claim does not hold the admitted address") // ErrConflict means a claim with the operation's name has other inputs. ErrConflict = errors.New("the boot address claim has other inputs") + // ErrExhausted means IPAM has no free provisioning address. Nothing was + // claimed, so the operation must not be created. + ErrExhausted = errors.New("IPAM has no free provisioning address") + // ErrRefused means IPAM refused the claim, for example for a class or + // scope it does not know. Nothing was claimed. + ErrRefused = errors.New("IPAM refused the boot address claim") + // ErrUnreachable means IPAM could not be read, so a claim's state is + // unknown. Admission waits rather than deciding. + ErrUnreachable = errors.New("IPAM could not be read") + // ErrReleaseUnverified means the claim is gone but IPAM still records an + // allocation for it. + ErrReleaseUnverified = errors.New("the boot address is still allocated") ) +// ipamCause returns the first IPAM cause type of an API error, such as +// ClaimExists or Exhausted, and the error's status. +func ipamCause(err error) (string, *apierrors.StatusError) { + var status *apierrors.StatusError + if !errors.As(err, &status) { + return "", nil + } + if details := status.ErrStatus.Details; details != nil { + for _, cause := range details.Causes { + if cause.Type != "" { + return string(cause.Type), status + } + } + } + return "", status +} + +// createError classifies IPAM's refusal of a claim create. IPAM reports +// exhaustion as 507, with an Exhausted cause and the pool's name when one +// pool ran out, and other refusals of the claim as 400, 409 or 422 with a +// cause. A ClaimExists conflict is handled before this. +func createError(err error) error { + cause, status := ipamCause(err) + switch { + case status == nil: + return err + case status.ErrStatus.Code == http.StatusInsufficientStorage || cause == "Exhausted": + if details := status.ErrStatus.Details; details != nil && details.Name != "" { + return fmt.Errorf("%w: pool %s is full", ErrExhausted, details.Name) + } + return ErrExhausted + case apierrors.IsBadRequest(err) || apierrors.IsInvalid(err) || apierrors.IsConflict(err): + return fmt.Errorf("%w: %s", ErrRefused, status.ErrStatus.Message) + } + return err +} + +// claimExists reports whether a create lost to a claim of the same name. +// IPAM answers 409 Conflict with a ClaimExists cause. +func claimExists(err error) bool { + cause, _ := ipamCause(err) + return apierrors.IsAlreadyExists(err) || (apierrors.IsConflict(err) && cause == "ClaimExists") +} + // ClaimName is the only name an operation's boot address claim may have. func ClaimName(operation string) string { return operation + "-boot" } @@ -89,7 +156,8 @@ func (c Claimer) desired(allocation, operation string) *unstructured.Unstructure } // Claim returns the operation's bound boot address, creating its claim once. -// It returns ErrPending until IPAM binds the claim. +// It returns ErrPending until IPAM binds the claim, and ErrExhausted or +// ErrRefused when IPAM refuses it. func (c Claimer) Claim(ctx context.Context, allocation, operation string) (*ops.BootNetworkInput, error) { if c.Client == nil || c.Namespace == "" || c.Class == "" || c.Kind == "" || allocation == "" || operation == "" { return nil, errors.New("bootaddress: a client, namespace, class, kind, allocation and operation are required") @@ -97,15 +165,15 @@ func (c Claimer) Claim(ctx context.Context, allocation, operation string) (*ops. desired := c.desired(allocation, operation) claim, err := c.get(ctx, desired.GetName()) if apierrors.IsNotFound(err) { - if err := c.Client.Create(ctx, desired); err != nil && !apierrors.IsAlreadyExists(err) { - return nil, err + if err := c.Client.Create(ctx, desired); err != nil && !claimExists(err) { + return nil, createError(err) } claim, err = c.get(ctx, desired.GetName()) } if err != nil { return nil, err } - if labels := claim.GetLabels(); labels[OperationLabel] != operation || labels[AllocationLabel] != allocation || labels[KindLabel] != c.Kind { + if labels := claim.GetLabels(); labels[OperationLabel] != operation || labels[AllocationLabel] != allocation || labels[KindLabel] != c.Kind || !deletes(claim) { return nil, fmt.Errorf("%w: %s", ErrConflict, claim.GetName()) } address, err := bound(claim) @@ -115,12 +183,18 @@ func (c Claimer) Claim(ctx context.Context, allocation, operation string) (*ops. return &ops.BootNetworkInput{AddressClaim: ops.LocalReference{Name: claim.GetName()}, Address: address}, nil } -// Release deletes the operation's claim. It returns true once the claim is -// gone. +// Release deletes the operation's claim. It returns true only once the +// release is verified: the claim is gone and IPAM records no allocation for +// it. The claim's reclaim policy is Delete, so IPAM removes its allocation in +// the transaction that removes the claim, and a claim found gone, even after +// a delete whose response was lost, was released. A delete that fails leaves +// the claim, and its address, held for a later call. IPAM ignores delete +// preconditions, so the claim's name and labels are the guard: a claim under +// the operation's name with its labels is that operation's claim. func (c Claimer) Release(ctx context.Context, operation string) (bool, error) { claim, err := c.get(ctx, ClaimName(operation)) if apierrors.IsNotFound(err) { - return true, nil + return c.unallocated(ctx, ClaimName(operation)) } if err != nil { return false, err @@ -128,13 +202,28 @@ func (c Claimer) Release(ctx context.Context, operation string) (bool, error) { if claim.GetLabels()[OperationLabel] != operation || claim.GetLabels()[KindLabel] != c.Kind { return false, fmt.Errorf("%w: %s", ErrConflict, claim.GetName()) } - if claim.GetDeletionTimestamp() == nil { - uid := claim.GetUID() - if err := c.Client.Delete(ctx, claim, client.Preconditions{UID: &uid}); err != nil && !apierrors.IsNotFound(err) { - return false, err + if err := c.Client.Delete(ctx, claim); err != nil && !apierrors.IsNotFound(err) { + return false, err + } + if _, err := c.get(ctx, claim.GetName()); !apierrors.IsNotFound(err) { + return false, err + } + return c.unallocated(ctx, claim.GetName()) +} + +// unallocated reports whether no IPAM allocation names the claim. +func (c Claimer) unallocated(ctx context.Context, 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 { + return false, err + } + for _, allocation := range list.Items { + if stringAt(&allocation, "spec", "claimRef", "name") == claim { + return false, fmt.Errorf("%w: %s holds it for %s", ErrReleaseUnverified, allocation.GetName(), claim) } } - return false, nil + return true, nil } // Operations returns the operations of the claimer's kind in an allocation @@ -165,7 +254,8 @@ func (c Claimer) get(ctx context.Context, name string) (*unstructured.Unstructur // address. The requester creates the claim before the operation, so a claim // created after its operation is a recreation, never the claim the operation // was built from, and is refused. Admission calls it with the provider -// project's reader. +// project's reader. It returns ErrUnreachable when the claim cannot be read +// for any reason but its absence, and ErrUnavailable otherwise. func Verify(ctx context.Context, reader client.Reader, operation ops.Operation, kind string, input ops.BootNetworkInput) error { if reader == nil { return ErrUnavailable @@ -176,8 +266,10 @@ func Verify(ctx context.Context, reader client.Reader, operation ops.Operation, } claim := &unstructured.Unstructured{} claim.SetGroupVersionKind(GVK) - if err := reader.Get(ctx, client.ObjectKey{Namespace: namespace, Name: input.AddressClaim.Name}, claim); err != nil { + if err := reader.Get(ctx, client.ObjectKey{Namespace: namespace, Name: input.AddressClaim.Name}, claim); apierrors.IsNotFound(err) { return fmt.Errorf("%w: %v", ErrUnavailable, err) + } else if err != nil { + return fmt.Errorf("%w: %v", ErrUnreachable, err) } created, opened := claim.GetCreationTimestamp(), operation.GetCreationTimestamp() if claim.GetDeletionTimestamp() != nil || created.IsZero() || opened.IsZero() || created.After(opened.Time) { @@ -186,6 +278,9 @@ func Verify(ctx context.Context, reader client.Reader, operation ops.Operation, if labels := claim.GetLabels(); labels[OperationLabel] != operation.GetName() || labels[KindLabel] != kind { return fmt.Errorf("%w: the claim belongs to another operation", ErrUnavailable) } + if !deletes(claim) { + return fmt.Errorf("%w: the claim would retain its address after release", ErrUnavailable) + } address, err := bound(claim) if err != nil { return fmt.Errorf("%w: %v", ErrUnavailable, err) @@ -197,6 +292,11 @@ func Verify(ctx context.Context, reader client.Reader, operation ops.Operation, return nil } +// deletes reports whether IPAM stored the claim with reclaim policy Delete. +func deletes(claim *unstructured.Unstructured) bool { + return stringAt(claim, "spec", "reclaimPolicy") == "Delete" +} + // bound returns a bound claim's IPv4 host address in canonical form. func bound(claim *unstructured.Unstructured) (string, error) { if stringAt(claim, "status", "phase") != "Bound" { diff --git a/internal/bootaddress/bootaddress_test.go b/internal/bootaddress/bootaddress_test.go index e12eae63..142a20dd 100644 --- a/internal/bootaddress/bootaddress_test.go +++ b/internal/bootaddress/bootaddress_test.go @@ -3,14 +3,18 @@ package bootaddress import ( "context" "errors" + "net/http" + "strings" "testing" "time" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" ) @@ -18,14 +22,36 @@ import ( const namespace = "fleet-provider" func claimer(t *testing.T, objects ...client.Object) (Claimer, client.Client) { + t.Helper() + return claimerWith(t, interceptor.Funcs{}, objects...) +} + +// claimerWith builds a claimer whose client calls pass through funcs, so a +// test can make IPAM answer as it does. +func claimerWith(t *testing.T, funcs interceptor.Funcs, objects ...client.Object) (Claimer, client.Client) { t.Helper() scheme := runtime.NewScheme() scheme.AddKnownTypeWithName(GVK, &unstructured.Unstructured{}) scheme.AddKnownTypeWithName(GVK.GroupVersion().WithKind("IPClaimList"), &unstructured.UnstructuredList{}) - c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objects...).Build() + scheme.AddKnownTypeWithName(AllocationGVK, &unstructured.Unstructured{}) + scheme.AddKnownTypeWithName(AllocationGVK.GroupVersion().WithKind("IPAllocationList"), &unstructured.UnstructuredList{}) + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objects...).WithInterceptorFuncs(funcs).Build() return Claimer{Client: c, Namespace: namespace, Class: "provisioning", Kind: "DeviceInstallation"}, c } +// ipamStatus is an IPAM refusal as IPAM writes it: an HTTP code, a reason, and +// one cause naming IPAM's own refusal. +func ipamStatus(code int32, reason metav1.StatusReason, cause, pool string) error { + return &apierrors.StatusError{ErrStatus: metav1.Status{ + Status: metav1.StatusFailure, Code: code, Reason: reason, Message: cause, + Details: &metav1.StatusDetails{Name: pool, Causes: []metav1.StatusCause{{Type: metav1.CauseType(cause)}}}, + }} +} + +func isClaim(object client.Object) bool { + return object.GetObjectKind().GroupVersionKind().Kind == GVK.Kind +} + func bind(t *testing.T, c client.Client, name, phase, address string) *unstructured.Unstructured { t.Helper() claim := &unstructured.Unstructured{} @@ -135,10 +161,248 @@ func TestVerifyRequiresTheExactBoundIncarnation(t *testing.T) { if err := Verify(ctx, nil, operation, "DeviceInstallation", good); !errors.Is(err, ErrUnavailable) { t.Fatal("no reader verified") } - if gone, err := c.Release(ctx, "alloc-a-install-1"); err != nil || gone { + if gone, err := c.Release(ctx, "alloc-a-install-1"); err != nil || !gone { t.Fatalf("release = %v, %v", gone, err) } if gone, err := c.Release(ctx, "alloc-a-install-1"); err != nil || !gone { t.Fatalf("second release = %v, %v", gone, err) } } + +// TestClaimFollowsIPAMsCreateContract finds the claim a racing create made, +// which IPAM reports as a ClaimExists conflict, and reports exhaustion and +// other refusals without leaving a claim behind. +func TestClaimFollowsIPAMsCreateContract(t *testing.T) { + ctx := context.Background() + var refusal error + raced := false + c, api := claimerWith(t, interceptor.Funcs{Create: func(ctx context.Context, api client.WithWatch, object client.Object, opts ...client.CreateOption) error { + if !isClaim(object) { + return api.Create(ctx, object, opts...) + } + if refusal != nil { + return refusal + } + if raced { + // Another reconcile created the claim first. + if err := api.Create(ctx, object.DeepCopyObject().(client.Object), opts...); err != nil { + return err + } + return ipamStatus(http.StatusConflict, metav1.StatusReasonConflict, "ClaimExists", "") + } + return api.Create(ctx, object, opts...) + }}) + raced = true + if _, err := c.Claim(ctx, "alloc-a", "alloc-a-install-1"); !errors.Is(err, ErrPending) { + t.Fatalf("a create that lost the race: %v", err) + } + bind(t, api, "alloc-a-install-1-boot", "Bound", "198.51.100.10") + if input, err := c.Claim(ctx, "alloc-a", "alloc-a-install-1"); err != nil || input.Address != "198.51.100.10" { + t.Fatalf("input = %+v, %v", input, err) + } + raced = false + for name, tc := range map[string]struct { + err error + want error + text string + }{ + "exhausted pool": {ipamStatus(http.StatusInsufficientStorage, "InsufficientStorage", "Exhausted", "lab-provisioning"), ErrExhausted, "pool lab-provisioning is full"}, + "exhausted parent": {ipamStatus(http.StatusInsufficientStorage, "InsufficientStorage", "Exhausted", ""), ErrExhausted, ""}, + "unknown class": {ipamStatus(http.StatusBadRequest, metav1.StatusReasonBadRequest, "ClassNotFound", ""), ErrRefused, "ClassNotFound"}, + "retained name": {ipamStatus(http.StatusConflict, metav1.StatusReasonConflict, "AllocationRetained", ""), ErrRefused, "AllocationRetained"}, + } { + refusal = tc.err + operation := "alloc-a-install-" + strings.ReplaceAll(name, " ", "-") + _, err := c.Claim(ctx, "alloc-a", operation) + if !errors.Is(err, tc.want) || !strings.Contains(err.Error(), tc.text) { + t.Errorf("%s: %v", name, err) + } + claim := &unstructured.Unstructured{} + claim.SetGroupVersionKind(GVK) + if err := api.Get(ctx, client.ObjectKey{Namespace: namespace, Name: ClaimName(operation)}, claim); !apierrors.IsNotFound(err) { + t.Errorf("%s: a refused claim exists: %v", name, err) + } + } + // An outage is neither a refusal nor an exhaustion. + refusal = apierrors.NewServiceUnavailable("ipam is down") + if _, err := c.Claim(ctx, "alloc-a", "alloc-a-install-down"); err == nil || errors.Is(err, ErrExhausted) || errors.Is(err, ErrRefused) { + t.Fatalf("an outage: %v", err) + } +} + +// TestReleaseIsVerifiedAndAnUnknownOutcomeKeepsTheAddressHeld returns true +// only when the claim is gone and no allocation names it. A delete that +// fails, or whose response is lost, returns false, and a later call settles +// it. +func TestReleaseIsVerifiedAndAnUnknownOutcomeKeepsTheAddressHeld(t *testing.T) { + ctx := context.Background() + mode := "" + c, api := claimerWith(t, interceptor.Funcs{Delete: func(ctx context.Context, api client.WithWatch, object client.Object, opts ...client.DeleteOption) error { + switch mode { + case "accepted": + // A delete that succeeds while the claim is still there is not a + // release. + return nil + case "fails": + // IPAM could not release, and the claim stays Releasing. + return apierrors.NewInternalError(errors.New("release allocation after 3 attempts")) + case "lost": + // IPAM released it, but the response never arrived. + if err := api.Delete(ctx, object, opts...); err != nil { + return err + } + return apierrors.NewTimeoutError("the response was lost", 1) + } + return api.Delete(ctx, object, opts...) + }}) + claim := func(operation string) { + t.Helper() + if _, err := c.Claim(ctx, "alloc-a", operation); !errors.Is(err, ErrPending) { + t.Fatal(err) + } + bind(t, api, ClaimName(operation), "Bound", "198.51.100.10") + } + exists := func(operation string) bool { + t.Helper() + claim := &unstructured.Unstructured{} + claim.SetGroupVersionKind(GVK) + err := api.Get(ctx, client.ObjectKey{Namespace: namespace, Name: ClaimName(operation)}, claim) + if err != nil && !apierrors.IsNotFound(err) { + t.Fatal(err) + } + return err == nil + } + + claim("alloc-a-install-1") + mode = "fails" + if gone, err := c.Release(ctx, "alloc-a-install-1"); err == nil || gone || !exists("alloc-a-install-1") { + t.Fatalf("a failed release = %v, %v", gone, err) + } + mode = "accepted" + if gone, err := c.Release(ctx, "alloc-a-install-1"); err != nil || gone || !exists("alloc-a-install-1") { + t.Fatalf("a release that left the claim = %v, %v", gone, err) + } + mode = "" + if gone, err := c.Release(ctx, "alloc-a-install-1"); err != nil || !gone { + t.Fatalf("the retried release = %v, %v", gone, err) + } + + claim("alloc-a-install-2") + mode = "lost" + if gone, err := c.Release(ctx, "alloc-a-install-2"); err == nil || gone { + t.Fatalf("a release with a lost response = %v, %v", gone, err) + } + mode = "" + if gone, err := c.Release(ctx, "alloc-a-install-2"); err != nil || !gone { + t.Fatalf("the release read after a lost response = %v, %v", gone, err) + } + + // The claim is gone, but IPAM still records an allocation for it. + allocation := &unstructured.Unstructured{} + allocation.SetGroupVersionKind(AllocationGVK) + allocation.SetNamespace(namespace) + allocation.SetName("alloc-0123456789abcdef") + allocation.Object["spec"] = map[string]any{"claimRef": map[string]any{"name": ClaimName("alloc-a-install-3")}} + if err := api.Create(ctx, allocation); err != nil { + t.Fatal(err) + } + if gone, err := c.Release(ctx, "alloc-a-install-3"); !errors.Is(err, ErrReleaseUnverified) || gone { + t.Fatalf("a release with a remaining allocation = %v, %v", gone, err) + } + + // The delete removes the claim, but an allocation still names it. + claim("alloc-a-install-4") + held := allocation.DeepCopy() + held.SetName("alloc-fedcba9876543210") + held.SetResourceVersion("") + held.Object["spec"] = map[string]any{"claimRef": map[string]any{"name": ClaimName("alloc-a-install-4")}} + if err := api.Create(ctx, held); err != nil { + t.Fatal(err) + } + if gone, err := c.Release(ctx, "alloc-a-install-4"); !errors.Is(err, ErrReleaseUnverified) || gone || exists("alloc-a-install-4") { + t.Fatalf("a deleted claim whose allocation remains = %v, %v", gone, err) + } +} + +// TestVerifyWaitsWhenIPAMCannotBeRead tells an outage, which admission +// waits out, from a missing claim, which it refuses. +func TestVerifyWaitsWhenIPAMCannotBeRead(t *testing.T) { + ctx := context.Background() + down := false + _, api := claimerWith(t, interceptor.Funcs{Get: func(ctx context.Context, api client.WithWatch, key client.ObjectKey, object client.Object, opts ...client.GetOption) error { + if down && isClaim(object) { + return apierrors.NewServiceUnavailable("ipam is down") + } + return api.Get(ctx, key, object, opts...) + }}) + 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"} + if err := Verify(ctx, api, operation, "DeviceInstallation", input); !errors.Is(err, ErrUnavailable) || errors.Is(err, ErrUnreachable) { + t.Fatalf("a missing claim: %v", err) + } + down = true + if err := Verify(ctx, api, operation, "DeviceInstallation", input); !errors.Is(err, ErrUnreachable) || errors.Is(err, ErrUnavailable) { + t.Fatalf("an outage: %v", err) + } +} + +// TestARecreatedMachineInheritsNoClaim gives a recreated Machine, whose +// allocation is named from its new identity, a claim of its own, and leaves +// the earlier allocation's claim to that allocation's release. +func TestARecreatedMachineInheritsNoClaim(t *testing.T) { + ctx := context.Background() + c, api := claimer(t) + if _, err := c.Claim(ctx, "alloc-old", "alloc-old-install-1"); !errors.Is(err, ErrPending) { + t.Fatal(err) + } + bind(t, api, "alloc-old-install-1-boot", "Bound", "198.51.100.10") + if _, err := c.Claim(ctx, "alloc-new", "alloc-new-install-1"); !errors.Is(err, ErrPending) { + t.Fatalf("the recreated Machine's claim: %v", err) + } + if operations, err := c.Operations(ctx, "alloc-new"); err != nil || len(operations) != 1 || operations[0] != "alloc-new-install-1" { + t.Fatalf("operations = %v, %v", operations, err) + } + // Reusing the earlier operation's name from the new allocation is a + // conflict, not an inherited address. + if _, err := c.Claim(ctx, "alloc-new", "alloc-old-install-1"); !errors.Is(err, ErrConflict) { + t.Fatalf("the earlier claim was inherited: %v", err) + } +} + +// TestARetainingClaimIsNeverUsed refuses a claim IPAM stored with any reclaim +// policy but Delete, whose address would outlive the claim, both to its +// requester and at admission. +func TestARetainingClaimIsNeverUsed(t *testing.T) { + ctx := context.Background() + c, api := claimer(t) + if _, err := c.Claim(ctx, "alloc-a", "alloc-a-install-1"); !errors.Is(err, ErrPending) { + t.Fatal(err) + } + claim := bind(t, api, "alloc-a-install-1-boot", "Bound", "198.51.100.10") + created := time.Date(2026, 11, 25, 12, 0, 0, 0, time.UTC) + claim.SetCreationTimestamp(metav1.NewTime(created)) + if err := api.Update(ctx, claim); err != nil { + t.Fatal(err) + } + 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"} + if err := Verify(ctx, api, operation, "DeviceInstallation", input); err != nil { + t.Fatal(err) + } + if err := unstructured.SetNestedField(claim.Object, "Retain", "spec", "reclaimPolicy"); err != nil { + t.Fatal(err) + } + if err := api.Update(ctx, claim); err != nil { + t.Fatal(err) + } + if _, err := c.Claim(ctx, "alloc-a", "alloc-a-install-1"); !errors.Is(err, ErrConflict) { + t.Fatalf("a retaining claim was used: %v", err) + } + if err := Verify(ctx, api, operation, "DeviceInstallation", input); !errors.Is(err, ErrUnavailable) { + t.Fatalf("a retaining claim verified: %v", err) + } +} diff --git a/internal/bootaddress/testdata/ipclaims.yaml b/internal/bootaddress/testdata/ipclaims.yaml index da73ce77..ac39c3b8 100644 --- a/internal/bootaddress/testdata/ipclaims.yaml +++ b/internal/bootaddress/testdata/ipclaims.yaml @@ -1,6 +1,7 @@ -# A stand-in for IPAM's IPClaim. IPAM serves the real kind from its own -# aggregated API server. Envtest and the Redfish lab's synchronized DHCP mode -# have none, so this CRD keeps only the fields Fleet reads. No deployment +# Stand-ins for IPAM's IPClaim and IPAllocation. IPAM serves the real kinds +# from its own aggregated API server. Envtest and the Redfish lab's +# synchronized DHCP mode have none, so these CRDs keep only the fields Fleet +# reads. No deployment # bundle includes it. apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition @@ -21,3 +22,25 @@ spec: properties: spec: {type: object, x-kubernetes-preserve-unknown-fields: true} status: {type: object, x-kubernetes-preserve-unknown-fields: true} +--- +# A stand-in for IPAM's IPAllocation, which Fleet lists to confirm that a +# released claim's address is no longer allocated. +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: ipallocations.ipam.miloapis.com +spec: + group: ipam.miloapis.com + names: {kind: IPAllocation, listKind: IPAllocationList, plural: ipallocations, singular: ipallocation} + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: {status: {}} + schema: + openAPIV3Schema: + type: object + properties: + spec: {type: object, x-kubernetes-preserve-unknown-fields: true} + status: {type: object, x-kubernetes-preserve-unknown-fields: true} diff --git a/internal/custody/admission_test.go b/internal/custody/admission_test.go index 569d692e..11fb76f9 100644 --- a/internal/custody/admission_test.go +++ b/internal/custody/admission_test.go @@ -1,6 +1,7 @@ package custody import ( + "context" "fmt" "reflect" "testing" @@ -9,11 +10,22 @@ import ( inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" "go.datum.net/fleet/internal/bootaddress" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "sigs.k8s.io/controller-runtime/pkg/client" ) +// ipamDown answers every IPAM claim read as an outage. +type ipamDown struct{ client.Client } + +func (c ipamDown) Get(ctx context.Context, key client.ObjectKey, object client.Object, opts ...client.GetOption) error { + if object.GetObjectKind().GroupVersionKind().Group == bootaddress.GVK.Group { + return apierrors.NewServiceUnavailable("ipam is down") + } + return c.Client.Get(ctx, key, object, opts...) +} + // requireUntouched fails if custody admitted anything or raised the fence. func (e *env) requireUntouched(name string, fence int64) { e.t.Helper() @@ -325,6 +337,14 @@ func TestAdmissionPreconditions(t *testing.T) { } e.requireUntouched(device.Name, fence) admitted := withAddress("bound", good) + // While IPAM cannot be read, the claim's state is unknown: the + // operation waits, admitted no further, and is checked again. + outage := e.coordinator(ipamDown{e.admin}) + if outcome := settleWith(t, e.ctx, outage, device.Name); outcome.RequeueAfter == 0 { + t.Fatalf("an undecided check did not ask to run again: %+v", outcome) + } + e.requirePhase(admitted, ops.PhasePending, ReasonBootAddress) + e.requireUntouched(device.Name, fence) e.settle(device.Name) if active := e.custody(device.Name).Spec.ActiveOperation; active == nil || active.Name != admitted.Name || active.Snapshot.BootMACAddress == "" { t.Fatalf("active = %+v, want the bound installation with the boot MAC from inventory", active) diff --git a/internal/custody/coordinator.go b/internal/custody/coordinator.go index bd35e444..4753759f 100644 --- a/internal/custody/coordinator.go +++ b/internal/custody/coordinator.go @@ -593,8 +593,14 @@ type decision struct { row Rule settles *ops.HeldOperationReference extra map[string]string + // retry means a check could not decide; the operation waits and is + // checked again. + retry bool } +// undecidedRetry is how soon a check that could not decide runs again. +const undecidedRetry = 5 * time.Second + // admit evaluates pending candidates and admits at most one with a single // conditional custody update. func (c *Coordinator) admit(ctx context.Context, custody *ops.DeviceCustody, device *inventory.Device) (Outcome, error) { @@ -616,6 +622,7 @@ func (c *Coordinator) admit(ctx context.Context, custody *ops.DeviceCustody, dev superseded := c.superseded(candidates, custody) queued := false changed := false + var requeue time.Duration for _, candidate := range candidates { operation, kind := candidate.operation, candidate.kind var d decision @@ -640,8 +647,11 @@ func (c *Coordinator) admit(ctx context.Context, custody *ops.DeviceCustody, dev return Outcome{}, err } changed = changed || wrote + if d.retry { + requeue = undecidedRetry + } } - return Outcome{Changed: changed}, nil + return Outcome{Changed: changed, RequeueAfter: requeue}, nil } // superseded returns pending operations replaced by a newer one of the same @@ -802,6 +812,12 @@ func (c *Coordinator) decide(ctx context.Context, kind *Kind, operation ops.Oper // that is not recorded, is the one reported. if kind.Check != nil { if refusal := c.Registry.declaredRefusal(kind.GVK.Kind, settleHookKind(kind, row, custody), kind.Check(ctx, admission)); refusal != nil { + // An undecided check is not a refusal: every row waits for + // it, and a staff operation still expires if it is never + // admitted. + if refusal.Retry { + return decision{phase: ops.PhasePending, reason: refusal.Reason, message: refusal.Message, retry: true} + } if since := waitingSince(operation, custody); row.Queue && refusal.Wait > 0 && now.Before(since.Add(refusal.Wait)) { return decision{phase: ops.PhasePending, reason: refusal.Reason, message: "waiting: " + refusal.Message} } diff --git a/internal/custody/harness_test.go b/internal/custody/harness_test.go index 7ad36e9e..9d279b8c 100644 --- a/internal/custody/harness_test.go +++ b/internal/custody/harness_test.go @@ -367,7 +367,7 @@ func (e *env) ipClaim(name, operation, kind, phase, address string) *unstructure claim.SetNamespace("default") claim.SetName(name) claim.SetLabels(map[string]string{bootaddress.OperationLabel: operation, bootaddress.KindLabel: kind}) - claim.Object["spec"] = map[string]any{"className": "provisioning"} + claim.Object["spec"] = map[string]any{"className": "provisioning", "reclaimPolicy": "Delete"} if err := e.admin.Create(e.ctx, claim); err != nil { e.t.Fatal(err) } diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index 66c37a03..09bdc60c 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -83,7 +83,12 @@ 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); err != nil { + if err := bootaddress.Verify(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.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 nil diff --git a/internal/custody/registry.go b/internal/custody/registry.go index 577cdd1f..da6e5526 100644 --- a/internal/custody/registry.go +++ b/internal/custody/registry.go @@ -230,6 +230,10 @@ type Refusal struct { // waiting for current discovery does. Any other row's operation ends // Failed at once. Zero never waits. Wait time.Duration + // Retry means the check could not decide, for example because a service + // it reads is unreachable. The operation stays Pending and is checked + // again; it is never admitted on an undecided check. + Retry bool } func (r *Refusal) Error() string { return r.Reason + ": " + r.Message }