Merge pull request #962 from seaweedfs/fix/served-topology-issued

master: a clean move releases the static topology home
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-12-02 12:46:06 -08:00
commit 9c56ca2e7e
3 files changed
+172 -4

No files matched your search

@@ -1,11 +1,11 @@
package master
import (
"sort"
"encoding/json"
"fmt"
"net"
"net/http"
"sort"
"sync"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
@@ -77,13 +77,20 @@ func (j *journalIsolation) setSelf(id storeident.Identity) {
func (h *Host) nodeServesVolumes(server string) bool { return len(h.volumesServedBy(server)) > 0 }
// volumesServedBy names, sorted and once each, every volume server holds
// work for: a placement slot (also every line it sources), a live line a
// move issued to it, or a static topology line on it.
// work for: a placement slot whose line no move minted elsewhere (also every
// line it sources), a live line a move issued to it, a static topology volume whose line a move minted on
// it, or a static topology home slot whose line no move minted.
func (h *Host) volumesServedBy(server string) []string {
seen := map[string]bool{}
lines := h.Publisher().PublishedAuthorityLines()
if h.lifecycle != nil {
for _, p := range h.lifecycle.Placements.ListPlacements() {
// A move does not rewrite the placement: once a move minted the
// volume's line on another host, the old placement slot holds
// nothing (the owner is counted below).
if owner, fromMove := lines[p.VolumeID].Owner(); fromMove && owner != server {
continue
}
for _, slot := range p.Slots {
if slot.ServerID == server {
seen[p.VolumeID] = true
@@ -101,6 +108,15 @@ func (h *Host) volumesServedBy(server string) []string {
if !ok {
continue
}
// A line a move minted is served on its owner only (counted above
// when the volume is live); the topology's home slot counts only for
// a line no move minted, so a clean move away releases the old home.
if owner, fromMove := line.Owner(); fromMove {
if owner == server {
seen[v.VolumeID] = true
}
continue
}
for _, slot := range v.Slots {
if slot.ServerID == server && slot.ReplicaID == line.ReplicaID {
seen[v.VolumeID] = true
@@ -0,0 +1,152 @@
package master
import (
"context"
"log"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/lifecycle"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/types/known/timestamppb"
)
// A volume imported from a cluster spec has its home both as a lifecycle
// placement and as the static topology's slot. After a clean move from the
// home node-a to node-b (the move rewrites neither), node-a holds nothing:
// it can be retired and the finalize does not name it; node-b holds the
// volume. The control, before the move, counts node-a.
func TestACleanMoveReleasesTheTopologyHome(t *testing.T) {
logs := &syncBuffer{}
m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, LifecycleProductLoop: true, LayoutCreateVolume: testLayoutCreateVolume,
Topology: authority.AcceptedTopology{Volumes: []authority.VolumeExpected{{VolumeID: "moved", Slots: []authority.ExpectedSlot{{ReplicaID: "r1", ServerID: "node-a"}}}}},
Logger: log.New(logs, "", 0),
WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) {
return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil
}})
if err != nil {
t.Fatal(err)
}
m.Start()
r := &isolationRig{m: m, logs: logs}
t.Cleanup(func() { closeTestMaster(t, m) })
conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = conn.Close() })
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
t.Cleanup(cancel)
for _, n := range []lifecycle.NodeRegistration{
{ServerID: "node-a", DataAddr: "127.0.0.1:19101", CtrlAddr: "127.0.0.1:19102"},
{ServerID: "node-b", DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302"},
} {
if _, err := m.Lifecycle().Nodes.RegisterNode(n); err != nil {
t.Fatal(err)
}
}
r.ws, r.lc, r.obs, r.ctx = control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn), control.NewObservationServiceClient(conn), ctx
served := func(server string) bool {
for _, v := range m.volumesServedBy(server) {
if v == "moved" {
return true
}
}
return false
}
// issueMove creates the volume, places it on node-a, serves it from
// node-a at epoch 1 and moves it cleanly to node-b. The control is
// checked on its first step's state through a fresh move fixture.
r.issueMove(t, "moved", "m1")
if served("node-a") {
t.Fatalf("after a clean move to node-b: node-a, the old home, still counted as holding the volume (%v)", m.volumesServedBy("node-a"))
}
if !served("node-b") {
t.Fatalf("after a clean move to node-b: node-b, the line's owner, is not counted (%v)", m.volumesServedBy("node-b"))
}
// The finalize does not name the old home, even with an old process
// report for the volume from it.
m.reads.note("node-a", "moved", "old-proc", 0)
if blocking, _ := m.finalizeCheck(1); len(blocking) != 0 {
t.Fatalf("finalize after the move blocks on %+v, want no host", blocking)
}
if _, err := r.lc.RetireHost(ctx, &control.RetireHostRequest{ServerId: "node-a", Confirm: "node-a"}); err != nil {
t.Fatalf("retire of the old home after a clean move: %v", err)
}
}
// The control for the move above: before any move, the home (placement and
// topology slot) holds the volume, and a level-0 report from it blocks the
// finalize.
func TestTheTopologyHomeHoldsTheVolumeBeforeAMove(t *testing.T) {
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
r.createVolume(t, "v")
r.place(t, "v", "node-a")
found := false
for _, v := range r.m.volumesServedBy("node-a") {
found = found || v == "v"
}
if !found {
t.Fatalf("before a move: node-a, the placement, is not counted (%v)", r.m.volumesServedBy("node-a"))
}
r.m.reads.note("node-a", "v", "old-proc", 0)
if blocking, _ := r.m.finalizeCheck(1); len(blocking) != 1 || blocking[0].server != "node-a" {
t.Fatalf("finalize before the move: blocking %+v, want node-a", blocking)
}
}
// The topology-only control: with no placement at all, the static
// topology's home slot holds the volume whose line no move minted, and a
// level-0 report from it blocks the finalize (so the topology branch is
// pinned by itself, not masked by a placement).
func TestTheTopologyHomeAloneHoldsTheVolumeBeforeAMove(t *testing.T) {
m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(),
Topology: authority.AcceptedTopology{Volumes: []authority.VolumeExpected{{VolumeID: "v", Slots: []authority.ExpectedSlot{{ReplicaID: "r1", ServerID: "node-a"}}}}},
Freshness: authority.FreshnessConfig{FreshnessWindow: 30 * time.Second, PendingGrace: 50 * time.Millisecond},
ControllerConfig: authority.TopologyControllerConfig{ExpectedSlotsPerVolume: 1, RetryWindow: 5 * time.Second},
Logger: log.New(&syncBuffer{}, "", 0)})
if err != nil {
t.Fatal(err)
}
m.Start()
t.Cleanup(func() { closeTestMaster(t, m) })
conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = conn.Close() })
obs := control.NewObservationServiceClient(conn)
deadline := time.Now().Add(10 * time.Second)
for {
if _, err := obs.ReportHeartbeat(context.Background(), &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, ReadsLevel: 1,
Slots: []*control.HeartbeatSlot{{VolumeId: "v", ReplicaId: "r1", DataAddr: "127.0.0.1:19131", CtrlAddr: "127.0.0.1:19132", Incarnation: "p1", Reachable: true, Eligible: true}}}); err != nil {
t.Fatal(err)
}
if _, ok := m.Publisher().VolumeAuthorityLine("v"); ok {
break
}
if time.Now().After(deadline) {
t.Fatal("fixture: the topology line for v was never published")
}
time.Sleep(100 * time.Millisecond)
}
if m.lifecycle != nil {
if _, ok := m.lifecycle.Placements.GetPlacement("v"); ok {
t.Fatal("fixture: v has a placement; the control must hold through the topology only")
}
}
found := false
for _, v := range m.volumesServedBy("node-a") {
found = found || v == "v"
}
if !found {
t.Fatalf("topology only: node-a, the home slot holding v's line, is not counted (%v)", m.volumesServedBy("node-a"))
}
m.reads.note("node-a", "v", "old-proc", 0)
if blocking, _ := m.finalizeCheck(1); len(blocking) != 1 || blocking[0].server != "node-a" {
t.Fatalf("topology only: finalize blocking %+v, want node-a", blocking)
}
}
+1 -1
View File
@@ -934,7 +934,7 @@ Notes:
| `INV-FMT-FINALIZE-001` | The finalize is refused, naming them, only while a fresh report of a process holding a volume reads below 1; hosts with no or a stale report are listed, not blocking. Else it writes the envelope durably, then switches the publisher under both its locks, then answers; a failed write leaves level 0. | FormatGate Finalize | `core/host/master/format_gate.go` `FinalizeFormat`, `finalizeCheck`; `core/authority/workspace_lease_v100.go` `FinalizeFormatLevel` | `TestFinalizeFormatBlocksOnAnOldHolderAndIsDurable`, `TestFinalizeFormatListsTheHostsItCannotConfirm`, `TestAFailedFinalizeWriteLeavesLevel0`, `TestAHolderRestartedOnAnOldBinaryIsNotReissuedItsLine` (`core/host/master/format_gate_test.go`); `TestHost_ApplyFact_LineIssuedForAnotherProcessIsNotAdopted` (`core/host/volume/line_incarnation_test.go`); `TestClusterFinalizeFormat` (`cmd/sw-block/cluster_format_test.go`); `TestClusterFinalizeFormatTypedAnswer` (`cmd/sw-block/cluster_format_json_test.go`) | `FormatGate` `FinalizeKeepsHosts` (mutation `finalize_ignores_reports`); `FormatGateMaster` (mutations `old_starts_after_finalize`, `finalize_not_atomic`) | ACTIVE |
| `INV-FMT-ELIGIBLE-001` | At level L no new work goes to a server known to read below L: no placement or move target (binary_too_old). An unreported server is placeable; no line is granted to a holder process before its own report. Heartbeats are recorded, never refused. Placed work stays. Every assignment carries L. | FormatGate Assign (placement, move, failover) | `core/host/master/format_gate.go` `formatEligible`, `formatTooOld`, `placementTooOld`, `grantTooOld`; `core/host/master/journal_isolation.go` `newWorkRefused`, `reconcilePlacements`; `core/host/master/workspace_binding.go` `PlaceWorkspace`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/services.go` `ReportHeartbeat`, `assignmentFact` | `TestFormatGateRecordsAnOldBinarysHeartbeatAtLevel1`, `TestFormatGateRefusesPlacementAndMoveOntoAnOldHost`, `TestFormatGateProductLoopPlacesOnlyOnHostsThatReadTheLevel`, `TestAssignmentFactCarriesTheFormatLevel` (`core/host/master/format_gate_test.go`) | `FormatGate` `NoStrand` (mutation `place_ignores_reads_level`) | ACTIVE |
| `INV-FMT-LEVEL0-V100-001` | At format level 0 the master writes as v1.0: grants clamp to the persisted horizon, an extender keeps it current, forced moves and re-grants wait for the later of horizon and deadline plus skew, records are version 1. Every grant raises the deadline at both levels. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted (level 0) | `core/authority/workspace_lease_v100.go` `renewV100Locked`, `extendWorkspaceLease`, `forcedMoveBarrierV100Locked`, `ackValidityLocked`, `envelopeVersionLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease` | `TestALevel0RenewalKeepsTheHorizonCurrent`, `TestALevel0GrantIsClampedToTheHorizon`, `TestTheForcedBarrierFollowsTheFormatLevel`, `TestRecordEnvelopeVersionFollowsTheFormatLevel` (`core/authority/workspace_format_level_test.go`) | `FormatGateMaster` `OneServer`, `GraceOnlyFinal` (mutations `level0_no_horizon`, `old_starts_after_finalize`) | ACTIVE |
| `INV-FMT-RETIRE-001` | A host retire, the node registry's only writer after start, is refused, naming the volumes, while the host holds a placement or a live line, and unless confirm repeats the id. A retired id is unregistered; if the host returns it registers again at its reported level. | FormatGate Retire | `core/host/master/format_gate.go` `RetireHost`; `core/host/master/journal_isolation.go` `volumesServedBy` | `TestRetireHostRefusesAHostThatHoldsWork` (`core/host/master/format_gate_test.go`); `TestClusterRetireHost` (`cmd/sw-block/cluster_format_test.go`); `TestNodeRegistryIsWrittenOnlyAtStartup` (`cmd/blockmaster/node_registry_guard_test.go`) | `FormatGate` r2 `OneServer` (mutation `retire_holding_host`) | ACTIVE |
| `INV-FMT-RETIRE-001` | A host retire, the node registry's only writer after start, is refused, naming the volumes, while the host holds a placement or a live line, and unless confirm repeats the id. A retired id is unregistered; if the host returns it registers again at its reported level. | FormatGate Retire | `core/host/master/format_gate.go` `RetireHost`; `core/host/master/journal_isolation.go` `volumesServedBy` | `TestRetireHostRefusesAHostThatHoldsWork` (`core/host/master/format_gate_test.go`); `TestACleanMoveReleasesTheTopologyHome`, `TestTheTopologyHomeHoldsTheVolumeBeforeAMove`, `TestTheTopologyHomeAloneHoldsTheVolumeBeforeAMove` (`core/host/master/served_topology_move_test.go`); `TestClusterRetireHost` (`cmd/sw-block/cluster_format_test.go`); `TestNodeRegistryIsWrittenOnlyAtStartup` (`cmd/blockmaster/node_registry_guard_test.go`) | `FormatGate` r2 `OneServer` (mutation `retire_holding_host`) | ACTIVE |
| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE |
| `INV-LIFECYCLE-STORE-DURABLE-001` | Node registration, volume record and placement-intent puts/replacements are atomic and durable: after a crash the record file is the complete old or the complete new record; a put that returned nil has fsynced the file and its directory. | M2 lifecycle record publication | `core/lifecycle/record_file.go` `writeRecordDurably`; `node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord`, `TestLifecyclePutSyncOrderAndFailure` (`core/lifecycle/store_crash_test.go`); `TestLifecycleStoreParentSync` (`core/lifecycle/store_parent_sync_test.go`) | � | ACTIVE |
| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/layout/create.go` `createVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCreateVolume_OverAnExistingHeadByState` (`core/frontend/chunkstore/layout/create_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE |