From f0b77c50c983e7cdb8f3b3dc584b074325143dc0 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Sun, 22 Nov 2026 13:21:34 +0100 Subject: [PATCH 01/16] fix(rest,cli): guard a replica delete only on a volume that stays linstor-csi's DeleteVolume deletes the replicas one by one in listing order. On a volume deleted during its initial sync that removed the sync source first; the remaining UpToDate copy was then the last complete copy next to an Inconsistent replica, the mid-sync guard refused it, and the volume could never be deleted: the driver retried every five minutes for good. LINSTOR has no such check on any delete path. The guard protects the data of a volume that outlives the delete, so it now steps aside when the whole definition is going: the RD carries DELETE, or linstor-csi set BalanceResourcesEnabled=False on it, which DeleteVolume does before its replica deletes and is the only notice they get. A peer that is itself being deleted no longer counts as stranded. The REST door and the CLI share the rule. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- internal/cli/write_more.go | 11 ++ internal/cli/write_more_test.go | 52 ++++++++ .../resource_delete_last_uptodate_u130.go | 20 +++ .../resource_delete_mid_initial_sync_test.go | 122 ++++++++++++++++++ pkg/validate/resource_delete.go | 37 ++++++ pkg/validate/validate_test.go | 55 ++++++++ 6 files changed, 297 insertions(+) create mode 100644 pkg/rest/resource_delete_mid_initial_sync_test.go diff --git a/internal/cli/write_more.go b/internal/cli/write_more.go index daa984ec7..dcfc073dd 100644 --- a/internal/cli/write_more.go +++ b/internal/cli/write_more.go @@ -554,6 +554,17 @@ func checkDeletable(ctx context.Context, run *runContext, rdName, node string) e return fmt.Errorf("get resource %s on %s: %w", rdName, node, err) } + // Only a replica dropped from a volume that stays is guarded; see + // validate.DefinitionBeingDeleted. + rd, err := run.Store.ResourceDefinitions().Get(ctx, rdName) + if err != nil && !isNotFound(err) { + return fmt.Errorf("get resource definition %s: %w", rdName, err) + } + + if err == nil && validate.DefinitionBeingDeleted(&rd) { + return nil + } + siblings, err := run.Store.Resources().ListByDefinition(ctx, rdName) if err != nil { return fmt.Errorf("list replicas of %s: %w", rdName, err) diff --git a/internal/cli/write_more_test.go b/internal/cli/write_more_test.go index 0cde90039..e4c413d52 100644 --- a/internal/cli/write_more_test.go +++ b/internal/cli/write_more_test.go @@ -358,3 +358,55 @@ func TestResourceGroupSpawnEnforcesBounds(t *testing.T) { t.Error("spawn accepted a sub-floor volume size") } } + +// The last complete copy of a volume that stays is still refused. +func TestResourceDeleteOfLastCompleteCopyStaysGuarded(t *testing.T) { + t.Parallel() + + app, _, _ := newApp(t, func(ctx context.Context, backend store.Store) { + seedDefinition(ctx, backend) + + for node, disk := range map[string]string{ + "node-a": "UpToDate", + "node-b": "Inconsistent", + } { + _ = backend.Resources().Create(ctx, &apiv1.Resource{ + Name: "pvc-x", NodeName: node, + Volumes: []apiv1.Volume{{State: apiv1.VolumeState{DiskState: disk}}}, + }) + } + }) + + if got := app.Run(t.Context(), []string{"r", "d", "node-a", "pvc-x"}); got == 0 { + t.Fatal("the last complete copy was deleted while a peer was still syncing") + } +} + +// A replica delete on a definition linstor-csi's DeleteVolume is tearing +// down (balancing switched off first) is not guarded: every replica is +// going, so the Inconsistent one is not stranded. +func TestResourceDeleteDuringVolumeTeardownIsNotGuarded(t *testing.T) { + t.Parallel() + + app, _, errBuf := newApp(t, func(ctx context.Context, backend store.Store) { + _ = backend.ResourceDefinitions().Create(ctx, &apiv1.ResourceDefinition{ + Name: "pvc-x", + Props: map[string]string{apiv1.PropBalanceResourcesEnabled: "False"}, + }) + + for node, disk := range map[string]string{ + "node-a": "UpToDate", + "node-b": "Inconsistent", + } { + _ = backend.Resources().Create(ctx, &apiv1.Resource{ + Name: "pvc-x", NodeName: node, + Volumes: []apiv1.Volume{{State: apiv1.VolumeState{DiskState: disk}}}, + }) + } + }) + + if got := app.Run(t.Context(), []string{"r", "d", "node-a", "pvc-x"}); got != 0 { + t.Fatalf("delete exit = %d (stderr: %s)", got, errBuf.String()) + } +} + diff --git a/pkg/rest/resource_delete_last_uptodate_u130.go b/pkg/rest/resource_delete_last_uptodate_u130.go index a371e32c0..6a141eb03 100644 --- a/pkg/rest/resource_delete_last_uptodate_u130.go +++ b/pkg/rest/resource_delete_last_uptodate_u130.go @@ -103,6 +103,26 @@ func (s *Server) refuseLastUpToDateDiskfulMidSyncDelete( return true } + // The guard is for a replica dropped from a volume that stays. When + // the whole definition is going (`rd d`, or linstor-csi's + // DeleteVolume deleting every replica in turn) the peer it would + // protect goes too, and refusing here only leaves a volume that can + // never be deleted. See validate.DefinitionBeingDeleted. + rd, err := s.Store.ResourceDefinitions().Get(ctx, rdName) + if err != nil { + if errors.Is(err, store.ErrNotFound) { + return true + } + + writeStoreError(w, err) + + return false + } + + if validate.DefinitionBeingDeleted(&rd) { + return true + } + siblings, err := s.Store.Resources().ListByDefinition(ctx, rdName) if err != nil { // A list failure must not silently allow a destructive delete diff --git a/pkg/rest/resource_delete_mid_initial_sync_test.go b/pkg/rest/resource_delete_mid_initial_sync_test.go new file mode 100644 index 000000000..096229524 --- /dev/null +++ b/pkg/rest/resource_delete_mid_initial_sync_test.go @@ -0,0 +1,122 @@ +// 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 rest + +import ( + "errors" + "net/http" + "testing" + + apiv1 "github.com/cozystack/blockstor/pkg/api/v1" + "github.com/cozystack/blockstor/pkg/store" +) + +// seedInitialSyncVolume lays out a three-replica volume deleted a few +// seconds after creation: node-a is the source of the initial sync, +// node-b already reached UpToDate, node-c is still Inconsistent and its +// connection to node-b is Established (DRBD sees nothing to resync). +func seedInitialSyncVolume(t *testing.T, st store.Store, rd string) { + t.Helper() + + seedU130RD(t, st, rd) + + inconsistent := diskfulReplica(rd, "node-c", drbdDiskStateInconsistent) + inconsistent.Volumes[0].State.ReplicationStates = map[string]apiv1.ReplicationState{ + "node-b": {ReplicationState: "Established"}, + } + + for _, res := range []*apiv1.Resource{ + diskfulReplica(rd, "node-a", drbdDiskStateUpToDate), + diskfulReplica(rd, "node-b", drbdDiskStateUpToDate), + inconsistent, + } { + if err := st.Resources().Create(t.Context(), res); err != nil { + t.Fatalf("seed %s: %v", res.NodeName, err) + } + } +} + +func deleteReplica(t *testing.T, base, rd, node string) int { + t.Helper() + + resp := httpDelete(t, base+"/v1/resource-definitions/"+rd+"/resources/"+node) + _ = resp.Body.Close() + + return resp.StatusCode +} + +// linstor-csi's DeleteVolume, call for call: switch balancing off on the +// definition, then delete the replicas one by one in listing order. The +// last complete copy is the second delete, while the Inconsistent replica +// is still there; refusing it left the volume undeletable, with the +// driver retrying every five minutes for good. LINSTOR answers all three +// deletes, and so must blockstor. +func TestCSIDeleteVolumeDuringInitialSyncDeletesEveryReplica(t *testing.T) { + st := store.NewInMemory() + rd := "pvc-initial-sync" + + seedInitialSyncVolume(t, st, rd) + + base, stop := startServerWithStore(t, st) + defer stop() + + put := httpPut(t, base+"/v1/resource-definitions/"+rd, + []byte(`{"override_props":{"BalanceResourcesEnabled":"False"}}`)) + _ = put.Body.Close() + + if put.StatusCode != http.StatusOK { + t.Fatalf("modify: got %d, want 200", put.StatusCode) + } + + for _, node := range []string{"node-a", "node-b", "node-c"} { + if code := deleteReplica(t, base, rd, node); code != http.StatusOK { + t.Fatalf("delete %s: got %d, want 200", node, code) + } + } + + left, err := st.Resources().ListByDefinition(t.Context(), rd) + if err != nil && !errors.Is(err, store.ErrNotFound) { + t.Fatalf("list: %v", err) + } + + if len(left) != 0 { + t.Errorf("%d replica(s) survived DeleteVolume: %+v", len(left), left) + } +} + +// The same replica delete on a volume that stays is still refused: the +// guard is lifted for a definition being deleted, not for every delete. +func TestSingleReplicaDeleteDuringInitialSyncStaysGuarded(t *testing.T) { + st := store.NewInMemory() + rd := "pvc-initial-sync-live" + + seedInitialSyncVolume(t, st, rd) + + base, stop := startServerWithStore(t, st) + defer stop() + + if code := deleteReplica(t, base, rd, "node-a"); code != http.StatusOK { + t.Fatalf("delete node-a: got %d, want 200 (node-b survives)", code) + } + + if code := deleteReplica(t, base, rd, "node-b"); code != http.StatusConflict { + t.Fatalf("delete node-b: got %d, want 409 (last complete copy)", code) + } +} + diff --git a/pkg/validate/resource_delete.go b/pkg/validate/resource_delete.go index f28cf4c83..544a81f54 100644 --- a/pkg/validate/resource_delete.go +++ b/pkg/validate/resource_delete.go @@ -20,6 +20,8 @@ package validate import ( "errors" + "slices" + "strings" apiv1 "github.com/cozystack/blockstor/pkg/api/v1" "github.com/cozystack/blockstor/pkg/naming" @@ -72,6 +74,12 @@ func MidSyncDeleteRefusal(target *apiv1.Resource, siblings []apiv1.Resource) boo continue } + // A peer already on its way out is not stranded by losing its + // source: nothing will ever read what it was syncing. + if slices.Contains(sib.Flags, apiv1.ResourceFlagDelete) { + continue + } + switch { case resourceIsConfirmedUpToDateSource(sib): confirmedSources++ @@ -89,6 +97,35 @@ func MidSyncDeleteRefusal(target *apiv1.Resource, siblings []apiv1.Resource) boo return midSyncPeers > 0 } +// DefinitionBeingDeleted reports whether the whole definition is being +// taken apart, as opposed to one replica of a volume that stays. +// +// MidSyncDeleteRefusal protects the data of a volume that outlives the +// delete. LINSTOR has no such check on any delete path; blockstor keeps it +// for a single replica dropped from a live volume, and nowhere else. When +// every replica is going, a peer left Inconsistent is about to go too, and +// refusing the source only strands the delete: the volume can then never +// be removed at all. +// +// Two shapes say the definition is going. The DELETE flag is LINSTOR's own +// mark for `rd d`. linstor-csi's DeleteVolume never sends `rd d` first: it +// sets BalanceResourcesEnabled=False on the definition, then deletes the +// replicas one by one, then the definition (pkg/client/linstor.go, Delete). +// That property write is the only notice the replica deletes get that they +// are one volume teardown. An operator who switched balancing off by hand +// loses the guard on that definition, which is where LINSTOR always is. +func DefinitionBeingDeleted(rd *apiv1.ResourceDefinition) bool { + if rd == nil { + return false + } + + if slices.Contains(rd.Flags, apiv1.ResourceFlagDelete) { + return true + } + + return strings.EqualFold(rd.Props[apiv1.PropBalanceResourcesEnabled], "false") +} + // ResourceIsDiskful reports whether a replica carries real backing storage // (not DISKLESS, not TIE_BREAKER). func ResourceIsDiskful(res *apiv1.Resource) bool { diff --git a/pkg/validate/validate_test.go b/pkg/validate/validate_test.go index 213f0e78d..235032ff2 100644 --- a/pkg/validate/validate_test.go +++ b/pkg/validate/validate_test.go @@ -308,6 +308,61 @@ func TestMidSyncDeleteRefusal(t *testing.T) { } } +// The shape a volume deleted during its initial sync is left in: the sync +// source is gone, one complete copy remains, and the other replica stays +// Inconsistent on an Established connection to it. The guard is for a +// volume that stays; once the definition is being deleted the remaining +// replicas have to be deletable, or the volume never goes away. +func TestMidSyncDeleteRefusalLiftedWhileDefinitionIsDeleted(t *testing.T) { + t.Parallel() + + target := diskful("node-b", "UpToDate") + stranded := []apiv1.Resource{diskful("node-c", "Inconsistent")} + + if !validate.MidSyncDeleteRefusal(&target, stranded) { + t.Fatal("a single replica delete of the last complete copy must stay guarded") + } + + for name, tc := range map[string]struct { + rd apiv1.ResourceDefinition + deleted bool + }{ + "a live definition": {apiv1.ResourceDefinition{}, false}, + "balancing switched on": { + apiv1.ResourceDefinition{Props: map[string]string{apiv1.PropBalanceResourcesEnabled: "true"}}, false, + }, + "rd d flagged it DELETE": { + apiv1.ResourceDefinition{Flags: []string{apiv1.ResourceFlagDelete}}, true, + }, + "linstor-csi DeleteVolume switched balancing off": { + apiv1.ResourceDefinition{Props: map[string]string{apiv1.PropBalanceResourcesEnabled: "False"}}, true, + }, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + rd := tc.rd + if got := validate.DefinitionBeingDeleted(&rd); got != tc.deleted { + t.Errorf("DefinitionBeingDeleted = %v, want %v", got, tc.deleted) + } + }) + } +} + +// A peer that is itself being deleted cannot be stranded: deleting the +// source after it is the order SortForDeletion produces. +func TestMidSyncDeleteRefusalIgnoresPeerBeingDeleted(t *testing.T) { + t.Parallel() + + target := diskful("node-b", "UpToDate") + going := diskful("node-c", "Inconsistent") + going.Flags = []string{apiv1.ResourceFlagDelete} + + if validate.MidSyncDeleteRefusal(&target, []apiv1.Resource{going}) { + t.Error("refused over a peer that is already being deleted") + } +} + func TestResourceIsDiskful(t *testing.T) { t.Parallel() From ca0c85753e6f3e45dca74e3945a43f5bcd0ea559 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Sun, 22 Nov 2026 13:21:34 +0100 Subject: [PATCH 02/16] fix(store,cli): delete the incomplete replicas of a volume first Removing the source of an initial sync while its target is still Inconsistent can leave the target with a cleared bitmap on an Established connection to the remaining UpToDate peer: DRBD sees nothing to resync and the replica stays Inconsistent for good. That is how the stuck volume got its second, never-syncing replica. Where blockstor itself deletes replicas one at a time (the rd d cascade, r d naming several nodes) the diskful replicas that are not complete copies yet now go first, so a source never goes while something still depends on it, and an r d naming every replica is not refused over a peer the same command was about to delete. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- internal/cli/write_more.go | 50 ++++++++++++++- internal/cli/write_more_test.go | 35 +++++++++++ pkg/store/cascade.go | 3 + pkg/store/cascade_order_test.go | 66 ++++++++++++++++++++ pkg/store/storetest/delete_recorder.go | 85 ++++++++++++++++++++++++++ pkg/validate/resource_delete.go | 24 ++++++++ pkg/validate/validate_test.go | 27 ++++++++ 7 files changed, 289 insertions(+), 1 deletion(-) create mode 100644 pkg/store/cascade_order_test.go create mode 100644 pkg/store/storetest/delete_recorder.go diff --git a/internal/cli/write_more.go b/internal/cli/write_more.go index dcfc073dd..f1e5c7ac0 100644 --- a/internal/cli/write_more.go +++ b/internal/cli/write_more.go @@ -512,7 +512,12 @@ func resourceDelete(ctx context.Context, run *runContext) error { last := len(run.Flags.Positionals) - 1 rdName := run.Flags.Positionals[last] - for _, node := range run.Flags.Positionals[:last] { + nodes, err := deletionOrder(ctx, run, rdName, run.Flags.Positionals[:last]) + if err != nil { + return err + } + + for _, node := range nodes { err := checkDeletable(ctx, run, rdName, node) if err != nil { return err @@ -527,6 +532,49 @@ func resourceDelete(ctx context.Context, run *runContext) error { return nil } +// deletionOrder puts the named replicas in the order they are safe to +// delete one at a time (validate.SortForDeletion): `r d a b c ` naming a +// syncing replica after its source would otherwise drop the source first and +// be refused on the replica it was about to delete anyway. +func deletionOrder(ctx context.Context, run *runContext, rdName string, named []string) ([]string, error) { + if len(named) < 2 { + return named, nil + } + + replicas, err := run.Store.Resources().ListByDefinition(ctx, rdName) + if err != nil { + if isNotFound(err) { + return named, nil + } + + return nil, fmt.Errorf("list replicas of %s: %w", rdName, err) + } + + validate.SortForDeletion(replicas) + + ordered := make([]string, 0, len(named)) + taken := make([]bool, len(named)) + + for i := range replicas { + for j, node := range named { + if !taken[j] && naming.Same(node, replicas[i].NodeName) { + ordered = append(ordered, node) + taken[j] = true + } + } + } + + // Names with no replica behind them keep their place at the end; the + // delete is idempotent for them. + for j, node := range named { + if !taken[j] { + ordered = append(ordered, node) + } + } + + return ordered, nil +} + // checkDeletable refuses a delete that would strand a peer still resyncing // from this replica — upstream U130. // diff --git a/internal/cli/write_more_test.go b/internal/cli/write_more_test.go index e4c413d52..437910e53 100644 --- a/internal/cli/write_more_test.go +++ b/internal/cli/write_more_test.go @@ -359,6 +359,41 @@ func TestResourceGroupSpawnEnforcesBounds(t *testing.T) { } } +// `r d` naming every replica of a volume still in its initial sync, the +// source first: the Inconsistent replica is deleted before the copies it +// depends on, so the last complete copy is never refused over a peer the +// same command was about to delete. +func TestResourceDeleteOfEveryReplicaMidInitialSync(t *testing.T) { + t.Parallel() + + app, _, errBuf := newApp(t, func(ctx context.Context, backend store.Store) { + seedDefinition(ctx, backend) + + for node, disk := range map[string]string{ + "node-a": "UpToDate", + "node-b": "Inconsistent", + } { + _ = backend.Resources().Create(ctx, &apiv1.Resource{ + Name: "pvc-x", NodeName: node, + Volumes: []apiv1.Volume{{State: apiv1.VolumeState{DiskState: disk}}}, + }) + } + }) + + if got := app.Run(t.Context(), []string{"r", "d", "node-a", "node-b", "pvc-x"}); got != 0 { + t.Fatalf("delete exit = %d (stderr: %s)", got, errBuf.String()) + } + + resources, err := appStore(t, app).Resources().List(t.Context()) + if err != nil { + t.Fatalf("list: %v", err) + } + + if len(resources) != 0 { + t.Errorf("replicas survived the delete: %+v", resources) + } +} + // The last complete copy of a volume that stays is still refused. func TestResourceDeleteOfLastCompleteCopyStaysGuarded(t *testing.T) { t.Parallel() diff --git a/pkg/store/cascade.go b/pkg/store/cascade.go index c2496621b..ca3917d8a 100644 --- a/pkg/store/cascade.go +++ b/pkg/store/cascade.go @@ -27,6 +27,7 @@ import ( apiv1 "github.com/cozystack/blockstor/pkg/api/v1" "github.com/cozystack/blockstor/pkg/naming" + "github.com/cozystack/blockstor/pkg/validate" ) // The teardown a delete has to perform, shared by the two write doors. @@ -79,6 +80,8 @@ func CascadeDeleteResources(ctx context.Context, st Store, rdName string) error return nil } + validate.SortForDeletion(children) + for i := range children { err = st.Resources().Delete(ctx, rdName, children[i].NodeName) if err != nil && !errors.Is(err, ErrNotFound) { diff --git a/pkg/store/cascade_order_test.go b/pkg/store/cascade_order_test.go new file mode 100644 index 000000000..47c98c32b --- /dev/null +++ b/pkg/store/cascade_order_test.go @@ -0,0 +1,66 @@ +// 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 store_test + +import ( + "testing" + + apiv1 "github.com/cozystack/blockstor/pkg/api/v1" + "github.com/cozystack/blockstor/pkg/store" + "github.com/cozystack/blockstor/pkg/store/storetest" +) + +// The cascade of a volume still in its initial sync deletes the +// Inconsistent replica before the UpToDate copies it depends on, so the +// source of the sync is never the first replica to go. +func TestCascadeDeletesIncompleteReplicasFirst(t *testing.T) { + t.Parallel() + + ctx := t.Context() + backend := store.NewInMemory() + + if err := backend.ResourceDefinitions().Create(ctx, &apiv1.ResourceDefinition{Name: "pvc-sync"}); err != nil { + t.Fatalf("seed RD: %v", err) + } + + for node, disk := range map[string]string{ + "node-a": "UpToDate", + "node-b": "UpToDate", + "node-c": "Inconsistent", + } { + if err := backend.Resources().Create(ctx, &apiv1.Resource{ + Name: "pvc-sync", NodeName: node, + Volumes: []apiv1.Volume{{State: apiv1.VolumeState{DiskState: disk}}}, + }); err != nil { + t.Fatalf("seed %s: %v", node, err) + } + } + + rec := storetest.NewDeleteRecorder(backend) + + if err := store.CascadeDeleteResources(ctx, rec, "pvc-sync"); err != nil { + t.Fatalf("cascade: %v", err) + } + + deletes := rec.Deletes() + if len(deletes) != 3 || deletes[0].Node != "node-c" { + t.Errorf("deletes = %+v, want the Inconsistent node-c first", deletes) + } +} + diff --git a/pkg/store/storetest/delete_recorder.go b/pkg/store/storetest/delete_recorder.go new file mode 100644 index 000000000..64e8245c5 --- /dev/null +++ b/pkg/store/storetest/delete_recorder.go @@ -0,0 +1,85 @@ +// 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 storetest + +import ( + "context" + "slices" + "sync" + + apiv1 "github.com/cozystack/blockstor/pkg/api/v1" + "github.com/cozystack/blockstor/pkg/store" +) + +// ReplicaDelete is one replica delete a DeleteRecorder saw. +type ReplicaDelete struct { + Node string + // DefinitionFlagged reports whether the parent definition already + // carried DELETE when the replica was deleted. + DefinitionFlagged bool +} + +// DeleteRecorder wraps a store and notes every replica delete in order, +// with whether its definition had been flagged DELETE by then. The `rd d` +// doors are tested with it: the flag has to be on the definition before +// the first replica goes, and the replicas go in validate.SortForDeletion +// order. +type DeleteRecorder struct { + store.Store + + mu sync.Mutex + deletes []ReplicaDelete +} + +// NewDeleteRecorder wraps backend. +func NewDeleteRecorder(backend store.Store) *DeleteRecorder { + return &DeleteRecorder{Store: backend} +} + +// Resources returns the recording replica store. +func (r *DeleteRecorder) Resources() store.ResourceStore { + return recordingResources{ResourceStore: r.Store.Resources(), rec: r} +} + +// Deletes returns the replica deletes seen so far. +func (r *DeleteRecorder) Deletes() []ReplicaDelete { + r.mu.Lock() + defer r.mu.Unlock() + + return slices.Clone(r.deletes) +} + +type recordingResources struct { + store.ResourceStore + + rec *DeleteRecorder +} + +func (r recordingResources) Delete(ctx context.Context, rdName, node string) error { + rd, err := r.rec.ResourceDefinitions().Get(ctx, rdName) + + r.rec.mu.Lock() + r.rec.deletes = append(r.rec.deletes, ReplicaDelete{ + Node: node, + DefinitionFlagged: err == nil && slices.Contains(rd.Flags, apiv1.ResourceFlagDelete), + }) + r.rec.mu.Unlock() + + return r.ResourceStore.Delete(ctx, rdName, node) //nolint:wrapcheck // pass-through test double +} diff --git a/pkg/validate/resource_delete.go b/pkg/validate/resource_delete.go index 544a81f54..b59a5e17e 100644 --- a/pkg/validate/resource_delete.go +++ b/pkg/validate/resource_delete.go @@ -126,6 +126,30 @@ func DefinitionBeingDeleted(rd *apiv1.ResourceDefinition) bool { return strings.EqualFold(rd.Props[apiv1.PropBalanceResourcesEnabled], "false") } +// SortForDeletion orders replicas the way they are safe to delete one at a +// time: the diskful replicas that are not complete copies yet first, every +// other replica after them in its original order. +// +// Removing the source of an initial sync while its target is still +// Inconsistent can leave the target with a cleared bitmap on an Established +// connection to the remaining UpToDate peer: DRBD sees nothing to resync +// and the replica stays Inconsistent for good. Taking the incomplete +// replicas away first means a source never goes while something still +// depends on it. +func SortForDeletion(replicas []apiv1.Resource) { + slices.SortStableFunc(replicas, func(a, b apiv1.Resource) int { + return deletionRank(&a) - deletionRank(&b) + }) +} + +func deletionRank(res *apiv1.Resource) int { + if ResourceIsDiskful(res) && resourceIsMidSync(res) { + return 0 + } + + return 1 +} + // ResourceIsDiskful reports whether a replica carries real backing storage // (not DISKLESS, not TIE_BREAKER). func ResourceIsDiskful(res *apiv1.Resource) bool { diff --git a/pkg/validate/validate_test.go b/pkg/validate/validate_test.go index 235032ff2..bb0a75169 100644 --- a/pkg/validate/validate_test.go +++ b/pkg/validate/validate_test.go @@ -363,6 +363,33 @@ func TestMidSyncDeleteRefusalIgnoresPeerBeingDeleted(t *testing.T) { } } +// Deleting replicas one at a time, the incomplete ones go first, so the +// source of an initial sync is never the first replica removed. +func TestSortForDeletionPutsIncompleteReplicasFirst(t *testing.T) { + t.Parallel() + + witness := apiv1.Resource{NodeName: "node-d", Flags: []string{apiv1.ResourceFlagTieBreaker}} + replicas := []apiv1.Resource{ + diskful("node-a", "UpToDate"), + diskful("node-b", "UpToDate"), + witness, + diskful("node-c", "Inconsistent"), + diskful("node-e", "SyncTarget"), + } + + validate.SortForDeletion(replicas) + + got := make([]string, 0, len(replicas)) + for i := range replicas { + got = append(got, replicas[i].NodeName) + } + + want := []string{"node-c", "node-e", "node-a", "node-b", "node-d"} + if !slices.Equal(got, want) { + t.Errorf("delete order = %v, want %v", got, want) + } +} + func TestResourceIsDiskful(t *testing.T) { t.Parallel() From 5b3fd43a3a7d46b005171d9bcd1ee9eb706b0162 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Sun, 22 Nov 2026 13:21:34 +0100 Subject: [PATCH 03/16] fix(rest,cli,controller): flag a definition DELETE before its replicas rd d deleted the replicas first and the definition last, so the RD reconciler saw a live definition with two diskful replicas between replica deletes and added a tiebreaker, which the next pass of the cascade then removed again. LINSTOR flags a definition DELETE before it walks the replicas. Both rd d doors now do the same, and the reconciler treats the flag like a deletion timestamp: no witness is added or removed on a definition being deleted. The flag also lifts the mid-sync replica guard for the whole walk. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- internal/cli/write.go | 5 + internal/cli/write_more_test.go | 39 ++++++ ...nsure_tiebreaker_rd_flagged_delete_test.go | 117 ++++++++++++++++++ .../resourcedefinition_controller.go | 6 +- pkg/rest/resource_definitions.go | 14 ++- .../resource_delete_mid_initial_sync_test.go | 57 +++++++++ pkg/store/cascade.go | 27 ++++ pkg/store/cascade_order_test.go | 34 +++++ 8 files changed, 296 insertions(+), 3 deletions(-) create mode 100644 internal/controller/ensure_tiebreaker_rd_flagged_delete_test.go diff --git a/internal/cli/write.go b/internal/cli/write.go index bd7eccbe1..fcf707453 100644 --- a/internal/cli/write.go +++ b/internal/cli/write.go @@ -401,6 +401,11 @@ func resourceDefinitionDelete(ctx context.Context, run *runContext) error { // Then the replicas. Dropping the definition alone leaves them with no // parent to stamp a deletion on, so the satellite finalizer never runs // and the DRBD minor, port and peer entries stay live on every node. + err = store.MarkDefinitionDeleting(ctx, run.Store, name) + if err != nil { + return fmt.Errorf("delete resource definition %s: %w", name, err) + } + err = store.CascadeDeleteResources(ctx, run.Store, name) if err != nil { return fmt.Errorf("delete replicas of %s: %w", name, err) diff --git a/internal/cli/write_more_test.go b/internal/cli/write_more_test.go index 437910e53..19d7673ee 100644 --- a/internal/cli/write_more_test.go +++ b/internal/cli/write_more_test.go @@ -25,6 +25,7 @@ import ( apiv1 "github.com/cozystack/blockstor/pkg/api/v1" "github.com/cozystack/blockstor/pkg/store" + "github.com/cozystack/blockstor/pkg/store/storetest" ) func seedDefinition(ctx context.Context, backend store.Store) { @@ -445,3 +446,41 @@ func TestResourceDeleteDuringVolumeTeardownIsNotGuarded(t *testing.T) { } } +// `rd d` flags the definition DELETE before the first replica goes and +// deletes the Inconsistent replica before its source, the way the REST +// door does. +func TestDefinitionDeleteFlagsDefinitionBeforeItsReplicas(t *testing.T) { + t.Parallel() + + app, _, errBuf := newApp(t, func(ctx context.Context, backend store.Store) { + seedDefinition(ctx, backend) + + for node, disk := range map[string]string{ + "node-a": "UpToDate", + "node-b": "Inconsistent", + } { + _ = backend.Resources().Create(ctx, &apiv1.Resource{ + Name: "pvc-x", NodeName: node, + Volumes: []apiv1.Volume{{State: apiv1.VolumeState{DiskState: disk}}}, + }) + } + }) + + rec := storetest.NewDeleteRecorder(appStore(t, app)) + app.StoreFor = func(context.Context) (store.Store, error) { return rec, nil } + + if got := app.Run(t.Context(), []string{"rd", "d", "pvc-x"}); got != 0 { + t.Fatalf("delete exit = %d (stderr: %s)", got, errBuf.String()) + } + + deletes := rec.Deletes() + if len(deletes) == 0 || deletes[0].Node != "node-b" { + t.Errorf("deletes = %+v, want the Inconsistent node-b first", deletes) + } + + for _, d := range deletes { + if !d.DefinitionFlagged { + t.Errorf("replica on %s deleted before the definition was flagged DELETE", d.Node) + } + } +} diff --git a/internal/controller/ensure_tiebreaker_rd_flagged_delete_test.go b/internal/controller/ensure_tiebreaker_rd_flagged_delete_test.go new file mode 100644 index 000000000..2a90fc6ea --- /dev/null +++ b/internal/controller/ensure_tiebreaker_rd_flagged_delete_test.go @@ -0,0 +1,117 @@ +// 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 controller_test + +import ( + "context" + "slices" + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + blockstoriov1alpha1 "github.com/cozystack/blockstor/api/v1alpha1" + controllerpkg "github.com/cozystack/blockstor/internal/controller" + apiv1 "github.com/cozystack/blockstor/pkg/api/v1" + "github.com/cozystack/blockstor/pkg/store" +) + +// rd d flags the definition DELETE before it walks the replicas, and the +// definition object itself only goes after them. Between two replica +// deletes the reconciler sees two diskful replicas and no witness; on a +// definition being deleted it must not add one (nor remove one), or every +// pass of the delete adds a tiebreaker and takes it away again. +func TestEnsureTiebreakerLeavesDefinitionFlaggedDeleteAlone(t *testing.T) { + t.Parallel() + + for name, seed := range map[string][]*apiv1.Resource{ + "no witness is added": { + {Name: "pvc-going", NodeName: "n1"}, + {Name: "pvc-going", NodeName: "n2"}, + }, + "the witness is not removed": { + {Name: "pvc-going", NodeName: "n1"}, + { + Name: "pvc-going", NodeName: "n3", + Flags: []string{apiv1.ResourceFlagDiskless, apiv1.ResourceFlagTieBreaker}, + }, + }, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + st := store.NewInMemory() + + seedNodes(t, ctx, st, "n1", "n2", "n3") + + err := st.ResourceDefinitions().Create(ctx, &apiv1.ResourceDefinition{ + Name: "pvc-going", Flags: []string{apiv1.ResourceFlagDelete}, + }) + if err != nil { + t.Fatalf("seed RD: %v", err) + } + + for _, res := range seed { + if err := st.Resources().Create(ctx, res); err != nil { + t.Fatalf("seed %s: %v", res.NodeName, err) + } + } + + rdCRD := &blockstoriov1alpha1.ResourceDefinition{ + ObjectMeta: metav1.ObjectMeta{Name: "pvc-going"}, + Spec: blockstoriov1alpha1.ResourceDefinitionSpec{ + Flags: []string{apiv1.ResourceFlagDelete}, + }, + } + + rec := &controllerpkg.ResourceDefinitionReconciler{ + Client: fake.NewClientBuilder().WithScheme(newScheme(t)).WithObjects(rdCRD).Build(), + Scheme: newScheme(t), + Store: st, + } + + if err := rec.EnsureTiebreaker(ctx, rdCRD); err != nil { + t.Fatalf("ensureTiebreaker: %v", err) + } + + got, err := st.Resources().ListByDefinition(ctx, "pvc-going") + if err != nil { + t.Fatalf("list: %v", err) + } + + nodes := make([]string, 0, len(got)) + for i := range got { + nodes = append(nodes, got[i].NodeName) + } + + want := make([]string, 0, len(seed)) + for _, res := range seed { + want = append(want, res.NodeName) + } + + slices.Sort(nodes) + slices.Sort(want) + + if !slices.Equal(nodes, want) { + t.Errorf("replicas = %v, want them untouched: %v", nodes, want) + } + }) + } +} diff --git a/internal/controller/resourcedefinition_controller.go b/internal/controller/resourcedefinition_controller.go index e533a3fdf..905ef900f 100644 --- a/internal/controller/resourcedefinition_controller.go +++ b/internal/controller/resourcedefinition_controller.go @@ -660,7 +660,11 @@ func (r *ResourceDefinitionReconciler) rdIsDeleting(_ context.Context, rd *block return true } - return !rd.DeletionTimestamp.IsZero() + // The DELETE flag is set before the replicas are walked + // (store.MarkDefinitionDeleting); the definition itself is only + // deleted after them, so its DeletionTimestamp comes too late to keep + // a witness from being added and removed between replica deletes. + return !rd.DeletionTimestamp.IsZero() || slices.Contains(rd.Spec.Flags, apiv1.ResourceFlagDelete) } // directOrCached returns the APIReader-direct reader when available diff --git a/pkg/rest/resource_definitions.go b/pkg/rest/resource_definitions.go index b906589d1..cdbecb106 100644 --- a/pkg/rest/resource_definitions.go +++ b/pkg/rest/resource_definitions.go @@ -1226,11 +1226,21 @@ func (s *Server) handleRDDelete(w http.ResponseWriter, r *http.Request) { // Upstream LINSTOR does this server-side too: deleting an RD // flags the RD with DELETE, then walks Resources and stamps // DELETE on each. The satellite drives the teardown from - // there. Our equivalent is: per-child Resources().Delete() - // stamps DeletionTimestamp on the CRD; the satellite's + // there. Our equivalent is: the RD is flagged DELETE first + // (store.MarkDefinitionDeleting, which keeps the tiebreaker + // reconciler off it and lifts the mid-sync replica guard), then + // per-child Resources().Delete() stamps DeletionTimestamp on the + // CRD; the satellite's // existing `blockstor.org/satellite-resource` // finalizer then drains DRBD before the apiserver removes // the object. + err = store.MarkDefinitionDeleting(r.Context(), s.Store, name) + if err != nil { + writeStoreError(w, err) + + return + } + err = s.cascadeDeleteResources(r.Context(), name) if err != nil { writeStoreError(w, err) diff --git a/pkg/rest/resource_delete_mid_initial_sync_test.go b/pkg/rest/resource_delete_mid_initial_sync_test.go index 096229524..bc85f3383 100644 --- a/pkg/rest/resource_delete_mid_initial_sync_test.go +++ b/pkg/rest/resource_delete_mid_initial_sync_test.go @@ -25,6 +25,7 @@ import ( apiv1 "github.com/cozystack/blockstor/pkg/api/v1" "github.com/cozystack/blockstor/pkg/store" + "github.com/cozystack/blockstor/pkg/store/storetest" ) // seedInitialSyncVolume lays out a three-replica volume deleted a few @@ -120,3 +121,59 @@ func TestSingleReplicaDeleteDuringInitialSyncStaysGuarded(t *testing.T) { } } +// A definition flagged DELETE (rd d marks it before walking the replicas) +// is being deleted as a whole too. +func TestReplicaDeleteOfDefinitionFlaggedDeleteIsNotGuarded(t *testing.T) { + st := store.NewInMemory() + rd := "pvc-initial-sync-rdd" + + seedInitialSyncVolume(t, st, rd) + + if err := st.Resources().Delete(t.Context(), rd, "node-a"); err != nil { + t.Fatalf("drop node-a: %v", err) + } + + if err := store.MarkDefinitionDeleting(t.Context(), st, rd); err != nil { + t.Fatalf("mark: %v", err) + } + + base, stop := startServerWithStore(t, st) + defer stop() + + if code := deleteReplica(t, base, rd, "node-b"); code != http.StatusOK { + t.Fatalf("delete node-b: got %d, want 200", code) + } +} + +// rd d flags the definition DELETE before the first replica goes, so the +// RD reconciler keeps its hands off the tiebreaker for the whole walk, and +// deletes the Inconsistent replica before its source. +func TestRDDeleteFlagsDefinitionBeforeItsReplicas(t *testing.T) { + backend := store.NewInMemory() + rd := "pvc-initial-sync-flag" + + seedInitialSyncVolume(t, backend, rd) + + rec := storetest.NewDeleteRecorder(backend) + + base, stop := startServerWithStore(t, rec) + defer stop() + + resp := httpDelete(t, base+"/v1/resource-definitions/"+rd) + _ = resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Fatalf("rd d: got %d, want 200", resp.StatusCode) + } + + deletes := rec.Deletes() + if len(deletes) == 0 || deletes[0].Node != "node-c" { + t.Errorf("deletes = %+v, want the Inconsistent node-c first", deletes) + } + + for _, d := range deletes { + if !d.DefinitionFlagged { + t.Errorf("replica on %s deleted before the definition was flagged DELETE", d.Node) + } + } +} diff --git a/pkg/store/cascade.go b/pkg/store/cascade.go index ca3917d8a..3c80e21d8 100644 --- a/pkg/store/cascade.go +++ b/pkg/store/cascade.go @@ -93,6 +93,33 @@ func CascadeDeleteResources(ctx context.Context, st Store, rdName string) error return nil } +// MarkDefinitionDeleting flags the definition DELETE before its replicas +// are walked, the way LINSTOR flags a definition it is deleting. The two +// `rd d` doors call it ahead of CascadeDeleteResources; a clone rollback +// does not, because it may keep the definition it cascades. +// +// The flag is what tells everything else the definition is going as a +// whole: the RD reconciler stops creating and removing tiebreakers on it, +// so a witness does not land between two replica deletes only to be reaped +// by the next pass, and validate.DefinitionBeingDeleted lifts the mid-sync +// delete guard, which protects a volume that stays. A definition that is +// already gone has nothing to mark. +func MarkDefinitionDeleting(ctx context.Context, st Store, rdName string) error { + err := st.ResourceDefinitions().PatchResourceDefinitionSpec(ctx, rdName, + func(rd *apiv1.ResourceDefinition) error { + if !slices.Contains(rd.Flags, apiv1.ResourceFlagDelete) { + rd.Flags = append(rd.Flags, apiv1.ResourceFlagDelete) + } + + return nil + }) + if err != nil && !errors.Is(err, ErrNotFound) { + return fmt.Errorf("mark %s for deletion: %w", rdName, err) + } + + return nil +} + // ReplicasOnNode is the node-scoped replica read a node's fate is decided on, // asked in every spelling the node's objects can carry. ReferencesOnNode and // CascadeOrphansForLostNode ask the storage pools the same way. diff --git a/pkg/store/cascade_order_test.go b/pkg/store/cascade_order_test.go index 47c98c32b..87855d9a3 100644 --- a/pkg/store/cascade_order_test.go +++ b/pkg/store/cascade_order_test.go @@ -19,6 +19,7 @@ limitations under the License. package store_test import ( + "slices" "testing" apiv1 "github.com/cozystack/blockstor/pkg/api/v1" @@ -64,3 +65,36 @@ func TestCascadeDeletesIncompleteReplicasFirst(t *testing.T) { } } +// MarkDefinitionDeleting flags the definition once, and is a no-op on a +// definition that is already gone. +func TestMarkDefinitionDeleting(t *testing.T) { + t.Parallel() + + ctx := t.Context() + backend := store.NewInMemory() + + if err := backend.ResourceDefinitions().Create(ctx, &apiv1.ResourceDefinition{Name: "pvc-going"}); err != nil { + t.Fatalf("seed RD: %v", err) + } + + for range 2 { + if err := store.MarkDefinitionDeleting(ctx, backend, "pvc-going"); err != nil { + t.Fatalf("mark: %v", err) + } + } + + rd, err := backend.ResourceDefinitions().Get(ctx, "pvc-going") + if err != nil { + t.Fatalf("get: %v", err) + } + + if n := len(slices.DeleteFunc(slices.Clone(rd.Flags), func(f string) bool { + return f != apiv1.ResourceFlagDelete + })); n != 1 { + t.Errorf("flags = %v, want DELETE exactly once", rd.Flags) + } + + if err := store.MarkDefinitionDeleting(ctx, backend, "pvc-gone"); err != nil { + t.Errorf("mark a missing definition: %v", err) + } +} From 399d027bd306c0efe671c397844f469a4c5f929c Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Sun, 22 Nov 2026 14:00:34 +0100 Subject: [PATCH 04/16] fix(validate,rest,cli): keep the U130 guard when a Primary is up BalanceResourcesEnabled=false was taken as proof that linstor-csi's DeleteVolume is tearing the volume down. Operators set the same property to place replicas by hand, which is exactly where U130 happens: a second diskful added next to a diskless Primary and the original dropped before the sync finishes. That delete passed and left the Primary with no complete copy. DeleteVolume waits until no replica is InUse before it deletes any, so the property now counts only while nothing is InUse. The DELETE flag set by rd d still lifts the guard on its own. The comment also stops claiming DeleteVolume always deletes the definition: it keeps it while a snapshot needs it. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- internal/cli/write_more.go | 12 +++--- internal/cli/write_more_test.go | 35 ++++++++++++++++++ .../resource_delete_last_uptodate_u130.go | 8 ++-- .../resource_delete_mid_initial_sync_test.go | 37 +++++++++++++++++++ pkg/validate/resource_delete.go | 33 ++++++++++++----- pkg/validate/validate_test.go | 36 ++++++++++++++---- 6 files changed, 135 insertions(+), 26 deletions(-) diff --git a/internal/cli/write_more.go b/internal/cli/write_more.go index f1e5c7ac0..1c3d175e1 100644 --- a/internal/cli/write_more.go +++ b/internal/cli/write_more.go @@ -602,22 +602,24 @@ func checkDeletable(ctx context.Context, run *runContext, rdName, node string) e return fmt.Errorf("get resource %s on %s: %w", rdName, node, err) } - // Only a replica dropped from a volume that stays is guarded; see - // validate.DefinitionBeingDeleted. rd, err := run.Store.ResourceDefinitions().Get(ctx, rdName) if err != nil && !isNotFound(err) { return fmt.Errorf("get resource definition %s: %w", rdName, err) } - if err == nil && validate.DefinitionBeingDeleted(&rd) { - return nil - } + rdFound := err == nil siblings, err := run.Store.Resources().ListByDefinition(ctx, rdName) if err != nil { return fmt.Errorf("list replicas of %s: %w", rdName, err) } + // Only a replica dropped from a volume that stays is guarded; see + // validate.DefinitionBeingDeleted. + if rdFound && validate.DefinitionBeingDeleted(&rd, siblings) { + return nil + } + if validate.MidSyncDeleteRefusal(&target, siblings) { return fmt.Errorf("refusing to delete %s on %s: %w (pass --force to override)", rdName, node, validate.ErrLastSyncSourceDelete) diff --git a/internal/cli/write_more_test.go b/internal/cli/write_more_test.go index 19d7673ee..6c74bb0a4 100644 --- a/internal/cli/write_more_test.go +++ b/internal/cli/write_more_test.go @@ -484,3 +484,38 @@ func TestDefinitionDeleteFlagsDefinitionBeforeItsReplicas(t *testing.T) { } } } + +// U130 on a definition placed by hand: balancing off, a diskless Primary, +// a diskful replica still syncing. Deleting the complete copy stays +// refused; only a teardown with nothing InUse lifts the guard. +func TestResourceDeleteWithBalancingOffAndAPrimaryStaysGuarded(t *testing.T) { + t.Parallel() + + app, _, _ := newApp(t, func(ctx context.Context, backend store.Store) { + _ = backend.ResourceDefinitions().Create(ctx, &apiv1.ResourceDefinition{ + Name: "pvc-x", + Props: map[string]string{apiv1.PropBalanceResourcesEnabled: "False"}, + }) + + for node, disk := range map[string]string{ + "node-a": "UpToDate", + "node-b": "Inconsistent", + } { + _ = backend.Resources().Create(ctx, &apiv1.Resource{ + Name: "pvc-x", NodeName: node, + Volumes: []apiv1.Volume{{State: apiv1.VolumeState{DiskState: disk}}}, + }) + } + + inUse := true + _ = backend.Resources().Create(ctx, &apiv1.Resource{ + Name: "pvc-x", NodeName: "node-p", + Flags: []string{apiv1.ResourceFlagDiskless}, + State: apiv1.ResourceState{InUse: &inUse}, + }) + }) + + if got := app.Run(t.Context(), []string{"r", "d", "node-a", "pvc-x"}); got == 0 { + t.Fatal("the Primary's last complete copy was deleted while a peer was still syncing") + } +} diff --git a/pkg/rest/resource_delete_last_uptodate_u130.go b/pkg/rest/resource_delete_last_uptodate_u130.go index 6a141eb03..1332c17e5 100644 --- a/pkg/rest/resource_delete_last_uptodate_u130.go +++ b/pkg/rest/resource_delete_last_uptodate_u130.go @@ -119,10 +119,6 @@ func (s *Server) refuseLastUpToDateDiskfulMidSyncDelete( return false } - if validate.DefinitionBeingDeleted(&rd) { - return true - } - siblings, err := s.Store.Resources().ListByDefinition(ctx, rdName) if err != nil { // A list failure must not silently allow a destructive delete @@ -138,6 +134,10 @@ func (s *Server) refuseLastUpToDateDiskfulMidSyncDelete( return false } + if validate.DefinitionBeingDeleted(&rd, siblings) { + return true + } + if !resourceMidSyncDeleteRefusal(target, siblings) { return true } diff --git a/pkg/rest/resource_delete_mid_initial_sync_test.go b/pkg/rest/resource_delete_mid_initial_sync_test.go index bc85f3383..6b08f9e68 100644 --- a/pkg/rest/resource_delete_mid_initial_sync_test.go +++ b/pkg/rest/resource_delete_mid_initial_sync_test.go @@ -177,3 +177,40 @@ func TestRDDeleteFlagsDefinitionBeforeItsReplicas(t *testing.T) { } } } + +// U130 on a definition whose replicas are placed by hand: balancing is +// switched off, a diskless Primary runs on it, a second diskful replica is +// still syncing, and the original is deleted. The property alone does not +// make this a teardown; DeleteVolume only deletes once nothing is InUse. +func TestReplicaDeleteWithBalancingOffAndAPrimaryStaysGuarded(t *testing.T) { + st := store.NewInMemory() + rd := "pvc-hand-placed" + + if err := st.ResourceDefinitions().Create(t.Context(), &apiv1.ResourceDefinition{ + Name: rd, + Props: map[string]string{apiv1.PropBalanceResourcesEnabled: "False"}, + }); err != nil { + t.Fatalf("seed RD: %v", err) + } + + inUse := true + primary := disklessReplica(rd, "node-p", apiv1.ResourceFlagDiskless) + primary.State.InUse = &inUse + + for _, res := range []*apiv1.Resource{ + diskfulReplica(rd, "node-a", drbdDiskStateUpToDate), + diskfulReplica(rd, "node-b", drbdDiskStateInconsistent), + primary, + } { + if err := st.Resources().Create(t.Context(), res); err != nil { + t.Fatalf("seed %s: %v", res.NodeName, err) + } + } + + base, stop := startServerWithStore(t, st) + defer stop() + + if code := deleteReplica(t, base, rd, "node-a"); code != http.StatusConflict { + t.Fatalf("delete node-a: got %d, want 409 (the Primary's last complete copy)", code) + } +} diff --git a/pkg/validate/resource_delete.go b/pkg/validate/resource_delete.go index b59a5e17e..e6e06654a 100644 --- a/pkg/validate/resource_delete.go +++ b/pkg/validate/resource_delete.go @@ -98,7 +98,8 @@ func MidSyncDeleteRefusal(target *apiv1.Resource, siblings []apiv1.Resource) boo } // DefinitionBeingDeleted reports whether the whole definition is being -// taken apart, as opposed to one replica of a volume that stays. +// taken apart, as opposed to one replica of a volume that stays. replicas +// are the definition's replicas as they stand. // // MidSyncDeleteRefusal protects the data of a volume that outlives the // delete. LINSTOR has no such check on any delete path; blockstor keeps it @@ -108,13 +109,21 @@ func MidSyncDeleteRefusal(target *apiv1.Resource, siblings []apiv1.Resource) boo // be removed at all. // // Two shapes say the definition is going. The DELETE flag is LINSTOR's own -// mark for `rd d`. linstor-csi's DeleteVolume never sends `rd d` first: it -// sets BalanceResourcesEnabled=False on the definition, then deletes the -// replicas one by one, then the definition (pkg/client/linstor.go, Delete). -// That property write is the only notice the replica deletes get that they -// are one volume teardown. An operator who switched balancing off by hand -// loses the guard on that definition, which is where LINSTOR always is. -func DefinitionBeingDeleted(rd *apiv1.ResourceDefinition) bool { +// mark for `rd d`, and it settles the question. linstor-csi's DeleteVolume +// never sends `rd d` first: it sets BalanceResourcesEnabled=False on the +// definition, waits until no replica is InUse, then deletes the replicas +// one by one and the volume definitions after them; the definition itself +// goes only when no snapshot still needs it (pkg/client/linstor.go, +// Delete). That property write is the only notice the replica deletes get +// that they are one volume teardown. +// +// The same property is what an operator sets to place replicas by hand, +// and a hand placement is exactly where U130 happens: a second diskful +// added next to a diskless Primary and the original dropped before the +// sync finishes. So the property alone counts only while nothing is +// InUse, which is the state DeleteVolume waits for and a volume with a +// Primary is never in. +func DefinitionBeingDeleted(rd *apiv1.ResourceDefinition, replicas []apiv1.Resource) bool { if rd == nil { return false } @@ -123,7 +132,13 @@ func DefinitionBeingDeleted(rd *apiv1.ResourceDefinition) bool { return true } - return strings.EqualFold(rd.Props[apiv1.PropBalanceResourcesEnabled], "false") + if !strings.EqualFold(rd.Props[apiv1.PropBalanceResourcesEnabled], "false") { + return false + } + + return !slices.ContainsFunc(replicas, func(res apiv1.Resource) bool { + return res.State.InUse != nil && *res.State.InUse + }) } // SortForDeletion orders replicas the way they are safe to delete one at a diff --git a/pkg/validate/validate_test.go b/pkg/validate/validate_test.go index bb0a75169..84e138030 100644 --- a/pkg/validate/validate_test.go +++ b/pkg/validate/validate_test.go @@ -323,26 +323,46 @@ func TestMidSyncDeleteRefusalLiftedWhileDefinitionIsDeleted(t *testing.T) { t.Fatal("a single replica delete of the last complete copy must stay guarded") } + inUse := true + primary := apiv1.Resource{ + NodeName: "node-p", + Flags: []string{apiv1.ResourceFlagDiskless}, + State: apiv1.ResourceState{InUse: &inUse}, + } + notInUse := false + secondary := primary + secondary.State = apiv1.ResourceState{InUse: ¬InUse} + + balancingOff := apiv1.ResourceDefinition{Props: map[string]string{apiv1.PropBalanceResourcesEnabled: "False"}} + flagged := apiv1.ResourceDefinition{Flags: []string{apiv1.ResourceFlagDelete}} + for name, tc := range map[string]struct { - rd apiv1.ResourceDefinition - deleted bool + rd apiv1.ResourceDefinition + replicas []apiv1.Resource + deleted bool }{ - "a live definition": {apiv1.ResourceDefinition{}, false}, + "a live definition": {apiv1.ResourceDefinition{}, nil, false}, "balancing switched on": { - apiv1.ResourceDefinition{Props: map[string]string{apiv1.PropBalanceResourcesEnabled: "true"}}, false, + apiv1.ResourceDefinition{Props: map[string]string{apiv1.PropBalanceResourcesEnabled: "true"}}, nil, false, }, - "rd d flagged it DELETE": { - apiv1.ResourceDefinition{Flags: []string{apiv1.ResourceFlagDelete}}, true, + "rd d flagged it DELETE": {flagged, nil, true}, + "rd d flagged it DELETE with a Primary left": { + flagged, []apiv1.Resource{primary}, true, }, "linstor-csi DeleteVolume switched balancing off": { - apiv1.ResourceDefinition{Props: map[string]string{apiv1.PropBalanceResourcesEnabled: "False"}}, true, + balancingOff, append([]apiv1.Resource{secondary}, stranded...), true, + }, + // U130 on a hand-placed definition: a Primary still runs on it, + // which DeleteVolume never leaves behind. + "balancing off by hand with a Primary": { + balancingOff, append([]apiv1.Resource{primary}, stranded...), false, }, } { t.Run(name, func(t *testing.T) { t.Parallel() rd := tc.rd - if got := validate.DefinitionBeingDeleted(&rd); got != tc.deleted { + if got := validate.DefinitionBeingDeleted(&rd, tc.replicas); got != tc.deleted { t.Errorf("DefinitionBeingDeleted = %v, want %v", got, tc.deleted) } }) From 1066bce22307b1a06d51214b31fc5c36d21c6119 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Sun, 22 Nov 2026 14:00:41 +0100 Subject: [PATCH 05/16] test(validate): a source that is being deleted is no source Skipping peers flagged DELETE before counting sources made the guard stricter: an UpToDate copy on its way out no longer vouches for a peer still syncing. That closes r d of the source followed by r d of the other complete copy while a third replica syncs, which passed before because the first copy still counted. Pin it so a later reordering of the loop does not reopen it. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- pkg/validate/validate_test.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/pkg/validate/validate_test.go b/pkg/validate/validate_test.go index 84e138030..617e351e9 100644 --- a/pkg/validate/validate_test.go +++ b/pkg/validate/validate_test.go @@ -383,6 +383,21 @@ func TestMidSyncDeleteRefusalIgnoresPeerBeingDeleted(t *testing.T) { } } +// A complete copy that is itself being deleted is no source for the peer +// still syncing: `r d` of the source, then `r d` of the other complete +// copy, must not pass on the strength of the first one. +func TestMidSyncDeleteRefusalDoesNotCountDeletingSource(t *testing.T) { + t.Parallel() + + target := diskful("node-b", "UpToDate") + going := diskful("node-a", "UpToDate") + going.Flags = []string{apiv1.ResourceFlagDelete} + + if !validate.MidSyncDeleteRefusal(&target, []apiv1.Resource{going, diskful("node-c", "Inconsistent")}) { + t.Error("counted a source that is being deleted, stranding the syncing peer") + } +} + // Deleting replicas one at a time, the incomplete ones go first, so the // source of an initial sync is never the first replica removed. func TestSortForDeletionPutsIncompleteReplicasFirst(t *testing.T) { From 2b935a8f4be5cb0821257f1d14509eda1200a101 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Sun, 22 Nov 2026 14:00:46 +0100 Subject: [PATCH 06/16] test(rest,cli): refuse a replica delete when the RD cannot be read The mid-sync guard now reads the definition on every replica delete without force, to tell a teardown from a single delete. A failed read that is not NotFound has to refuse the delete rather than skip the guard, and nothing covered that new error path on either door. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- internal/cli/write_more_test.go | 28 ++++++++++ .../resource_delete_mid_initial_sync_test.go | 20 +++++++ pkg/store/storetest/failing_definition_get.go | 52 +++++++++++++++++++ 3 files changed, 100 insertions(+) create mode 100644 pkg/store/storetest/failing_definition_get.go diff --git a/internal/cli/write_more_test.go b/internal/cli/write_more_test.go index 6c74bb0a4..d8dff20a1 100644 --- a/internal/cli/write_more_test.go +++ b/internal/cli/write_more_test.go @@ -519,3 +519,31 @@ func TestResourceDeleteWithBalancingOffAndAPrimaryStaysGuarded(t *testing.T) { t.Fatal("the Primary's last complete copy was deleted while a peer was still syncing") } } + +// A definition read that fails refuses the delete rather than skipping the +// guard. +func TestResourceDeleteRefusedWhenTheDefinitionCannotBeRead(t *testing.T) { + t.Parallel() + + app, _, _ := newApp(t, func(ctx context.Context, backend store.Store) { + seedDefinition(ctx, backend) + + _ = backend.Resources().Create(ctx, &apiv1.Resource{ + Name: "pvc-x", NodeName: "node-a", + Volumes: []apiv1.Volume{{State: apiv1.VolumeState{DiskState: "UpToDate"}}}, + }) + }) + + backend := appStore(t, app) + app.StoreFor = func(context.Context) (store.Store, error) { + return storetest.FailingDefinitionGet{Store: backend}, nil + } + + if got := app.Run(t.Context(), []string{"r", "d", "node-a", "pvc-x"}); got == 0 { + t.Fatal("delete went through although the definition could not be read") + } + + if _, err := backend.Resources().Get(t.Context(), "pvc-x", "node-a"); err != nil { + t.Errorf("node-a was deleted: %v", err) + } +} diff --git a/pkg/rest/resource_delete_mid_initial_sync_test.go b/pkg/rest/resource_delete_mid_initial_sync_test.go index 6b08f9e68..3679f1326 100644 --- a/pkg/rest/resource_delete_mid_initial_sync_test.go +++ b/pkg/rest/resource_delete_mid_initial_sync_test.go @@ -214,3 +214,23 @@ func TestReplicaDeleteWithBalancingOffAndAPrimaryStaysGuarded(t *testing.T) { t.Fatalf("delete node-a: got %d, want 409 (the Primary's last complete copy)", code) } } + +// The guard reads the definition to tell a teardown from a single delete. +// A read it cannot make refuses the delete instead of letting it through. +func TestReplicaDeleteRefusedWhenTheDefinitionCannotBeRead(t *testing.T) { + backend := store.NewInMemory() + rd := "pvc-unreadable" + + seedInitialSyncVolume(t, backend, rd) + + base, stop := startServerWithStore(t, storetest.FailingDefinitionGet{Store: backend}) + defer stop() + + if code := deleteReplica(t, base, rd, "node-a"); code == http.StatusOK { + t.Fatal("delete went through although the definition could not be read") + } + + if _, err := backend.Resources().Get(t.Context(), rd, "node-a"); err != nil { + t.Errorf("node-a was deleted: %v", err) + } +} diff --git a/pkg/store/storetest/failing_definition_get.go b/pkg/store/storetest/failing_definition_get.go new file mode 100644 index 000000000..758512fc7 --- /dev/null +++ b/pkg/store/storetest/failing_definition_get.go @@ -0,0 +1,52 @@ +// 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 storetest + +import ( + "context" + "errors" + + apiv1 "github.com/cozystack/blockstor/pkg/api/v1" + "github.com/cozystack/blockstor/pkg/store" +) + +// ErrDefinitionGet is the error FailingDefinitionGet answers every +// definition read with. +var ErrDefinitionGet = errors.New("storetest: definition read failed") + +// FailingDefinitionGet wraps a store whose definition reads fail with +// something other than NotFound. A delete guard that has to read the +// definition is tested with it: a read it cannot make must refuse the +// delete, not let it through. +type FailingDefinitionGet struct { + store.Store +} + +// ResourceDefinitions returns the failing definition store. +func (f FailingDefinitionGet) ResourceDefinitions() store.ResourceDefinitionStore { + return failingDefinitions{ResourceDefinitionStore: f.Store.ResourceDefinitions()} +} + +type failingDefinitions struct { + store.ResourceDefinitionStore +} + +func (failingDefinitions) Get(context.Context, string) (apiv1.ResourceDefinition, error) { + return apiv1.ResourceDefinition{}, ErrDefinitionGet +} From 6a142ed59b651b7408be2724df5e351bb310dd12 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Sun, 22 Nov 2026 14:00:54 +0100 Subject: [PATCH 07/16] refactor(store): stop ordering the rd d cascade A replica delete only stamps a deletion timestamp; the satellites take DRBD down in parallel and independently, so the order the cascade stamps replicas in decides nothing about which one actually goes first. Sorting there only suggested a guarantee that does not exist. The order still matters for r d naming several nodes, where the mid-sync guard runs between two deletes and would otherwise refuse a source over a peer the same command removes. That path keeps it, and the comment now says so. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- internal/cli/write_more_test.go | 9 ++--- .../resource_delete_mid_initial_sync_test.go | 7 ++-- pkg/store/cascade.go | 3 -- ...ade_order_test.go => cascade_mark_test.go} | 39 ------------------- pkg/store/storetest/delete_recorder.go | 3 +- pkg/validate/resource_delete.go | 13 ++++--- pkg/validate/validate_test.go | 4 +- 7 files changed, 17 insertions(+), 61 deletions(-) rename pkg/store/{cascade_order_test.go => cascade_mark_test.go} (58%) diff --git a/internal/cli/write_more_test.go b/internal/cli/write_more_test.go index d8dff20a1..e72e2c2a2 100644 --- a/internal/cli/write_more_test.go +++ b/internal/cli/write_more_test.go @@ -446,9 +446,8 @@ func TestResourceDeleteDuringVolumeTeardownIsNotGuarded(t *testing.T) { } } -// `rd d` flags the definition DELETE before the first replica goes and -// deletes the Inconsistent replica before its source, the way the REST -// door does. +// `rd d` flags the definition DELETE before the first replica goes, the +// way the REST door does. func TestDefinitionDeleteFlagsDefinitionBeforeItsReplicas(t *testing.T) { t.Parallel() @@ -474,8 +473,8 @@ func TestDefinitionDeleteFlagsDefinitionBeforeItsReplicas(t *testing.T) { } deletes := rec.Deletes() - if len(deletes) == 0 || deletes[0].Node != "node-b" { - t.Errorf("deletes = %+v, want the Inconsistent node-b first", deletes) + if len(deletes) != 2 { + t.Errorf("deletes = %+v, want both replicas", deletes) } for _, d := range deletes { diff --git a/pkg/rest/resource_delete_mid_initial_sync_test.go b/pkg/rest/resource_delete_mid_initial_sync_test.go index 3679f1326..024502426 100644 --- a/pkg/rest/resource_delete_mid_initial_sync_test.go +++ b/pkg/rest/resource_delete_mid_initial_sync_test.go @@ -146,8 +146,7 @@ func TestReplicaDeleteOfDefinitionFlaggedDeleteIsNotGuarded(t *testing.T) { } // rd d flags the definition DELETE before the first replica goes, so the -// RD reconciler keeps its hands off the tiebreaker for the whole walk, and -// deletes the Inconsistent replica before its source. +// RD reconciler keeps its hands off the tiebreaker for the whole walk. func TestRDDeleteFlagsDefinitionBeforeItsReplicas(t *testing.T) { backend := store.NewInMemory() rd := "pvc-initial-sync-flag" @@ -167,8 +166,8 @@ func TestRDDeleteFlagsDefinitionBeforeItsReplicas(t *testing.T) { } deletes := rec.Deletes() - if len(deletes) == 0 || deletes[0].Node != "node-c" { - t.Errorf("deletes = %+v, want the Inconsistent node-c first", deletes) + if len(deletes) != 3 { + t.Errorf("deletes = %+v, want all three replicas", deletes) } for _, d := range deletes { diff --git a/pkg/store/cascade.go b/pkg/store/cascade.go index 3c80e21d8..2493632f8 100644 --- a/pkg/store/cascade.go +++ b/pkg/store/cascade.go @@ -27,7 +27,6 @@ import ( apiv1 "github.com/cozystack/blockstor/pkg/api/v1" "github.com/cozystack/blockstor/pkg/naming" - "github.com/cozystack/blockstor/pkg/validate" ) // The teardown a delete has to perform, shared by the two write doors. @@ -80,8 +79,6 @@ func CascadeDeleteResources(ctx context.Context, st Store, rdName string) error return nil } - validate.SortForDeletion(children) - for i := range children { err = st.Resources().Delete(ctx, rdName, children[i].NodeName) if err != nil && !errors.Is(err, ErrNotFound) { diff --git a/pkg/store/cascade_order_test.go b/pkg/store/cascade_mark_test.go similarity index 58% rename from pkg/store/cascade_order_test.go rename to pkg/store/cascade_mark_test.go index 87855d9a3..7f5ab6de2 100644 --- a/pkg/store/cascade_order_test.go +++ b/pkg/store/cascade_mark_test.go @@ -24,47 +24,8 @@ import ( apiv1 "github.com/cozystack/blockstor/pkg/api/v1" "github.com/cozystack/blockstor/pkg/store" - "github.com/cozystack/blockstor/pkg/store/storetest" ) -// The cascade of a volume still in its initial sync deletes the -// Inconsistent replica before the UpToDate copies it depends on, so the -// source of the sync is never the first replica to go. -func TestCascadeDeletesIncompleteReplicasFirst(t *testing.T) { - t.Parallel() - - ctx := t.Context() - backend := store.NewInMemory() - - if err := backend.ResourceDefinitions().Create(ctx, &apiv1.ResourceDefinition{Name: "pvc-sync"}); err != nil { - t.Fatalf("seed RD: %v", err) - } - - for node, disk := range map[string]string{ - "node-a": "UpToDate", - "node-b": "UpToDate", - "node-c": "Inconsistent", - } { - if err := backend.Resources().Create(ctx, &apiv1.Resource{ - Name: "pvc-sync", NodeName: node, - Volumes: []apiv1.Volume{{State: apiv1.VolumeState{DiskState: disk}}}, - }); err != nil { - t.Fatalf("seed %s: %v", node, err) - } - } - - rec := storetest.NewDeleteRecorder(backend) - - if err := store.CascadeDeleteResources(ctx, rec, "pvc-sync"); err != nil { - t.Fatalf("cascade: %v", err) - } - - deletes := rec.Deletes() - if len(deletes) != 3 || deletes[0].Node != "node-c" { - t.Errorf("deletes = %+v, want the Inconsistent node-c first", deletes) - } -} - // MarkDefinitionDeleting flags the definition once, and is a no-op on a // definition that is already gone. func TestMarkDefinitionDeleting(t *testing.T) { diff --git a/pkg/store/storetest/delete_recorder.go b/pkg/store/storetest/delete_recorder.go index 64e8245c5..7fb24a1b1 100644 --- a/pkg/store/storetest/delete_recorder.go +++ b/pkg/store/storetest/delete_recorder.go @@ -38,8 +38,7 @@ type ReplicaDelete struct { // DeleteRecorder wraps a store and notes every replica delete in order, // with whether its definition had been flagged DELETE by then. The `rd d` // doors are tested with it: the flag has to be on the definition before -// the first replica goes, and the replicas go in validate.SortForDeletion -// order. +// the first replica goes. type DeleteRecorder struct { store.Store diff --git a/pkg/validate/resource_delete.go b/pkg/validate/resource_delete.go index e6e06654a..02a92235a 100644 --- a/pkg/validate/resource_delete.go +++ b/pkg/validate/resource_delete.go @@ -145,12 +145,13 @@ func DefinitionBeingDeleted(rd *apiv1.ResourceDefinition, replicas []apiv1.Resou // time: the diskful replicas that are not complete copies yet first, every // other replica after them in its original order. // -// Removing the source of an initial sync while its target is still -// Inconsistent can leave the target with a cleared bitmap on an Established -// connection to the remaining UpToDate peer: DRBD sees nothing to resync -// and the replica stays Inconsistent for good. Taking the incomplete -// replicas away first means a source never goes while something still -// depends on it. +// It matters where the mid-sync guard runs between two deletes, which is +// `r d` naming several nodes: naming a source before the replica syncing +// from it would have the guard refuse the source over a peer the same +// command was about to delete. Once the incomplete replica is deleted it +// carries DELETE, and MidSyncDeleteRefusal no longer counts it. It does not +// order the teardown itself: a delete only stamps the replica, and the +// satellites take DRBD down in parallel. func SortForDeletion(replicas []apiv1.Resource) { slices.SortStableFunc(replicas, func(a, b apiv1.Resource) int { return deletionRank(&a) - deletionRank(&b) diff --git a/pkg/validate/validate_test.go b/pkg/validate/validate_test.go index 617e351e9..07d8f2ae7 100644 --- a/pkg/validate/validate_test.go +++ b/pkg/validate/validate_test.go @@ -398,8 +398,8 @@ func TestMidSyncDeleteRefusalDoesNotCountDeletingSource(t *testing.T) { } } -// Deleting replicas one at a time, the incomplete ones go first, so the -// source of an initial sync is never the first replica removed. +// `r d` naming several replicas deletes the incomplete ones first, so the +// guard never refuses a source over a peer the same command removes. func TestSortForDeletionPutsIncompleteReplicasFirst(t *testing.T) { t.Parallel() From 5e52430a3d05999d1bad70eef960524eb9e77240 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Tue, 24 Nov 2026 01:35:28 +0100 Subject: [PATCH 08/16] fix(store): refuse a definition over the replicas of a deleted one Deleting a definition while one of its nodes was down left that node's replica draining under the name until the node came back, while the definition object itself was gone at once. linstor-csi rolls back a failed CreateVolume this way and retries it, so the retry created a definition of the same name over the old replica. The new replicas counted it as one of their own: it held the lowest DRBD node id, so neither new replica was elected the initial UpToDate source; its stale UpToDate status at the deterministic day0 generation was copied into both as a seed, which skips the winner seed; and its identity made the block size decision write DRBD's 512 default. The volume came up Inconsistent on every diskful replica with nothing to sync from. LINSTOR keeps a deleted definition, flagged DELETE, until every satellite confirms its replica gone, so a create of the same name fails with FAIL_EXISTS_RSC_DFN and linstor-csi retries it until the node is back. Both stores now refuse the create the same way while a replica under the name is being deleted. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- pkg/rest/rd_create_draining_test.go | 74 +++++++++++++++++++++++ pkg/store/draining.go | 69 +++++++++++++++++++++ pkg/store/inmemory.go | 6 +- pkg/store/inmemory_resource_definition.go | 19 +++++- pkg/store/k8s/k8s.go | 2 +- pkg/store/k8s/resource_definitions.go | 17 ++++++ pkg/store/storetest/storetest.go | 54 +++++++++++++++++ 7 files changed, 237 insertions(+), 4 deletions(-) create mode 100644 pkg/rest/rd_create_draining_test.go create mode 100644 pkg/store/draining.go diff --git a/pkg/rest/rd_create_draining_test.go b/pkg/rest/rd_create_draining_test.go new file mode 100644 index 000000000..5694814db --- /dev/null +++ b/pkg/rest/rd_create_draining_test.go @@ -0,0 +1,74 @@ +// 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 rest + +import ( + "net/http" + "testing" + + apiv1 "github.com/cozystack/blockstor/pkg/api/v1" + "github.com/cozystack/blockstor/pkg/store" +) + +// TestRDCreateWaitsForTheDeletedDefinitionsReplicas is linstor-csi's retry of +// a CreateVolume whose first attempt it rolled back while a node was down: +// the rollback deleted the definition, the down node's replica of it stays +// until its satellite tears it down, and the retry creates the definition +// again under the same name. LINSTOR still holds the old definition then and +// answers the create with FAIL_EXISTS_RSC_DFN until the node is back, so +// linstor-csi keeps retrying. Created over the old replica, the new volume +// took it for one of its own and came up Inconsistent on every replica. +func TestRDCreateWaitsForTheDeletedDefinitionsReplicas(t *testing.T) { + t.Parallel() + + st := store.NewInMemory() + ctx := t.Context() + + draining := apiv1.Resource{Name: "pvc-retry", NodeName: "node-down", Flags: []string{apiv1.ResourceFlagDelete}} + if err := st.Resources().Create(ctx, &draining); err != nil { + t.Fatalf("seed draining replica: %v", err) + } + + base, stop := startServerWithStore(t, st) + defer stop() + + body := []byte(`{"resource_definition":{"name":"pvc-retry"}}`) + + resp := httpPost(t, base+"/v1/resource-definitions", body) + _ = resp.Body.Close() + + if resp.StatusCode != http.StatusConflict { + t.Fatalf("create over a draining replica: status %d, want 409", resp.StatusCode) + } + + if _, err := st.ResourceDefinitions().Get(ctx, "pvc-retry"); err == nil { + t.Fatal("the refused create left a definition behind") + } + + if err := st.Resources().Delete(ctx, "pvc-retry", "node-down"); err != nil { + t.Fatalf("drain the replica: %v", err) + } + + resp = httpPost(t, base+"/v1/resource-definitions", body) + _ = resp.Body.Close() + + if resp.StatusCode != http.StatusCreated { + t.Fatalf("create once the replica is gone: status %d, want 201", resp.StatusCode) + } +} diff --git a/pkg/store/draining.go b/pkg/store/draining.go new file mode 100644 index 000000000..ff2e40f25 --- /dev/null +++ b/pkg/store/draining.go @@ -0,0 +1,69 @@ +// 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 store + +import ( + "slices" + "strings" + + "github.com/cockroachdb/errors" + + apiv1 "github.com/cozystack/blockstor/pkg/api/v1" +) + +// ErrDefinitionReplicasDraining refuses a definition whose name still has +// replicas of an earlier definition being deleted under it. +var ErrDefinitionReplicasDraining = errors.New("replicas of an earlier definition under that name are still being deleted") + +// RefuseOverDrainingReplicas is the check both stores run before they create +// a definition: none of the replicas under its name may be on their way out. +// +// LINSTOR keeps a deleted definition, flagged DELETE, until every satellite +// has confirmed its replica gone, so a definition of the same name cannot be +// created while a node holding one of them is offline. linstor-csi retries +// such a CreateVolume until the name is free. Here the definition object goes +// at once and its replicas drain on their own; a definition created over them +// would count a replica of the old one as its own. The old replica carries the +// old volume's DRBD node id, disk state and generation, and the new replicas +// then elect it as their initial UpToDate source, take a seed generation from +// it, and size their block from it, and come up Inconsistent with nothing to +// sync from once it is gone. +// +// A replica that is not being deleted is not refused: an orphan left by a +// cascade that did not finish, or one placed under a name on purpose, is the +// restore doors' to judge (RefuseReplicasWithoutDefinition). +func RefuseOverDrainingReplicas(name string, replicas []apiv1.Resource) error { + var draining []string + + for i := range replicas { + if slices.Contains(replicas[i].Flags, apiv1.ResourceFlagDelete) { + draining = append(draining, replicas[i].NodeName) + } + } + + if len(draining) == 0 { + return nil + } + + slices.Sort(draining) + + return errors.Wrapf(errors.Mark(ErrAlreadyExists, ErrDefinitionReplicasDraining), + "resource definition %q is still being deleted: its replicas on %s are not gone yet; retry once they are", + name, strings.Join(draining, ", ")) +} diff --git a/pkg/store/inmemory.go b/pkg/store/inmemory.go index a9c355733..44e3b043e 100644 --- a/pkg/store/inmemory.go +++ b/pkg/store/inmemory.go @@ -47,12 +47,14 @@ type InMemory struct { // NewInMemory constructs an InMemory store with empty per-resource maps. func NewInMemory() *InMemory { + resources := &inMemoryResources{m: map[rKey]apiv1.Resource{}} + return &InMemory{ nodes: &inMemoryNodes{m: map[string]apiv1.Node{}}, storagePools: &inMemoryStoragePools{m: map[spKey]apiv1.StoragePool{}}, resourceGroups: &inMemoryResourceGroups{m: map[string]apiv1.ResourceGroup{}}, - resourceDefinitions: &inMemoryResourceDefinitions{m: map[string]apiv1.ResourceDefinition{}}, - resources: &inMemoryResources{m: map[rKey]apiv1.Resource{}}, + resourceDefinitions: &inMemoryResourceDefinitions{m: map[string]apiv1.ResourceDefinition{}, replicas: resources}, + resources: resources, volumeDefinitions: &inMemoryVolumeDefinitions{m: map[vdKey]apiv1.VolumeDefinition{}}, snapshots: &inMemorySnapshots{m: map[snapKey]apiv1.Snapshot{}}, physicalDevices: &inMemoryPhysicalDevices{m: map[string]apiv1.PhysicalDevice{}}, diff --git a/pkg/store/inmemory_resource_definition.go b/pkg/store/inmemory_resource_definition.go index 8853f1462..ae10f881f 100644 --- a/pkg/store/inmemory_resource_definition.go +++ b/pkg/store/inmemory_resource_definition.go @@ -32,6 +32,11 @@ import ( type inMemoryResourceDefinitions struct { mu sync.RWMutex m map[string]apiv1.ResourceDefinition + + // replicas is read before a create: a name whose replicas of an + // earlier definition are still being deleted is refused + // (RefuseOverDrainingReplicas). + replicas *inMemoryResources } // ListUncached has nothing to bypass here: this store is the API server. @@ -70,11 +75,23 @@ func (s *inMemoryResourceDefinitions) GetUncached(ctx context.Context, name stri return s.Get(ctx, name) } -func (s *inMemoryResourceDefinitions) Create(_ context.Context, rd *apiv1.ResourceDefinition) error { +func (s *inMemoryResourceDefinitions) Create(ctx context.Context, rd *apiv1.ResourceDefinition) error { if rd == nil { return errors.New("nil ResourceDefinition") } + if s.replicas != nil { + replicas, err := s.replicas.ListByDefinition(ctx, rd.Name) + if err != nil { + return err + } + + err = RefuseOverDrainingReplicas(rd.Name, replicas) + if err != nil { + return err + } + } + s.mu.Lock() defer s.mu.Unlock() diff --git a/pkg/store/k8s/k8s.go b/pkg/store/k8s/k8s.go index 6c0da59cf..a63d4a1a1 100644 --- a/pkg/store/k8s/k8s.go +++ b/pkg/store/k8s/k8s.go @@ -96,8 +96,8 @@ func NewWithAPIReader(c ctrlclient.Client, apiReader ctrlclient.Reader) *Store { s.nodes = &nodes{c: c, apiReader: apiReader} s.storagePools = &storagePools{c: c, apiReader: apiReader} s.resourceGroups = &resourceGroups{c: c} - s.resourceDefinitions = &resourceDefinitions{c: c, apiReader: apiReader} s.resources = &resources{c: c, apiReader: apiReader} + s.resourceDefinitions = &resourceDefinitions{c: c, apiReader: apiReader, replicas: s.resources} s.volumeDefinitions = &volumeDefinitions{c: c, apiReader: apiReader} s.snapshots = &snapshots{c: c, apiReader: apiReader} s.physicalDevices = &physicalDevices{c: c} diff --git a/pkg/store/k8s/resource_definitions.go b/pkg/store/k8s/resource_definitions.go index f419f97c5..bc2c8802e 100644 --- a/pkg/store/k8s/resource_definitions.go +++ b/pkg/store/k8s/resource_definitions.go @@ -48,6 +48,11 @@ type resourceDefinitions struct { // NotFound we re-read live before concluding the RD is absent. nil in // non-production stores (in-memory / unit) → keep the cached result. apiReader ctrlclient.Reader + + // replicas is read past the cache before a create: a name whose + // replicas of an earlier definition are still being deleted is + // refused (store.RefuseOverDrainingReplicas). + replicas *resources } func (s *resourceDefinitions) List(ctx context.Context) ([]apiv1.ResourceDefinition, error) { @@ -97,6 +102,18 @@ func (s *resourceDefinitions) Create(ctx context.Context, in *apiv1.ResourceDefi return errors.New("nil ResourceDefinition") } + if s.replicas != nil { + replicas, err := s.replicas.ListByDefinitionUncached(ctx, in.Name) + if err != nil { + return errors.Wrapf(err, "list the replicas under %q", in.Name) + } + + err = store.RefuseOverDrainingReplicas(in.Name, replicas) + if err != nil { + return err //nolint:wrapcheck // already names the definition and wraps store.ErrAlreadyExists + } + } + crd := wireToCRDRD(in) err := s.c.Create(ctx, crd) diff --git a/pkg/store/storetest/storetest.go b/pkg/store/storetest/storetest.go index 9d99562fc..3e7d76226 100644 --- a/pkg/store/storetest/storetest.go +++ b/pkg/store/storetest/storetest.go @@ -24,6 +24,7 @@ package storetest import ( "slices" + "strings" "testing" "github.com/cockroachdb/errors" @@ -1244,6 +1245,9 @@ func RunResourceDefinitionStore(t *testing.T, newStore Factory) { t.Errorf("dup: got %v, want ErrAlreadyExists", err) } }) + t.Run("CreateRefusedOverDrainingReplicas", func(t *testing.T) { + testRDCreateRefusedOverDrainingReplicas(t, newStore) + }) t.Run("GetMissing", func(t *testing.T) { _, err := newStore(t).ResourceDefinitions().Get(t.Context(), "ghost") if !errors.Is(err, store.ErrNotFound) { @@ -2304,6 +2308,56 @@ func testAnySpellingAddressesOneNode(t *testing.T, newStore Factory) { } } +// testRDCreateRefusedOverDrainingReplicas: a definition deleted while one of +// its nodes is down leaves that node's replica draining under the name. A new +// definition of the same name is refused until it is gone, as LINSTOR, which +// keeps the old definition until then, refuses it; a replica that is not +// being deleted does not hold the name. +func testRDCreateRefusedOverDrainingReplicas(t *testing.T, newStore Factory) { + t.Helper() + + s := newStore(t) + ctx := t.Context() + + if err := s.ResourceDefinitions().Create(ctx, &apiv1.ResourceDefinition{Name: "pvc-d"}); err != nil { + t.Fatalf("Create definition: %v", err) + } + + draining := apiv1.Resource{Name: "pvc-d", NodeName: "node-down", Flags: []string{apiv1.ResourceFlagDelete}} + if err := s.Resources().Create(ctx, &draining); err != nil { + t.Fatalf("Create draining replica: %v", err) + } + + if err := s.Resources().Create(ctx, &apiv1.Resource{Name: "pvc-d", NodeName: "node-up"}); err != nil { + t.Fatalf("Create orphan replica: %v", err) + } + + if err := s.ResourceDefinitions().Delete(ctx, "pvc-d"); err != nil { + t.Fatalf("Delete definition: %v", err) + } + + err := s.ResourceDefinitions().Create(ctx, &apiv1.ResourceDefinition{Name: "pvc-d"}) + if !errors.Is(err, store.ErrDefinitionReplicasDraining) || !errors.Is(err, store.ErrAlreadyExists) { + t.Fatalf("Create over a draining replica = %v, want ErrDefinitionReplicasDraining and ErrAlreadyExists", err) + } + + if !strings.Contains(err.Error(), "node-down") || strings.Contains(err.Error(), "node-up") { + t.Errorf("refusal %q should name the draining replica's node and only it", err) + } + + if _, getErr := s.ResourceDefinitions().Get(ctx, "pvc-d"); !errors.Is(getErr, store.ErrNotFound) { + t.Errorf("Get after the refused create = %v, want ErrNotFound", getErr) + } + + if err := s.Resources().Delete(ctx, "pvc-d", "node-down"); err != nil { + t.Fatalf("Delete draining replica: %v", err) + } + + if err := s.ResourceDefinitions().Create(ctx, &apiv1.ResourceDefinition{Name: "pvc-d"}); err != nil { + t.Errorf("Create once the draining replica is gone: %v", err) + } +} + // testAnySpellingAddressesOneReplica: a replica is addressed by the keys of // its definition's and its node's names. func testAnySpellingAddressesOneReplica(t *testing.T, newStore Factory) { From 984337b28573c52d72a1bcf811dd8c252a15730c Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Tue, 24 Nov 2026 01:53:55 +0100 Subject: [PATCH 09/16] fix(rest): answer a refused definition create with FAIL_EXISTS_RSC_DFN The definition create wrote its store error untyped, so a duplicate name, and since the draining refusal a name whose earlier definition is still tearing replicas down, came back as a bare error with no FAIL_EXISTS band. LINSTOR answers both with FAIL_EXISTS_RSC_DFN, and golinstor and the python client key a duplicate definition on it. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- pkg/rest/rd_create_draining_test.go | 15 +++++++++++++++ pkg/rest/resource_definitions.go | 5 ++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/pkg/rest/rd_create_draining_test.go b/pkg/rest/rd_create_draining_test.go index 5694814db..7c12dde0f 100644 --- a/pkg/rest/rd_create_draining_test.go +++ b/pkg/rest/rd_create_draining_test.go @@ -19,6 +19,7 @@ limitations under the License. package rest import ( + "encoding/json" "net/http" "testing" @@ -51,12 +52,26 @@ func TestRDCreateWaitsForTheDeletedDefinitionsReplicas(t *testing.T) { body := []byte(`{"resource_definition":{"name":"pvc-retry"}}`) resp := httpPost(t, base+"/v1/resource-definitions", body) + + var rcs []apiv1.APICallRc + + decodeErr := json.NewDecoder(resp.Body).Decode(&rcs) _ = resp.Body.Close() if resp.StatusCode != http.StatusConflict { t.Fatalf("create over a draining replica: status %d, want 409", resp.StatusCode) } + // linstor-csi only needs an error to retry on, but golinstor and the + // python client key a duplicate definition on this band. + if decodeErr != nil || len(rcs) == 0 { + t.Fatalf("decode the refusal: %v (%d entries)", decodeErr, len(rcs)) + } + + if rcs[0].RetCode&apiCallRcFailExistsRscDfn != apiCallRcFailExistsRscDfn { + t.Errorf("ret_code %#x lacks FAIL_EXISTS_RSC_DFN", rcs[0].RetCode) + } + if _, err := st.ResourceDefinitions().Get(ctx, "pvc-retry"); err == nil { t.Fatal("the refused create left a definition behind") } diff --git a/pkg/rest/resource_definitions.go b/pkg/rest/resource_definitions.go index cdbecb106..987789a45 100644 --- a/pkg/rest/resource_definitions.go +++ b/pkg/rest/resource_definitions.go @@ -343,7 +343,10 @@ func (s *Server) handleRDCreate(w http.ResponseWriter, r *http.Request) { err = s.Store.ResourceDefinitions().Create(r.Context(), &rd) if err != nil { - writeStoreError(w, err) + // Typed, so a duplicate name, or one whose earlier definition is + // still draining replicas, carries FAIL_EXISTS_RSC_DFN as LINSTOR's + // does. + writeStoreErrorTyped(w, err, storeKindResourceDfn) return } From 7f77e8874d9cbf3af24cf32e956c0748e73713c2 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Tue, 24 Nov 2026 01:53:55 +0100 Subject: [PATCH 10/16] fix(restore): say a target is still being deleted instead of missing Both restore doors read an AlreadyExists from the definition create as a definition already under the name, and went to adopt or judge it. The draining refusal is AlreadyExists with no definition behind it, so the read that followed came back NotFound and that is what the caller got: a 404 from REST, "not found" from the CLI, for a name whose earlier definition is still tearing down a replica on a node that is down. The refusal now goes back as it is, with FAIL_EXISTS_RSC_DFN on the REST door like the plain create, naming the nodes to wait for. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- internal/cli/snapshot.go | 6 ++ internal/cli/snapshot_restore_orphans_test.go | 29 +++++++ pkg/rest/restore_draining_target_test.go | 81 +++++++++++++++++++ pkg/rest/snapshot_restore.go | 12 ++- pkg/store/draining.go | 7 ++ 5 files changed, 132 insertions(+), 3 deletions(-) create mode 100644 pkg/rest/restore_draining_target_test.go diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index 18f968a35..3a863c908 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -343,6 +343,12 @@ func snapshotRestoreResource(ctx context.Context, run *runContext) error { } err = run.Store.ResourceDefinitions().Create(ctx, def) + if store.IsReplicasDraining(err) { + // No definition to restore into: its predecessor is still + // draining replicas, and the refusal names their nodes. + return fmt.Errorf("restore %s onto %s: %w", snap.Name, args.toResource, err) + } + if errors.Is(err, store.ErrAlreadyExists) { return restoreIntoExistingTarget(ctx, run, args, &snap, err) } diff --git a/internal/cli/snapshot_restore_orphans_test.go b/internal/cli/snapshot_restore_orphans_test.go index b0915ae71..c9f6b3c72 100644 --- a/internal/cli/snapshot_restore_orphans_test.go +++ b/internal/cli/snapshot_restore_orphans_test.go @@ -21,6 +21,7 @@ package cli_test import ( "context" "errors" + "strings" "testing" apiv1 "github.com/cozystack/blockstor/pkg/api/v1" @@ -54,3 +55,31 @@ func TestSnapshotRestoreRefusesATargetWithOrphanReplicas(t *testing.T) { t.Fatalf("the refusal left a definition behind: err=%v", err) } } + +// A restore into a name whose earlier definition is still draining a replica +// on a node that is down is refused as the plain create is: the definition is +// still being deleted, and the refusal names the node. Read as an existing +// target instead, it answered that the definition was not found. +func TestSnapshotRestoreIntoANameStillBeingDeletedSaysSo(t *testing.T) { + t.Parallel() + + app, _, errBuf := newApp(t, func(ctx context.Context, backend store.Store) { + seedSnapshotSource(ctx, backend) + _ = backend.Resources().Create(ctx, &apiv1.Resource{ + Name: "pvc-drain", NodeName: "node-down", Flags: []string{apiv1.ResourceFlagDelete}, + }) + }) + + if got := app.Run(t.Context(), restoreResourceArgv("pvc-drain")); got == 0 { + t.Fatal("restore over a draining replica succeeded") + } + + msg := errBuf.String() + if !strings.Contains(msg, "still being deleted") || !strings.Contains(msg, "node-down") { + t.Fatalf("refusal = %q, want it to say the definition is still being deleted on node-down", msg) + } + + if strings.Contains(msg, "not found") { + t.Fatalf("refusal = %q, answered as a missing definition", msg) + } +} diff --git a/pkg/rest/restore_draining_target_test.go b/pkg/rest/restore_draining_target_test.go new file mode 100644 index 000000000..4286a7803 --- /dev/null +++ b/pkg/rest/restore_draining_target_test.go @@ -0,0 +1,81 @@ +// 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 rest + +import ( + "encoding/json" + "errors" + "net/http" + "strings" + "testing" + + apiv1 "github.com/cozystack/blockstor/pkg/api/v1" + "github.com/cozystack/blockstor/pkg/store" +) + +// A restore retried after its rollback, while a node holding a replica of the +// rolled-back definition is down, is refused the way the plain create is: 409, +// FAIL_EXISTS_RSC_DFN, and a message naming the node. The adopt path read the +// refusal as a leftover definition, found none, and answered 404. +func TestRestoreIntoANameStillBeingDeletedAnswers409(t *testing.T) { + t.Parallel() + + st := store.NewInMemory() + ctx := t.Context() + seedDeployedCloneSource(t, st, "src-drain") + seedRestoreSnapshot(t, st, "src-drain", "snap-drain", []string{"node-a"}) + + if err := st.Resources().Create(ctx, &apiv1.Resource{ + Name: "dst-drain", NodeName: "node-down", Flags: []string{apiv1.ResourceFlagDelete}, + }); err != nil { + t.Fatalf("seed the draining replica: %v", err) + } + + base, stop := startServerWithStore(t, st) + defer stop() + + raw, err := json.Marshal(map[string]any{"to_resource": "dst-drain", "node_names": []string{"node-a"}}) + if err != nil { + t.Fatalf("marshal: %v", err) + } + + resp := httpPost(t, base+"/v1/resource-definitions/src-drain/snapshot-restore-resource/snap-drain", raw) + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode != http.StatusConflict { + t.Fatalf("restore over a draining replica: status %d, want 409", resp.StatusCode) + } + + var rcs []apiv1.APICallRc + if err := json.NewDecoder(resp.Body).Decode(&rcs); err != nil || len(rcs) == 0 { + t.Fatalf("decode the refusal: %v (%d entries)", err, len(rcs)) + } + + if rcs[0].RetCode&apiCallRcFailExistsRscDfn != apiCallRcFailExistsRscDfn { + t.Errorf("ret_code %#x lacks FAIL_EXISTS_RSC_DFN", rcs[0].RetCode) + } + + if !strings.Contains(rcs[0].Message, "node-down") { + t.Errorf("message %q does not name the draining node", rcs[0].Message) + } + + if _, err := st.ResourceDefinitions().Get(ctx, "dst-drain"); !errors.Is(err, store.ErrNotFound) { + t.Errorf("the refusal left a definition behind: err=%v", err) + } +} diff --git a/pkg/rest/snapshot_restore.go b/pkg/rest/snapshot_restore.go index 72d1108d4..840302c9d 100644 --- a/pkg/rest/snapshot_restore.go +++ b/pkg/rest/snapshot_restore.go @@ -612,7 +612,10 @@ func (s *Server) writeRestoreMaterialiseFailed( // // A replica still being deleted, or one holding no data, carries no // FAIL_EXISTS band: the replica it names is not one that exists for the -// caller to use, and the 409 is the retryable failure it is. +// caller to use, and the 409 is the retryable failure it is. A definition +// whose predecessor is still draining replicas does carry +// FAIL_EXISTS_RSC_DFN: LINSTOR still holds that definition, flagged DELETE, +// and answers a create of its name with that band. func materialiseRefusalKind(err error) (storeResourceKind, bool) { var partial *materialiseAfterCreateError if errors.As(err, &partial) { @@ -622,7 +625,7 @@ func materialiseRefusalKind(err error) (storeResourceKind, bool) { switch { case errors.Is(err, errReplicaStillDeleting): return storeKindUnknown, true - case errors.Is(err, errAdoptedLeftoverRollingBack): + case errors.Is(err, errAdoptedLeftoverRollingBack), errors.Is(err, store.ErrDefinitionReplicasDraining): return storeKindResourceDfn, true default: return storeKindUnknown, true @@ -1544,7 +1547,10 @@ func (s *Server) createOrAdoptRestoredRD(ctx context.Context, newRD *apiv1.Resou return true, "", nil } - if !errors.Is(err, store.ErrAlreadyExists) { + // A name whose earlier definition is still draining replicas has no + // definition to adopt: read as a leftover, the refusal turned into a + // NotFound for a definition that is still being deleted. + if !errors.Is(err, store.ErrAlreadyExists) || errors.Is(err, store.ErrDefinitionReplicasDraining) { return false, "", err //nolint:wrapcheck // surfaced via writeStoreError } diff --git a/pkg/store/draining.go b/pkg/store/draining.go index ff2e40f25..55fcb0cbf 100644 --- a/pkg/store/draining.go +++ b/pkg/store/draining.go @@ -67,3 +67,10 @@ func RefuseOverDrainingReplicas(name string, replicas []apiv1.Resource) error { "resource definition %q is still being deleted: its replicas on %s are not gone yet; retry once they are", name, strings.Join(draining, ", ")) } + +// IsReplicasDraining reports whether err is RefuseOverDrainingReplicas' +// refusal. The refusal is a cockroachdb mark, which the standard library's +// errors.Is does not see; callers on that package ask here. +func IsReplicasDraining(err error) bool { + return errors.Is(err, ErrDefinitionReplicasDraining) +} From d2ee887007a60affc7fbf80f1beb1422f9f7d346 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Tue, 24 Nov 2026 01:55:13 +0100 Subject: [PATCH 11/16] test(store): refuse a definition over a finalizer-held replica The contract test seeds the draining replica with a DELETE flag in its spec. In production nothing writes that flag: the satellite finalizer holds the deleted object and the read projects DELETE from its deletion timestamp. Cover that shape on the Kubernetes store, so the refusal and the projection are tested together. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- pkg/store/k8s/rd_create_draining_test.go | 103 +++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 pkg/store/k8s/rd_create_draining_test.go diff --git a/pkg/store/k8s/rd_create_draining_test.go b/pkg/store/k8s/rd_create_draining_test.go new file mode 100644 index 000000000..6909d2698 --- /dev/null +++ b/pkg/store/k8s/rd_create_draining_test.go @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: Apache-2.0 + +package k8s_test + +import ( + "context" + "strings" + "testing" + + crdv1alpha1 "github.com/cozystack/blockstor/api/v1alpha1" + apiv1 "github.com/cozystack/blockstor/pkg/api/v1" + "github.com/cozystack/blockstor/pkg/store" + "github.com/cozystack/blockstor/pkg/store/k8s" +) + +// A replica drains the way production drains it: its satellite's finalizer +// holds the object after the delete, and nothing writes a DELETE flag into its +// spec; the flag the refusal reads is projected from the deletion timestamp. +// The contract test seeds the flag directly and so never covered that. +func TestRDCreateRefusedOverAFinalizerHeldReplica(t *testing.T) { + if fixture == nil { + t.Skip("envtest assets not installed; run `make setup-envtest` to enable") + } + + const ( + rdName = "pvc-drain-fin" + finalizer = "blockstor.org/satellite-resource" + ) + + ctx := t.Context() + st := k8s.NewWithAPIReader(fixture.client, fixture.client) + + if err := st.ResourceDefinitions().Create(ctx, &apiv1.ResourceDefinition{Name: rdName}); err != nil { + t.Fatalf("create definition: %v", err) + } + + if err := st.Resources().Create(ctx, &apiv1.Resource{Name: rdName, NodeName: "node-down"}); err != nil { + t.Fatalf("create replica: %v", err) + } + + crd := replicaCRD(ctx, t, rdName) + + release := func() { + cur := replicaCRD(context.Background(), t, rdName) + if cur == nil { + return + } + + cur.Finalizers = nil + _ = fixture.client.Update(context.Background(), cur) + } + t.Cleanup(release) + + crd.Finalizers = append(crd.Finalizers, finalizer) + if err := fixture.client.Update(ctx, crd); err != nil { + t.Fatalf("hold the replica with the satellite finalizer: %v", err) + } + + if err := fixture.client.Delete(ctx, crd); err != nil { + t.Fatalf("delete the replica: %v", err) + } + + if held := replicaCRD(ctx, t, rdName); held == nil || held.DeletionTimestamp.IsZero() || + len(held.Spec.Flags) != 0 { + t.Fatalf("fixture: want a finalizer-held replica with a deletion timestamp and no spec flags, got %+v", held) + } + + if err := st.ResourceDefinitions().Delete(ctx, rdName); err != nil { + t.Fatalf("delete definition: %v", err) + } + + err := st.ResourceDefinitions().Create(ctx, &apiv1.ResourceDefinition{Name: rdName}) + if !store.IsReplicasDraining(err) || !strings.Contains(err.Error(), "node-down") { + t.Fatalf("create over the finalizer-held replica = %v, want the draining refusal naming node-down", err) + } + + release() + + if err := st.ResourceDefinitions().Create(ctx, &apiv1.ResourceDefinition{Name: rdName}); err != nil { + t.Fatalf("create once the replica is gone: %v", err) + } + + t.Cleanup(func() { _ = st.ResourceDefinitions().Delete(context.Background(), rdName) }) +} + +// replicaCRD reads the one Resource object under rdName from the API server, +// or nil when there is none. +func replicaCRD(ctx context.Context, t *testing.T, rdName string) *crdv1alpha1.Resource { + t.Helper() + + var list crdv1alpha1.ResourceList + if err := fixture.client.List(ctx, &list); err != nil { + t.Fatalf("list replicas: %v", err) + } + + for i := range list.Items { + if list.Items[i].Spec.ResourceDefinitionName == rdName { + return &list.Items[i] + } + } + + return nil +} From a640e3adbee4a7b0397e38c5810e9c4d1644399c Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Tue, 24 Nov 2026 01:58:14 +0100 Subject: [PATCH 12/16] fix(controller): elect and seed from the replicas that stay The create door now refuses a definition over the draining replica of an earlier one, but a definition applied as an object does not go through it, and a replica deleted from a live volume is still read as a peer while its satellite tears it down. The initial Primary election and the seed generation pick both counted such a replica: it could hold the lowest node id, so no replica that stays seeded, and its UpToDate day0 generation was copied as the seed of the new ones. Both now skip a replica with a deletion timestamp or the DELETE flag, as the tiebreaker reconciler already does. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- internal/controller/resource_controller.go | 8 +++ internal/controller/seed_leaving_peer_test.go | 56 +++++++++++++++++++ pkg/dispatcher/dispatcher.go | 17 ++++++ pkg/dispatcher/leaving_peer_test.go | 53 ++++++++++++++++++ 4 files changed, 134 insertions(+) create mode 100644 internal/controller/seed_leaving_peer_test.go create mode 100644 pkg/dispatcher/leaving_peer_test.go diff --git a/internal/controller/resource_controller.go b/internal/controller/resource_controller.go index 8d7c12305..1c6b5e382 100644 --- a/internal/controller/resource_controller.go +++ b/internal/controller/resource_controller.go @@ -39,6 +39,7 @@ import ( blockstoriov1alpha1 "github.com/cozystack/blockstor/api/v1alpha1" apiv1 "github.com/cozystack/blockstor/pkg/api/v1" + "github.com/cozystack/blockstor/pkg/dispatcher" "github.com/cozystack/blockstor/pkg/drbd" "github.com/cozystack/blockstor/pkg/effectiveprops" "github.com/cozystack/blockstor/pkg/naming" @@ -1179,6 +1180,13 @@ func pickSeedFromPeers(peers []blockstoriov1alpha1.Resource, targetName string, continue } + // A peer being deleted may be the replica of an earlier + // definition under this name: its UpToDate generation is that + // volume's, and seeding from it skips the seed this one needs. + if dispatcher.ReplicaLeaving(&peers[i]) { + continue + } + gi := volumeCurrentGI(&peers[i], volumeNumber) if gi == "" { continue diff --git a/internal/controller/seed_leaving_peer_test.go b/internal/controller/seed_leaving_peer_test.go new file mode 100644 index 000000000..9b5729d9a --- /dev/null +++ b/internal/controller/seed_leaving_peer_test.go @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 + +package controller + +import ( + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + blockstoriov1alpha1 "github.com/cozystack/blockstor/api/v1alpha1" + apiv1 "github.com/cozystack/blockstor/pkg/api/v1" + "github.com/cozystack/blockstor/pkg/drbd" +) + +// The draining replica of an earlier definition under the same name reported +// UpToDate at that name's day0 generation, so it passed the data gate and its +// generation was copied into the new replicas as their seed. The seed then +// stood in for the one the new volume needed, and its replicas came up +// Inconsistent. A peer on its way out seeds nothing. +func TestPickSeedFromPeersSkipsALeavingPeer(t *testing.T) { + t.Parallel() + + const rdName = "pvc-reused" + + day0 := drbd.Day0GIFor(rdName, 0) + + upToDate := func(name string) blockstoriov1alpha1.Resource { + r := blockstoriov1alpha1.Resource{} + r.Name = name + r.Spec.ResourceDefinitionName = rdName + r.Status.Volumes = []blockstoriov1alpha1.ResourceVolumeStatus{ + {VolumeNumber: 0, DiskState: string(drbd.DiskStateUpToDate), CurrentGI: day0}, + } + + return r + } + + now := metav1.Now() + + held := upToDate(rdName + ".node-down") + held.DeletionTimestamp = &now + held.Finalizers = []string{"blockstor.org/satellite-resource"} + + flagged := upToDate(rdName + ".node-down") + flagged.Spec.Flags = []string{apiv1.ResourceFlagDelete} + + for name, leaving := range map[string]blockstoriov1alpha1.Resource{"finalizer-held": held, "flagged": flagged} { + if got := pickSeedFromPeers([]blockstoriov1alpha1.Resource{leaving}, rdName+".node-a", 0); got != "" { + t.Errorf("%s: seed = %q, want none from a leaving peer", name, got) + } + } + + if got := pickSeedFromPeers([]blockstoriov1alpha1.Resource{upToDate(rdName + ".node-b")}, rdName+".node-a", 0); got != day0 { + t.Errorf("a peer that stays: seed = %q, want %q", got, day0) + } +} diff --git a/pkg/dispatcher/dispatcher.go b/pkg/dispatcher/dispatcher.go index 9cacbdd23..7ba3dfc72 100644 --- a/pkg/dispatcher/dispatcher.go +++ b/pkg/dispatcher/dispatcher.go @@ -743,12 +743,29 @@ func lowestDiskfulID(target *blockstoriov1alpha1.Resource, peers []blockstoriov1 consider(target) for i := range peers { + // A peer on its way out is not this volume's replica to elect: + // under a name whose earlier definition is still draining it + // carries that volume's node id, and holding the lowest it kept + // either new replica from seeding the initial Primary. + if ReplicaLeaving(&peers[i]) { + continue + } + consider(&peers[i]) } return low } +// ReplicaLeaving reports whether a replica is being deleted: its object +// carries a deletion timestamp, held by the satellite finalizer while DRBD +// tears it down, or the DELETE flag LINSTOR stamps on it. Such a replica +// still answers reads, with the node id, disk state and generation it had, +// and is no source for a decision about the replicas that stay. +func ReplicaLeaving(r *blockstoriov1alpha1.Resource) bool { + return !r.DeletionTimestamp.IsZero() || slices.Contains(r.Spec.Flags, apiv1.ResourceFlagDelete) +} + // diskfulPeersAllocated reports whether every diskful replica (target // + peers) carries an allocated Status.DRBDNodeID. Returns false the // instant one diskful replica has a nil id — the caller must treat diff --git a/pkg/dispatcher/leaving_peer_test.go b/pkg/dispatcher/leaving_peer_test.go new file mode 100644 index 000000000..0c1706998 --- /dev/null +++ b/pkg/dispatcher/leaving_peer_test.go @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: Apache-2.0 + +package dispatcher + +import ( + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + blockstoriov1alpha1 "github.com/cozystack/blockstor/api/v1alpha1" + apiv1 "github.com/cozystack/blockstor/pkg/api/v1" +) + +// A definition created over the draining replica of an earlier one under the +// same name saw that replica as a peer holding node id 0. It won the initial +// Primary election, which it never runs, so neither new replica seeded and +// the volume stayed Inconsistent. The election is among the replicas that +// stay, whether the leaving one is held by its finalizer or flagged DELETE. +func TestLowestDiskfulIDSkipsALeavingPeer(t *testing.T) { + t.Parallel() + + replica := func(node string, id int32) blockstoriov1alpha1.Resource { + r := blockstoriov1alpha1.Resource{} + r.Name = "pvc-" + node + r.Spec.NodeName = node + r.Spec.DRBDNodeID = &id + + return r + } + + now := metav1.Now() + + held := replica("node-down", 0) + held.DeletionTimestamp = &now + held.Finalizers = []string{"blockstor.org/satellite-resource"} + + flagged := replica("node-down", 0) + flagged.Spec.Flags = []string{apiv1.ResourceFlagDelete} + + for name, leaving := range map[string]blockstoriov1alpha1.Resource{"finalizer-held": held, "flagged": flagged} { + target := replica("node-a", 1) + peers := []blockstoriov1alpha1.Resource{leaving, replica("node-b", 2)} + + if got := lowestDiskfulID(&target, peers); got != 1 { + t.Errorf("%s: lowest diskful id = %d, want 1 (the leaving peer's 0 does not count)", name, got) + } + } + + target := replica("node-a", 1) + if got := lowestDiskfulID(&target, []blockstoriov1alpha1.Resource{replica("node-down", 0)}); got != 0 { + t.Errorf("a peer that stays: lowest diskful id = %d, want 0", got) + } +} From 0557810a48e75c789b0470e078be5d5cbcff1a49 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Tue, 24 Nov 2026 02:04:46 +0100 Subject: [PATCH 13/16] fix(rest): answer rd d once the online replicas are torn down LINSTOR answers a definition delete once the online satellites have confirmed their replicas gone, and keeps the definition only for an offline node. Here the reply waited at most for the cache, five seconds, so with every node up a delete and a create of the same name failed whenever the ZFS or DRBD teardown took longer: the create is now refused while any replica of the old definition is draining. The delete now waits, reading past the cache and for at most twenty seconds, for the replicas on reachable nodes to go. Replicas on an offline node are not waited for; the create stays refused over them until the node is back, as in LINSTOR. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- pkg/rest/rd_delete_drain.go | 93 ++++++++++++++++++ pkg/rest/rd_delete_drain_test.go | 162 +++++++++++++++++++++++++++++++ pkg/rest/resource_definitions.go | 5 + 3 files changed, 260 insertions(+) create mode 100644 pkg/rest/rd_delete_drain.go create mode 100644 pkg/rest/rd_delete_drain_test.go diff --git a/pkg/rest/rd_delete_drain.go b/pkg/rest/rd_delete_drain.go new file mode 100644 index 000000000..e479ee4b6 --- /dev/null +++ b/pkg/rest/rd_delete_drain.go @@ -0,0 +1,93 @@ +// 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 rest + +import ( + "context" + "time" + + "github.com/cozystack/blockstor/pkg/store" +) + +// rdReplicaDrainBudget bounds how long a definition delete waits for the +// replicas on reachable nodes to finish tearing down. It sits well inside +// the CSI sidecars' call timeout, which linstor-csi's DeleteVolume, and the +// rollback inside a failed CreateVolume, both run under. +// +//nolint:gochecknoglobals // tunable +var rdReplicaDrainBudget = 20 * time.Second + +// rdReplicaDrainPoll is the cadence of the drain wait's reads. +// +//nolint:gochecknoglobals // tunable +var rdReplicaDrainPoll = 250 * time.Millisecond + +// waitForOnlineReplicasDrained holds a definition delete until no replica of +// it is left on a node that is reachable, or rdReplicaDrainBudget runs out. +// +// LINSTOR answers `rd d` once the online satellites confirm their replicas +// gone, and keeps the definition, flagged DELETE, only for an offline node. +// Here the definition object goes at once, and a create of the same name is +// refused while any replica of the old one is still draining +// (store.RefuseOverDrainingReplicas). Without this wait a delete followed by a +// create of the same name, with every node up, failed whenever the teardown +// took longer than the reply. Replicas on an offline node are not waited for: +// they drain when the node is back, and the create is refused until then, as +// LINSTOR refuses it. +// +// Read past the cache: a cache trailing the teardown would hold the reply for +// a replica already gone. The budget running out, or a read failing, answers +// the delete anyway: it has been committed, and the create that follows says +// which nodes are still draining. +func (s *Server) waitForOnlineReplicasDrained(ctx context.Context, name string) { + if s == nil || s.Store == nil { + return + } + + deadline := time.Now().Add(rdReplicaDrainBudget) + + for { + if !s.replicasLeftOnOnlineNodes(ctx, name) || time.Now().After(deadline) { + return + } + + select { + case <-ctx.Done(): + return + case <-time.After(rdReplicaDrainPoll): + } + } +} + +// replicasLeftOnOnlineNodes reports whether a replica under name is still +// there on a node that is not offline. +func (s *Server) replicasLeftOnOnlineNodes(ctx context.Context, name string) bool { + replicas, err := store.LiveReplicas(ctx, s.Store, name) + if err != nil { + return false + } + + for i := range replicas { + if isNodeOnline(ctx, s.Store.Nodes(), replicas[i].NodeName) { + return true + } + } + + return false +} diff --git a/pkg/rest/rd_delete_drain_test.go b/pkg/rest/rd_delete_drain_test.go new file mode 100644 index 000000000..fbcda9400 --- /dev/null +++ b/pkg/rest/rd_delete_drain_test.go @@ -0,0 +1,162 @@ +// 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 rest + +import ( + "context" + "net/http" + "slices" + "testing" + "time" + + apiv1 "github.com/cozystack/blockstor/pkg/api/v1" + "github.com/cozystack/blockstor/pkg/store" +) + +// finalizerHeldResources deletes a replica the way the Kubernetes store does +// while its satellite's finalizer holds it: the replica stays, flagged DELETE, +// until the satellite has torn it down (here, until the test removes it). +type finalizerHeldResources struct { + store.ResourceStore +} + +func (f finalizerHeldResources) Delete(ctx context.Context, rdName, node string) error { + return f.PatchResourceSpec(ctx, rdName, node, func(r *apiv1.Resource) error { //nolint:wrapcheck // test helper + if !slices.Contains(r.Flags, apiv1.ResourceFlagDelete) { + r.Flags = append(r.Flags, apiv1.ResourceFlagDelete) + } + + return nil + }) +} + +type finalizerHeldStore struct { + store.Store + + resources finalizerHeldResources +} + +func (f finalizerHeldStore) Resources() store.ResourceStore { return f.resources } + +func newFinalizerHeldStore() (finalizerHeldStore, *store.InMemory) { + inner := store.NewInMemory() + + return finalizerHeldStore{Store: inner, resources: finalizerHeldResources{inner.Resources()}}, inner +} + +// LINSTOR answers `rd d` once the online satellites have torn their replicas +// down, so a create of the same name right after it goes through. The delete +// answered as soon as the objects were marked, and the create that followed +// was refused over replicas still tearing down on nodes that were up. +// +// The teardown outlasts the cache wait's own budget, which already held the +// reply for a teardown shorter than it. +func TestRDDeleteWaitsForReplicasOnOnlineNodes(t *testing.T) { + t.Parallel() + + teardown := cacheConvergeBudget + time.Second + + st, inner := newFinalizerHeldStore() + ctx := t.Context() + + seedDrainFixture(t, inner, "pvc-online", apiv1.NodeTypeOnline) + + base, stop := startServerWithStore(t, st) + defer stop() + + go func() { + time.Sleep(teardown) + + _ = inner.Resources().Delete(context.WithoutCancel(ctx), "pvc-online", "node-1") + }() + + start := time.Now() + + resp := httpDelete(t, base+"/v1/resource-definitions/pvc-online") + _ = resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Fatalf("rd d: status %d, want 200", resp.StatusCode) + } + + if elapsed := time.Since(start); elapsed < teardown { + t.Fatalf("rd d answered after %v, before the online replica's %v teardown finished", elapsed, teardown) + } + + resp = httpPost(t, base+"/v1/resource-definitions", []byte(`{"resource_definition":{"name":"pvc-online"}}`)) + _ = resp.Body.Close() + + if resp.StatusCode != http.StatusCreated { + t.Fatalf("rd c right after rd d: status %d, want 201", resp.StatusCode) + } +} + +// A replica on an offline node drains only when the node is back. The delete +// does not wait for it, and the create of the same name is refused until then, +// as LINSTOR refuses it. +func TestRDDeleteDoesNotWaitForAnOfflineNode(t *testing.T) { + t.Parallel() + + st, inner := newFinalizerHeldStore() + + seedDrainFixture(t, inner, "pvc-offline", apiv1.NodeTypeOffline) + + base, stop := startServerWithStore(t, st) + defer stop() + + start := time.Now() + + resp := httpDelete(t, base+"/v1/resource-definitions/pvc-offline") + _ = resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Fatalf("rd d: status %d, want 200", resp.StatusCode) + } + + // The cache wait still runs its own 5s budget over the replica that + // stays; the drain wait adds nothing on top of it for an offline node. + if elapsed := time.Since(start); elapsed > cacheConvergeBudget+2*time.Second { + t.Fatalf("rd d waited %v for a replica on an offline node", elapsed) + } + + resp = httpPost(t, base+"/v1/resource-definitions", []byte(`{"resource_definition":{"name":"pvc-offline"}}`)) + _ = resp.Body.Close() + + if resp.StatusCode != http.StatusConflict { + t.Fatalf("rd c over the offline node's replica: status %d, want 409", resp.StatusCode) + } +} + +func seedDrainFixture(t *testing.T, st *store.InMemory, rdName, connection string) { + t.Helper() + + ctx := t.Context() + + if err := st.Nodes().Create(ctx, &apiv1.Node{Name: "node-1", ConnectionStatus: connection}); err != nil { + t.Fatalf("seed node: %v", err) + } + + if err := st.ResourceDefinitions().Create(ctx, &apiv1.ResourceDefinition{Name: rdName}); err != nil { + t.Fatalf("seed definition: %v", err) + } + + if err := st.Resources().Create(ctx, &apiv1.Resource{Name: rdName, NodeName: "node-1"}); err != nil { + t.Fatalf("seed replica: %v", err) + } +} diff --git a/pkg/rest/resource_definitions.go b/pkg/rest/resource_definitions.go index 987789a45..804ab76cc 100644 --- a/pkg/rest/resource_definitions.go +++ b/pkg/rest/resource_definitions.go @@ -1298,6 +1298,11 @@ func (s *Server) handleRDDelete(w http.ResponseWriter, r *http.Request) { // refuses a definition that has snapshots. reaped := reapClonedSnapshot(r.Context(), s.Store, name, clonedFrom) + // Answered once the reachable satellites have torn their replicas + // down, as LINSTOR answers it, so a create of the same name that + // follows is not refused over them. + s.waitForOnlineReplicasDrained(r.Context(), name) + // Bug 124: block the response until the local informer cache has // observed the RD + child Resource deletions. Without this gate, // `linstor rd d ` returns SUCCESS and the very next From ab8b378826a3d4451efa0eda890c8a0e71d524ce Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Tue, 24 Nov 2026 02:19:33 +0100 Subject: [PATCH 14/16] refactor: keep the delete and restore handlers within funlen The drain wait and the draining-refusal check pushed handleRDDelete and snapshotRestoreResource past the linter's length budget. The delete's two waits are one call now, and the restore checks for the refusal where it already lands on an AlreadyExists. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- internal/cli/snapshot.go | 12 ++++++------ pkg/rest/rd_delete_drain.go | 7 +++++++ pkg/rest/resource_definitions.go | 10 ++++------ 3 files changed, 17 insertions(+), 12 deletions(-) diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index 3a863c908..e16a2cf4c 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -343,12 +343,6 @@ func snapshotRestoreResource(ctx context.Context, run *runContext) error { } err = run.Store.ResourceDefinitions().Create(ctx, def) - if store.IsReplicasDraining(err) { - // No definition to restore into: its predecessor is still - // draining replicas, and the refusal names their nodes. - return fmt.Errorf("restore %s onto %s: %w", snap.Name, args.toResource, err) - } - if errors.Is(err, store.ErrAlreadyExists) { return restoreIntoExistingTarget(ctx, run, args, &snap, err) } @@ -452,6 +446,12 @@ func restoreIntoExistingTarget( ) error { rdName := args.toResource + // No definition to restore into: its predecessor is still draining + // replicas, and the refusal names their nodes. + if store.IsReplicasDraining(createErr) { + return fmt.Errorf("restore %s onto %s: %w", snap.Name, rdName, createErr) + } + existing, err := run.Store.ResourceDefinitions().Get(ctx, rdName) if err != nil { return fmt.Errorf("get resource definition %s: %w", rdName, err) diff --git a/pkg/rest/rd_delete_drain.go b/pkg/rest/rd_delete_drain.go index e479ee4b6..65a13d28f 100644 --- a/pkg/rest/rd_delete_drain.go +++ b/pkg/rest/rd_delete_drain.go @@ -38,6 +38,13 @@ var rdReplicaDrainBudget = 20 * time.Second //nolint:gochecknoglobals // tunable var rdReplicaDrainPoll = 250 * time.Millisecond +// waitForRDTeardown is what a definition delete waits for before it answers: +// the replicas on reachable nodes torn down, then the local cache caught up. +func (s *Server) waitForRDTeardown(ctx context.Context, name string) { + s.waitForOnlineReplicasDrained(ctx, name) + s.waitForRDDeletionVisible(ctx, name) +} + // waitForOnlineReplicasDrained holds a definition delete until no replica of // it is left on a node that is reachable, or rdReplicaDrainBudget runs out. // diff --git a/pkg/rest/resource_definitions.go b/pkg/rest/resource_definitions.go index 804ab76cc..0f29c25c6 100644 --- a/pkg/rest/resource_definitions.go +++ b/pkg/rest/resource_definitions.go @@ -1298,17 +1298,15 @@ func (s *Server) handleRDDelete(w http.ResponseWriter, r *http.Request) { // refuses a definition that has snapshots. reaped := reapClonedSnapshot(r.Context(), s.Store, name, clonedFrom) - // Answered once the reachable satellites have torn their replicas - // down, as LINSTOR answers it, so a create of the same name that - // follows is not refused over them. - s.waitForOnlineReplicasDrained(r.Context(), name) - // Bug 124: block the response until the local informer cache has // observed the RD + child Resource deletions. Without this gate, // `linstor rd d ` returns SUCCESS and the very next // `linstor r l` shows phantom rows for 5–30 s until the cache // catches up on its watch stream. See pkg/rest/cache_invalidation.go. - s.waitForRDDeletionVisible(r.Context(), name) + // Before that, the reachable satellites tear their replicas down, as + // LINSTOR waits for them, so a create of the same name that follows + // is not refused over them (waitForOnlineReplicasDrained). + s.waitForRDTeardown(r.Context(), name) answer := []apiv1.APICallRc{{ RetCode: maskInfo, From 36ad7cb1171c7f9fac9641a03e270ce8baf47f87 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Tue, 24 Nov 2026 15:49:00 +0100 Subject: [PATCH 15/16] docs(parity): list the draining definition as an accepted delta While a deleted definition's replicas drain, rd l no longer lists it but rd c of the same name is refused with FAIL_EXISTS_RSC_DFN. LINSTOR keeps the definition listed, flagged DELETE, and its rd d reply waits on the satellites. The outcome of the create matches; the listing and the rd d reply differ, and the row names the tests that pin both. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- docs/cli-parity-known-deltas.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/cli-parity-known-deltas.md b/docs/cli-parity-known-deltas.md index 4818834d0..df436b72b 100644 --- a/docs/cli-parity-known-deltas.md +++ b/docs/cli-parity-known-deltas.md @@ -72,6 +72,7 @@ Row IDs match the command-catalogue indexes used by `cli-parity-refresh.sh` (see | 16 | `ps l` (physical-storage list — `size` field) | WIRE_SHAPE | 2026-12-31 | BS `/v1/physical-storage` omits the per-device `size` key that python-linstor's `show_physical_storage` reads unconditionally (`linstor/responses.py` `devices.size`), so `linstor ps l` raises `KeyError: 'size'` and exits 2 against BS where upstream renders the table and exits 0. `ps l` is a hardware-discovery convenience surface; linstor-csi / piraeus-operator never call it, and the device-pool creation path (`ps create-device-pool`, cli-matrix `ps-cdp-*`) is unaffected. Tracked as a missing wire field to populate on the physical-storage DTO; whitelisted until then. | | 86 | `node interface modify --active` | BEHAVIOR | permanent | blockstor has no satellite-to-controller connection to re-target: the satellite talks only to the Kubernetes API through the in-cluster Service. `NodeNetInterface` carries no `Active` field, and the REST `is_active` flag is synthesised on read as "first interface", so `--active` changes nothing. To make another interface active, reorder `spec.netInterfaces` so it comes first; a changed address reaches the node's DRBD configuration after its satellite pod restarts. Pinned by `TestSatelliteFlagsLackControllerBindAddress` and `TestNodeCRDHasNoActiveField` in `pkg/satellite/stream/redial_spec_test.go`. | | 105 | `n describe` / `r lv` (`/v1/view/resources` volume of a replica with no resolvable pool) | WIRE_SHAPE | permanent | A diskful replica whose satellite has not reported a volume yet is listed with one placeholder volume per volume definition, as LINSTOR lists the replica's own volumes (`Json.apiToResourceWithVolumes`). The placeholder names the pool LINSTOR would resolve (`CtrlStorPoolResolveHelper.resolveStorPool`: the StorPoolName chain, then the diskful neighbours' pools, then `DfltStorPool`, first one present on the node). When none resolves, it is listed with an empty `storage_pool_name`. LINSTOR cannot produce that row, because it creates every Volume with a resolved pool; python-linstor's `construct_rsc` then calls `add_child` on the `None` that `find_child("")` returns, so `n describe` fails for that replica until its satellite reports the volume. Deliberate: the alternative is an empty `volumes` list, on which linstor-scheduler-extender indexes `volumes[0]` without a length check and panics on every filter call, keeping the pod Pending. Pinned by `pkg/rest/view_client_contract_test.go::TestViewUnresolvablePoolStillListsTheVolume`. | +| 106 | `rd d ` then `rd c ` while a replica still drains | BEHAVIOR | permanent | LINSTOR keeps a deleted definition, flagged DELETE, until every satellite confirms its replica gone (`CtrlRscDfnDeleteApiCallHandler`): `rd l` keeps listing it, its `rd d` reply waits on the online satellites and warns about one that is not connected, and an `rd c` of the same name is refused with FAIL_EXISTS_RSC_DFN. blockstor removes the definition object at once and lets the replicas drain on their own. `rd d` waits up to 20s for the replicas on online nodes and then answers; a replica on an offline node, or one still draining past that budget, is not waited for. While such a replica drains, `rd l` no longer lists the definition, but `rd c` and a snapshot restore into the same name are refused with FAIL_EXISTS_RSC_DFN (HTTP 409) naming the nodes still draining, so linstor-csi retries the create as it does against LINSTOR. The outcome of a create matches; the divergence is the listing and the `rd d` reply. Pinned by `TestRDDeleteWaitsForReplicasOnOnlineNodes`, `TestRDDeleteDoesNotWaitForAnOfflineNode`, `TestRDCreateWaitsForTheDeletedDefinitionsReplicas`, `TestRestoreIntoANameStillBeingDeletedAnswers409` (pkg/rest) and `TestRDCreateRefusedOverAFinalizerHeldReplica` (pkg/store/k8s). | ## Open (block merge until addressed) From d575f87334ca556a2a38f147fe88556de94096c1 Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Tue, 24 Nov 2026 15:49:01 +0100 Subject: [PATCH 16/16] docs(validate): own the unattached hand move the lifted guard misses The comment read as if every hand placement runs next to a Primary. An operator who turns balancing off to move a volume nothing has attached, adds a diskful and drops the only UpToDate copy mid-sync is not guarded: from the definition that is DeleteVolume's shape, and LINSTOR lets that delete through as well. Say so, and pin the case in the table so the trade-off stays deliberate. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- pkg/validate/resource_delete.go | 16 +++++++++++----- pkg/validate/validate_test.go | 7 +++++++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/pkg/validate/resource_delete.go b/pkg/validate/resource_delete.go index 02a92235a..b95a4333c 100644 --- a/pkg/validate/resource_delete.go +++ b/pkg/validate/resource_delete.go @@ -118,11 +118,17 @@ func MidSyncDeleteRefusal(target *apiv1.Resource, siblings []apiv1.Resource) boo // that they are one volume teardown. // // The same property is what an operator sets to place replicas by hand, -// and a hand placement is exactly where U130 happens: a second diskful -// added next to a diskless Primary and the original dropped before the -// sync finishes. So the property alone counts only while nothing is -// InUse, which is the state DeleteVolume waits for and a volume with a -// Primary is never in. +// and a hand placement is where U130 happens: a second diskful added and +// the original dropped before the sync finishes. So the property alone +// counts only while nothing is InUse, which is the state DeleteVolume +// waits for. That keeps the guard for a hand placement next to a +// Primary, and only for that one. An operator who switches balancing +// off to move a volume nothing has attached, adds a diskful and drops +// the only UpToDate copy before the sync finishes is not guarded: from +// the definition alone that is DeleteVolume's shape, and LINSTOR, which +// has no such guard on any path, lets the delete through as well. The +// choice is deliberate; the "balancing off by hand, nothing InUse" case +// of TestMidSyncDeleteRefusalLiftedWhileDefinitionIsDeleted pins it. func DefinitionBeingDeleted(rd *apiv1.ResourceDefinition, replicas []apiv1.Resource) bool { if rd == nil { return false diff --git a/pkg/validate/validate_test.go b/pkg/validate/validate_test.go index 07d8f2ae7..e3f6bbca0 100644 --- a/pkg/validate/validate_test.go +++ b/pkg/validate/validate_test.go @@ -357,6 +357,13 @@ func TestMidSyncDeleteRefusalLiftedWhileDefinitionIsDeleted(t *testing.T) { "balancing off by hand with a Primary": { balancingOff, append([]apiv1.Resource{primary}, stranded...), false, }, + // A hand move of a volume nothing has attached looks like + // DeleteVolume from the definition, so the guard is lifted and + // dropping the only UpToDate copy mid-sync goes through, as it + // does in LINSTOR. Deliberate; see DefinitionBeingDeleted. + "balancing off by hand, nothing InUse": { + balancingOff, append([]apiv1.Resource{secondary}, stranded...), true, + }, } { t.Run(name, func(t *testing.T) { t.Parallel()