// SPDX-License-Identifier: Apache-2.0 /* Copyright 2026 Cozystack contributors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package k8s import ( "context" "maps" "slices" "sort" "strconv" "github.com/cockroachdb/errors" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/util/retry" ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/log" crdv1alpha1 "github.com/cozystack/blockstor/api/v1alpha1" apiv1 "github.com/cozystack/blockstor/pkg/api/v1" "github.com/cozystack/blockstor/pkg/store" ) // Labels used to index Resource CRDs by their composite key. const ( LabelResourceDefinition = "blockstor.org/resource-definition" ) type resources struct { c ctrlclient.Client // rds lets a replica delete take the resource-connection props of // its node off the definition (see dropConnectionProps). rds *resourceDefinitions // apiReader is the manager's direct, uncached reader. ListByNode uses // it when it is there; see nodeScopedReader for why that read in // particular cannot come from a cache. apiReader ctrlclient.Reader } func resourceCRDName(rd, node string) string { return Name(rd + "." + node) } func (s *resources) List(ctx context.Context) ([]apiv1.Resource, error) { var crdList crdv1alpha1.ResourceList err := s.c.List(ctx, &crdList) if err != nil { return nil, errors.Wrap(err, "list Resource CRDs") } out := make([]apiv1.Resource, 0, len(crdList.Items)) for i := range crdList.Items { out = append(out, crdToWireResource(&crdList.Items[i])) } sort.Slice(out, func(i, j int) bool { if out[i].Name != out[j].Name { return out[i].Name < out[j].Name } return out[i].NodeName < out[j].NodeName }) return out, nil } // ListByNode asks the API server for the node's replicas instead of pulling // the whole cluster back and filtering here. // // The selector is on the spec.nodeName selectable field the CRD declares. That // is deliberately not the label the objects usually carry: a replica applied // by hand has no label, and a selector over it would return a // partial-but-correct subset — the Bug 038 shape, where the missing replicas // were invisible rather than an error. func (s *resources) ListByNode(ctx context.Context, node string) ([]apiv1.Resource, error) { reader := s.nodeScopedReader() spellings, err := nodeSpellings(ctx, reader, node) if err != nil { return nil, err } out, err := s.listUnderSpellings(ctx, reader, FieldResourceNodeName, spellings, func(r *crdv1alpha1.Resource, spelling string) bool { return r.Spec.NodeName == spelling }) if err != nil { return nil, err } // Every replica here is on the same node, so the definition is what // distinguishes them. sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) return out, nil } func (s *resources) ListByDefinition(ctx context.Context, rdName string) ([]apiv1.Resource, error) { // Scoped on the authoritative Spec.ResourceDefinitionName, never on a // label. // // Bug 038: an earlier "fast path" trusted a label-selector // (`LabelResourceDefinition`) and only fell back to a full scan when the // selector returned ZERO items, on the assumption that a // partial-but-correct subset was impossible because "every REST writer // sets the label". That assumption breaks for MIXED RDs: a source RD // whose diskful replicas were applied via `kubectl apply` (e2e fixtures, // operator-authored manifests — NO label) but whose auto-tiebreaker // witness was stamped by the controller (WITH the label). The selector // then returned only the labeled witness, the fallback was skipped, and // the unlabeled diskful replicas became invisible. The snapshot-restore / // clone handler reads this list to resolve the SOURCE pool // (storPoolsByNodeFromSourceRD); with the diskful replicas hidden it // stamped the clone replicas with an EMPTY StorPoolName and the satellite // failed every reconcile with `unknown storage pool ""` (clone.sh never // converges). // // A selectable FIELD does not have that failure mode: it selects on the // spec value every replica carries, whoever wrote it, and a server that // cannot serve the selector says so instead of answering short. return s.listByDefinitionThrough(ctx, s.c, rdName) } // ListByDefinitionUncached answers what ListByDefinition answers from the API // server when the store has a direct reader, for a decision that cannot take a // cache's word: whether a definition another replica of this server just // prepared holds a live replica. func (s *resources) ListByDefinitionUncached(ctx context.Context, rdName string) ([]apiv1.Resource, error) { return s.listByDefinitionThrough(ctx, s.nodeScopedReader(), rdName) } func (s *resources) Get(ctx context.Context, rdName, node string) (apiv1.Resource, error) { var crd crdv1alpha1.Resource err := s.c.Get(ctx, types.NamespacedName{Name: resourceCRDName(rdName, node)}, &crd) if err != nil { if apierrors.IsNotFound(err) { return apiv1.Resource{}, errors.Wrapf(store.ErrNotFound, "resource %q on node %q", rdName, node) } return apiv1.Resource{}, errors.Wrapf(err, "get Resource %s/%s", rdName, node) } return crdToWireResource(&crd), nil } // GetUncached answers what Get answers from the API server when the store has // a direct reader, for a decision that cannot take a cache's word: whether a // replica a Create collided with is still there, and whether it is going. func (s *resources) GetUncached(ctx context.Context, rdName, node string) (apiv1.Resource, error) { if s.apiReader == nil { return s.Get(ctx, rdName, node) } var crd crdv1alpha1.Resource err := s.apiReader.Get(ctx, types.NamespacedName{Name: resourceCRDName(rdName, node)}, &crd) if err != nil { if apierrors.IsNotFound(err) { return apiv1.Resource{}, errors.Wrapf(store.ErrNotFound, "resource %q on node %q", rdName, node) } return apiv1.Resource{}, errors.Wrapf(err, "get Resource %s/%s live", rdName, node) } return crdToWireResource(&crd), nil } func (s *resources) Create(ctx context.Context, in *apiv1.Resource) error { if in == nil { return errors.New("nil Resource") } // The spec stores the definition's and the node's CR names, which is // what the controller and the satellite look them up and compare by, // and the registered spellings are kept for display (see spellings.go). // The object itself is named from the registered spellings, the way // Get addresses it. rd, err := storedRDName(ctx, s.c, in.Name) if err != nil { return err } node, err := storedNodeName(ctx, s.c, in.NodeName) if err != nil { return err } shown := *in shown.Name = rd.display shown.NodeName = node.display crd := wireToCRDResource(&shown) dropNameAnnotations(crd.Annotations) crd.Spec.ResourceDefinitionName = rd.crName crd.Spec.NodeName = node.crName crd.Labels[LabelResourceDefinition] = rd.crName crd.Labels[LabelNodeName] = node.crName rd.annotate(&crd.ObjectMeta, AnnotationLinstorRDName) node.annotate(&crd.ObjectMeta, AnnotationLinstorNodeName) err = s.c.Create(ctx, crd) if err != nil { if apierrors.IsAlreadyExists(err) { return errors.Wrapf(store.ErrAlreadyExists, "resource %q on node %q", in.Name, in.NodeName) } return errors.Wrapf(err, "create Resource %s/%s", in.Name, in.NodeName) } return nil } func (s *resources) Update(ctx context.Context, in *apiv1.Resource) error { if in == nil { return errors.New("nil Resource") } var existing crdv1alpha1.Resource key := types.NamespacedName{Name: resourceCRDName(in.Name, in.NodeName)} err := s.c.Get(ctx, key, &existing) if err != nil { if apierrors.IsNotFound(err) { return errors.Wrapf(store.ErrNotFound, "resource %q on node %q", in.Name, in.NodeName) } return errors.Wrapf(err, "get Resource %s/%s", in.Name, in.NodeName) } // Bug 206: Spec.Volumes carries the controller-stamped per-volume // seeding state (SeedFromGI for DRBD's initial-sync fast path) and // has no counterpart on the wire `Resource` shape — upstream // LINSTOR exposes these knobs via the satellite-side reconciler, // not the REST surface. `wireToCRDResourceSpec` rebuilds the Spec // from the wire, so a naïve replace would silently wipe Volumes on // every routine modify (prop bump, flag toggle, layer-stack change) // and DRBD would do a full initial-sync over the wire instead of // the seeded fast path. Carry it across explicitly — mirrors the // VolumeDefinitions carry-across `resourceDefinitions.Update` does. prevVolumes := existing.Spec.Volumes // Identity-to-spec: DRBDPort / DRBDNodeID are controller-allocated // (clusterIP model) with no wire counterpart — a naïve wire-rebuild // would wipe them on every routine REST modify, forcing the // allocator to re-pick fresh values → port/node-id change → DRBD // reconnect/resync. Carry them across, mirroring Spec.Volumes. prevPort := existing.Spec.DRBDPort prevNodeID := existing.Spec.DRBDNodeID // Skip-init-sync hardening: SkipInitialSync is a controller-stamped // append-only decision with no wire counterpart — carry it across so // a golinstor REST modify can't strip it and flip the satellite back // to the unsafe day0-skip default (the offline-safety regression). prevSkipInit := existing.Spec.SkipInitialSync // The names in spec are the parents' CR names, fixed at Create; the // wire carries the display spellings (see spellings.go). prevRD, prevNode := existing.Spec.ResourceDefinitionName, existing.Spec.NodeName existing.Spec = wireToCRDResourceSpec(in) existing.Spec.Volumes = prevVolumes existing.Spec.DRBDPort = prevPort existing.Spec.DRBDNodeID = prevNodeID existing.Spec.SkipInitialSync = prevSkipInit existing.Spec.ResourceDefinitionName, existing.Spec.NodeName = prevRD, prevNode // Bug 67: round-trip wire-side Annotations through metadata so the // REST writer's `blockstor.org/peer-changed` bump actually reaches // the CRD ObjectMeta — without this the bump would silently no-op // and the satellite's local-Resource watch would never fire. // // Bug 210: merge rather than wholesale-replace so the satellite- // stamped `blockstor.org/volume-numbers` annotation (Bug 107 cascade- // delete fallback) survives a wire-snapshot that raced the stamp. // Without this, a routine `linstor r ` between Get and Update // wipes the annotation; a concurrent RD cascade-delete that hits // `lookupVolumeNumbers` during the harm window leaks the backing // LV / zvol. Mirrors the RD / RG / Snapshot stores. mergeUserAnnotationsInto(&existing.ObjectMeta, withoutCallerNameAnnotations(in.Annotations), crdv1alpha1.ResourceAnnotationVolumeNumbers, crdv1alpha1.ResourceAnnotationLiveMigrateApplied, AnnotationLinstorRDName, AnnotationLinstorNodeName) err = s.c.Update(ctx, &existing) if err != nil { return errors.Wrapf(err, "update Resource %s/%s", in.Name, in.NodeName) } return nil } // PatchResourceSpec runs `mutate` against the freshly-fetched current // wire-shape Resource and persists the mutated value via a typed-Patch // (JSON-merge-patch) under `RetryOnConflict` with the Bug 201 backoff. // On 409 the cycle re-runs against fresh state — so concurrent disjoint // edits (r modify, toggle-disk, r activate, autoplace) converge instead // of silently dropping the loser via the wholesale `Update`'s un-retried // wire-snapshot replace (Bug 204b). // // Annotations follow `Update`'s contract: nil wire means "no annotation // work requested" (preserve existing); non-nil replaces the annotation // set atomically. The closure operates on wire-shape Annotations. func (s *resources) PatchResourceSpec(ctx context.Context, rdName, node string, mutate func(*apiv1.Resource) error) error { if mutate == nil { return errors.New("nil mutate") } return errors.Wrapf(retry.RetryOnConflict(patchRetryBackoff(), func() error { var existing crdv1alpha1.Resource key := types.NamespacedName{Name: resourceCRDName(rdName, node)} err := s.c.Get(ctx, key, &existing) if err != nil { if apierrors.IsNotFound(err) { return errors.Wrapf(store.ErrNotFound, "resource %q on node %q", rdName, node) } return errors.Wrapf(err, "get Resource %s/%s", rdName, node) } base := existing.DeepCopy() wire := crdToWireResource(&existing) err = mutate(&wire) if err != nil { return err } // Bug 206: preserve controller-stamped Spec.Volumes across // the wire-rebuild — see the matching carry-across in `Update` // above. `base := existing.DeepCopy()` happened BEFORE this // assignment, so the JSON-merge-patch diff still computes // correctly against the pre-mutate state. prevVolumes := existing.Spec.Volumes // Identity-to-spec: carry controller-allocated DRBDPort / // DRBDNodeID across the wire-rebuild — see the matching // carry-across in `Update` above. prevPort := existing.Spec.DRBDPort prevNodeID := existing.Spec.DRBDNodeID // Skip-init-sync hardening: carry SkipInitialSync across — see // the matching carry-across in `Update` above. prevSkipInit := existing.Spec.SkipInitialSync // The CR names in spec: see the matching carry-across in `Update`. prevRD, prevNode := existing.Spec.ResourceDefinitionName, existing.Spec.NodeName existing.Spec = wireToCRDResourceSpec(&wire) existing.Spec.Volumes = prevVolumes existing.Spec.DRBDPort = prevPort existing.Spec.DRBDNodeID = prevNodeID existing.Spec.SkipInitialSync = prevSkipInit existing.Spec.ResourceDefinitionName, existing.Spec.NodeName = prevRD, prevNode // Bug 210: merge rather than wholesale-replace so the // satellite-stamped `blockstor.org/volume-numbers` (Bug 107) // survives even if the closure built `wire.Annotations` // from a stale snapshot that pre-dated the satellite stamp. // PatchResourceSpec already has 409-retry via // MergeFromWithOptimisticLock, but the merge keeps the // annotation invariant uniform with the wholesale `Update` // path and protects against future closures that explicitly // reset live.Annotations. mergeUserAnnotationsInto(&existing.ObjectMeta, withoutCallerNameAnnotations(wire.Annotations), crdv1alpha1.ResourceAnnotationVolumeNumbers, crdv1alpha1.ResourceAnnotationLiveMigrateApplied, AnnotationLinstorRDName, AnnotationLinstorNodeName) return s.c.Patch(ctx, &existing, ctrlclient.MergeFromWithOptions(base, ctrlclient.MergeFromWithOptimisticLock{})) }), "patch Resource %s/%s", rdName, node) } func (s *resources) Delete(ctx context.Context, rdName, node string) error { // The connection props go first, so a failure to drop them leaves // the replica in place and a retried delete drops them still. err := s.dropConnectionProps(ctx, rdName, node) if err != nil { return err } crd := &crdv1alpha1.Resource{ObjectMeta: metav1.ObjectMeta{Name: resourceCRDName(rdName, node)}} err = s.c.Delete(ctx, crd) if err != nil { if apierrors.IsNotFound(err) { return errors.Wrapf(store.ErrNotFound, "resource %q on node %q", rdName, node) } return errors.Wrapf(err, "delete Resource %s/%s", rdName, node) } return nil } // DeleteIfTieBreaker deletes the named replica only if it is still an // auto-tiebreaker witness (carries TIE_BREAKER) at the freshly-observed // object version. The delete is issued under a Preconditions guard on // both the ResourceVersion AND the UID of the object we just read: // // - ResourceVersion precondition: a concurrent in-place promotion // (pkg/placer.promoteWitness flips DISKLESS+TIE_BREAKER → diskful via // a JSON-merge-patch, bumping ResourceVersion) lands in the gap // between our Get and our Delete. The apiserver rejects the // version-guarded delete with Conflict, so the just-promoted diskful // replica is NOT clobbered — the exact Bug 393 race. We translate the // Conflict into a benign "skipped" (false, nil): the next reconcile // re-evaluates the now-diskful row and leaves it alone. // - UID precondition: closes the delete-then-recreate ABA window — if // the witness were deleted and a fresh Resource recreated on the same // (rd, node) name between our Get and Delete, the UID would differ and // the apiserver rejects the delete rather than removing the new row. // // A NotFound (already reaped by a racing reconcile) is also a benign // (false, nil). Genuine transport/permission errors propagate. func (s *resources) DeleteIfTieBreaker(ctx context.Context, rdName, node string) (bool, error) { name := resourceCRDName(rdName, node) var crd crdv1alpha1.Resource err := s.c.Get(ctx, types.NamespacedName{Name: name}, &crd) if err != nil { if apierrors.IsNotFound(err) { return false, nil } return false, errors.Wrapf(err, "get Resource %s/%s", rdName, node) } // Re-check identity under the version we are about to pin: a row that // no longer carries TIE_BREAKER has been promoted to the relocate / // backfill target (or downgraded to a plain diskless peer) and must // never be reaped by the witness pass. if !slices.Contains(crd.Spec.Flags, apiv1.ResourceFlagTieBreaker) { return false, nil } resourceVersion := crd.ResourceVersion uid := crd.UID del := &crdv1alpha1.Resource{ObjectMeta: metav1.ObjectMeta{Name: name}} err = s.c.Delete(ctx, del, ctrlclient.Preconditions{ ResourceVersion: &resourceVersion, UID: &uid, }) if err != nil { // Conflict: the row was mutated (promoted to diskful) between // our Get and the version-guarded Delete — abort the reap so the // freshly-promoted replica survives. NotFound: already reaped by // a racing reconcile. Both are convergence-benign no-ops. if apierrors.IsConflict(err) || apierrors.IsNotFound(err) { return false, nil } return false, errors.Wrapf(err, "delete Resource %s/%s", rdName, node) } // After the delete, not before: the precondition may yet refuse // it. A witness carries no connection props of its own in // practice, so a failure here is not worth failing the reap for. _ = s.dropConnectionProps(ctx, rdName, node) return true, nil } // SatelliteFieldOwner is the SSA field-manager identity the // satellite uses for its observed-state writes (DrbdState, // per-volume DiskState/CurrentGI). The controller uses // `ControllerFieldOwner` for its allocator outputs (DRBDPort, // DRBDMinor, DRBDNodeID). Distinct field owners let SSA's merge // algorithm preserve each side's writes when the two collide on // the same Status subresource. Phase 10.2. const ( SatelliteFieldOwner = "blockstor-satellite" ControllerFieldOwner = "blockstor-controller" ) // SetState writes the runtime-observed state via Server-Side Apply // on the Status subresource. Called from the satellite's events2 // observer path when role/disk state changes — these must not race // concurrent Spec mutations (auto-diskful, resize, evacuation) nor // the controller's allocator writes to DRBDPort/Minor/NodeID. // // SSA with `FieldOwner=blockstor-satellite` makes the merge // per-field: only the fields the satellite explicitly sets in the // apply object are claimed; the controller's allocator outputs // (`DRBDPort`, `DRBDMinor`, `DRBDNodeID`) stay untouched even // across racing Status writes. Phase 10.2. // // state.DrbdState lands on Status.DrbdState; per-volume // DiskState/CurrentGI land on Status.Volumes[i] (the listMapKey is // `volumeNumber`, so SSA matches up entries correctly). func (s *resources) SetState(ctx context.Context, rdName, node string, state apiv1.ResourceState, volumes []apiv1.VolumeObservation) error { name := resourceCRDName(rdName, node) // Verify the Resource exists before applying — apiserver Apply // would happily create a half-formed Resource if it didn't, // and we'd rather surface NotFound to callers (events2 // observer treats it as a convergence-pending case and skips). var existing crdv1alpha1.Resource err := s.c.Get(ctx, types.NamespacedName{Name: name}, &existing) if err != nil { if apierrors.IsNotFound(err) { return errors.Wrapf(store.ErrNotFound, "resource %q on node %q", rdName, node) } return errors.Wrapf(err, "get Resource %s/%s", rdName, node) } apply := &crdv1alpha1.Resource{ TypeMeta: metav1.TypeMeta{Kind: "Resource", APIVersion: crdv1alpha1.GroupVersion.String()}, ObjectMeta: metav1.ObjectMeta{Name: name}, Status: crdv1alpha1.ResourceStatus{ InUse: ptrBoolOrFalse(state.InUse), DrbdState: state.DrbdState, Volumes: buildVolumeStatusForApply(volumes), }, } // Note: client.Apply is the Patch-type-based SSA path. The // newer Client.Apply / SubResource.Apply methods need // applyconfiguration-gen output for our CRDs, which we don't // produce yet — sticking to the patch-type API keeps the // dependency tree shallow. err = s.c.Status().Patch(ctx, apply, ctrlclient.Apply, //nolint:staticcheck // SA1019: applyconfiguration-gen output not yet available for our CRDs ctrlclient.FieldOwner(SatelliteFieldOwner), ctrlclient.ForceOwnership) if err != nil { return errors.Wrapf(err, "ssa apply Resource Status %s/%s", rdName, node) } return nil } // ClearDRBDPort drops Status.DRBDPort on the named Resource so the // controller's allocator (resource_controller.allocateDRBDFields) // re-picks a fresh free port on its next reconcile. The activate // REST handler invokes this when the operator passes // `?reallocate-port=true` to recover from a port collision via the // deactivate + activate recipe (Bug 46). // // Implementation: JSON merge patch with `{"status":{"drbdPort":null}}` // on the Status subresource. SSA can't naturally express "clear // this single field" without re-Applying as the original field // owner (`ControllerFieldOwner`) which would also touch DRBDNodeID // and DRBDMinor — both of which we want to preserve. A merge patch // is field-surgical: only `drbdPort` is removed; DRBDMinor / // DRBDNodeID / observer-claimed Volumes survive. func (s *resources) ClearDRBDPort(ctx context.Context, rdName, node string) error { name := resourceCRDName(rdName, node) // Verify the Resource exists first. Without this, an apiserver // merge-patch on a missing object returns a 404 we'd have to // translate downstream; surfacing ErrNotFound up-front keeps the // store contract uniform with the rest of the methods. var existing crdv1alpha1.Resource err := s.c.Get(ctx, types.NamespacedName{Name: name}, &existing) if err != nil { if apierrors.IsNotFound(err) { return errors.Wrapf(store.ErrNotFound, "resource %q on node %q", rdName, node) } return errors.Wrapf(err, "get Resource %s/%s", rdName, node) } // Fast-path: nothing to clear. Avoids a no-op apiserver round // trip for the common case where the operator hits activate // without `?reallocate-port=true` on a freshly-Created Resource // the controller hasn't allocated yet. if existing.Status.DRBDPort == nil { return nil } patch := ctrlclient.RawPatch(types.MergePatchType, []byte(`{"status":{"drbdPort":null}}`)) err = s.c.Status().Patch(ctx, &existing, patch) if err != nil { if apierrors.IsNotFound(err) { return errors.Wrapf(store.ErrNotFound, "resource %q on node %q", rdName, node) } return errors.Wrapf(err, "clear Status.DRBDPort on Resource %s/%s", rdName, node) } return nil } func (s *resources) listByDefinitionThrough( ctx context.Context, reader ctrlclient.Reader, rdName string, ) ([]apiv1.Resource, error) { spellings, err := rdSpellings(ctx, reader, rdName) if err != nil { return nil, err } out, err := s.listUnderSpellings(ctx, reader, FieldResourceDefinitionName, spellings, func(r *crdv1alpha1.Resource, spelling string) bool { return r.Spec.ResourceDefinitionName == spelling }) if err != nil { return nil, err } // Every replica here belongs to the same definition, so the node is what // distinguishes them. sort.Slice(out, func(i, j int) bool { return out[i].NodeName < out[j].NodeName }) return out, nil } // buildVolumeStatusForApply turns a slice of per-volume // observations into the SSA-shaped Status.Volumes payload. Only // non-empty fields land in the apply object so SSA doesn't claim // ownership of fields the satellite didn't explicitly set. // // The Status.Volumes slice is a `+listType=map +listMapKey=volumeNumber` // list, so the apiserver merges the apply against the existing // state by volume number — a frame that only carries DiskState // for vol 0 leaves vol 1's CurrentGI alone. func buildVolumeStatusForApply(observations []apiv1.VolumeObservation) []crdv1alpha1.ResourceVolumeStatus { if len(observations) == 0 { return nil } out := make([]crdv1alpha1.ResourceVolumeStatus, 0, len(observations)) for _, vol := range observations { out = append(out, crdv1alpha1.ResourceVolumeStatus{ VolumeNumber: vol.VolumeNumber, DiskState: vol.State.DiskState, CurrentGI: vol.State.CurrentGi, }) } return out } // withDeletingFlag appends the upstream-canonical `DELETE` flag to a // CRD's spec Flags slice when the object carries a DeletionTimestamp // (E4 / two-phase RD deletion). controller-runtime keeps returning a // CRD with a non-nil DeletionTimestamp from List/Get for as long as a // finalizer is held — in blockstor that window is "the // satellite-resource finalizer hasn't drained DRBD yet", e.g. because // the owning satellite is down. Surfacing DELETE here makes // `linstor rd l` / `linstor r l` render the State column as DELETING // during that interim, matching upstream LINSTOR's two-phase delete // visibility (the satellites confirm the on-node teardown before the // object disappears from the DB). // // Idempotent: if the spec already carries DELETE (a future cascade // path might stamp it explicitly) the flag is not duplicated. The // input slice is never mutated — a fresh slice is returned only when a // flag must be added, otherwise the original is passed through. func withDeletingFlag(flags []string, deleting bool) []string { if !deleting { return flags } if slices.Contains(flags, apiv1.ResourceFlagDelete) { return flags } out := make([]string, 0, len(flags)+1) out = append(out, flags...) out = append(out, apiv1.ResourceFlagDelete) return out } func crdToWireResource(crd *crdv1alpha1.Resource) apiv1.Resource { props := mergeProps(crd.Spec.Props, typedToProps(crd.Spec.DRBDOptions, crd.Spec.ExtraProps)) // Phase 10.3 step: re-emit typed StoragePool back into Props // so golinstor + the dispatcher's legacy fallback see the // upstream-compatible shape on GET. if crd.Spec.StoragePool != "" { if props == nil { props = map[string]string{} } props["StorPoolName"] = crd.Spec.StoragePool } return apiv1.Resource{ Name: shownName(&crd.ObjectMeta, AnnotationLinstorRDName, crd.Spec.ResourceDefinitionName), NodeName: shownName(&crd.ObjectMeta, AnnotationLinstorNodeName, crd.Spec.NodeName), Props: props, Flags: withDeletingFlag(crd.Spec.Flags, crd.DeletionTimestamp != nil), // Resource CRD has no LayerStack — that lives on the parent RD. // Looking it up here turns every list/view into an N+1 query, so // we approximate with the default stack. The Python CLI only // uses this to render the Layers column on `linstor r list`; // blockstor's actual layer placement is driven by the RD spec // at apply time, not by this read-only echo. LayerObject: layerObjectFromCRD(crd), State: apiv1.ResourceState{ InUse: boolPtr(crd.Status.InUse), DrbdState: crd.Status.DrbdState, ToggleDiskRetries: crd.Status.ToggleDiskRetries, }, ToggleDiskCancel: crd.Spec.ToggleDiskCancel, Volumes: volumesWithReplicationStates( volumesFromStatus(crd.Status.Volumes), crd.Status.Connections, ), UUID: string(crd.UID), Annotations: withoutNameAnnotations(cloneAnnotations(crd.Annotations)), // Upstream LINSTOR populates `create_timestamp` (the Python // CLI's `CreatedOn` column). The Resource CRD's // metadata.creationTimestamp is the per-replica creation time // and the natural, persistence-free source for it. CreateTimestamp: crdCreateTimestampMs(crd), ApplyFailure: applyFailureFromStatus(crd.Status.ApplyFailure), } } // applyFailureFromStatus projects the satellite's last apply error onto // the wire Resource, nil when the last pass succeeded. func applyFailureFromStatus(in *crdv1alpha1.ResourceApplyFailure) *apiv1.ApplyFailure { if in == nil { return nil } out := &apiv1.ApplyFailure{Message: in.Message, SizesKib: make(map[int32]int64, len(in.Volumes))} for _, vol := range in.Volumes { out.SizesKib[vol.VolumeNumber] = vol.SizeKib } return out } // crdCreateTimestampMs translates a Resource CRD's // metadata.creationTimestamp into the upstream `create_timestamp` // wire field (unix milliseconds). Returns 0 (dropped by omitempty) // when the timestamp is unset, e.g. a hand-built CRD in a unit test. func crdCreateTimestampMs(crd *crdv1alpha1.Resource) int64 { if crd.CreationTimestamp.IsZero() { return 0 } return crd.CreationTimestamp.UnixMilli() } // volumesFromStatus projects the CRD `Status.Volumes` onto wire // `[]Volume`. State carries DiskState + CurrentGI (Generation // Identifier) — the latter is what the controller seeds new // replicas with for skipping the full initial-sync. The Python CLI // derives the per-resource rsc_state from `volumes[].state.disk_state`; // without this projection, the rsc_state stays "Unknown" and the // CLI suppresses the Conns column + --faulty filter. // boolPtr returns a *bool pointing at the value. Used to satisfy the // apiv1 tri-state contract for ResourceState.InUse: nil means "not // observed yet"; *false means "observed Secondary"; *true means // "observed Primary". Without the pointer, false serialises as // absent under omitempty. func boolPtr(v bool) *bool { return &v } // ptrBoolOrFalse is the inverse of boolPtr for the SSA-Apply path: // the CRD's Status.InUse field is a plain bool, so nil from the // apiv1 shape must collapse to false before write. func ptrBoolOrFalse(p *bool) bool { if p == nil { return false } return *p } func volumesFromStatus(in []crdv1alpha1.ResourceVolumeStatus) []apiv1.Volume { if len(in) == 0 { return nil } // Per-resource layer stack isn't stored on the Resource CRD (it // lives on the parent RD). For the rsc_state gating the Python // CLI does, the only thing that matters is that the FIRST entry // is DRBD; the default stack DRBD/STORAGE covers every diskful // layout we currently materialise. layerDataList := volumeLayerDataFromStack(apiv1.DefaultLayerStack()) out := make([]apiv1.Volume, 0, len(in)) for i := range in { volStatus := &in[i] out = append(out, apiv1.Volume{ VolumeNumber: volStatus.VolumeNumber, StoragePool: volStatus.StoragePool, DevicePath: volStatus.DevicePath, AllocatedKib: volStatus.AllocatedKib, UsableKib: volStatus.UsableKib, State: apiv1.VolumeState{ DiskState: volStatus.DiskState, CurrentGi: volStatus.CurrentGI, OutOfSyncKib: volStatus.OutOfSyncKib, }, LayerDataList: layerDataList, AppliedSizeKib: volStatus.AppliedSizeKib, }) } return out } // volumesWithReplicationStates folds the resource-level per-peer // replication state into each volume's state.replication_states // map. The Python CLI reads exactly this shape for the Repl column // — it cannot infer per-peer replication from // `layer_object.drbd.connections[].replication_state`, even though // blockstor stores the data there too. // // The replication state is the volume's own with that peer // (peerVolumes[].replicationState) and done_percentage that volume's // `done`, so a two-volume resource reports each volume's own resync, // as LINSTOR does from its per-peer, per-volume DrbdVolume. The // connection-level replicationState is whichever volume's frame came // last; it is only the fallback for a volume the satellite has not // reported per volume yet. LINSTOR fills done_percentage whenever the // satellite reported one (Json.apiToVolumeState), whatever the // replication state, and so does this. func volumesWithReplicationStates( vols []apiv1.Volume, conns []crdv1alpha1.ResourceConnectionStatus, ) []apiv1.Volume { if len(vols) == 0 || len(conns) == 0 { return vols } for i := range vols { states := make(map[string]apiv1.ReplicationState, len(conns)) for j := range conns { c := &conns[j] peerVol := findPeerVolume(c.PeerVolumes, vols[i].VolumeNumber) repl := c.ReplicationState if peerVol != nil && peerVol.ReplicationState != "" { repl = peerVol.ReplicationState } if repl == "" { continue } states[c.PeerNodeName] = apiv1.ReplicationState{ ReplicationState: repl, DonePercentage: peerVolumeDone(peerVol), } } if len(states) > 0 { vols[i].State.ReplicationStates = states } } return vols } // findPeerVolume returns one volume's entry of a connection's // per-volume peer view, nil when the satellite reported none. func findPeerVolume(peerVolumes []crdv1alpha1.PeerVolumeStatus, volumeNumber int32) *crdv1alpha1.PeerVolumeStatus { for i := range peerVolumes { if peerVolumes[i].VolumeNumber == volumeNumber { return &peerVolumes[i] } } return nil } // peerVolumeDone parses the `done` token the satellite recorded for // one volume on one connection. nil when the volume has none or the // token does not parse: no progress is better than a made-up one. func peerVolumeDone(peerVol *crdv1alpha1.PeerVolumeStatus) *float64 { if peerVol == nil || peerVol.Done == "" { return nil } done, err := strconv.ParseFloat(peerVol.Done, 64) if err != nil { return nil } return &done } // volumeLayerDataFromStack mirrors the resource-level layer stack // onto each volume's `layer_data_list`. The Python CLI's // `volume_expects_disk_state` reads `layer_data_list[0].type == DRBD` // to decide whether the State column should trust the observed // `disk_state` — without this, the column always shows "Created". func volumeLayerDataFromStack(stack []string) []apiv1.VolumeLayerData { if len(stack) == 0 { stack = apiv1.DefaultLayerStack() } out := make([]apiv1.VolumeLayerData, 0, len(stack)) for _, kind := range stack { out = append(out, apiv1.VolumeLayerData{Type: kind}) } return out } // layerObjectFromCRD wraps `layerObjectFromStack` with the CRD-side // glue: it injects the per-replica DRBD runtime state (TCP port, // per-peer connection map) into the top-of-stack `Drbd` field. The // Python CLI's `--faulty` filter reads `connections[*].connected` // to color broken peers red and to gate inclusion in the faulty // subset; without this `r list --faulty` cannot see disconnected // peers and silently passes them as healthy. func layerObjectFromCRD(crd *crdv1alpha1.Resource) *apiv1.ResourceLayer { top := layerObjectFromStack(nil, crd.Spec.Flags) if top == nil { return nil } // Inject DRBD runtime only on the DRBD layer itself (top of the // default stack). If a future RG advertises a non-DRBD stack // (`[STORAGE]` only) this is a no-op — `Drbd` stays nil and the // CLI renders an empty Conns column for that resource. if top.Type == apiv1.LayerKindDRBD { top.Drbd = drbdLayerFromStatus(&crd.Status) } // Hydrate the STORAGE leaf for diskful replicas — F19 keeps the // leaf always emitted, but only diskful replicas have actual // storage_volumes derived from Status.Volumes. Diskless / tiebreaker // replicas keep the empty payload layerObjectFromStack stamped. hydrateStorageLeaf(top, crd) return top } // hydrateStorageLeaf walks the children chain looking for the STORAGE // leaf and (for diskful replicas) attaches per-volume payload derived // from the satellite-observed `Resource.Status.Volumes`. For diskless // replicas the STORAGE leaf is left with the `provider_kind=DISKLESS` // marker that layerObjectFromStack already stamped — no volumes are // emitted because there's no backing device on this node. F19. func hydrateStorageLeaf(top *apiv1.ResourceLayer, crd *crdv1alpha1.Resource) { if top == nil { return } diskless := false for _, f := range crd.Spec.Flags { if f == apiv1.ResourceFlagDiskless || f == apiv1.ResourceFlagTieBreaker { diskless = true break } } storage := findStorageLeaf(top) if storage == nil { return } if diskless { // layerObjectFromStack has already set provider_kind=DISKLESS // and left storage_volumes empty — nothing more to hydrate. return } if len(crd.Status.Volumes) == 0 { return } vols := make([]apiv1.StorageVolumeLayer, 0, len(crd.Status.Volumes)) for i := range crd.Status.Volumes { vol := &crd.Status.Volumes[i] vols = append(vols, apiv1.StorageVolumeLayer{ VolumeNumber: vol.VolumeNumber, DevicePath: vol.DevicePath, AllocatedSizeKib: vol.AllocatedKib, UsableSizeKib: vol.UsableKib, DiskState: vol.DiskState, }) } if storage.Storage == nil { storage.Storage = &apiv1.StorageResourceLayer{} } storage.Storage.StorageVolumes = vols } // findStorageLeaf walks the layer_object children chain (always // single-branch in blockstor's layouts) and returns the STORAGE entry, // or nil if the stack carries no STORAGE layer (e.g. a future // non-DRBD-only deployment). func findStorageLeaf(layer *apiv1.ResourceLayer) *apiv1.ResourceLayer { for cursor := layer; cursor != nil; { if cursor.Type == apiv1.LayerKindStorage { return cursor } if len(cursor.Children) == 0 { return nil } cursor = &cursor.Children[0] } return nil } // drbdLayerFromStatus builds the wire-side `DrbdResourceLayer` from // the satellite-observed CRD Status. Returns nil when no observable // runtime state exists yet (Resource just created, satellite hasn't // reconciled it). func drbdLayerFromStatus(st *crdv1alpha1.ResourceStatus) *apiv1.DrbdResourceLayer { var out apiv1.DrbdResourceLayer hasAny := false if st.DRBDPort != nil { out.TCPPorts = []int32{*st.DRBDPort} hasAny = true } if len(st.Connections) > 0 { out.Connections = make(map[string]apiv1.DrbdConnection, len(st.Connections)) for i := range st.Connections { c := &st.Connections[i] out.Connections[c.PeerNodeName] = apiv1.DrbdConnection{ Connected: c.Connected, Message: c.Message, ReplicationState: c.ReplicationState, } } hasAny = true } // Per-volume DRBD disk-state — Python CLI's `linstor r l` State // column reads this exact path; without it the column shows a // literal "Created" regardless of the observed disk_state in // Status.Volumes[i].DiskState. if len(st.Volumes) > 0 { out.DrbdVolumes = make([]apiv1.DrbdVolume, 0, len(st.Volumes)) for i := range st.Volumes { vol := &st.Volumes[i] if vol.DiskState == "" && vol.DevicePath == "" { continue } out.DrbdVolumes = append(out.DrbdVolumes, apiv1.DrbdVolume{ VolumeNumber: vol.VolumeNumber, DiskState: vol.DiskState, DevicePath: vol.DevicePath, }) hasAny = true } } if st.PromotionScore != nil || st.MayPromote != nil { out.PromotionScore = st.PromotionScore out.MayPromote = st.MayPromote hasAny = true } if !hasAny { return nil } return &out } // layerObjectFromStack assembles the upstream-LINSTOR `layer_object` // tree from a flat layer-stack slice. Returns nil when the stack is // empty — the wire shape uses `omitempty`, but the Python CLI's // `rsc.layer_data.layer_stack` dereferences the result // unconditionally, so callers that need CLI compatibility should // supply a fallback (default DRBD/STORAGE) before invoking this. // // DISKLESS / TIE_BREAKER resources keep the STORAGE child but the // payload differs from a diskful replica: the layer carries // `provider_kind=DISKLESS` and an empty `storage_volumes` list, // matching upstream LINSTOR's wire shape (`linstor r l` Layers column // renders `DRBD,STORAGE` for tiebreakers, not `DRBD` alone). F19. // // Diskful replicas synthesize one STORAGE volume per status-observed // volume in the layer payload via layerObjectFromCRD — the bare-stack // helper here only marks the layer kind; per-volume hydration happens // in the CRD-aware wrapper. func layerObjectFromStack(stack, flags []string) *apiv1.ResourceLayer { if len(stack) == 0 { stack = apiv1.DefaultLayerStack() } if len(stack) == 0 { return nil } diskless := false for _, f := range flags { if f == apiv1.ResourceFlagDiskless || f == apiv1.ResourceFlagTieBreaker { diskless = true break } } top := &apiv1.ResourceLayer{Type: stack[0]} cursor := top for _, t := range stack[1:] { child := apiv1.ResourceLayer{Type: t} if t == apiv1.LayerKindStorage && diskless { // F19: tiebreakers / operator-placed diskless replicas // still expose a STORAGE leaf so the CLI's Layers column // renders `DRBD,STORAGE` — the satellite simply has no // backing device on this node, which the payload encodes // via `provider_kind=DISKLESS` and an empty volume list. child.Storage = &apiv1.StorageResourceLayer{ ProviderKind: apiv1.StoragePoolKindDiskless, } } cursor.Children = []apiv1.ResourceLayer{child} cursor = &cursor.Children[0] } return top } func wireToCRDResource(in *apiv1.Resource) *crdv1alpha1.Resource { return &crdv1alpha1.Resource{ ObjectMeta: metav1.ObjectMeta{ Name: resourceCRDName(in.Name, in.NodeName), Labels: map[string]string{ LabelResourceDefinition: in.Name, LabelNodeName: in.NodeName, }, Annotations: cloneAnnotations(in.Annotations), }, Spec: wireToCRDResourceSpec(in), } } func wireToCRDResourceSpec(in *apiv1.Resource) crdv1alpha1.ResourceSpec { typed, extras := propsToTyped(in.Props) residual := stripDRBDProps(in.Props) return crdv1alpha1.ResourceSpec{ ResourceDefinitionName: in.Name, NodeName: in.NodeName, Props: residual, DRBDOptions: typed, ExtraProps: extras, Flags: in.Flags, // Phase 10.3 step: lift Props["StorPoolName"] into the // typed slot. The legacy key stays in residual Props (it's // non-DRBD, so stripDRBDProps left it alone) for forward- // compat — readers still consulting Props will see it. StoragePool: in.Props["StorPoolName"], // Bug 40: the REST cancel verb writes this through the // wire shape on PUT toggle-disk?cancel=true. The satellite // reconciler watches it and unwinds a partial conversion. ToggleDiskCancel: in.ToggleDiskCancel, } } // listScoped answers a scoped question with a scoped read, and falls back to // the exhaustive one when the server cannot serve the selector. // // The same call has two implementations behind it. Against an uncached reader // it becomes a fieldSelector on the wire and the API server filters; against // a manager's cached client it is served from the index NewManager registers // (see fieldIndexes). Either can be missing — a cluster whose CRD predates the // selectable field REJECTS the query, and a cache with no index for the field // fails it — and both fail loudly rather than answering partially, which is // what makes falling back to the exhaustive read safe rather than a silent // downgrade to a wrong answer. // // The fallback is logged because it is not free: it is the whole-cluster read // the scoped one exists to avoid, and an operator wondering why a large // cluster crawls deserves to find out from the logs rather than from a // profiler. func (s *resources) listScoped( ctx context.Context, reader ctrlclient.Reader, field, value string, keep func(*crdv1alpha1.Resource) bool, ) ([]apiv1.Resource, error) { var crdList crdv1alpha1.ResourceList err := reader.List(ctx, &crdList, ctrlclient.MatchingFields{field: value}) if err == nil { out := make([]apiv1.Resource, 0, len(crdList.Items)) for i := range crdList.Items { out = append(out, crdToWireResource(&crdList.Items[i])) } return out, nil } if !SelectorUnsupported(err) { return nil, errors.Wrapf(err, "list Resource CRDs for %s=%q", field, value) } log.FromContext(ctx).V(1).Info("scoped Resource read unavailable; reading every replica instead", "field", field, "value", value, "reason", err.Error()) return s.listExhaustively(ctx, reader, field, value, keep) } // listUnderSpellings runs listScoped once per spelling and returns every // replica once. The CRD name folds the definition and the node, so two rows // with the same folded pair are one object. func (s *resources) listUnderSpellings( ctx context.Context, reader ctrlclient.Reader, field string, spellings []string, keep func(*crdv1alpha1.Resource, string) bool, ) ([]apiv1.Resource, error) { var out []apiv1.Resource seen := map[string]struct{}{} for _, spelling := range spellings { found, err := s.listScoped(ctx, reader, field, spelling, func(r *crdv1alpha1.Resource) bool { return keep(r, spelling) }) if err != nil { return nil, err } for i := range found { key := resourceCRDName(found[i].Name, found[i].NodeName) if _, dup := seen[key]; dup { continue } seen[key] = struct{}{} out = append(out, found[i]) } } if out == nil { out = []apiv1.Resource{} } return out, nil } // listExhaustively is the pre-selectable-field read: every Resource, filtered // here. It is what listScoped falls back to, and it stays correct whatever the // server can or cannot select on. func (s *resources) listExhaustively( ctx context.Context, reader ctrlclient.Reader, field, value string, keep func(*crdv1alpha1.Resource) bool, ) ([]apiv1.Resource, error) { var crdList crdv1alpha1.ResourceList err := reader.List(ctx, &crdList) if err != nil { return nil, errors.Wrapf(err, "list Resource CRDs for %s=%q", field, value) } out := make([]apiv1.Resource, 0, len(crdList.Items)) for i := range crdList.Items { if !keep(&crdList.Items[i]) { continue } out = append(out, crdToWireResource(&crdList.Items[i])) } return out, nil } // nodeScopedReader answers the reads a node's fate is decided on. // // `node delete` refuses while anything still references the node, and // `--force` cascades away what does. Both decisions are made on one read and // then acted on destructively, so a cached answer that trails the API server // by a beat is not a slow answer, it is a wrong one in both directions: a // replica the read misses is a node deleted out from under it, and a pool the // read misses is left pointing at a node that no longer exists. // // There is no cache-retry poll behind these the way there is on the REST // create paths (get*WithCacheRetry), because there is nothing to converge // towards — the caller is about to delete, not to read again. // // This is not the uncached-Get fallback NewWithAPIReader warns against. That // warning is about raw Gets, where a fast cached NotFound is the contract and // a store-level bypass short-circuits the REST layer's convergence wait. This // is one List on two operator commands that run once per dead node, and the // field selector still travels: an uncached client sends it to the API server, // which answers it from the selectable field the CRD declares. func (s *resources) nodeScopedReader() ctrlclient.Reader { if s.apiReader != nil { return s.apiReader } return s.c } // dropConnectionProps takes the resource-connection props of node off // the definition, as LINSTOR deletes the connections of a resource with // it: a replica created on the node later starts from none, and does not // pick up a stale allow-two-primaries or protocol. Every delete path // (REST, CLI, the tiebreaker and lost-node reapers) goes through here. func (s *resources) dropConnectionProps(ctx context.Context, rdName, node string) error { if s.rds == nil { return nil } rd, err := s.rds.Get(ctx, rdName) if err != nil { if errors.Is(err, store.ErrNotFound) { return nil } return errors.Wrapf(err, "get ResourceDefinition %s", rdName) } if !apiv1.DropResourceConnectionProps(node, maps.Clone(rd.Props)) { return nil } err = s.rds.PatchResourceDefinitionSpec(ctx, rdName, func(live *apiv1.ResourceDefinition) error { apiv1.DropResourceConnectionProps(node, live.Props) return nil }) if err != nil && !errors.Is(err, store.ErrNotFound) { return errors.Wrapf(err, "drop connection props of %s from %s", node, rdName) } return nil }