diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go index 128cfc0291..2a43a9c5b9 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -616,10 +616,61 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { lastEpoch := map[string]uint64{} var extensions atomic.Int64 heldEntered, heldRelease := make(chan struct{}), make(chan struct{}) - var holdOnce, releaseOnce sync.Once - releaseHold := func() { releaseOnce.Do(func() { close(heldRelease) }) } + var releaseOnce sync.Once + // The publisher clock is frozen while the extension write is held (#247 + // hang): the held write holds p.mu, so every other volume's extender queues + // and no horizon can move. With a running clock a late test goroutine could + // let horizons expire before each volume got a grant under the hold (the + // progress condition never holds), or before the writers run after the + // release (a revoke ACK finds the lease expired). This test is about lock + // and store ordering, not about lease expiry. + // The clock stays frozen after the release until the clean volume's revoke + // ACK: the endpoint refreshes, the revocation and the ACK queue on p.mu + // behind every volume's extension write (fsync), which on a loaded machine + // can outlast the clean volume's grant, and a revoking lease is never + // extended (in-time ACK has its own tests). The writer then resumes the + // clock from the frozen instant, so it neither jumps over a horizon nor runs + // backwards; extensions run in real time alongside the moves and Close. + // Now/Freeze/Resume are one transaction each. + clock := &leaseTestClock{} + releaseHold := func() { + releaseOnce.Do(func() { close(heldRelease) }) + } var classifying atomic.Bool - var holding atomic.Bool // set when the extension write is held, before it blocks + var holding atomic.Bool // set when the extension write is held, before it blocks + var heldVol atomic.Value // string: the volume whose extension write is held + var holdTaken atomic.Bool + var holdMu sync.Mutex + var skippedHolds atomic.Int64 // extension writes not held: some eligible volume lacked headroom + var p *Publisher + // headroom witnesses, at the frozen instant and from each volume's own + // renewal view (the fields RenewWorkspaceLease reads, under the leaf + // leaseMu), that a renewal of every eligible volume and of the clean volume + // grants positive host validity: lease present and live, durable horizon + // minus half the skew after now, and now before the granted deadline. The + // frozen clock and the queued extenders keep it so for the whole hold and, + // for the clean volume, through its revocation and ACK. + var noHeadroom atomic.Value // string: the last volume found without headroom, and why + headroom := func() bool { + now := clock.Now().UnixNano() + p.leaseMu.Lock() + defer p.leaseMu.Unlock() + for _, i := range append(append([]int{}, eligible...), cleanVol) { // the clean volume is revoked and ACKed frozen + lv := p.leaseViews[vol(i)] + if lv == nil || !lv.d.bound || !lv.d.leasePresent || lv.d.revoking || lv.d.movePending || + lv.d.uncertain || lv.d.storeless || lv.d.horizon-lv.d.maxSkewNS/2 <= now || now >= lv.deadline.UnixNano() { + why := "no view" + if lv != nil { + why = fmt.Sprintf("bound=%v present=%v revoking=%v pending=%v uncertain=%v validity=%v deadline-now=%v", + lv.d.bound, lv.d.leasePresent, lv.d.revoking, lv.d.movePending, lv.d.uncertain, + time.Duration(lv.d.horizon-lv.d.maxSkewNS/2-now), time.Duration(lv.deadline.UnixNano()-now)) + } + noHeadroom.Store(vol(i) + ": " + why) + return false + } + } + return true + } hs.setBefore(func(r DurableRecord) error { time.Sleep(5 * time.Millisecond) // a slow store if !classifying.Load() || r.Workspace == nil || r.Workspace.Lease == nil { @@ -636,9 +687,23 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { if ext { extensions.Add(1) first := false - holdOnce.Do(func() { first = true }) + if !holdTaken.Load() { + holdMu.Lock() + if !holdTaken.Load() { + clock.Freeze() + if headroom() { + holdTaken.Store(true) + first = true + } else { + clock.Resume() // try again at a later extension write + skippedHolds.Add(1) + } + } + holdMu.Unlock() + } if first { - holding.Store(true) // before the hold: a renewal started after this saw it + heldVol.Store(r.VolumeID) // the volume whose extension write is held + holding.Store(true) // before the hold: a renewal started after this saw it close(heldEntered) <-heldRelease } @@ -648,13 +713,17 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { // The publisher clock is real time plus an offset. The forced-move volume // is granted at offset -10 s, so by offset 0 its horizon + skew barrier has // passed; the clock only moves forward. - var offNS atomic.Int64 - offNS.Store(int64(-10 * time.Second)) - p := NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, func() time.Time { return time.Now().Add(time.Duration(offNS.Load())) })) + clock.SetOffset(-10 * time.Second) + p = NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, clock.Now)) t.Cleanup(p.CloseWorkspaceExtenders) ctx := context.Background() bindAndGrant(t, p, vol(forcedVol), "r") // never renewed again - offNS.Store(0) + clock.SetOffset(0) + // Set-up writes are real store writes (fsync): on a loaded machine binding + // the volumes can take longer than a TTL, and the first-bound volume would + // expire before its renewer starts (by design it never recovers). The clock + // stays frozen through the set-up and resumes just before the renewers. + clock.Freeze() for i := 0; i < n; i++ { if i != forcedVol { bindAndGrant(t, p, vol(i), "r") @@ -664,10 +733,14 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { st := p.WorkspaceState(vol(i)) lastH[vol(i)], lastEpoch[vol(i)] = st.Lease.ExpiresAtNS, st.Lease.Epoch } + clock.Resume() classifying.Store(true) var grants [n]atomic.Int64 - var underHold [n]atomic.Int64 // grants of calls that started while the extension write was held + var underHold [n]atomic.Int64 // grants of calls that started while the extension write was held + var returnedUnderHold [n]atomic.Int64 // calls (any outcome) that started while the extension write was held + var refusedUnderHold atomic.Value // string: a refusal of a call started under the hold, before the writers + var writersGo atomic.Bool // set before the writers start var maxGrant [n]atomic.Int64 var slowest atomic.Int64 stop := make(chan struct{}) @@ -681,6 +754,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { // every worker, and only then let the fixtures close. t.Cleanup(func() { releaseHold() + clock.Resume() stopRenewers() settled := make(chan struct{}) go func() { wg.Wait(); close(settled) }() @@ -715,11 +789,21 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { default: } fresh := holding.Load() // the call starts while the extension write is held + beforeWriters := !writersGo.Load() start := time.Now() l, err := p.RenewWorkspaceLease(ctx, vol(i), "r", 1) if d := int64(time.Since(start)); d > slowest.Load() { slowest.Store(d) } + if fresh { + returnedUnderHold[i].Add(1) + // Headroom was witnessed at the frozen instant: until the + // writers start, every such renewal must grant (any refusal, + // a horizon error included, fails). + if beforeWriters && (err != nil || l.Revoking) { + refusedUnderHold.CompareAndSwap(nil, fmt.Sprintf("%s: %+v %v", vol(i), l, err)) + } + } if err == nil && !l.Revoking { grants[i].Add(1) if fresh { @@ -735,12 +819,29 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { } // Handshake 1: the first extension write is held inside the store. - <-heldEntered // progress, no timer (#227): renewers keep triggering extensions + // Progress handshakes (#227) with a real-time failure exit (never a pass): + // the cleanup releases the hold and joins every worker. + select { + case <-heldEntered: // renewers keep triggering extensions + case <-time.After(30 * time.Second): + nh, _ := noHeadroom.Load().(string) + t.Fatalf("no extension write was held within 30 s (%d extension writes, %d not held for lack of headroom; last: %s)", + extensions.Load(), skippedHolds.Load(), nh) + } + // A late test goroutine (machine load), longer than a horizon (1.5 x TTL): + // with the clock frozen under the hold, no volume can lose its lease here. + time.Sleep(3500 * time.Millisecond) // Handshake 2: renewals keep succeeding while it is held. // Progress, no timer (#227): every eligible volume gains a grant from a call // that STARTED while the extension write was held (a reply computed before - // the hold does not count). Renewals that waited for it would never return. - for { + // the hold does not count); renewals that waited for it would never return. + // The hold was taken only with headroom witnessed for every eligible volume + // at the frozen instant, so no refusal is allowed here. + held, _ := heldVol.Load().(string) + for give := time.Now().Add(30 * time.Second); ; time.Sleep(5 * time.Millisecond) { + if r, _ := refusedUnderHold.Load().(string); r != "" { + t.Fatalf("under the held extension of %s, with headroom witnessed: refused %s", held, r) + } all := true for _, i := range eligible { if underHold[i].Load() == 0 { @@ -750,9 +851,15 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { if all { break } - time.Sleep(5 * time.Millisecond) + if time.Now().After(give) { + t.Fatalf("under the held extension of %s within 30 s: grants %v, returned calls %v", held, + underHoldCounts(&underHold, eligible), underHoldCounts(&returnedUnderHold, eligible)) + } } + t.Logf("under the held extension of %s (%d extension writes not held for lack of headroom): grants %v", held, + skippedHolds.Load(), underHoldCounts(&underHold, eligible)) // Writers and Close start while the extension write is held. + writersGo.Store(true) writersStarted = true go func() { for k := 0; k < 5; k++ { @@ -761,11 +868,16 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { return } } + // Still frozen since the hold (the refreshes above needed p.mu, which the + // held write owned); the clean volume's headroom was witnessed then. if err := p.BeginWorkspaceRevocation(ctx, vol(cleanVol), "r", 1); err != nil { + clock.Resume() writersDone <- fmt.Errorf("revocation: %w", err) return } - if err := p.AckWorkspaceRevocation(ctx, vol(cleanVol), WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err != nil { + err := p.AckWorkspaceRevocation(ctx, vol(cleanVol), WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}) + clock.Resume() + if err != nil { writersDone <- fmt.Errorf("ack: %w", err) return } @@ -979,3 +1091,125 @@ func TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite(t *testing.T) { t.Fatal("aborted extender left the single-flight flag set") } } + +// leaseTestClock is a test publisher clock: real time plus an offset, or a +// frozen instant. Now, Freeze, Resume and SetOffset are each one transaction +// under mu, and Now never returns an earlier time than a previous Now. +type leaseTestClock struct { + mu sync.Mutex + off time.Duration + frozen time.Time // zero = running + last time.Time +} + +func (c *leaseTestClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + t := c.frozen + if t.IsZero() { + t = time.Now().Add(c.off) + } + if t.Before(c.last) { + t = c.last + } + c.last = t + return t +} + +// Freeze stops the clock at its current reading. +func (c *leaseTestClock) Freeze() { + c.mu.Lock() + defer c.mu.Unlock() + if c.frozen.IsZero() { + c.frozen = time.Now().Add(c.off) + if c.frozen.Before(c.last) { + c.frozen = c.last + } + } +} + +// Resume restarts a frozen clock from its frozen instant. +func (c *leaseTestClock) Resume() { + c.mu.Lock() + defer c.mu.Unlock() + if !c.frozen.IsZero() { + c.off = c.frozen.Sub(time.Now()) + c.frozen = time.Time{} + } +} + +func (c *leaseTestClock) SetOffset(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.off = d +} + +func underHoldCounts(u *[8]atomic.Int64, eligible []int) []int64 { + out := make([]int64, 0, len(eligible)) + for _, i := range eligible { + out = append(out, u[i].Load()) + } + return out +} + +// Readers running across freeze/resume transitions never see the test clock +// go backwards, and a resume does not jump forward over the frozen interval. +func TestLeaseTestClockMonotonicAcrossFreezeResume(t *testing.T) { + c := &leaseTestClock{} + var stop atomic.Bool + var wg sync.WaitGroup + errs := make(chan string, 8) + // Registered before launch: every exit, a Fatal included, stops and joins + // the readers (bounded). + t.Cleanup(func() { + stop.Store(true) + joined := make(chan struct{}) + go func() { wg.Wait(); close(joined) }() + select { + case <-joined: + case <-time.After(10 * time.Second): + t.Error("clock readers did not settle") + } + }) + for r := 0; r < 4; r++ { + wg.Add(1) + go func() { + defer wg.Done() + prev := c.Now() + for !stop.Load() { + now := c.Now() + if now.Before(prev) { + select { + case errs <- fmt.Sprintf("clock went backwards: %v after %v", now, prev): + default: + } + return + } + prev = now + } + }() + } + for k := 0; k < 50; k++ { + c.Freeze() + at := c.Now() + time.Sleep(2 * time.Millisecond) + if got := c.Now(); !got.Equal(at) { + t.Fatalf("frozen clock moved: %v -> %v", at, got) + } + r0 := time.Now() + c.Resume() + got := c.Now() + // After a resume the clock advances by at most the real time since the + // resume began (no jump over the frozen interval), and never backwards. + if got.Before(at) || got.Sub(at) > time.Since(r0) { + t.Fatalf("resume moved the clock by %v (real time since resume %v)", got.Sub(at), time.Since(r0)) + } + time.Sleep(time.Millisecond) + } + stop.Store(true) + wg.Wait() + close(errs) + for e := range errs { + t.Fatal(e) + } +} diff --git a/seaweed-block/core/host/master/workspace_move_refusal_test.go b/seaweed-block/core/host/master/workspace_move_refusal_test.go new file mode 100644 index 0000000000..9a7e113705 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_move_refusal_test.go @@ -0,0 +1,202 @@ +package master + +import ( + "bytes" + "context" + "log" + "strings" + "sync" + "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/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" +) + +type syncBuffer struct { + mu sync.Mutex + b bytes.Buffer +} + +func (s *syncBuffer) Write(p []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.Write(p) +} + +func (s *syncBuffer) String() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.String() +} + +// A refused move names the precondition that failed, in the gRPC status and +// in the master log: an unknown source, an unregistered target node, a +// target that is the source, or target endpoints that are not registered +// (with what is registered: the node's pair, or the volume's live bindings +// on that node). +func TestWorkspaceMoveRefusalNamesTheMissingPrecondition(t *testing.T) { + logs := &syncBuffer{} + m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + 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() + defer closeTestMaster(t, m) + conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + ws, lc := control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn) + 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) + } + } + for _, v := range []string{"placed", "unplaced", "bound"} { + if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: v, SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + } + if _, err := m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "placed", DesiredRF: 1, + Candidates: []lifecycle.PlacementCandidate{{VolumeID: "placed", ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil { + t.Fatal(err) + } + // "bound" has explicit per-volume bindings: its source on node-a and a + // prepared target on node-b at slot 2. + for _, b := range []*control.WorkspaceBinding{ + {VolumeId: "bound", ServerId: "node-a", DataAddr: "127.0.0.1:19121", CtrlAddr: "127.0.0.1:19122"}, + {VolumeId: "bound", ServerId: "node-b", DataAddr: "127.0.0.1:19321", CtrlAddr: "127.0.0.1:19322"}, + } { + if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + } + if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "bound", ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal(err) + } + + move := func(vol, server, data, ctrl string) *control.WorkspaceMove { + return &control.WorkspaceMove{RequestId: vol + "-" + server + "-" + data, VolumeId: vol, ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", + TargetServerId: server, TargetDataAddr: data, TargetCtrlAddr: ctrl, Kind: "clean"} + } + for _, c := range []struct { + name string + q *control.WorkspaceMove + want string + }{ + {"unknown source", move("unplaced", "node-b", "127.0.0.1:19301", "127.0.0.1:19302"), `move source unknown: no issued move or placement names replica "r1" at epoch 1`}, + {"unknown target node", move("placed", "node-z", "127.0.0.1:19301", "127.0.0.1:19302"), `move target node "node-z" is not registered`}, + {"target is the source", move("placed", "node-a", "127.0.0.1:19101", "127.0.0.1:19102"), `move target "node-a" is the current source host`}, + {"target on another host", move("placed", "node-b", "10.9.9.9:19311", "127.0.0.1:19312"), + `move target endpoints 10.9.9.9:19311/127.0.0.1:19312 on "node-b" are not registered (not on the node's hosts: it registers 127.0.0.1:19301/127.0.0.1:19302; no per-volume binding is prepared)`}, + {"explicit binding elsewhere", move("bound", "node-b", "127.0.0.1:19301", "127.0.0.1:19302"), + `move target endpoints 127.0.0.1:19301/127.0.0.1:19302 on "node-b" are not registered (live bindings on that node: 127.0.0.1:19321/127.0.0.1:19322)`}, + } { + t.Run(c.name, func(t *testing.T) { + _, err := ws.MoveWorkspace(ctx, c.q) + if status.Code(err) != codes.FailedPrecondition || status.Convert(err).Message() != c.want { + t.Fatalf("refusal %v; want FailedPrecondition %q", err, c.want) + } + if line := `MoveWorkspace refused volume="` + c.q.VolumeId + `" request="` + c.q.RequestId + `": ` + c.want; !strings.Contains(logs.String(), line) { + t.Fatalf("log lacks %q:\n%s", line, logs.String()) + } + }) + } + // Slot-0 and slot-1 targets on the node's host pass these preconditions + // (they fail later, at the clean-move ACK check, for a different reason). + for _, data := range []string{"127.0.0.1:19301", "127.0.0.1:19311"} { + _, err = ws.MoveWorkspace(ctx, move("placed", "node-b", data, "127.0.0.1:19312")) + if err == nil || strings.Contains(err.Error(), "move target") || strings.Contains(err.Error(), "move source") { + t.Fatalf("target %s on the node's host: %v; want past the endpoint preconditions", data, err) + } + } +} + +// blockingWriter blocks the first write that contains marker until +// released; other writes pass. +type blockingWriter struct { + marker string + entered, release chan struct{} + once sync.Once +} + +func (b *blockingWriter) Write(p []byte) (int, error) { + if !strings.Contains(string(p), b.marker) { + return len(p), nil + } + first := false + b.once.Do(func() { first = true }) + if first { + close(b.entered) + <-b.release + } + return len(p), nil +} + +// A refused move is logged after workspaceMu is released: while the log +// writer is blocked, another workspace RPC still gets the lock. +func TestWorkspaceMoveRefusalLogsOutsideTheWorkspaceLock(t *testing.T) { + w := &blockingWriter{marker: "MoveWorkspace refused", entered: make(chan struct{}), release: make(chan struct{})} + m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, Logger: log.New(w, "", 0), + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }}) + if err != nil { + t.Fatal(err) + } + m.Start() + defer closeTestMaster(t, m) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(w.release) }) } + defer release() + conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + ws := control.NewWorkspaceServiceClient(conn) + if _, err := control.NewLifecycleServiceClient(conn).CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "v", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { + _, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "r", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", + TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "clean"}) + done <- err + }() + select { + case <-w.entered: + case <-time.After(10 * time.Second): + t.Fatal("the refusal was never logged") + } + qctx, qcancel := context.WithTimeout(ctx, 5*time.Second) + defer qcancel() + if _, err := ws.QueryWorkspace(qctx, &control.WorkspaceVolume{VolumeId: "v"}); err != nil { + t.Fatalf("workspace RPC while the refusal log is blocked: %v; want workspaceMu free", err) + } + release() + select { + case err := <-done: + if status.Code(err) != codes.FailedPrecondition { + t.Fatalf("move: %v", err) + } + case <-time.After(10 * time.Second): + t.Fatal("the move did not return after the log was released") + } +} diff --git a/seaweed-block/core/host/master/workspace_move_slot_test.go b/seaweed-block/core/host/master/workspace_move_slot_test.go new file mode 100644 index 0000000000..f6a31dbac6 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_move_slot_test.go @@ -0,0 +1,133 @@ +package master + +import ( + "context" + "strconv" + "strings" + "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" +) + +// The T08 shape: two volumes without per-volume bindings, nodes registered +// at slot 0 of their host. "a1" holds slot 0 on node-a; "a2" lives on +// node-b and moves back to node-a. Its target lands on slot 1 (slot 0 is +// held) and is granted; a target on a1's live slot-0 endpoints is refused by +// the collision check, and one on another host's address by the ownership +// check. The grant routes a2 to the slot-1 endpoints it asked for. +func TestWorkspaceMoveToAnotherSlotOnTheTargetHost(t *testing.T) { + heads := map[string]authority.WorkspaceHead{"a2": {Gen: 9, Epoch: 1, Holder: "node-b/r1", RemoteLSN: 42, Detached: true}} + m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, + WorkspaceHeadReader: func(_ context.Context, v string) (authority.WorkspaceHead, error) { return heads[v], nil }}) + if err != nil { + t.Fatal(err) + } + m.Start() + defer closeTestMaster(t, m) + conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + ws, lc := control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn) + slot := func(base, n int) (string, string) { + return "127.0.0.1:" + strconv.Itoa(base+10*n+1), "127.0.0.1:" + strconv.Itoa(base+10*n+2) + } + for _, n := range []struct { + id string + base int + }{{"node-a", 19100}, {"node-b", 19300}} { + d, c := slot(n.base, 0) + if _, err := m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: n.id, DataAddr: d, CtrlAddr: c}); err != nil { + t.Fatal(err) + } + } + place := func(vol, server string, base int) authority.AuthorityBasis { + t.Helper() + if _, err := lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: vol, SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + if _, err := m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: vol, DesiredRF: 1, + Candidates: []lifecycle.PlacementCandidate{{VolumeID: vol, ServerID: server, ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil { + t.Fatal(err) + } + d, c := slot(base, 0) + if _, err := control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: server, SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: vol, ReplicaId: "r1", DataAddr: d, CtrlAddr: c}}}); err != nil { + t.Fatal(err) + } + if _, err := m.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + return waitAuthorityLine(t, m.Publisher(), vol) + } + a1 := place("a1", "node-a", 19100) // holds node-a slot 0 + a2 := place("a2", "node-b", 19300) + if a1.DataAddr != "127.0.0.1:19101" || a2.DataAddr != "127.0.0.1:19301" { + t.Fatalf("fixture lines a1=%+v a2=%+v", a1, a2) + } + // a2 stops cleanly on node-b: lease, revocation, ACK of its detached HEAD. + id := &control.WorkspaceIdentity{VolumeId: "a2", ReplicaId: "r1", Epoch: a2.Epoch} + if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil { + t.Fatal(err) + } + if _, err := ws.RevokeWorkspace(ctx, id); err != nil { + t.Fatal(err) + } + if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil { + t.Fatal(err) + } + move := func(req, data, ctrl string) *control.WorkspaceMove { + return &control.WorkspaceMove{RequestId: req, VolumeId: "a2", ExpectedReplicaId: "r1", ExpectedEpoch: a2.Epoch, TargetReplicaId: "r1", + TargetServerId: "node-a", TargetDataAddr: data, TargetCtrlAddr: ctrl, Kind: "clean"} + } + d0, c0 := slot(19100, 0) + if _, err := ws.MoveWorkspace(ctx, move("onto-a1", d0, c0)); err == nil || !strings.Contains(err.Error(), "endpoint belongs to live assignment") { + t.Fatalf("move onto a1's live slot-0 endpoints: %v; want the collision refusal", err) + } + if _, err := ws.MoveWorkspace(ctx, move("other-host", "10.9.9.9:19111", "10.9.9.9:19112")); err == nil || !strings.Contains(err.Error(), `endpoints 10.9.9.9:19111/10.9.9.9:19112 on "node-a" are not registered`) { + t.Fatalf("move to another host's address: %v; want the ownership refusal", err) + } + d1, c1 := slot(19100, 1) + if _, err := ws.MoveWorkspace(ctx, move("ctrl-other-host", d1, "10.9.9.9:19112")); err == nil || !strings.Contains(err.Error(), `on "node-a" are not registered`) { + t.Fatalf("move with its ctrl endpoint on another host: %v; want the ownership refusal", err) + } + // Invalid endpoints on the right host are refused before anything is + // written: the epoch, the journal, the lease and the ACK stay as they were. + before := m.Publisher().WorkspaceState("a2") + for _, bad := range []struct{ name, data, ctrl string }{ + {"non-numeric port", "127.0.0.1:bad", c1}, + {"port 0", "127.0.0.1:0", c1}, + {"port 65536", d1, "127.0.0.1:65536"}, + {"empty port", "127.0.0.1:", c1}, + {"data equals ctrl", d1, d1}, + } { + if _, err := ws.MoveWorkspace(ctx, move("bad-"+bad.name, bad.data, bad.ctrl)); err == nil || !strings.Contains(err.Error(), "move target endpoints invalid") { + t.Fatalf("%s: %v; want the invalid-endpoint refusal", bad.name, err) + } + after := m.Publisher().WorkspaceState("a2") + line, _ := m.Publisher().VolumeAuthorityLine("a2") + if line.Epoch != a2.Epoch || after == nil || len(after.Moves) != 0 || after.Ack == nil || before.Ack == nil || *after.Ack != *before.Ack || after.Lease == nil || !after.Lease.Revoking { + t.Fatalf("%s: state changed by a refused move: line %+v state %+v", bad.name, line, after) + } + } + g, err := ws.MoveWorkspace(ctx, move("slot-1", d1, c1)) + if err != nil { + t.Fatalf("move to node-a slot 1 while slot 0 is held: %v", err) + } + line, ok := m.Publisher().VolumeAuthorityLine("a2") + if !g.Issued || g.NewHost != "node-a" || g.OldHost != "node-b" || !ok || line.Epoch != g.NewEpoch || line.DataAddr != d1 || line.CtrlAddr != c1 { + t.Fatalf("grant %+v line %+v; want a2 issued on node-a at %s/%s", g, line, d1, c1) + } + if l1, _ := m.Publisher().VolumeAuthorityLine("a1"); l1.DataAddr != d0 || l1.Epoch != a1.Epoch { + t.Fatalf("a1 changed: %+v", l1) + } +} diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index f8a068cff9..fabe00514c 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -2,6 +2,8 @@ package master import ( "context" + "fmt" + "strings" "time" "github.com/seaweedfs/seaweed-block/core/authority" @@ -143,6 +145,14 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) } // Remote reads never hold the workspace mutation lock. Re-read every // local precondition below; Publisher checks the expected epoch atomically. + // A refusal is logged after the lock is released (deferred first, so it + // runs last): a slow log writer never holds workspaceMu. + var refusal string + defer func() { + if refusal != "" { + s.host.log.Printf("blockmaster: MoveWorkspace refused volume=%q request=%q: %s", q.GetVolumeId(), q.GetRequestId(), refusal) + } + }() s.host.workspaceMu.Lock() defer s.host.workspaceMu.Unlock() if err := ctx.Err(); err != nil { @@ -157,14 +167,32 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) if err != nil { return nil, workspaceError(err) } - matched := !explicit && target.DataAddr == q.GetTargetDataAddr() && target.CtrlAddr == q.GetTargetCtrlAddr() + // A volume without per-volume bindings may move to any port on the + // target node's registered hosts (a host runs several slots): the host + // match ties the endpoints to that node's registration (it trusts the + // registration; it is not an identity proof). The collision check below + // still refuses endpoints another assignment or binding owns. + matched := !explicit && sameHost(q.GetTargetDataAddr(), target.DataAddr) && sameHost(q.GetTargetCtrlAddr(), target.CtrlAddr) + endpointErr := lifecycle.ValidateWorkspaceEndpoints(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: q.GetTargetServerId(), DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}) for _, b := range bindings { if !b.Retired && b.ServerID == q.GetTargetServerId() && b.DataAddr == q.GetTargetDataAddr() && b.CtrlAddr == q.GetTargetCtrlAddr() { matched = true } } - if oldHost == "" || !ok || target.ServerID == oldHost || !matched { - return nil, status.Error(codes.FailedPrecondition, "move needs known source slot and registered target endpoints") + switch { + case endpointErr != nil: + refusal = fmt.Sprintf("move target endpoints invalid: %v", endpointErr) + case oldHost == "": + refusal = fmt.Sprintf("move source unknown: no issued move or placement names replica %q at epoch %d", q.GetExpectedReplicaId(), q.GetExpectedEpoch()) + case !ok: + refusal = fmt.Sprintf("move target node %q is not registered", q.GetTargetServerId()) + case target.ServerID == oldHost: + refusal = fmt.Sprintf("move target %q is the current source host", target.ServerID) + case !matched: + refusal = fmt.Sprintf("move target endpoints %s/%s on %q are not registered (%s)", q.GetTargetDataAddr(), q.GetTargetCtrlAddr(), target.ServerID, registeredTargetEndpoints(target, bindings, explicit)) + } + if refusal != "" { + return nil, status.Error(codes.FailedPrecondition, refusal) } if err = s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil { return nil, workspaceError(err) @@ -180,6 +208,32 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) return grantFact(r), nil } +// sameHost reports whether two host:port addresses name the same host: +// canonical host parts (equivalent IP spellings equal), no name resolution. +func sameHost(a, b string) bool { + ha := lifecycle.WorkspaceEndpointHost(a) + return ha != "" && ha == lifecycle.WorkspaceEndpointHost(b) +} + +// registeredTargetEndpoints describes what a move to target may name: the +// node's own pair for a volume without explicit bindings, else its live +// bindings on that node. +func registeredTargetEndpoints(target lifecycle.NodeRegistration, bindings []lifecycle.WorkspaceBinding, explicit bool) string { + if !explicit { + return fmt.Sprintf("not on the node's hosts: it registers %s/%s; no per-volume binding is prepared", target.DataAddr, target.CtrlAddr) + } + var live []string + for _, b := range bindings { + if !b.Retired && b.ServerID == target.ServerID { + live = append(live, b.DataAddr+"/"+b.CtrlAddr) + } + } + if len(live) == 0 { + return "the volume has explicit bindings but none live on that node" + } + return "live bindings on that node: " + strings.Join(live, ", ") +} + func (s *services) QueryWorkspace(ctx context.Context, q *control.WorkspaceVolume) (*control.WorkspaceStatus, error) { s.host.workspaceMu.Lock() defer s.host.workspaceMu.Unlock() diff --git a/seaweed-block/core/lifecycle/workspace_bindings.go b/seaweed-block/core/lifecycle/workspace_bindings.go index 5d51a472ba..d3fbefd8e9 100644 --- a/seaweed-block/core/lifecycle/workspace_bindings.go +++ b/seaweed-block/core/lifecycle/workspace_bindings.go @@ -119,6 +119,25 @@ func validateWorkspaceBinding(b WorkspaceBinding) error { return nil } +// ValidateWorkspaceEndpoints applies a binding's endpoint rules (host:port +// with a numeric port 1..65535, data and ctrl distinct) without registering +// anything. +func ValidateWorkspaceEndpoints(b WorkspaceBinding) error { return validateWorkspaceBinding(b) } + +// WorkspaceEndpointHost returns addr's host in canonical form (equivalent IP +// spellings compare equal; names lower-cased; no DNS), or "" if addr is not +// host:port. +func WorkspaceEndpointHost(addr string) string { + h, _, err := net.SplitHostPort(addr) + if err != nil || h == "" { + return "" + } + if ip := net.ParseIP(h); ip != nil { + return ip.String() + } + return strings.ToLower(h) +} + // Compare numeric ports and equivalent IP spellings without DNS/network I/O. func workspaceEndpointKey(addr string) string { h, p, err := net.SplitHostPort(addr) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 24fc76a55c..f310af1eea 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -93,6 +93,7 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | | Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | +| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding; each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | | Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | | Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace` | `INV-AUTH-MOVE-JOURNAL-001` |