Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
207 changes: 207 additions & 0 deletions pkg/store/k8s/drbd_minor_carry_bug433_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
// 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_test

import (
"context"
"testing"

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"

crdv1alpha1 "github.com/cozystack/blockstor/api/v1alpha1"
apiv1 "github.com/cozystack/blockstor/pkg/api/v1"
"github.com/cozystack/blockstor/pkg/store/k8s"
)

// Bug 433: the per-volume DRBDMinor (RD.Spec.VolumeDefinitions[].DRBDMinor)
// is the /dev/drbd<N> device identity. Per the CRD contract
// (api/v1alpha1/resourcedefinition_types.go) "a non-nil value is
// authoritative and is NEVER overwritten … the store-side
// VolumeDefinitions carry-across preserves the value through a REST
// modify". DRBDMinor has NO counterpart on the wire shape
// apiv1.VolumeDefinition (which carries only VolumeNumber/SizeKib/Props/
// Flags), so a VD-scoped modify that round-trips the entry through
// wireToCRDVD — volumeDefinitions.Update and PatchVolumeDefinitionSpec —
// silently zeroes the minor.
//
// This is the same wire-rebuild-drops-operator-only-field class as the
// carry-across family (Bug 206 RD.VolumeDefinitions, Bug 208 Node ranges,
// Bug 209 RD.Encryption). Only the VD-scoped element rebuild dropped it:
// the RD-scoped path preserves the whole VolumeDefinitions slice
// wholesale, so the minor rode along for free.
//
// Fix: both VD-scoped write paths route their write-back through
// wireToCRDVDPreserving, which carries DRBDMinor across the rebuild.
//
// These tests FAIL on the pre-fix tree (the minor comes back nil) and
// PASS with the carry-across in place.

const (
bug433Minor int32 = 20000
bug433OneGiB int64 = 1 * 1024 * 1024
bug433TwoGiB int64 = 2 * 1024 * 1024
)

// bug433SeedStore builds a k8s store fronting a fake client that holds a
// single RD with one volume carrying a non-nil DRBDMinor (the device
// identity we assert survives every routine modify).
func bug433SeedStore(t *testing.T, rdName string) (*k8s.Store, client.Client) {
t.Helper()

scheme := runtime.NewScheme()
if err := crdv1alpha1.AddToScheme(scheme); err != nil {
t.Fatalf("AddToScheme: %v", err)
}

minor := bug433Minor
seed := crdv1alpha1.ResourceDefinition{
ObjectMeta: metav1.ObjectMeta{Name: rdName},
Spec: crdv1alpha1.ResourceDefinitionSpec{
VolumeDefinitions: []crdv1alpha1.ResourceDefinitionVolume{
{
VolumeNumber: 0,
SizeKib: bug433OneGiB,
DRBDMinor: &minor,
},
},
},
}

cli := fake.NewClientBuilder().WithScheme(scheme).
WithObjects(&seed).
WithStatusSubresource(&crdv1alpha1.ResourceDefinition{}).
Build()

return k8s.New(cli), cli
}

// bug433DRBDMinor reads the durable DRBDMinor pointer for (rd, vol0)
// straight off the RD CRD (nil = wiped).
func bug433DRBDMinor(t *testing.T, cli client.Client, rdName string) *int32 {
t.Helper()

var got crdv1alpha1.ResourceDefinition
if err := cli.Get(context.Background(), client.ObjectKey{Name: rdName}, &got); err != nil {
t.Fatalf("get RD %q: %v", rdName, err)
}

for i := range got.Spec.VolumeDefinitions {
if got.Spec.VolumeDefinitions[i].VolumeNumber == 0 {
return got.Spec.VolumeDefinitions[i].DRBDMinor
}
}

t.Fatalf("RD %q: volume 0 vanished", rdName)

return nil
}

// assertMinorPreserved fails unless (rd, vol0) still carries the seeded
// device identity.
func bug433AssertMinorPreserved(t *testing.T, cli client.Client, rdName, via string) {
t.Helper()

m := bug433DRBDMinor(t, cli, rdName)
if m == nil {
t.Fatalf("%s WIPED the volume's DRBDMinor to nil (Bug 433). The per-volume DRBDMinor is "+
"the /dev/drbd<N> device identity; the CRD contract says a non-nil minor is NEVER "+
"overwritten and is preserved across a REST modify. wireToCRDVD drops it — the "+
"VD-scoped write must route through wireToCRDVDPreserving.", via)
}

if *m != bug433Minor {
t.Fatalf("%s CHANGED the volume's DRBDMinor: got %d want %d — the device identity of a "+
"live volume must not move on a routine modify (Bug 433).", via, *m, bug433Minor)
}
}

// TestBug433_PatchVDSpecResizePreservesDRBDMinor — a legal in-bounds
// `vd set-size` grow must not touch the volume's DRBD device minor.
func TestBug433_PatchVDSpecResizePreservesDRBDMinor(t *testing.T) {
t.Parallel()

const rd = "bug433-resize"

s, cli := bug433SeedStore(t, rd)

err := s.VolumeDefinitions().PatchVolumeDefinitionSpec(context.Background(), rd, 0,
func(vd *apiv1.VolumeDefinition) error {
vd.SizeKib = bug433TwoGiB

return nil
})
if err != nil {
t.Fatalf("patch (resize): %v", err)
}

bug433AssertMinorPreserved(t, cli, rd, "`vd set-size` grow (PatchVolumeDefinitionSpec)")
}

// TestBug433_PatchVDSpecPropModifyPreservesDRBDMinor — a pure
// `vd set-property` edit (no size change) must not touch the device
// identity.
func TestBug433_PatchVDSpecPropModifyPreservesDRBDMinor(t *testing.T) {
t.Parallel()

const rd = "bug433-props"

s, cli := bug433SeedStore(t, rd)

err := s.VolumeDefinitions().PatchVolumeDefinitionSpec(context.Background(), rd, 0,
func(vd *apiv1.VolumeDefinition) error {
if vd.Props == nil {
vd.Props = map[string]string{}
}
vd.Props["Aux/bug433-probe"] = "x"

return nil
})
if err != nil {
t.Fatalf("patch (props): %v", err)
}

bug433AssertMinorPreserved(t, cli, rd, "`vd set-property` (PatchVolumeDefinitionSpec)")
}

// TestBug433_UpdatePreservesDRBDMinor — the sibling wholesale
// volumeDefinitions.Update path has the identical drop; a REST modify
// routed through it must likewise keep the device identity.
func TestBug433_UpdatePreservesDRBDMinor(t *testing.T) {
t.Parallel()

const rd = "bug433-update"

s, cli := bug433SeedStore(t, rd)

// The wire shape carries no DRBDMinor, so an operator Update supplies
// only VolumeNumber/SizeKib/Props/Flags — the store must carry the
// device identity across from the live CRD entry.
err := s.VolumeDefinitions().Update(context.Background(), rd, &apiv1.VolumeDefinition{
VolumeNumber: 0,
SizeKib: bug433TwoGiB,
})
if err != nil {
t.Fatalf("update: %v", err)
}

bug433AssertMinorPreserved(t, cli, rd, "volumeDefinitions.Update")
}
37 changes: 33 additions & 4 deletions pkg/store/k8s/typed_field_carry_across_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,31 @@ var classifications = map[string]specClassification{ //nolint:gochecknoglobals /
},
mustCarryAcross: map[string]bool{},
},
"ResourceDefinitionVolume": {
// Not a Spec: the inline element-shape of
// ResourceDefinitionSpec.VolumeDefinitions, rebuilt per-element by
// wireToCRDVD (wire shape apiv1.VolumeDefinition) on the VD-scoped
// Update / PatchVolumeDefinitionSpec paths.
kind: "ResourceDefinitionVolume element (pkg/store/k8s/volume_definitions.go::wireToCRDVD / wireToCRDVDPreserving; wire shape apiv1.VolumeDefinition)",
wireDerived: map[string]bool{
"VolumeNumber": true,
"SizeKib": true,
"Props": true,
"Flags": true,
},
mustCarryAcross: map[string]bool{
// Bug 433: the per-volume DRBDMinor is the /dev/drbd<N>
// device identity and has NO counterpart on
// apiv1.VolumeDefinition. The RD-scoped write preserves the
// whole VolumeDefinitions slice wholesale (so the minor rode
// along for free — see ResourceDefinitionSpec above), but the
// VD-scoped element rebuild dropped it until the write-back
// was routed through wireToCRDVDPreserving. Same
// wire-rebuild-drops-operator-only-field class as Bug 206 /
// 208 / 209.
"DRBDMinor": true,
},
},
}

// specsUnderTest lists every CRD Spec whose Update / Patch path
Expand All @@ -263,10 +288,13 @@ var classifications = map[string]specClassification{ //nolint:gochecknoglobals /
// not apply.
//
// ResourceDefinitionVolume is the inline element-shape of
// ResourceDefinitionSpec.VolumeDefinitions and is itself rebuilt by
// `wireToCRDVD`, but every field there has a wire counterpart on
// apiv1.VolumeDefinition (volumeNumber, sizeKib, props, flags) — no
// operator-only fields to carry across.
// ResourceDefinitionSpec.VolumeDefinitions, itself rebuilt per-element by
// `wireToCRDVD` on the VD-scoped Update / PatchVolumeDefinitionSpec
// paths. It carries one operator-only field with NO wire counterpart —
// DRBDMinor, the /dev/drbd<N> device identity (Bug 433) — so it IS under
// test here (this is what the pre-433 "every field has a wire
// counterpart" assumption missed). The store-side write-back routes
// through wireToCRDVDPreserving to carry the minor across the rebuild.
func specsUnderTest() []reflect.Type {
return []reflect.Type{
reflect.TypeOf(crdv1alpha1.NodeSpec{}),
Expand All @@ -276,6 +304,7 @@ func specsUnderTest() []reflect.Type {
reflect.TypeOf(crdv1alpha1.StoragePoolSpec{}),
reflect.TypeOf(crdv1alpha1.SnapshotSpec{}),
reflect.TypeOf(crdv1alpha1.PhysicalDeviceSpec{}),
reflect.TypeOf(crdv1alpha1.ResourceDefinitionVolume{}),
}
}

Expand Down
38 changes: 35 additions & 3 deletions pkg/store/k8s/volume_definitions.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,9 @@ func (s *volumeDefinitions) Update(ctx context.Context, rdName string, vd *apiv1
return errors.Wrapf(store.ErrNotFound, "volume %d on resource definition %q", vd.VolumeNumber, rdName)
}

rd.Spec.VolumeDefinitions[idx] = wireToCRDVD(vd)
// Bug 433: carry the operator-only DRBDMinor across the wire
// rebuild so a routine REST modify can't wipe the device identity.
rd.Spec.VolumeDefinitions[idx] = wireToCRDVDPreserving(&rd.Spec.VolumeDefinitions[idx], vd)

return s.c.Update(ctx, rd)
}), "update RD %q for volume %d", rdName, vd.VolumeNumber)
Expand Down Expand Up @@ -321,8 +323,10 @@ func (s *volumeDefinitions) PatchVolumeDefinitionSpec(ctx context.Context, rdNam
}

// Re-derive the inline CRD entry from the mutated wire value
// and write it back into the parent RD's slice.
rd.Spec.VolumeDefinitions[idx] = wireToCRDVD(&wire)
// and write it back into the parent RD's slice. Bug 433: the
// wire shape has no DRBDMinor, so carry the operator-only device
// identity across the rebuild instead of zeroing it.
rd.Spec.VolumeDefinitions[idx] = wireToCRDVDPreserving(&rd.Spec.VolumeDefinitions[idx], &wire)

return s.c.Patch(ctx, rd, ctrlclient.MergeFromWithOptions(base, ctrlclient.MergeFromWithOptimisticLock{}))
}), "patch RD %q for volume %d", rdName, volumeNumber)
Expand Down Expand Up @@ -456,6 +460,34 @@ func wireToCRDVD(vd *apiv1.VolumeDefinition) crdv1alpha1.ResourceDefinitionVolum
}
}

// wireToCRDVDPreserving re-derives the inline CRD VolumeDefinition entry
// from a mutated wire value while carrying across the CRD-only typed
// fields that have NO counterpart on the wire shape.
//
// Today that is the per-volume DRBDMinor — the /dev/drbd<N> device
// identity, which apiv1.VolumeDefinition does not carry (it transcodes
// only VolumeNumber/SizeKib/Props/Flags). A naive wireToCRDVD round-trip
// therefore zeroes the minor. Per the CRD contract a non-nil minor is
// authoritative and "is NEVER overwritten … the store-side
// VolumeDefinitions carry-across preserves the value through a REST
// modify" (api/v1alpha1/resourcedefinition_types.go). Both VD-scoped
// write paths (volumeDefinitions.Update, PatchVolumeDefinitionSpec) MUST
// route their write-back through this helper so a legal `vd set-size` /
// `vd set-property` cannot silently change the DRBD device identity of a
// live volume.
//
// Bug 433 — the same wire-rebuild-drops-operator-only-field class as the
// carry-across family (Bug 206 RD.VolumeDefinitions, Bug 208 Node ranges,
// Bug 209 RD.Encryption). The RD-scoped path preserves the whole
// VolumeDefinitions slice wholesale (so DRBDMinor rode along for free),
// which is why only the VD-scoped element rebuild dropped it.
func wireToCRDVDPreserving(prev *crdv1alpha1.ResourceDefinitionVolume, wire *apiv1.VolumeDefinition) crdv1alpha1.ResourceDefinitionVolume {
out := wireToCRDVD(wire)
out.DRBDMinor = prev.DRBDMinor

return out
}
Comment on lines +484 to +489

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To enforce defensive programming and prevent potential nil pointer dereferences in the future, it is safer to add a nil check for the prev pointer before accessing its fields. While the current callers pass a non-nil pointer, safeguarding this helper function ensures robustness against future refactoring or reuse.

Suggested change
func wireToCRDVDPreserving(prev *crdv1alpha1.ResourceDefinitionVolume, wire *apiv1.VolumeDefinition) crdv1alpha1.ResourceDefinitionVolume {
out := wireToCRDVD(wire)
out.DRBDMinor = prev.DRBDMinor
return out
}
func wireToCRDVDPreserving(prev *crdv1alpha1.ResourceDefinitionVolume, wire *apiv1.VolumeDefinition) crdv1alpha1.ResourceDefinitionVolume {
out := wireToCRDVD(wire)
if prev != nil {
out.DRBDMinor = prev.DRBDMinor
}
return out
}


// vdByNumber returns the embedded volume-definition with the given
// VolumeNumber, or nil when the RD spec does not carry it.
func vdByNumber(rd *crdv1alpha1.ResourceDefinition, volumeNumber int32) *crdv1alpha1.ResourceDefinitionVolume {
Expand Down
1 change: 1 addition & 0 deletions tests/e2e/cli-matrix/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ A cell counts as **FAIL** if either leg times out, the `linstor` CLI exits non-z
| `snap-restore-snapshotless-node-rejected.sh` | 397 | P0 DATA INTEGRITY. `snapshot resource restore` onto a node NOT holding the snapshot is rejected (no silent empty replica, no orphan RD); restoring onto the snapshot's own nodes converges UpToDate AND every replica holds the real snapshot bytes (marker read per-replica), never a silently-empty UpToDate copy. |
| `rd-clone-vd-data-plane.sh` | 020 | `linstor rd clone <src> <dst>` on a VD-bearing source (plain CLI body, no `use_zfs_clone`) AND the raw-REST `use_zfs_clone=true` body linstor-csi sends both materialise a real clone: 2 replicas UpToDate, marker bytes from the source present on EVERY clone replica (promote each in turn), clone status COMPLETE, internal `clone-<dst>` snapshot visible on the source. Pre-fix: 400 on `use_zfs_clone`, 501 on VD-bearing sources (Bug 114 gate). |
| `encryption-passphrase-luks-rd.sh` | 023 | Secret-only LUKS flow: `linstor encryption create-passphrase` alone (legacy `DrbdOptions/EncryptPassphrase` controller prop asserted ABSENT throughout) unlocks `rd c -l drbd,luks,storage` + autoplace to UpToDate, and the Secret-backed passphrase actually opens the LUKS header on each replica's backing device. Requires the Bug-023 fix (PR #143); pre-fix the rd-create is rejected with "LUKS layer requires DrbdOptions/EncryptPassphrase to be set first". |
| `vd-modify-preserves-drbd-minor.sh` | 433 | A legal in-bounds VD-scoped modify (`vd set-size` grow / `vd set-property`) must NOT change the per-volume DRBDMinor — the /dev/drbd<N> device identity. Creates rd-a (lowest minor Ma) + rd-b (next minor Mb), frees Ma by deleting rd-a, then modifies rd-b: its DRBDMinor AND device path must stay Mb over a settle window. Pre-fix `wireToCRDVD` dropped the minor on the VD-scoped write-back and the allocator re-stamped the freed lower Ma — a permanent device-identity change on a live resized volume. |

## Running

Expand Down
Loading