From 52cd6debc5d24bed706b409603ba8aa53b1194ab Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 14:24:53 -0800 Subject: [PATCH 1/3] feat: register per-volume workspace endpoints and chosen-node intent --- seaweed-block/core/authority/workspace.go | 14 + seaweed-block/core/host/master/host.go | 38 ++- .../core/host/master/product_loop.go | 2 + seaweed-block/core/host/master/services.go | 5 + .../core/host/master/workspace_binding.go | 140 +++++++++ .../host/master/workspace_binding_test.go | 266 ++++++++++++++++++ .../core/host/master/workspace_protocol.md | 42 ++- .../core/host/master/workspace_service.go | 49 ++-- .../core/lifecycle/workspace_bindings.go | 244 ++++++++++++++++ .../core/lifecycle/workspace_bindings_test.go | 43 +++ .../core/rpc/control/workspace.pb.go | 213 ++++++++++++-- .../core/rpc/control/workspace_grpc.pb.go | 90 +++++- seaweed-block/core/rpc/proto/workspace.proto | 13 + 13 files changed, 1100 insertions(+), 59 deletions(-) create mode 100644 seaweed-block/core/host/master/workspace_binding.go create mode 100644 seaweed-block/core/host/master/workspace_binding_test.go create mode 100644 seaweed-block/core/lifecycle/workspace_bindings.go create mode 100644 seaweed-block/core/lifecycle/workspace_bindings_test.go diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 87e829887d..4e8dac0ae4 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -118,6 +118,20 @@ type WorkspaceMoveRequest struct { // MoveWorkspace is the authority-owned guarded RF1 move seam. The host layer // validates volume eligibility and reads HEAD before calling this boundary. +// RecordWorkspacePlacement serializes initial desired placement persistence +// against authority publication. persist must not call back into Publisher. +func (p *Publisher) RecordWorkspacePlacement(ctx context.Context, volume string, persist func() error) error { + p.mu.Lock() + defer p.mu.Unlock() + if err := ctx.Err(); err != nil { + return err + } + if _, _, ok := p.workspaceLineLocked(volume); ok { + return fmt.Errorf("workspace placement: volume already assigned; use move") + } + return persist() +} + func (p *Publisher) MoveWorkspace(ctx context.Context, req WorkspaceMoveRequest, head WorkspaceHead) (WorkspaceMoveRecord, error) { if err := ctx.Err(); err != nil { return WorkspaceMoveRecord{}, err diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index 47e670b187..91c4da613a 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -85,9 +85,10 @@ type Config struct { // blockmaster. The stores are controller input only; assignment // publication remains owned by authority.Controller/Publisher. type LifecycleStores struct { - Volumes *lifecycle.FileStore - Nodes *lifecycle.NodeInventoryStore - Placements *lifecycle.PlacementIntentStore + Volumes *lifecycle.FileStore + Nodes *lifecycle.NodeInventoryStore + Placements *lifecycle.PlacementIntentStore + WorkspaceBindings *lifecycle.WorkspaceBindingStore } // Host is the composed master-side block product daemon. Lifecycle @@ -105,11 +106,14 @@ type Host struct { grpc *grpc.Server topo authority.AcceptedTopology lifecycle *LifecycleStores - events *eventRing - promotionMu sync.RWMutex - promotionProber PromotionEvidenceProvider - cancel context.CancelFunc - wg sync.WaitGroup + // RPC registration/place/move/ACK/delete and product ticks serialize here. + // Order: workspaceMu -> publisher or lifecycle store locks (not reversed). + workspaceMu sync.Mutex + events *eventRing + promotionMu sync.RWMutex + promotionProber PromotionEvidenceProvider + cancel context.CancelFunc + wg sync.WaitGroup started atomic.Bool } @@ -241,6 +245,13 @@ func New(cfg Config) (*Host, error) { h.obs = obs h.ln = ln h.lifecycle = lifecycleStores + if h.lifecycle != nil { + if err := h.reconcileWorkspaceBindings(); err != nil { + _ = ln.Close() + _ = boot.Close() + return nil, fmt.Errorf("master.New: workspace binding recovery: %w", err) + } + } if cfg.FrontendPublicationRuntimeHTTP { addr := cfg.FrontendPublicationRuntimeListen @@ -295,10 +306,15 @@ func openLifecycleStores(dir string) (*LifecycleStores, error) { if err != nil { return nil, err } + bindings, err := lifecycle.OpenWorkspaceBindingStore(filepath.Join(dir, "workspace-bindings")) + if err != nil { + return nil, err + } return &LifecycleStores{ - Volumes: volumes, - Nodes: nodes, - Placements: placements, + Volumes: volumes, + Nodes: nodes, + Placements: placements, + WorkspaceBindings: bindings, }, nil } diff --git a/seaweed-block/core/host/master/product_loop.go b/seaweed-block/core/host/master/product_loop.go index 9f8ad00153..aa67f24ae6 100644 --- a/seaweed-block/core/host/master/product_loop.go +++ b/seaweed-block/core/host/master/product_loop.go @@ -50,6 +50,8 @@ func (h *Host) SetPromotionEvidenceProvider(p PromotionEvidenceProvider) { // directive queue. It never calls Publisher.apply; Publisher remains the only // authority minter through its normal Run loop. func (h *Host) RunLifecycleProductTick() (LifecycleProductTickResult, error) { + h.workspaceMu.Lock() + defer h.workspaceMu.Unlock() stores := h.Lifecycle() if stores == nil { return LifecycleProductTickResult{}, nil diff --git a/seaweed-block/core/host/master/services.go b/seaweed-block/core/host/master/services.go index eea17026d8..00aa74f318 100644 --- a/seaweed-block/core/host/master/services.go +++ b/seaweed-block/core/host/master/services.go @@ -75,6 +75,8 @@ func (s *services) CreateVolume(ctx context.Context, req *control.CreateVolumeRe } func (s *services) DeleteVolume(ctx context.Context, req *control.DeleteVolumeRequest) (*control.DeleteVolumeResponse, error) { + s.host.workspaceMu.Lock() + defer s.host.workspaceMu.Unlock() stores := s.host.Lifecycle() if stores == nil { return nil, status.Error(codes.FailedPrecondition, "lifecycle store is not configured") @@ -88,6 +90,9 @@ func (s *services) DeleteVolume(ctx context.Context, req *control.DeleteVolumeRe if err := stores.Volumes.DeleteVolume(req.GetVolumeId()); err != nil { return nil, lifecycleError("delete volume", err) } + if err := stores.WorkspaceBindings.DeleteVolume(req.GetVolumeId()); err != nil { + return nil, lifecycleError("delete workspace bindings", err) + } return &control.DeleteVolumeResponse{}, nil } diff --git a/seaweed-block/core/host/master/workspace_binding.go b/seaweed-block/core/host/master/workspace_binding.go new file mode 100644 index 0000000000..15e22f0cc9 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_binding.go @@ -0,0 +1,140 @@ +package master + +import ( + "context" + "fmt" + + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +func bindingFact(b lifecycle.WorkspaceBinding) *control.WorkspaceBinding { + return &control.WorkspaceBinding{VolumeId: b.VolumeID, ServerId: b.ServerID, DataAddr: b.DataAddr, CtrlAddr: b.CtrlAddr, Retired: b.Retired} +} + +func (s *services) RegisterWorkspaceBinding(ctx context.Context, q *control.WorkspaceBinding) (*control.WorkspaceBinding, error) { + s.host.workspaceMu.Lock() + defer s.host.workspaceMu.Unlock() + if err := s.workspaceVolume(q.GetVolumeId()); err != nil { + return nil, err + } + if err := ctx.Err(); err != nil { + return nil, workspaceError(err) + } + if err := s.host.reconcileWorkspaceBindings(); err != nil { + return nil, workspaceError(err) + } + if _, ok := s.host.lifecycle.Nodes.GetNode(q.GetServerId()); !ok { + return nil, workspaceError(fmt.Errorf("workspace binding: unknown server")) + } + b := lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: q.GetServerId(), DataAddr: q.GetDataAddr(), CtrlAddr: q.GetCtrlAddr(), Retired: q.GetRetired()} + // Legacy assignments also reserve their live endpoints. Merely preparing + // the first explicit target must not make the old source pair reusable. + for _, v := range s.host.lifecycle.Volumes.ListVolumes() { + if v.Spec.VolumeID == b.VolumeID { + continue + } + line, ok := s.host.Publisher().VolumeAuthorityLine(v.Spec.VolumeID) + if !ok { + continue + } + state := s.host.Publisher().WorkspaceState(v.Spec.VolumeID) + if state != nil && state.Ack != nil && state.Ack.Epoch == line.Epoch { + continue + } + if b.EndpointsOverlap(lifecycle.WorkspaceBinding{DataAddr: line.DataAddr, CtrlAddr: line.CtrlAddr}) { + return nil, workspaceError(fmt.Errorf("workspace binding: endpoint belongs to live assignment")) + } + } + if err := s.host.lifecycle.WorkspaceBindings.Register(b); err != nil { + return nil, workspaceError(err) + } + return bindingFact(b), nil +} + +func (h *Host) workspaceSourceHost(volume, replica string, epoch uint64) string { + if state := h.Publisher().WorkspaceState(volume); state != nil { + for _, r := range state.Moves { + if r.Issued && r.NewReplicaID == replica && r.NewEpoch == epoch { + return r.NewHost + } + } + } + if p, ok := h.lifecycle.Placements.GetPlacement(volume); ok { + for _, slot := range p.Slots { + if slot.ReplicaID == replica { + return slot.ServerID + } + } + } + return "" +} + +// Recover retirement after a crash between the authority ACK/issued record +// and binding persistence. Epoch-tagged retirements cannot retire a later +// re-registration when an old Move/ACK is retried or replayed on restart. +// Caller owns workspaceMu, or Host.New has not exposed the host yet. +func (h *Host) reconcileWorkspaceBindings() error { + for _, v := range h.lifecycle.Volumes.ListVolumes() { + volume := v.Spec.VolumeID + state := h.Publisher().WorkspaceState(volume) + if state == nil { + continue + } + for _, m := range state.Moves { + if m.Issued { + if err := h.lifecycle.WorkspaceBindings.Retire(volume, m.OldHost, m.OldEpoch); err != nil { + return err + } + } + } + if a := state.Ack; a != nil { + host := h.workspaceSourceHost(volume, a.ReplicaID, a.Epoch) + if host != "" { + if err := h.lifecycle.WorkspaceBindings.Retire(volume, host, a.Epoch); err != nil { + return err + } + } + } + } + return nil +} + +func (s *services) PlaceWorkspace(ctx context.Context, q *control.WorkspacePlacement) (*control.WorkspaceEmpty, error) { + s.host.workspaceMu.Lock() + defer s.host.workspaceMu.Unlock() + if err := s.workspaceVolume(q.GetVolumeId()); err != nil { + return nil, err + } + list, _, err := s.host.lifecycle.WorkspaceBindings.Get(q.GetVolumeId()) + if err != nil { + return nil, workspaceError(err) + } + var binding *lifecycle.WorkspaceBinding + for _, b := range list { + if b.ServerID == q.GetServerId() && !b.Retired { + copy := b + binding = © + } + } + if binding == nil || q.GetReplicaId() == "" { + return nil, workspaceError(fmt.Errorf("workspace placement: active prepared binding and replica required")) + } + if _, ok := s.host.lifecycle.Nodes.GetNode(q.GetServerId()); !ok { + return nil, workspaceError(fmt.Errorf("workspace placement: unknown server")) + } + err = s.host.Publisher().RecordWorkspacePlacement(ctx, q.GetVolumeId(), func() error { + if p, ok := s.host.lifecycle.Placements.GetPlacement(q.GetVolumeId()); ok { + if len(p.Slots) == 1 && p.Slots[0].ServerID == binding.ServerID && p.Slots[0].ReplicaID == q.GetReplicaId() && p.Slots[0].DataAddr == binding.DataAddr && p.Slots[0].CtrlAddr == binding.CtrlAddr { + return nil + } + return fmt.Errorf("workspace placement: existing intent differs") + } + _, e := s.host.lifecycle.Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: q.GetVolumeId(), DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{{VolumeID: q.GetVolumeId(), ServerID: binding.ServerID, ReplicaID: q.GetReplicaId(), Source: lifecycle.PlacementSourceExistingReplica, DataAddr: binding.DataAddr, CtrlAddr: binding.CtrlAddr}}}) + return e + }) + if err != nil { + return nil, workspaceError(err) + } + return &control.WorkspaceEmpty{}, nil +} diff --git a/seaweed-block/core/host/master/workspace_binding_test.go b/seaweed-block/core/host/master/workspace_binding_test.go new file mode 100644 index 0000000000..18bf59ba89 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_binding_test.go @@ -0,0 +1,266 @@ +package master + +import ( + "context" + "fmt" + "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" +) + +func TestWorkspaceBindingPlacesRF1OnChosenNode(t *testing.T) { + h, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }}) + if err != nil { + t.Fatal(err) + } + h.Start() + defer closeTestMaster(t, h) + conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + client := control.NewWorkspaceServiceClient(conn) + if _, err = control.NewLifecycleServiceClient(conn).CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "chosen", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + if _, err = h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-chosen", DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); err != nil { + t.Fatal(err) + } + b := &control.WorkspaceBinding{VolumeId: "chosen", ServerId: "node-chosen", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"} + if _, err = client.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatalf("register chosen per-volume binding: %v", err) + } + if _, err = client.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "chosen", ServerId: "node-chosen", ReplicaId: "r1"}); err != nil { + t.Fatal("place chosen RF1", err) + } + p, ok := h.Lifecycle().Placements.GetPlacement("chosen") + if !ok || len(p.Slots) != 1 || p.Slots[0].ServerID != "node-chosen" || p.Slots[0].DataAddr != b.DataAddr || p.Slots[0].CtrlAddr != b.CtrlAddr { + t.Fatal("wrong chosen intent", p) + } + if _, ok := h.Publisher().VolumeAuthorityLine("chosen"); ok { + t.Fatal("placement minted authority without observation") + } + if _, err = control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-chosen", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, Slots: []*control.HeartbeatSlot{{VolumeId: "chosen", ReplicaId: "r1", DataAddr: b.DataAddr, CtrlAddr: b.CtrlAddr}}}); err != nil { + t.Fatal(err) + } + if _, err = h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + line := waitAuthorityLine(t, h.Publisher(), "chosen") + if line.ReplicaID != "r1" || line.DataAddr != b.DataAddr || line.CtrlAddr != b.CtrlAddr { + t.Fatal("wrong chosen assignment", line) + } + if _, err = client.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "chosen", ServerId: "node-chosen", ReplicaId: "different"}); err == nil { + t.Fatal("assigned volume accepted new placement") + } +} + +func TestWorkspaceBindingsMoveTwoVolumesToOneHost(t *testing.T) { + workspaceBindingsMove(t, false) +} + +func TestWorkspaceBindingsForcedRetiresOnlyAfterIssue(t *testing.T) { + workspaceBindingsMove(t, true) +} + +func workspaceBindingsMove(t *testing.T, forced bool) { + cfg := Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil + }} + h, err := New(cfg) + if err != nil { + t.Fatal(err) + } + h.Start() + defer closeTestMaster(t, h) + conn, err := grpc.NewClient(h.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() + client := control.NewWorkspaceServiceClient(conn) + for _, server := range []string{"node-a", "node-b"} { + if _, err = h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: server, DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); err != nil { + t.Fatal(err) + } + } + volumes := []string{"vol-one", "vol-two"} + if forced { + volumes = volumes[:1] + } + for i, vol := range volumes { + if _, err = control.NewLifecycleServiceClient(conn).CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: vol, SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + src := &control.WorkspaceBinding{VolumeId: vol, ServerId: "node-a", DataAddr: fmt.Sprintf("127.0.0.1:%d", 19200+i), CtrlAddr: fmt.Sprintf("127.0.0.1:%d", 19100+i)} + target := &control.WorkspaceBinding{VolumeId: vol, ServerId: "node-b", DataAddr: fmt.Sprintf("127.0.0.1:%d", 29200+i), CtrlAddr: fmt.Sprintf("127.0.0.1:%d", 29100+i)} + for _, b := range []*control.WorkspaceBinding{src, target} { + if _, err = client.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + } + if _, err = client.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: vol, ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal(err) + } + if _, err = control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, Slots: []*control.HeartbeatSlot{{VolumeId: vol, ReplicaId: "r1", DataAddr: src.DataAddr, CtrlAddr: src.CtrlAddr}}}); err != nil { + t.Fatal(err) + } + if _, err = h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + line := waitAuthorityLine(t, h.Publisher(), vol) + id := &control.WorkspaceIdentity{VolumeId: vol, ReplicaId: "r1", Epoch: line.Epoch} + lease, e := client.RenewWorkspaceLease(ctx, id) + if e != nil { + t.Fatal(e) + } + if forced { + select { + case <-time.After(time.Until(time.Unix(0, lease.ExpiresAtNs)) + 20*time.Millisecond): + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + } else { + if _, err = client.RevokeWorkspace(ctx, id); err != nil { + t.Fatal(err) + } + if _, err = client.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil { + t.Fatal(err) + } + } + before, e := client.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: vol}) + if e != nil { + t.Fatal(e) + } + for _, b := range before.Bindings { + if b.ServerId == "node-a" && b.Retired == forced { + t.Fatal("source retirement occurred at wrong boundary", b) + } + } + q := &control.WorkspaceMove{RequestId: vol + "-bad", VolumeId: vol, ExpectedReplicaId: "r1", ExpectedEpoch: line.Epoch, TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:9200", TargetCtrlAddr: "127.0.0.1:9100", Kind: "clean"} + if forced { + q.Kind = "forced" + q.Force = true + } + if _, err = client.MoveWorkspace(ctx, q); err == nil { + t.Fatal("explicit volume fell back to legacy node pair") + } + q.RequestId = vol + "-move" + q.TargetDataAddr = target.DataAddr + q.TargetCtrlAddr = target.CtrlAddr + if _, err = client.MoveWorkspace(ctx, q); err != nil { + t.Fatal("prepared per-volume target refused", err) + } + got, ok := h.Publisher().VolumeAuthorityLine(vol) + if !ok || got.Epoch != 2 || got.DataAddr != target.DataAddr || got.CtrlAddr != target.CtrlAddr { + t.Fatal("wrong moved authority", got) + } + placement, _ := h.Lifecycle().Placements.GetPlacement(vol) + if placement.Slots[0].ServerID != "node-a" { + t.Fatal("move rewrote source intent", placement) + } + state, err := client.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: vol}) + if err != nil { + t.Fatal(err) + } + if len(state.Bindings) != 2 { + t.Fatal("missing bindings", state) + } + for _, b := range state.Bindings { + if (b.ServerId == "node-a") != b.Retired { + t.Fatal("wrong binding lifecycle", b) + } + } + } + closeTestMaster(t, h) + h2, err := New(cfg) + if err != nil { + t.Fatal("restart", err) + } + h2.Start() + defer closeTestMaster(t, h2) + c2, err := grpc.NewClient(h2.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer c2.Close() + for _, v := range volumes { + state, e := control.NewWorkspaceServiceClient(c2).QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: v}) + if e != nil { + t.Fatal(e) + } + if len(state.Bindings) != 2 || len(state.Moves) != 1 || state.Moves[0].NewEpoch != 2 { + t.Fatal("restart lost binding/grant", state) + } + for _, b := range state.Bindings { + if (b.ServerId == "node-a") != b.Retired { + t.Fatal("restart changed retirement", b) + } + } + } +} + +func TestWorkspaceBindingsRejectCollisionsAndLiveChangesAndDeleteCleans(t *testing.T) { + h, e := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }}) + if e != nil { + t.Fatal(e) + } + h.Start() + defer closeTestMaster(t, h) + c, e := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if e != nil { + t.Fatal(e) + } + defer c.Close() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + client, life := control.NewWorkspaceServiceClient(c), control.NewLifecycleServiceClient(c) + for _, v := range []string{"a", "b", "c"} { + if _, e = life.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: v, SizeBytes: 1 << 20, ReplicationFactor: 1}); e != nil { + t.Fatal(e) + } + } + if _, e = h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node", DataAddr: "127.0.0.1:9000", CtrlAddr: "127.0.0.1:9001"}); e != nil { + t.Fatal(e) + } + a := &control.WorkspaceBinding{VolumeId: "a", ServerId: "unknown", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"} + if _, e = client.RegisterWorkspaceBinding(ctx, a); e == nil { + t.Fatal("unknown server accepted") + } + a.ServerId = "node" + for i := 0; i < 2; i++ { + if _, e = client.RegisterWorkspaceBinding(ctx, a); e != nil { + t.Fatal("idempotent registration", e) + } + } + changed := &control.WorkspaceBinding{VolumeId: a.VolumeId, ServerId: a.ServerId, DataAddr: "127.0.0.1:10002", CtrlAddr: a.CtrlAddr} + if _, e = client.RegisterWorkspaceBinding(ctx, changed); e == nil { + t.Fatal("live binding changed") + } + for _, pair := range [][2]string{{a.DataAddr, a.CtrlAddr}, {a.CtrlAddr, "127.0.0.1:10003"}, {"127.0.0.1:010000", "127.0.0.1:10003"}, {"[::ffff:127.0.0.1]:10000", "127.0.0.1:10003"}} { + if _, e = client.RegisterWorkspaceBinding(ctx, &control.WorkspaceBinding{VolumeId: "b", ServerId: "node", DataAddr: pair[0], CtrlAddr: pair[1]}); e == nil { + t.Fatal("live endpoint collision accepted") + } + } + if _, e = life.DeleteVolume(ctx, &control.DeleteVolumeRequest{VolumeId: "a"}); e != nil { + t.Fatal(e) + } + if _, bound, e := h.Lifecycle().WorkspaceBindings.Get("a"); e != nil || bound { + t.Fatal("deleted volume retained binding", bound, e) + } + a.VolumeId = "c" + if _, e = client.RegisterWorkspaceBinding(ctx, a); e != nil { + t.Fatal("deleted volume did not release endpoints", e) + } +} diff --git a/seaweed-block/core/host/master/workspace_protocol.md b/seaweed-block/core/host/master/workspace_protocol.md index 2f261b8a36..d203060234 100644 --- a/seaweed-block/core/host/master/workspace_protocol.md +++ b/seaweed-block/core/host/master/workspace_protocol.md @@ -4,9 +4,49 @@ The opt-in master surface is `WorkspaceService` in `workspace.proto`. Enable it with `blockmaster --workspace-rpc --workspace-head-base-url ` and a lifecycle store. Other volumes continue using the existing assignment protocol. Workspace operations require an existing RF=1 volume. The target node -must be registered with matching data/control endpoints; the source node comes +must be registered; explicit volumes use their prepared per-volume endpoints, +while volumes with no binding retain node-pair compatibility. The source comes from its placement or the previous issued move, not a caller's evidence flag. +## Per-volume endpoint preparation and placement + +W6 allocates listener ports and calls `RegisterWorkspaceBinding` with volume, +registered server ID, data address and control address before placement or move. +The binding is a durable endpoint reservation, not authority or readiness. +Registration is idempotent for the same pair; changing a live binding or taking +another live volume's endpoint is refused. Prepared pairs also reserve their +ports. Numeric IP/port spellings are normalized for collision checks without +performing DNS lookup. Callers must use consistent DNS names for endpoints. + +`PlaceWorkspace {volume_id, server_id, replica_id}` records chosen-node intent +for an existing, unassigned RF=1 volume with an active prepared binding. It does +not create a volume or mint an epoch. Existing different placement intent is +refused rather than silently replacing a queued plan. Observation and the +existing controller/publisher path still establish the assignment. Repeated +identical intent is allowed before assignment; assigned volumes use Move. + +Move validates the PREPARED target binding and leaves the source placement +unchanged. Once a volume has any explicit binding, it never uses the legacy +node-level pair, even if all its bindings are retired. CLEAN retires the source +binding only after its durable clean ACK. FORCED retires it only after the new +epoch is issued. Retirement carries the old epoch, making crash recovery and +old-request replay harmless to a later re-prepared binding. Registration may +reuse retired ports; a live target must be prepared again before another move. +Volume deletion removes its binding marker and reservations after deleting +lifecycle state. Failed deletion can be retried. + +Bindings are a file-synced, atomic snapshot with directory fsync. Ambiguous +publication errors fence binding reads/mutations until restart. Startup and +registration reconcile retirement from persisted ACK/issued move records, so +a crash between authority persistence and binding retirement is recoverable. +`QueryWorkspace` returns the per-volume bindings including their retired state. + +Host workspace operations and product ticks serialize with `workspaceMu`. +Lock order is host workspace mutex, then Publisher or lifecycle-store locks. +Initial placement persists under a Publisher unassigned guard; its callback +must never call Publisher. Store reads do not hold their mutex while calling +Publisher. Lease renewal remains independent of the host workspace mutex. + The RPCs grant/renew a lease, request revocation, record the old holder's ACK, request a move, and query persisted state. Leases bind volume, holder and epoch. The master owns a 30-second expiry. After expiry, that same assignment cannot diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index d26dcf29ab..a34685e1ad 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -76,6 +76,8 @@ func (s *services) RevokeWorkspace(ctx context.Context, q *control.WorkspaceIden } func (s *services) AckWorkspaceRevoked(ctx context.Context, q *control.WorkspaceRevocationAck) (*control.WorkspaceEmpty, error) { + s.host.workspaceMu.Lock() + defer s.host.workspaceMu.Unlock() id := q.GetIdentity() if err := s.workspaceVolume(id.GetVolumeId()); err != nil { return nil, err @@ -83,6 +85,9 @@ func (s *services) AckWorkspaceRevoked(ctx context.Context, q *control.Workspace if err := s.host.Publisher().AckWorkspaceRevocation(ctx, id.GetVolumeId(), authority.WorkspaceRevokeAck{ReplicaID: id.GetReplicaId(), Epoch: id.GetEpoch(), HeadGen: q.GetHeadGen()}); err != nil { return nil, workspaceError(err) } + if err := s.host.reconcileWorkspaceBindings(); err != nil { + return nil, workspaceError(err) + } return &control.WorkspaceEmpty{}, nil } @@ -92,28 +97,24 @@ func grantFact(r authority.WorkspaceMoveRecord) *control.WorkspaceGrant { } func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { + s.host.workspaceMu.Lock() + defer s.host.workspaceMu.Unlock() if err := s.workspaceVolume(q.GetVolumeId()); err != nil { return nil, err } - oldHost := "" - if state := s.host.Publisher().WorkspaceState(q.GetVolumeId()); state != nil { - for _, r := range state.Moves { - if r.Issued && r.NewReplicaID == q.GetExpectedReplicaId() && r.NewEpoch == q.GetExpectedEpoch() { - oldHost = r.NewHost - } - } - } - if oldHost == "" { - if placement, ok := s.host.lifecycle.Placements.GetPlacement(q.GetVolumeId()); ok { - for _, slot := range placement.Slots { - if slot.ReplicaID == q.GetExpectedReplicaId() { - oldHost = slot.ServerID - } - } - } - } + oldHost := s.host.workspaceSourceHost(q.GetVolumeId(), q.GetExpectedReplicaId(), q.GetExpectedEpoch()) target, ok := s.host.lifecycle.Nodes.GetNode(q.GetTargetServerId()) - if oldHost == "" || !ok || target.ServerID == oldHost || target.DataAddr != q.GetTargetDataAddr() || target.CtrlAddr != q.GetTargetCtrlAddr() { + bindings, explicit, err := s.host.lifecycle.WorkspaceBindings.Get(q.GetVolumeId()) + if err != nil { + return nil, workspaceError(err) + } + matched := !explicit && target.DataAddr == q.GetTargetDataAddr() && target.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") } // Always bound the configured reader, even when the caller omitted a deadline. @@ -128,14 +129,26 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) if err != nil { return nil, workspaceError(err) } + if err = s.host.reconcileWorkspaceBindings(); err != nil { + return nil, workspaceError(err) + } return grantFact(r), nil } func (s *services) QueryWorkspace(ctx context.Context, q *control.WorkspaceVolume) (*control.WorkspaceStatus, error) { + s.host.workspaceMu.Lock() + defer s.host.workspaceMu.Unlock() if err := s.workspaceVolume(q.GetVolumeId()); err != nil { return nil, err } out := &control.WorkspaceStatus{} + bindings, _, err := s.host.lifecycle.WorkspaceBindings.Get(q.GetVolumeId()) + if err != nil { + return nil, workspaceError(err) + } + for _, b := range bindings { + out.Bindings = append(out.Bindings, bindingFact(b)) + } state := s.host.Publisher().WorkspaceState(q.GetVolumeId()) if state == nil { return out, nil diff --git a/seaweed-block/core/lifecycle/workspace_bindings.go b/seaweed-block/core/lifecycle/workspace_bindings.go new file mode 100644 index 0000000000..52b6bd2914 --- /dev/null +++ b/seaweed-block/core/lifecycle/workspace_bindings.go @@ -0,0 +1,244 @@ +package lifecycle + +import ( + "bytes" + "encoding/json" + "fmt" + "net" + "os" + "path/filepath" + "strconv" + "strings" + "sync" +) + +// WorkspaceBinding is prepared endpoint ownership, not assignment/readiness. +// Retired entries remain as a per-volume marker: explicit volumes never fall +// back to node-level addresses, even after all their bindings are retired. +type WorkspaceBinding struct { + VolumeID string `json:"volume_id"` + ServerID string `json:"server_id"` + DataAddr string `json:"data_addr"` + CtrlAddr string `json:"ctrl_addr"` + Retired bool `json:"retired,omitempty"` + RetiredEpoch uint64 `json:"retired_epoch,omitempty"` // idempotent authority retirement event +} + +type WorkspaceBindingStore struct { + mu sync.Mutex + dir string + records map[string][]WorkspaceBinding + uncertain bool +} + +func OpenWorkspaceBindingStore(dir string) (*WorkspaceBindingStore, error) { + if err := os.MkdirAll(dir, 0755); err != nil { + return nil, err + } + s := &WorkspaceBindingStore{dir: dir, records: map[string][]WorkspaceBinding{}} + b, err := os.ReadFile(filepath.Join(dir, "bindings.json")) + if os.IsNotExist(err) { + return s, nil + } + if err != nil { + return nil, err + } + if err = json.Unmarshal(b, &s.records); err != nil { + return nil, err + } + if s.records == nil { + return nil, fmt.Errorf("workspace bindings: null state") + } + for v, list := range s.records { + if err = validateVolumeID(v); err != nil { + return nil, err + } + seen := map[string]bool{} + for _, r := range list { + if r.VolumeID != v || seen[r.ServerID] { + return nil, fmt.Errorf("workspace bindings: inconsistent record") + } + seen[r.ServerID] = true + if err = validateWorkspaceBinding(r); err != nil { + return nil, err + } + if !r.Retired { + if err = bindingCollision(s.records, r); err != nil { + return nil, err + } + } + } + } + return s, nil +} + +func validateWorkspaceBinding(b WorkspaceBinding) error { + if err := validateVolumeID(b.VolumeID); err != nil { + return err + } + if err := validateServerID(b.ServerID); err != nil { + return err + } + for _, a := range []string{b.DataAddr, b.CtrlAddr} { + h, p, e := net.SplitHostPort(a) + n, e2 := strconv.Atoi(p) + if e != nil || e2 != nil || h == "" || n < 1 || n > 65535 { + return fmt.Errorf("workspace binding: invalid endpoint %q", a) + } + } + if workspaceEndpointKey(b.DataAddr) == workspaceEndpointKey(b.CtrlAddr) { + return fmt.Errorf("workspace binding: endpoints must differ") + } + return nil +} + +// Compare numeric ports and equivalent IP spellings without DNS/network I/O. +func workspaceEndpointKey(addr string) string { + h, p, err := net.SplitHostPort(addr) + if err != nil { + return addr + } + n, err := strconv.Atoi(p) + if err != nil { + return addr + } + if ip := net.ParseIP(h); ip != nil { + h = ip.String() + } else { + h = strings.ToLower(h) + } + return net.JoinHostPort(h, strconv.Itoa(n)) +} + +func (b WorkspaceBinding) EndpointsOverlap(other WorkspaceBinding) bool { + d, c := workspaceEndpointKey(b.DataAddr), workspaceEndpointKey(b.CtrlAddr) + od, oc := workspaceEndpointKey(other.DataAddr), workspaceEndpointKey(other.CtrlAddr) + return d == od || d == oc || c == od || c == oc +} + +func bindingCollision(all map[string][]WorkspaceBinding, b WorkspaceBinding) error { + for _, list := range all { + for _, r := range list { + if r.Retired || (r.VolumeID == b.VolumeID && r.ServerID == b.ServerID) { + continue + } + if b.EndpointsOverlap(r) { + return fmt.Errorf("workspace binding: endpoint reserved by %s on %s", r.VolumeID, r.ServerID) + } + } + } + return nil +} + +func (s *WorkspaceBindingStore) Get(volume string) ([]WorkspaceBinding, bool, error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.uncertain { + return nil, false, fmt.Errorf("workspace bindings uncertain; restart required") + } + list, ok := s.records[volume] + return append([]WorkspaceBinding(nil), list...), ok, nil +} + +func (s *WorkspaceBindingStore) Register(b WorkspaceBinding) error { + if b.Retired { + return fmt.Errorf("workspace binding: retired is server-owned") + } + if err := validateWorkspaceBinding(b); err != nil { + return err + } + return s.update(func(all map[string][]WorkspaceBinding) error { + if err := bindingCollision(all, b); err != nil { + return err + } + list := all[b.VolumeID] + for i, r := range list { + if r.ServerID == b.ServerID { + if !r.Retired && r.DataAddr == b.DataAddr && r.CtrlAddr == b.CtrlAddr { + return nil + } + if !r.Retired { + return fmt.Errorf("workspace binding: live binding cannot change") + } + list[i] = b + list[i].RetiredEpoch = r.RetiredEpoch + all[b.VolumeID] = list + return nil + } + } + all[b.VolumeID] = append(list, b) + return nil + }) +} + +func (s *WorkspaceBindingStore) Retire(volume, server string, epoch uint64) error { + return s.update(func(all map[string][]WorkspaceBinding) error { + for i := range all[volume] { + if all[volume][i].ServerID == server && epoch > all[volume][i].RetiredEpoch { + all[volume][i].Retired = true + all[volume][i].RetiredEpoch = epoch + } + } + return nil + }) +} + +func (s *WorkspaceBindingStore) DeleteVolume(volume string) error { + return s.update(func(all map[string][]WorkspaceBinding) error { delete(all, volume); return nil }) +} + +// Atomic snapshot includes collision ownership across volumes. No in-memory +// mutation is committed before durable publication. An ambiguous filesystem +// error latches the store fail-closed until reload, including read admission. +func (s *WorkspaceBindingStore) update(change func(map[string][]WorkspaceBinding) error) error { + s.mu.Lock() + defer s.mu.Unlock() + if s.uncertain { + return fmt.Errorf("workspace bindings uncertain; restart required") + } + all := make(map[string][]WorkspaceBinding, len(s.records)) + for v, l := range s.records { + all[v] = append([]WorkspaceBinding(nil), l...) + } + if err := change(all); err != nil { + return err + } + b, err := json.Marshal(all) + if err != nil { + return err + } + old, _ := json.Marshal(s.records) + if bytes.Equal(b, old) { + return nil + } + f, err := os.CreateTemp(s.dir, "bindings-*.tmp") + if err != nil { + return err + } + defer os.Remove(f.Name()) + if _, err = f.Write(b); err == nil { + err = f.Sync() + } + closeErr := f.Close() + if err == nil { + err = closeErr + } + if err != nil { + return err + } + if err = os.Rename(f.Name(), filepath.Join(s.dir, "bindings.json")); err != nil { + s.uncertain = true + return err + } + d, err := os.Open(s.dir) + if err == nil { + err = d.Sync() + _ = d.Close() + } + if err != nil { + s.uncertain = true + return err + } + s.records = all + return nil +} diff --git a/seaweed-block/core/lifecycle/workspace_bindings_test.go b/seaweed-block/core/lifecycle/workspace_bindings_test.go new file mode 100644 index 0000000000..65292a5a48 --- /dev/null +++ b/seaweed-block/core/lifecycle/workspace_bindings_test.go @@ -0,0 +1,43 @@ +package lifecycle + +import "testing" + +func TestWorkspaceBindingRetirementReplayDoesNotRetireRepreparedTarget(t *testing.T) { + dir := t.TempDir() + s, e := OpenWorkspaceBindingStore(dir) + if e != nil { + t.Fatal(e) + } + b := WorkspaceBinding{VolumeID: "v", ServerID: "node", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"} + if e = s.Register(b); e != nil { + t.Fatal(e) + } + if e = s.Retire("v", "node", 1); e != nil { + t.Fatal(e) + } + if list, bound, e := s.Get("v"); e != nil || !bound || !list[0].Retired { + t.Fatal("retirement lost explicit marker", list, bound, e) + } + b.DataAddr = "127.0.0.1:10002" + if e = s.Register(b); e != nil { + t.Fatal(e) + } + if e = s.Retire("v", "node", 1); e != nil { + t.Fatal(e) + } + s, e = OpenWorkspaceBindingStore(dir) + if e != nil { + t.Fatal(e) + } + list, bound, e := s.Get("v") + if e != nil || !bound || len(list) != 1 || list[0].Retired || list[0].DataAddr != b.DataAddr { + t.Fatal("old retirement killed new binding", list, bound, e) + } + if e = s.Retire("v", "node", 2); e != nil { + t.Fatal(e) + } + list, _, e = s.Get("v") + if e != nil || !list[0].Retired { + t.Fatal(list, e) + } +} diff --git a/seaweed-block/core/rpc/control/workspace.pb.go b/seaweed-block/core/rpc/control/workspace.pb.go index 77860cb7db..af8db26e4b 100644 --- a/seaweed-block/core/rpc/control/workspace.pb.go +++ b/seaweed-block/core/rpc/control/workspace.pb.go @@ -550,6 +550,7 @@ type WorkspaceStatus struct { Lease *WorkspaceLeaseFact `protobuf:"bytes,1,opt,name=lease,proto3" json:"lease,omitempty"` RevocationAck *WorkspaceRevocationAck `protobuf:"bytes,2,opt,name=revocation_ack,json=revocationAck,proto3" json:"revocation_ack,omitempty"` Moves []*WorkspaceGrant `protobuf:"bytes,3,rep,name=moves,proto3" json:"moves,omitempty"` + Bindings []*WorkspaceBinding `protobuf:"bytes,4,rep,name=bindings,proto3" json:"bindings,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -605,6 +606,149 @@ func (x *WorkspaceStatus) GetMoves() []*WorkspaceGrant { return nil } +func (x *WorkspaceStatus) GetBindings() []*WorkspaceBinding { + if x != nil { + return x.Bindings + } + return nil +} + +type WorkspaceBinding struct { + state protoimpl.MessageState `protogen:"open.v1"` + VolumeId string `protobuf:"bytes,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"` + ServerId string `protobuf:"bytes,2,opt,name=server_id,json=serverId,proto3" json:"server_id,omitempty"` + DataAddr string `protobuf:"bytes,3,opt,name=data_addr,json=dataAddr,proto3" json:"data_addr,omitempty"` + CtrlAddr string `protobuf:"bytes,4,opt,name=ctrl_addr,json=ctrlAddr,proto3" json:"ctrl_addr,omitempty"` + Retired bool `protobuf:"varint,5,opt,name=retired,proto3" json:"retired,omitempty"` // server output only + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkspaceBinding) Reset() { + *x = WorkspaceBinding{} + mi := &file_workspace_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkspaceBinding) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkspaceBinding) ProtoMessage() {} + +func (x *WorkspaceBinding) ProtoReflect() protoreflect.Message { + mi := &file_workspace_proto_msgTypes[8] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkspaceBinding.ProtoReflect.Descriptor instead. +func (*WorkspaceBinding) Descriptor() ([]byte, []int) { + return file_workspace_proto_rawDescGZIP(), []int{8} +} + +func (x *WorkspaceBinding) GetVolumeId() string { + if x != nil { + return x.VolumeId + } + return "" +} + +func (x *WorkspaceBinding) GetServerId() string { + if x != nil { + return x.ServerId + } + return "" +} + +func (x *WorkspaceBinding) GetDataAddr() string { + if x != nil { + return x.DataAddr + } + return "" +} + +func (x *WorkspaceBinding) GetCtrlAddr() string { + if x != nil { + return x.CtrlAddr + } + return "" +} + +func (x *WorkspaceBinding) GetRetired() bool { + if x != nil { + return x.Retired + } + return false +} + +type WorkspacePlacement struct { + state protoimpl.MessageState `protogen:"open.v1"` + VolumeId string `protobuf:"bytes,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"` + ServerId string `protobuf:"bytes,2,opt,name=server_id,json=serverId,proto3" json:"server_id,omitempty"` + ReplicaId string `protobuf:"bytes,3,opt,name=replica_id,json=replicaId,proto3" json:"replica_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkspacePlacement) Reset() { + *x = WorkspacePlacement{} + mi := &file_workspace_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkspacePlacement) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkspacePlacement) ProtoMessage() {} + +func (x *WorkspacePlacement) ProtoReflect() protoreflect.Message { + mi := &file_workspace_proto_msgTypes[9] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkspacePlacement.ProtoReflect.Descriptor instead. +func (*WorkspacePlacement) Descriptor() ([]byte, []int) { + return file_workspace_proto_rawDescGZIP(), []int{9} +} + +func (x *WorkspacePlacement) GetVolumeId() string { + if x != nil { + return x.VolumeId + } + return "" +} + +func (x *WorkspacePlacement) GetServerId() string { + if x != nil { + return x.ServerId + } + return "" +} + +func (x *WorkspacePlacement) GetReplicaId() string { + if x != nil { + return x.ReplicaId + } + return "" +} + var File_workspace_proto protoreflect.FileDescriptor const file_workspace_proto_rawDesc = "" + @@ -658,12 +802,26 @@ const file_workspace_proto_rawDesc = "" + "\x06issued\x18\n" + " \x01(\bR\x06issued\x12\x19\n" + "\bold_host\x18\v \x01(\tR\aoldHost\x12\x19\n" + - "\bnew_host\x18\f \x01(\tR\anewHost\"\xeb\x01\n" + + "\bnew_host\x18\f \x01(\tR\anewHost\"\xb2\x02\n" + "\x0fWorkspaceStatus\x12A\n" + "\x05lease\x18\x01 \x01(\v2+.seaweedfs.block.control.WorkspaceLeaseFactR\x05lease\x12V\n" + "\x0erevocation_ack\x18\x02 \x01(\v2/.seaweedfs.block.control.WorkspaceRevocationAckR\rrevocationAck\x12=\n" + - "\x05moves\x18\x03 \x03(\v2'.seaweedfs.block.control.WorkspaceGrantR\x05moves2\xa7\x04\n" + - "\x10WorkspaceService\x12n\n" + + "\x05moves\x18\x03 \x03(\v2'.seaweedfs.block.control.WorkspaceGrantR\x05moves\x12E\n" + + "\bbindings\x18\x04 \x03(\v2).seaweedfs.block.control.WorkspaceBindingR\bbindings\"\xa0\x01\n" + + "\x10WorkspaceBinding\x12\x1b\n" + + "\tvolume_id\x18\x01 \x01(\tR\bvolumeId\x12\x1b\n" + + "\tserver_id\x18\x02 \x01(\tR\bserverId\x12\x1b\n" + + "\tdata_addr\x18\x03 \x01(\tR\bdataAddr\x12\x1b\n" + + "\tctrl_addr\x18\x04 \x01(\tR\bctrlAddr\x12\x18\n" + + "\aretired\x18\x05 \x01(\bR\aretired\"m\n" + + "\x12WorkspacePlacement\x12\x1b\n" + + "\tvolume_id\x18\x01 \x01(\tR\bvolumeId\x12\x1b\n" + + "\tserver_id\x18\x02 \x01(\tR\bserverId\x12\x1d\n" + + "\n" + + "replica_id\x18\x03 \x01(\tR\treplicaId2\x81\x06\n" + + "\x10WorkspaceService\x12p\n" + + "\x18RegisterWorkspaceBinding\x12).seaweedfs.block.control.WorkspaceBinding\x1a).seaweedfs.block.control.WorkspaceBinding\x12f\n" + + "\x0ePlaceWorkspace\x12+.seaweedfs.block.control.WorkspacePlacement\x1a'.seaweedfs.block.control.WorkspaceEmpty\x12n\n" + "\x13RenewWorkspaceLease\x12*.seaweedfs.block.control.WorkspaceIdentity\x1a+.seaweedfs.block.control.WorkspaceLeaseFact\x12j\n" + "\x0fRevokeWorkspace\x12*.seaweedfs.block.control.WorkspaceIdentity\x1a+.seaweedfs.block.control.WorkspaceLeaseFact\x12o\n" + "\x13AckWorkspaceRevoked\x12/.seaweedfs.block.control.WorkspaceRevocationAck\x1a'.seaweedfs.block.control.WorkspaceEmpty\x12`\n" + @@ -682,7 +840,7 @@ func file_workspace_proto_rawDescGZIP() []byte { return file_workspace_proto_rawDescData } -var file_workspace_proto_msgTypes = make([]protoimpl.MessageInfo, 8) +var file_workspace_proto_msgTypes = make([]protoimpl.MessageInfo, 10) var file_workspace_proto_goTypes = []any{ (*WorkspaceIdentity)(nil), // 0: seaweedfs.block.control.WorkspaceIdentity (*WorkspaceVolume)(nil), // 1: seaweedfs.block.control.WorkspaceVolume @@ -692,27 +850,34 @@ var file_workspace_proto_goTypes = []any{ (*WorkspaceMove)(nil), // 5: seaweedfs.block.control.WorkspaceMove (*WorkspaceGrant)(nil), // 6: seaweedfs.block.control.WorkspaceGrant (*WorkspaceStatus)(nil), // 7: seaweedfs.block.control.WorkspaceStatus + (*WorkspaceBinding)(nil), // 8: seaweedfs.block.control.WorkspaceBinding + (*WorkspacePlacement)(nil), // 9: seaweedfs.block.control.WorkspacePlacement } var file_workspace_proto_depIdxs = []int32{ - 0, // 0: seaweedfs.block.control.WorkspaceRevocationAck.identity:type_name -> seaweedfs.block.control.WorkspaceIdentity - 3, // 1: seaweedfs.block.control.WorkspaceStatus.lease:type_name -> seaweedfs.block.control.WorkspaceLeaseFact - 4, // 2: seaweedfs.block.control.WorkspaceStatus.revocation_ack:type_name -> seaweedfs.block.control.WorkspaceRevocationAck - 6, // 3: seaweedfs.block.control.WorkspaceStatus.moves:type_name -> seaweedfs.block.control.WorkspaceGrant - 0, // 4: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:input_type -> seaweedfs.block.control.WorkspaceIdentity - 0, // 5: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:input_type -> seaweedfs.block.control.WorkspaceIdentity - 4, // 6: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:input_type -> seaweedfs.block.control.WorkspaceRevocationAck - 5, // 7: seaweedfs.block.control.WorkspaceService.MoveWorkspace:input_type -> seaweedfs.block.control.WorkspaceMove - 1, // 8: seaweedfs.block.control.WorkspaceService.QueryWorkspace:input_type -> seaweedfs.block.control.WorkspaceVolume - 3, // 9: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:output_type -> seaweedfs.block.control.WorkspaceLeaseFact - 3, // 10: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:output_type -> seaweedfs.block.control.WorkspaceLeaseFact - 2, // 11: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:output_type -> seaweedfs.block.control.WorkspaceEmpty - 6, // 12: seaweedfs.block.control.WorkspaceService.MoveWorkspace:output_type -> seaweedfs.block.control.WorkspaceGrant - 7, // 13: seaweedfs.block.control.WorkspaceService.QueryWorkspace:output_type -> seaweedfs.block.control.WorkspaceStatus - 9, // [9:14] is the sub-list for method output_type - 4, // [4:9] is the sub-list for method input_type - 4, // [4:4] is the sub-list for extension type_name - 4, // [4:4] is the sub-list for extension extendee - 0, // [0:4] is the sub-list for field type_name + 0, // 0: seaweedfs.block.control.WorkspaceRevocationAck.identity:type_name -> seaweedfs.block.control.WorkspaceIdentity + 3, // 1: seaweedfs.block.control.WorkspaceStatus.lease:type_name -> seaweedfs.block.control.WorkspaceLeaseFact + 4, // 2: seaweedfs.block.control.WorkspaceStatus.revocation_ack:type_name -> seaweedfs.block.control.WorkspaceRevocationAck + 6, // 3: seaweedfs.block.control.WorkspaceStatus.moves:type_name -> seaweedfs.block.control.WorkspaceGrant + 8, // 4: seaweedfs.block.control.WorkspaceStatus.bindings:type_name -> seaweedfs.block.control.WorkspaceBinding + 8, // 5: seaweedfs.block.control.WorkspaceService.RegisterWorkspaceBinding:input_type -> seaweedfs.block.control.WorkspaceBinding + 9, // 6: seaweedfs.block.control.WorkspaceService.PlaceWorkspace:input_type -> seaweedfs.block.control.WorkspacePlacement + 0, // 7: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:input_type -> seaweedfs.block.control.WorkspaceIdentity + 0, // 8: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:input_type -> seaweedfs.block.control.WorkspaceIdentity + 4, // 9: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:input_type -> seaweedfs.block.control.WorkspaceRevocationAck + 5, // 10: seaweedfs.block.control.WorkspaceService.MoveWorkspace:input_type -> seaweedfs.block.control.WorkspaceMove + 1, // 11: seaweedfs.block.control.WorkspaceService.QueryWorkspace:input_type -> seaweedfs.block.control.WorkspaceVolume + 8, // 12: seaweedfs.block.control.WorkspaceService.RegisterWorkspaceBinding:output_type -> seaweedfs.block.control.WorkspaceBinding + 2, // 13: seaweedfs.block.control.WorkspaceService.PlaceWorkspace:output_type -> seaweedfs.block.control.WorkspaceEmpty + 3, // 14: seaweedfs.block.control.WorkspaceService.RenewWorkspaceLease:output_type -> seaweedfs.block.control.WorkspaceLeaseFact + 3, // 15: seaweedfs.block.control.WorkspaceService.RevokeWorkspace:output_type -> seaweedfs.block.control.WorkspaceLeaseFact + 2, // 16: seaweedfs.block.control.WorkspaceService.AckWorkspaceRevoked:output_type -> seaweedfs.block.control.WorkspaceEmpty + 6, // 17: seaweedfs.block.control.WorkspaceService.MoveWorkspace:output_type -> seaweedfs.block.control.WorkspaceGrant + 7, // 18: seaweedfs.block.control.WorkspaceService.QueryWorkspace:output_type -> seaweedfs.block.control.WorkspaceStatus + 12, // [12:19] is the sub-list for method output_type + 5, // [5:12] is the sub-list for method input_type + 5, // [5:5] is the sub-list for extension type_name + 5, // [5:5] is the sub-list for extension extendee + 0, // [0:5] is the sub-list for field type_name } func init() { file_workspace_proto_init() } @@ -726,7 +891,7 @@ func file_workspace_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_workspace_proto_rawDesc), len(file_workspace_proto_rawDesc)), NumEnums: 0, - NumMessages: 8, + NumMessages: 10, NumExtensions: 0, NumServices: 1, }, diff --git a/seaweed-block/core/rpc/control/workspace_grpc.pb.go b/seaweed-block/core/rpc/control/workspace_grpc.pb.go index ee611a0396..25e43e9512 100644 --- a/seaweed-block/core/rpc/control/workspace_grpc.pb.go +++ b/seaweed-block/core/rpc/control/workspace_grpc.pb.go @@ -19,11 +19,13 @@ import ( const _ = grpc.SupportPackageIsVersion9 const ( - WorkspaceService_RenewWorkspaceLease_FullMethodName = "/seaweedfs.block.control.WorkspaceService/RenewWorkspaceLease" - WorkspaceService_RevokeWorkspace_FullMethodName = "/seaweedfs.block.control.WorkspaceService/RevokeWorkspace" - WorkspaceService_AckWorkspaceRevoked_FullMethodName = "/seaweedfs.block.control.WorkspaceService/AckWorkspaceRevoked" - WorkspaceService_MoveWorkspace_FullMethodName = "/seaweedfs.block.control.WorkspaceService/MoveWorkspace" - WorkspaceService_QueryWorkspace_FullMethodName = "/seaweedfs.block.control.WorkspaceService/QueryWorkspace" + WorkspaceService_RegisterWorkspaceBinding_FullMethodName = "/seaweedfs.block.control.WorkspaceService/RegisterWorkspaceBinding" + WorkspaceService_PlaceWorkspace_FullMethodName = "/seaweedfs.block.control.WorkspaceService/PlaceWorkspace" + WorkspaceService_RenewWorkspaceLease_FullMethodName = "/seaweedfs.block.control.WorkspaceService/RenewWorkspaceLease" + WorkspaceService_RevokeWorkspace_FullMethodName = "/seaweedfs.block.control.WorkspaceService/RevokeWorkspace" + WorkspaceService_AckWorkspaceRevoked_FullMethodName = "/seaweedfs.block.control.WorkspaceService/AckWorkspaceRevoked" + WorkspaceService_MoveWorkspace_FullMethodName = "/seaweedfs.block.control.WorkspaceService/MoveWorkspace" + WorkspaceService_QueryWorkspace_FullMethodName = "/seaweedfs.block.control.WorkspaceService/QueryWorkspace" ) // WorkspaceServiceClient is the client API for WorkspaceService service. @@ -32,6 +34,10 @@ const ( // // Opt-in RF=1 workspace authority protocol. Epochs are minted only by Publisher. type WorkspaceServiceClient interface { + // Register a caller-allocated per-volume pair before placement or move. + RegisterWorkspaceBinding(ctx context.Context, in *WorkspaceBinding, opts ...grpc.CallOption) (*WorkspaceBinding, error) + // Desired chosen-node intent only; this never directly mints authority. + PlaceWorkspace(ctx context.Context, in *WorkspacePlacement, opts ...grpc.CallOption) (*WorkspaceEmpty, error) RenewWorkspaceLease(ctx context.Context, in *WorkspaceIdentity, opts ...grpc.CallOption) (*WorkspaceLeaseFact, error) RevokeWorkspace(ctx context.Context, in *WorkspaceIdentity, opts ...grpc.CallOption) (*WorkspaceLeaseFact, error) AckWorkspaceRevoked(ctx context.Context, in *WorkspaceRevocationAck, opts ...grpc.CallOption) (*WorkspaceEmpty, error) @@ -47,6 +53,26 @@ func NewWorkspaceServiceClient(cc grpc.ClientConnInterface) WorkspaceServiceClie return &workspaceServiceClient{cc} } +func (c *workspaceServiceClient) RegisterWorkspaceBinding(ctx context.Context, in *WorkspaceBinding, opts ...grpc.CallOption) (*WorkspaceBinding, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(WorkspaceBinding) + err := c.cc.Invoke(ctx, WorkspaceService_RegisterWorkspaceBinding_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *workspaceServiceClient) PlaceWorkspace(ctx context.Context, in *WorkspacePlacement, opts ...grpc.CallOption) (*WorkspaceEmpty, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(WorkspaceEmpty) + err := c.cc.Invoke(ctx, WorkspaceService_PlaceWorkspace_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *workspaceServiceClient) RenewWorkspaceLease(ctx context.Context, in *WorkspaceIdentity, opts ...grpc.CallOption) (*WorkspaceLeaseFact, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(WorkspaceLeaseFact) @@ -103,6 +129,10 @@ func (c *workspaceServiceClient) QueryWorkspace(ctx context.Context, in *Workspa // // Opt-in RF=1 workspace authority protocol. Epochs are minted only by Publisher. type WorkspaceServiceServer interface { + // Register a caller-allocated per-volume pair before placement or move. + RegisterWorkspaceBinding(context.Context, *WorkspaceBinding) (*WorkspaceBinding, error) + // Desired chosen-node intent only; this never directly mints authority. + PlaceWorkspace(context.Context, *WorkspacePlacement) (*WorkspaceEmpty, error) RenewWorkspaceLease(context.Context, *WorkspaceIdentity) (*WorkspaceLeaseFact, error) RevokeWorkspace(context.Context, *WorkspaceIdentity) (*WorkspaceLeaseFact, error) AckWorkspaceRevoked(context.Context, *WorkspaceRevocationAck) (*WorkspaceEmpty, error) @@ -118,6 +148,12 @@ type WorkspaceServiceServer interface { // pointer dereference when methods are called. type UnimplementedWorkspaceServiceServer struct{} +func (UnimplementedWorkspaceServiceServer) RegisterWorkspaceBinding(context.Context, *WorkspaceBinding) (*WorkspaceBinding, error) { + return nil, status.Error(codes.Unimplemented, "method RegisterWorkspaceBinding not implemented") +} +func (UnimplementedWorkspaceServiceServer) PlaceWorkspace(context.Context, *WorkspacePlacement) (*WorkspaceEmpty, error) { + return nil, status.Error(codes.Unimplemented, "method PlaceWorkspace not implemented") +} func (UnimplementedWorkspaceServiceServer) RenewWorkspaceLease(context.Context, *WorkspaceIdentity) (*WorkspaceLeaseFact, error) { return nil, status.Error(codes.Unimplemented, "method RenewWorkspaceLease not implemented") } @@ -154,6 +190,42 @@ func RegisterWorkspaceServiceServer(s grpc.ServiceRegistrar, srv WorkspaceServic s.RegisterService(&WorkspaceService_ServiceDesc, srv) } +func _WorkspaceService_RegisterWorkspaceBinding_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(WorkspaceBinding) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WorkspaceServiceServer).RegisterWorkspaceBinding(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WorkspaceService_RegisterWorkspaceBinding_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WorkspaceServiceServer).RegisterWorkspaceBinding(ctx, req.(*WorkspaceBinding)) + } + return interceptor(ctx, in, info, handler) +} + +func _WorkspaceService_PlaceWorkspace_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(WorkspacePlacement) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WorkspaceServiceServer).PlaceWorkspace(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WorkspaceService_PlaceWorkspace_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WorkspaceServiceServer).PlaceWorkspace(ctx, req.(*WorkspacePlacement)) + } + return interceptor(ctx, in, info, handler) +} + func _WorkspaceService_RenewWorkspaceLease_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(WorkspaceIdentity) if err := dec(in); err != nil { @@ -251,6 +323,14 @@ var WorkspaceService_ServiceDesc = grpc.ServiceDesc{ ServiceName: "seaweedfs.block.control.WorkspaceService", HandlerType: (*WorkspaceServiceServer)(nil), Methods: []grpc.MethodDesc{ + { + MethodName: "RegisterWorkspaceBinding", + Handler: _WorkspaceService_RegisterWorkspaceBinding_Handler, + }, + { + MethodName: "PlaceWorkspace", + Handler: _WorkspaceService_PlaceWorkspace_Handler, + }, { MethodName: "RenewWorkspaceLease", Handler: _WorkspaceService_RenewWorkspaceLease_Handler, diff --git a/seaweed-block/core/rpc/proto/workspace.proto b/seaweed-block/core/rpc/proto/workspace.proto index d40cccf40c..0414ea99a2 100644 --- a/seaweed-block/core/rpc/proto/workspace.proto +++ b/seaweed-block/core/rpc/proto/workspace.proto @@ -4,6 +4,10 @@ option go_package = "github.com/seaweedfs/seaweed-block/core/rpc/control;control // Opt-in RF=1 workspace authority protocol. Epochs are minted only by Publisher. service WorkspaceService { + // Register a caller-allocated per-volume pair before placement or move. + rpc RegisterWorkspaceBinding(WorkspaceBinding) returns (WorkspaceBinding); + // Desired chosen-node intent only; this never directly mints authority. + rpc PlaceWorkspace(WorkspacePlacement) returns (WorkspaceEmpty); rpc RenewWorkspaceLease(WorkspaceIdentity) returns (WorkspaceLeaseFact); rpc RevokeWorkspace(WorkspaceIdentity) returns (WorkspaceLeaseFact); rpc AckWorkspaceRevoked(WorkspaceRevocationAck) returns (WorkspaceEmpty); @@ -34,4 +38,13 @@ message WorkspaceGrant { message WorkspaceStatus { WorkspaceLeaseFact lease = 1; WorkspaceRevocationAck revocation_ack = 2; repeated WorkspaceGrant moves = 3; + repeated WorkspaceBinding bindings = 4; +} +message WorkspaceBinding { + string volume_id = 1; string server_id = 2; + string data_addr = 3; string ctrl_addr = 4; + bool retired = 5; // server output only +} +message WorkspacePlacement { + string volume_id = 1; string server_id = 2; string replica_id = 3; } From a42401ef6ada6d981441d829ac6f4063672bd0cf Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 14:45:35 -0800 Subject: [PATCH 2/3] fix: close workspace binding admission and retirement schedules --- .../core/authority/observation_store.go | 17 ++ seaweed-block/core/authority/workspace.go | 22 ++ .../core/host/master/lifecycle_snapshot.go | 20 ++ .../core/host/master/product_loop.go | 59 +++- seaweed-block/core/host/master/services.go | 25 +- .../core/host/master/workspace_binding.go | 46 +-- .../master/workspace_binding_review_test.go | 279 ++++++++++++++++++ .../core/host/master/workspace_protocol.md | 14 +- .../core/host/master/workspace_service.go | 22 +- .../core/lifecycle/workspace_bindings.go | 67 ++++- .../core/lifecycle/workspace_bindings_test.go | 59 +++- 11 files changed, 586 insertions(+), 44 deletions(-) create mode 100644 seaweed-block/core/host/master/workspace_binding_review_test.go diff --git a/seaweed-block/core/authority/observation_store.go b/seaweed-block/core/authority/observation_store.go index 5ac6c1c3ab..fbf1bb65f2 100644 --- a/seaweed-block/core/authority/observation_store.go +++ b/seaweed-block/core/authority/observation_store.go @@ -130,6 +130,23 @@ func (s *ObservationStore) SlotFact(volumeID, replicaID string) (SlotFact, bool) return best, found } +// SlotFactOnServer never substitutes a same-replica claim from another host. +func (s *ObservationStore) SlotFactOnServer(serverID, volumeID, replicaID string) (SlotFact, bool) { + s.mu.Lock() + defer s.mu.Unlock() + obs, ok := s.observations[serverID] + now := s.now() + if !ok || (!obs.ExpiresAt.IsZero() && now.After(obs.ExpiresAt)) { + return SlotFact{}, false + } + for _, slot := range obs.Slots { + if slot.VolumeID == volumeID && slot.ReplicaID == replicaID && !slotExpired(slot, obs, now) && slot.DataAddr != "" && slot.CtrlAddr != "" { + return cloneSlot(slot), true + } + } + return SlotFact{}, false +} + // ReplicaIDsForVolume returns fresh, usable replica IDs currently // observed for a volume. It is a read-only evidence helper for // dynamic-lifecycle status surfaces; callers that own a static diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 4e8dac0ae4..09980dd1cd 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -132,6 +132,28 @@ func (p *Publisher) RecordWorkspacePlacement(ctx context.Context, volume string, return persist() } +// RecordWorkspaceDeletion protects reservation release against live or pending +// authority. A current clean ACK is proof of drain; a lease alone is not. +func (p *Publisher) RecordWorkspaceDeletion(ctx context.Context, volume string, pendingPlacement bool, persist func() error) error { + p.mu.Lock() + defer p.mu.Unlock() + if err := ctx.Err(); err != nil { + return err + } + s := p.workspace[volume] + if s != nil && len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued { + return fmt.Errorf("workspace delete: move pending") + } + if _, line, ok := p.workspaceLineLocked(volume); ok { + if s == nil || s.Ack == nil || s.Ack.Epoch != line.info.Epoch || s.Ack.ReplicaID != line.info.ReplicaID { + return fmt.Errorf("workspace delete: live authority requires clean revocation ACK") + } + } else if pendingPlacement { + return fmt.Errorf("workspace delete: placement may have queued authority") + } + return persist() +} + func (p *Publisher) MoveWorkspace(ctx context.Context, req WorkspaceMoveRequest, head WorkspaceHead) (WorkspaceMoveRecord, error) { if err := ctx.Err(); err != nil { return WorkspaceMoveRecord{}, err diff --git a/seaweed-block/core/host/master/lifecycle_snapshot.go b/seaweed-block/core/host/master/lifecycle_snapshot.go index b21388fb6a..96dd7ea02c 100644 --- a/seaweed-block/core/host/master/lifecycle_snapshot.go +++ b/seaweed-block/core/host/master/lifecycle_snapshot.go @@ -41,6 +41,26 @@ func (h *Host) verifyPlacements(placements []lifecycle.PlacementIntent, nodes [] } if obsStore != nil { for _, placement := range placements { + bindings, bound, err := h.lifecycle.WorkspaceBindings.Get(placement.VolumeID) + if bound || err != nil { + out := lifecycle.VerifiedPlacement{VolumeID: placement.VolumeID, Reason: lifecycle.VerifyReasonMissingObservation} + if err == nil && len(placement.Slots) == 1 { + slot := placement.Slots[0] + for _, b := range bindings { + if b.Retired || b.ServerID != slot.ServerID || b.DataAddr != slot.DataAddr || b.CtrlAddr != slot.CtrlAddr { + continue + } + fact, ok := obsStore.SlotFactOnServer(b.ServerID, placement.VolumeID, slot.ReplicaID) + if ok && fact.DataAddr == b.DataAddr && fact.CtrlAddr == b.CtrlAddr { + out.Verified = true + out.Reason = lifecycle.VerifyReasonOK + out.Slots = []lifecycle.VerifiedPlacementSlot{{ServerID: b.ServerID, ReplicaID: slot.ReplicaID, Source: slot.Source, DataAddr: b.DataAddr, CtrlAddr: b.CtrlAddr, VerifiedBy: "bound_server_observation"}} + } + } + } + verified = append(verified, out) + continue + } verified = append(verified, verifyPlacementWithObservationStore(placement, obsStore)) } return verified diff --git a/seaweed-block/core/host/master/product_loop.go b/seaweed-block/core/host/master/product_loop.go index aa67f24ae6..4b9bc82cfd 100644 --- a/seaweed-block/core/host/master/product_loop.go +++ b/seaweed-block/core/host/master/product_loop.go @@ -2,6 +2,7 @@ package master import ( "fmt" + "reflect" "strings" "github.com/seaweedfs/seaweed-block/core/authority" @@ -51,9 +52,9 @@ func (h *Host) SetPromotionEvidenceProvider(p PromotionEvidenceProvider) { // authority minter through its normal Run loop. func (h *Host) RunLifecycleProductTick() (LifecycleProductTickResult, error) { h.workspaceMu.Lock() - defer h.workspaceMu.Unlock() stores := h.Lifecycle() if stores == nil { + h.workspaceMu.Unlock() return LifecycleProductTickResult{}, nil } nodes := stores.Nodes.ListNodes() @@ -65,16 +66,29 @@ func (h *Host) RunLifecycleProductTick() (LifecycleProductTickResult, error) { VerifiedPlacements: len(verified), } h.recordPlacementVerifiedEvents(verified) + h.workspaceMu.Unlock() submitted, probeCount, blockedCount, directAsks, err := h.submitPlacementSnapshots(placements) + h.workspaceMu.Lock() + defer h.workspaceMu.Unlock() if err != nil { return result, err } + // A remote probe may have overlapped a placement/move/delete. Never use + // its captured intent after that local intent has changed. + if !reflect.DeepEqual(placements, stores.Placements.ListPlacements()) { + return result, nil + } + verified = h.verifyPlacements(placements, stores.Nodes.ListNodes()) result.PromotionProbes += probeCount result.PromotionBlocked += blockedCount if submitted { result.PublishedAsks++ } for _, ask := range directAsks { + if err := stores.WorkspaceBindings.CheckAvailable(lifecycle.WorkspaceBinding{VolumeID: ask.VolumeID, DataAddr: ask.DataAddr, CtrlAddr: ask.CtrlAddr}); err != nil { + result.SkippedUnverified++ + continue + } if h.assignmentAskAlreadyCurrent(ask.VolumeID, ask.ReplicaID, ask.DataAddr, ask.CtrlAddr) { result.SkippedCurrent++ continue @@ -97,6 +111,10 @@ func (h *Host) RunLifecycleProductTick() (LifecycleProductTickResult, error) { return result, err } for _, ask := range asks { + if err := stores.WorkspaceBindings.CheckAvailable(lifecycle.WorkspaceBinding{VolumeID: ask.VolumeID, ServerID: placement.Slots[0].ServerID, DataAddr: ask.DataAddr, CtrlAddr: ask.CtrlAddr}); err != nil { + result.SkippedUnverified++ + continue + } if h.assignmentAskAlreadyCurrent(ask.VolumeID, ask.ReplicaID, ask.DataAddr, ask.CtrlAddr) { result.SkippedCurrent++ continue @@ -111,9 +129,27 @@ func (h *Host) RunLifecycleProductTick() (LifecycleProductTickResult, error) { } func (h *Host) submitPlacementSnapshots(placements []lifecycle.PlacementIntent) (bool, int, int, []authority.AssignmentAsk, error) { + captured := placements + if h.obs == nil || h.ctrl == nil { return false, 0, 0, nil, nil } + // Explicit RF1 placements use only the server-and-pair verified direct + // path below; generic snapshots may select a different same-replica claim. + legacy := make([]lifecycle.PlacementIntent, 0, len(placements)) + for _, p := range placements { + _, bound, err := h.lifecycle.WorkspaceBindings.Get(p.VolumeID) + if err != nil { + return false, 0, 0, nil, err + } + if !bound { + legacy = append(legacy, p) + } + } + placements = legacy + if len(placements) == 0 { + return false, 0, 0, nil, nil + } topology, ok := acceptedTopologyFromPlacementIntents(placements) if !ok { return false, 0, 0, nil, nil @@ -125,6 +161,27 @@ func (h *Host) submitPlacementSnapshots(placements []lifecycle.PlacementIntent) probeCount += unsupportedProbeCount blockedCount += unsupportedBlockedCount directAsks = append(directAsks, unsupportedDirectAsks...) + // Probes above are remote. Only the final local validation and queueing + // serialize with workspace mutations, so unrelated CLEAN ACKs can proceed. + h.workspaceMu.Lock() + defer h.workspaceMu.Unlock() + if !reflect.DeepEqual(captured, h.lifecycle.Placements.ListPlacements()) { + return false, probeCount, blockedCount, nil, nil + } + for _, p := range placements { + if _, bound, err := h.lifecycle.WorkspaceBindings.Get(p.VolumeID); err != nil { + return false, probeCount, blockedCount, nil, err + } else if bound { + return false, probeCount, blockedCount, nil, nil + } + } + for _, v := range build.Snapshot.Volumes { + for _, slot := range v.Slots { + if err := h.lifecycle.WorkspaceBindings.CheckAvailable(lifecycle.WorkspaceBinding{VolumeID: v.VolumeID, DataAddr: slot.DataAddr, CtrlAddr: slot.CtrlAddr}); err != nil { + return false, probeCount, blockedCount, nil, nil + } + } + } return true, probeCount, blockedCount, directAsks, h.ctrl.SubmitObservedState(build.Snapshot, build.Report) } diff --git a/seaweed-block/core/host/master/services.go b/seaweed-block/core/host/master/services.go index 00aa74f318..8fa4cfbf49 100644 --- a/seaweed-block/core/host/master/services.go +++ b/seaweed-block/core/host/master/services.go @@ -77,6 +77,9 @@ func (s *services) CreateVolume(ctx context.Context, req *control.CreateVolumeRe func (s *services) DeleteVolume(ctx context.Context, req *control.DeleteVolumeRequest) (*control.DeleteVolumeResponse, error) { s.host.workspaceMu.Lock() defer s.host.workspaceMu.Unlock() + if err := ctx.Err(); err != nil { + return nil, workspaceError(err) + } stores := s.host.Lifecycle() if stores == nil { return nil, status.Error(codes.FailedPrecondition, "lifecycle store is not configured") @@ -84,15 +87,23 @@ func (s *services) DeleteVolume(ctx context.Context, req *control.DeleteVolumeRe if req.GetVolumeId() == "" { return nil, status.Error(codes.InvalidArgument, "volume_id is required") } - if err := stores.Placements.DeletePlacement(req.GetVolumeId()); err != nil { - return nil, lifecycleError("delete placement", err) - } - if err := stores.Volumes.DeleteVolume(req.GetVolumeId()); err != nil { - return nil, lifecycleError("delete volume", err) - } - if err := stores.WorkspaceBindings.DeleteVolume(req.GetVolumeId()); err != nil { + _, bound, err := stores.WorkspaceBindings.Get(req.GetVolumeId()) + if err != nil { return nil, lifecycleError("delete workspace bindings", err) } + _, placed := stores.Placements.GetPlacement(req.GetVolumeId()) + err = s.host.Publisher().RecordWorkspaceDeletion(ctx, req.GetVolumeId(), bound && placed, func() error { + if e := stores.Placements.DeletePlacement(req.GetVolumeId()); e != nil { + return e + } + if e := stores.Volumes.DeleteVolume(req.GetVolumeId()); e != nil { + return e + } + return stores.WorkspaceBindings.DeleteVolume(req.GetVolumeId()) + }) + if err != nil { + return nil, workspaceError(err) + } return &control.DeleteVolumeResponse{}, nil } diff --git a/seaweed-block/core/host/master/workspace_binding.go b/seaweed-block/core/host/master/workspace_binding.go index 15e22f0cc9..e8a8462834 100644 --- a/seaweed-block/core/host/master/workspace_binding.go +++ b/seaweed-block/core/host/master/workspace_binding.go @@ -28,23 +28,8 @@ func (s *services) RegisterWorkspaceBinding(ctx context.Context, q *control.Work return nil, workspaceError(fmt.Errorf("workspace binding: unknown server")) } b := lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: q.GetServerId(), DataAddr: q.GetDataAddr(), CtrlAddr: q.GetCtrlAddr(), Retired: q.GetRetired()} - // Legacy assignments also reserve their live endpoints. Merely preparing - // the first explicit target must not make the old source pair reusable. - for _, v := range s.host.lifecycle.Volumes.ListVolumes() { - if v.Spec.VolumeID == b.VolumeID { - continue - } - line, ok := s.host.Publisher().VolumeAuthorityLine(v.Spec.VolumeID) - if !ok { - continue - } - state := s.host.Publisher().WorkspaceState(v.Spec.VolumeID) - if state != nil && state.Ack != nil && state.Ack.Epoch == line.Epoch { - continue - } - if b.EndpointsOverlap(lifecycle.WorkspaceBinding{DataAddr: line.DataAddr, CtrlAddr: line.CtrlAddr}) { - return nil, workspaceError(fmt.Errorf("workspace binding: endpoint belongs to live assignment")) - } + if err := s.host.workspaceEndpointsAvailable(b); err != nil { + return nil, workspaceError(err) } if err := s.host.lifecycle.WorkspaceBindings.Register(b); err != nil { return nil, workspaceError(err) @@ -52,6 +37,33 @@ func (s *services) RegisterWorkspaceBinding(ctx context.Context, q *control.Work return bindingFact(b), nil } +// Caller holds workspaceMu through the subsequent local commit. Check both +// prepared reservations and live legacy lines, including this volume's source. +func (h *Host) workspaceEndpointsAvailable(b lifecycle.WorkspaceBinding) error { + if err := h.lifecycle.WorkspaceBindings.CheckAvailable(b); err != nil { + return err + } + // Legacy assignments also reserve their live endpoints. Merely preparing + // the first explicit target must not make the old source pair reusable. + for _, v := range h.lifecycle.Volumes.ListVolumes() { + line, ok := h.Publisher().VolumeAuthorityLine(v.Spec.VolumeID) + if !ok { + continue + } + state := h.Publisher().WorkspaceState(v.Spec.VolumeID) + if state != nil && state.Ack != nil && state.Ack.Epoch == line.Epoch { + continue + } + if b.EndpointsOverlap(lifecycle.WorkspaceBinding{DataAddr: line.DataAddr, CtrlAddr: line.CtrlAddr}) { + if b.VolumeID == v.Spec.VolumeID && h.workspaceSourceHost(b.VolumeID, line.ReplicaID, line.Epoch) == b.ServerID && b.DataAddr == line.DataAddr && b.CtrlAddr == line.CtrlAddr { + continue + } + return fmt.Errorf("workspace binding: endpoint belongs to live assignment") + } + } + return nil +} + func (h *Host) workspaceSourceHost(volume, replica string, epoch uint64) string { if state := h.Publisher().WorkspaceState(volume); state != nil { for _, r := range state.Moves { diff --git a/seaweed-block/core/host/master/workspace_binding_review_test.go b/seaweed-block/core/host/master/workspace_binding_review_test.go new file mode 100644 index 0000000000..1d6dcaa226 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_binding_review_test.go @@ -0,0 +1,279 @@ +package master + +import ( + "context" + "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" +) + +func reviewBindingHost(t *testing.T) (*Host, *grpc.ClientConn, context.Context) { + t.Helper() + return reviewBindingHostWithReader(t, func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil + }) +} + +func reviewBindingHostWithReader(t *testing.T, reader func(context.Context, string) (authority.WorkspaceHead, error)) (*Host, *grpc.ClientConn, context.Context) { + t.Helper() + h, e := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: reader}) + if e != nil { + t.Fatal(e) + } + h.Start() + t.Cleanup(func() { closeTestMaster(t, h) }) + c, e := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if e != nil { + t.Fatal(e) + } + t.Cleanup(func() { c.Close() }) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + t.Cleanup(cancel) + for _, server := range []string{"node-a", "node-b"} { + if _, e = h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: server, DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); e != nil { + t.Fatal(e) + } + } + return h, c, ctx +} + +func reviewLegacyBind(t *testing.T, h *Host, c *grpc.ClientConn, ctx context.Context, vol string) { + t.Helper() + reviewCreate(t, c, ctx, vol) + if _, e := h.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: vol, DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{{VolumeID: vol, ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); e != nil { + t.Fatal(e) + } + reviewHeartbeat(t, c, ctx, vol, "node-a", "127.0.0.1:10000", "127.0.0.1:10001") + if _, e := h.RunLifecycleProductTick(); e != nil { + t.Fatal(e) + } + if line := waitAuthorityLine(t, h.Publisher(), vol); line.Epoch != 1 { + t.Fatal(line) + } +} + +func TestWorkspaceBindingLegacyUpgradeCannotTakeOwnLiveSource(t *testing.T) { + h, c, ctx := reviewBindingHost(t) + reviewLegacyBind(t, h, c, ctx, "legacy") + client := control.NewWorkspaceServiceClient(c) + if _, e := client.RegisterWorkspaceBinding(ctx, &control.WorkspaceBinding{VolumeId: "legacy", ServerId: "node-b", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"}); e == nil { + t.Fatal("first target registration took own live source pair") + } + if _, e := client.RegisterWorkspaceBinding(ctx, &control.WorkspaceBinding{VolumeId: "legacy", ServerId: "node-a", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"}); e != nil { + t.Fatal("exact source-owner registration refused", e) + } +} + +func TestWorkspaceBindingLegacyMoveCannotTakePreparedReservation(t *testing.T) { + h, c, ctx := reviewBindingHost(t) + reviewLegacyBind(t, h, c, ctx, "legacy") + reviewCreate(t, c, ctx, "prepared") + client := control.NewWorkspaceServiceClient(c) + if _, e := client.RegisterWorkspaceBinding(ctx, &control.WorkspaceBinding{VolumeId: "prepared", ServerId: "node-b", DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); e != nil { + t.Fatal(e) + } + id := &control.WorkspaceIdentity{VolumeId: "legacy", ReplicaId: "r1", Epoch: 1} + if _, e := client.RenewWorkspaceLease(ctx, id); e != nil { + t.Fatal(e) + } + if _, e := client.RevokeWorkspace(ctx, id); e != nil { + t.Fatal(e) + } + if _, e := client.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); e != nil { + t.Fatal(e) + } + if _, e := client.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "legacy-move", VolumeId: "legacy", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:9200", TargetCtrlAddr: "127.0.0.1:9100", Kind: "clean"}); e == nil { + t.Fatal("legacy move took another volume's prepared reservation") + } + if line, _ := h.Publisher().VolumeAuthorityLine("legacy"); line.Epoch != 1 { + t.Fatal("refused move changed authority", line) + } +} + +func TestWorkspaceBindingDeleteCannotReleaseLiveAuthority(t *testing.T) { + h, c, ctx := reviewBindingHost(t) + reviewLegacyBind(t, h, c, ctx, "live") + client := control.NewWorkspaceServiceClient(c) + b := &control.WorkspaceBinding{VolumeId: "live", ServerId: "node-a", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"} + if _, e := client.RegisterWorkspaceBinding(ctx, b); e != nil { + t.Fatal(e) + } + if _, e := client.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "live", ReplicaId: "r1", Epoch: 1}); e != nil { + t.Fatal(e) + } + if _, e := control.NewLifecycleServiceClient(c).DeleteVolume(ctx, &control.DeleteVolumeRequest{VolumeId: "live"}); e == nil { + t.Fatal("delete released a live authority's reservation") + } + if _, ok := h.Lifecycle().Volumes.GetVolume("live"); !ok { + t.Fatal("refused deletion removed lifecycle state") + } + if _, bound, e := h.Lifecycle().WorkspaceBindings.Get("live"); e != nil || !bound { + t.Fatal("refused deletion removed binding", bound, e) + } +} + +func TestWorkspaceBindingCanceledQueuedDeleteDoesNotMutate(t *testing.T) { + h, c, ctx := reviewBindingHost(t) + reviewCreate(t, c, ctx, "queued") + if _, e := control.NewWorkspaceServiceClient(c).RegisterWorkspaceBinding(ctx, &control.WorkspaceBinding{VolumeId: "queued", ServerId: "node-a", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"}); e != nil { + t.Fatal(e) + } + canceled, cancel := context.WithCancel(ctx) + h.workspaceMu.Lock() + arrived := make(chan struct{}) + done := make(chan error, 1) + go func() { + close(arrived) + _, e := newServices(h).DeleteVolume(canceled, &control.DeleteVolumeRequest{VolumeId: "queued"}) + done <- e + }() + <-arrived + cancel() + h.workspaceMu.Unlock() + select { + case e := <-done: + if e == nil { + t.Error("canceled queued delete succeeded") + } + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + if _, ok := h.Lifecycle().Volumes.GetVolume("queued"); !ok { + t.Fatal("canceled queued delete removed lifecycle state") + } + if _, bound, e := h.Lifecycle().WorkspaceBindings.Get("queued"); e != nil || !bound { + t.Fatal("canceled queued delete removed binding", bound, e) + } +} + +func reviewCreate(t *testing.T, c *grpc.ClientConn, ctx context.Context, vol string) { + t.Helper() + if _, e := control.NewLifecycleServiceClient(c).CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: vol, SizeBytes: 1 << 20, ReplicationFactor: 1}); e != nil { + t.Fatal(e) + } +} + +func reviewHeartbeat(t *testing.T, c *grpc.ClientConn, ctx context.Context, vol, server, data, ctrl string) { + t.Helper() + if _, e := control.NewObservationServiceClient(c).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: server, SentAt: timestamppb.Now(), Reachable: true, Eligible: true, Slots: []*control.HeartbeatSlot{{VolumeId: vol, ReplicaId: "r1", DataAddr: data, CtrlAddr: ctrl}}}); e != nil { + t.Fatal(e) + } +} + +func TestWorkspaceBindingChosenObservationMustMatchServerAndPair(t *testing.T) { + for _, wrong := range []string{"server", "pair"} { + t.Run(wrong, func(t *testing.T) { + h, c, ctx := reviewBindingHost(t) + reviewCreate(t, c, ctx, "v") + client := control.NewWorkspaceServiceClient(c) + b := &control.WorkspaceBinding{VolumeId: "v", ServerId: "node-a", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"} + if _, e := client.RegisterWorkspaceBinding(ctx, b); e != nil { + t.Fatal(e) + } + if _, e := client.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "v", ServerId: "node-a", ReplicaId: "r1"}); e != nil { + t.Fatal(e) + } + server, data, ctrl := "node-a", b.DataAddr, b.CtrlAddr + if wrong == "server" { + server = "node-b" + } else { + data = "127.0.0.1:10002" + } + reviewHeartbeat(t, c, ctx, "v", server, data, ctrl) + result, e := h.RunLifecycleProductTick() + if e != nil { + t.Fatal(e) + } + if result.PublishedAsks != 0 { + t.Fatalf("wrong %s observation submitted assignment: %+v", wrong, result) + } + if _, ok := h.Publisher().VolumeAuthorityLine("v"); ok { + t.Fatal("wrong observation minted authority") + } + reviewHeartbeat(t, c, ctx, "v", "node-a", b.DataAddr, b.CtrlAddr) + if _, e = h.RunLifecycleProductTick(); e != nil { + t.Fatal(e) + } + line := waitAuthorityLine(t, h.Publisher(), "v") + if line.DataAddr != b.DataAddr || line.CtrlAddr != b.CtrlAddr { + t.Fatal("correct observation published wrong pair", line) + } + }) + } +} + +// The ACK must complete while the unrelated remote reader/prober remains held. +func TestWorkspaceBindingRemoteReadDoesNotBlockAck(t *testing.T) { + for _, mode := range []string{"head", "promotion"} { + t.Run(mode, func(t *testing.T) { + arrived, release := make(chan struct{}), make(chan struct{}) + h, c, ctx := reviewBindingHostWithReader(t, func(ctx context.Context, vol string) (authority.WorkspaceHead, error) { + close(arrived) + select { + case <-release: + case <-ctx.Done(): + return authority.WorkspaceHead{}, ctx.Err() + } + return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", Detached: true}, nil + }) + reviewLegacyBind(t, h, c, ctx, "ack") + client := control.NewWorkspaceServiceClient(c) + id := &control.WorkspaceIdentity{VolumeId: "ack", ReplicaId: "r1", Epoch: 1} + if _, e := client.RenewWorkspaceLease(ctx, id); e != nil { + t.Fatal(e) + } + if _, e := client.RevokeWorkspace(ctx, id); e != nil { + t.Fatal(e) + } + done := make(chan error, 1) + if mode == "head" { + reviewLegacyBind(t, h, c, ctx, "probe") + go func() { + _, e := client.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "held", VolumeId: "probe", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:9200", TargetCtrlAddr: "127.0.0.1:9100", Kind: "clean"}) + done <- e + }() + } else { + seedRF3Placement(t, h) + ingestRF3Observation(t, h, true, true, true) + if _, e := h.RunLifecycleProductTick(); e != nil { + t.Fatal(e) + } + waitAuthorityLine(t, h.Publisher(), "vol-rf3") + ingestRF3Observation(t, h, false, true, true) + h.SetPromotionEvidenceProvider(reviewHeldPromotion{arrived, release}) + go func() { _, e := h.RunLifecycleProductTick(); done <- e }() + } + select { + case <-arrived: + case <-ctx.Done(): + t.Fatal("remote call not reached", ctx.Err()) + } + ackCtx, cancel := context.WithTimeout(ctx, time.Second) + _, e := client.AckWorkspaceRevoked(ackCtx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}) + cancel() + close(release) + select { + case <-done: + case <-ctx.Done(): + t.Fatal("remote operation did not finish", ctx.Err()) + } + if e != nil { + t.Fatal("held remote operation blocked ACK", e) + } + }) + } +} + +type reviewHeldPromotion struct{ arrived, release chan struct{} } + +func (p reviewHeldPromotion) ProbePromotionCandidates(string, authority.AuthorityBasis, []authority.ReplicaCandidate) (PromotionProbeResult, error) { + close(p.arrived) + <-p.release + return PromotionProbeResult{}, nil +} diff --git a/seaweed-block/core/host/master/workspace_protocol.md b/seaweed-block/core/host/master/workspace_protocol.md index d203060234..b503342617 100644 --- a/seaweed-block/core/host/master/workspace_protocol.md +++ b/seaweed-block/core/host/master/workspace_protocol.md @@ -32,16 +32,22 @@ binding only after its durable clean ACK. FORCED retires it only after the new epoch is issued. Retirement carries the old epoch, making crash recovery and old-request replay harmless to a later re-prepared binding. Registration may reuse retired ports; a live target must be prepared again before another move. -Volume deletion removes its binding marker and reservations after deleting -lifecycle state. Failed deletion can be retried. +Volume deletion removes its binding marker and reservations only after a clean +revocation ACK for current authority. Pending moves and queued unassigned explicit +placement refuse deletion. Canceled queued deletes do not mutate state. Failed +deletion can be retried. Retirement watermarks are retained even before the first +explicit binding, without switching a legacy volume to explicit mode. -Bindings are a file-synced, atomic snapshot with directory fsync. Ambiguous +Bindings are a file-synced, atomic snapshot with directory fsync. Opening the +store also syncs its parent after directory creation, before admitting writes. Ambiguous publication errors fence binding reads/mutations until restart. Startup and registration reconcile retirement from persisted ACK/issued move records, so a crash between authority persistence and binding retirement is recoverable. `QueryWorkspace` returns the per-volume bindings including their retired state. -Host workspace operations and product ticks serialize with `workspaceMu`. +Host workspace mutations serialize with `workspaceMu`. Remote HEAD reads and +promotion probes run outside it; local intent, binding and reservation checks are +repeated under the lock before queueing or committing their results. Lock order is host workspace mutex, then Publisher or lifecycle-store locks. Initial placement persists under a Publisher unassigned guard; its callback must never call Publisher. Store reads do not hold their mutex while calling diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index a34685e1ad..f8f977ccf7 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -5,6 +5,7 @@ import ( "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/codes" "google.golang.org/grpc/status" @@ -97,8 +98,23 @@ func grantFact(r authority.WorkspaceMoveRecord) *control.WorkspaceGrant { } func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) (*control.WorkspaceGrant, error) { + if err := s.workspaceVolume(q.GetVolumeId()); err != nil { + return nil, err + } + // Always bound the configured reader, even when the caller omitted a deadline. + readCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + head, err := s.host.cfg.WorkspaceHeadReader(readCtx, q.GetVolumeId()) + if err != nil { + return nil, workspaceError(err) + } + // Remote reads never hold the workspace mutation lock. Re-read every + // local precondition below; Publisher checks the expected epoch atomically. s.host.workspaceMu.Lock() defer s.host.workspaceMu.Unlock() + if err := ctx.Err(); err != nil { + return nil, workspaceError(err) + } if err := s.workspaceVolume(q.GetVolumeId()); err != nil { return nil, err } @@ -117,11 +133,7 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) if oldHost == "" || !ok || target.ServerID == oldHost || !matched { return nil, status.Error(codes.FailedPrecondition, "move needs known source slot and registered target endpoints") } - // Always bound the configured reader, even when the caller omitted a deadline. - readCtx, cancel := context.WithTimeout(ctx, 5*time.Second) - defer cancel() - head, err := s.host.cfg.WorkspaceHeadReader(readCtx, q.GetVolumeId()) - if err != nil { + 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) } r, err := s.host.Publisher().MoveWorkspace(ctx, authority.WorkspaceMoveRequest{RequestID: q.GetRequestId(), VolumeID: q.GetVolumeId(), ExpectedReplicaID: q.GetExpectedReplicaId(), ExpectedHost: oldHost, TargetHost: target.ServerID, diff --git a/seaweed-block/core/lifecycle/workspace_bindings.go b/seaweed-block/core/lifecycle/workspace_bindings.go index 52b6bd2914..5d51a472ba 100644 --- a/seaweed-block/core/lifecycle/workspace_bindings.go +++ b/seaweed-block/core/lifecycle/workspace_bindings.go @@ -16,12 +16,13 @@ import ( // Retired entries remain as a per-volume marker: explicit volumes never fall // back to node-level addresses, even after all their bindings are retired. type WorkspaceBinding struct { - VolumeID string `json:"volume_id"` - ServerID string `json:"server_id"` - DataAddr string `json:"data_addr"` - CtrlAddr string `json:"ctrl_addr"` - Retired bool `json:"retired,omitempty"` - RetiredEpoch uint64 `json:"retired_epoch,omitempty"` // idempotent authority retirement event + VolumeID string `json:"volume_id"` + ServerID string `json:"server_id"` + DataAddr string `json:"data_addr"` + CtrlAddr string `json:"ctrl_addr"` + Retired bool `json:"retired,omitempty"` + RetiredEpoch uint64 `json:"retired_epoch,omitempty"` // idempotent authority retirement event + RetirementOnly bool `json:"retirement_only,omitempty"` // history before first explicit preparation } type WorkspaceBindingStore struct { @@ -32,9 +33,26 @@ type WorkspaceBindingStore struct { } func OpenWorkspaceBindingStore(dir string) (*WorkspaceBindingStore, error) { + return openWorkspaceBindingStore(dir, syncBindingParent) +} + +func syncBindingParent(dir string) error { + f, err := os.Open(dir) + if err != nil { + return err + } + defer f.Close() + return f.Sync() +} + +func openWorkspaceBindingStore(dir string, syncParent func(string) error) (*WorkspaceBindingStore, error) { if err := os.MkdirAll(dir, 0755); err != nil { return nil, err } + // Persist the directory entry before any binding can be acknowledged. + if err := syncParent(filepath.Dir(dir)); err != nil { + return nil, err + } s := &WorkspaceBindingStore{dir: dir, records: map[string][]WorkspaceBinding{}} b, err := os.ReadFile(filepath.Join(dir, "bindings.json")) if os.IsNotExist(err) { @@ -59,6 +77,15 @@ func OpenWorkspaceBindingStore(dir string) (*WorkspaceBindingStore, error) { return nil, fmt.Errorf("workspace bindings: inconsistent record") } seen[r.ServerID] = true + if r.RetirementOnly { + if !r.Retired || r.RetiredEpoch == 0 || r.DataAddr != "" || r.CtrlAddr != "" { + return nil, fmt.Errorf("workspace bindings: invalid retirement watermark") + } + if err = validateServerID(r.ServerID); err != nil { + return nil, err + } + continue + } if err = validateWorkspaceBinding(r); err != nil { return nil, err } @@ -136,8 +163,22 @@ func (s *WorkspaceBindingStore) Get(volume string) ([]WorkspaceBinding, bool, er if s.uncertain { return nil, false, fmt.Errorf("workspace bindings uncertain; restart required") } - list, ok := s.records[volume] - return append([]WorkspaceBinding(nil), list...), ok, nil + var list []WorkspaceBinding + for _, b := range s.records[volume] { + if !b.RetirementOnly { + list = append(list, b) + } + } + return list, len(list) > 0, nil +} + +func (s *WorkspaceBindingStore) CheckAvailable(b WorkspaceBinding) error { + s.mu.Lock() + defer s.mu.Unlock() + if s.uncertain { + return fmt.Errorf("workspace bindings uncertain; restart required") + } + return bindingCollision(s.records, b) } func (s *WorkspaceBindingStore) Register(b WorkspaceBinding) error { @@ -173,12 +214,20 @@ func (s *WorkspaceBindingStore) Register(b WorkspaceBinding) error { func (s *WorkspaceBindingStore) Retire(volume, server string, epoch uint64) error { return s.update(func(all map[string][]WorkspaceBinding) error { + found := false for i := range all[volume] { - if all[volume][i].ServerID == server && epoch > all[volume][i].RetiredEpoch { + if all[volume][i].ServerID != server { + continue + } + found = true + if epoch > all[volume][i].RetiredEpoch { all[volume][i].Retired = true all[volume][i].RetiredEpoch = epoch } } + if !found { + all[volume] = append(all[volume], WorkspaceBinding{VolumeID: volume, ServerID: server, Retired: true, RetiredEpoch: epoch, RetirementOnly: true}) + } return nil }) } diff --git a/seaweed-block/core/lifecycle/workspace_bindings_test.go b/seaweed-block/core/lifecycle/workspace_bindings_test.go index 65292a5a48..31bb66e78d 100644 --- a/seaweed-block/core/lifecycle/workspace_bindings_test.go +++ b/seaweed-block/core/lifecycle/workspace_bindings_test.go @@ -1,6 +1,40 @@ package lifecycle -import "testing" +import ( + "errors" + "os" + "path/filepath" + "testing" +) + +func TestWorkspaceBindingAbsentRetirementKeepsWatermark(t *testing.T) { + dir := t.TempDir() + s, e := OpenWorkspaceBindingStore(dir) + if e != nil { + t.Fatal(e) + } + if e = s.Retire("v", "old", 3); e != nil { + t.Fatal(e) + } + if _, bound, e := s.Get("v"); e != nil || bound { + t.Fatal("retirement-only history entered explicit binding mode", bound, e) + } + b := WorkspaceBinding{VolumeID: "v", ServerID: "old", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"} + if e = s.Register(b); e != nil { + t.Fatal(e) + } + s, e = OpenWorkspaceBindingStore(dir) + if e != nil { + t.Fatal(e) + } + if e = s.Retire("v", "old", 3); e != nil { + t.Fatal(e) + } + list, bound, e := s.Get("v") + if e != nil || !bound || len(list) != 1 || list[0].Retired { + t.Fatal("absent retirement lost watermark and retired new target", list, bound, e) + } +} func TestWorkspaceBindingRetirementReplayDoesNotRetireRepreparedTarget(t *testing.T) { dir := t.TempDir() @@ -41,3 +75,26 @@ func TestWorkspaceBindingRetirementReplayDoesNotRetireRepreparedTarget(t *testin t.Fatal(list, e) } } + +func TestWorkspaceBindingParentSyncBeforeOpen(t *testing.T) { + parent := t.TempDir() + dir := filepath.Join(parent, "bindings") + injected := errors.New("parent sync failed") + called := false + s, e := openWorkspaceBindingStore(dir, func(got string) error { + called = true + if got != parent { + t.Errorf("sync %q want %q", got, parent) + } + if _, e := os.Stat(dir); e != nil { + t.Error("directory must exist before parent sync", e) + } + return injected + }) + if !called || !errors.Is(e, injected) || s != nil { + t.Fatalf("open acknowledged unsynced parent: called=%v store=%v err=%v", called, s, e) + } + if _, e = OpenWorkspaceBindingStore(dir); e != nil { + t.Fatal("real parent sync positive", e) + } +} From 28e8b293d31e43b77273d1ab97b2bcd5e21c8673 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 15:07:19 -0800 Subject: [PATCH 3/3] fix: validate workspace ownership through authority publication --- seaweed-block/core/authority/authority.go | 15 ++- .../core/host/bootstrap/bootstrap.go | 4 +- seaweed-block/core/host/master/host.go | 3 +- .../core/host/master/product_loop_test.go | 16 +++ .../core/host/master/workspace_binding.go | 48 +++++++ .../master/workspace_binding_review_test.go | 122 ++++++++++++++++++ .../core/host/master/workspace_protocol.md | 10 +- 7 files changed, 214 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index cdf988bbbe..f14d05376b 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -152,7 +152,8 @@ type Publisher struct { // behaves as "never bound" until a new mint. loadErrs []error - observer PublishObserver + observer PublishObserver + publicationAdmission PublicationAdmission // Workspace state is serialized with assignment minting under mu. Remote // HEAD reads and subscriber delivery never run under this lock. @@ -163,6 +164,15 @@ type Publisher struct { workspaceLeaseDeadline map[string]time.Time } +// PublicationAdmission surrounds an ordinary mint with local ownership/lifetime +// admission. It must call publish synchronously, at most once, and must not do +// remote I/O. Configure only before Run. Guarded moves already own host admission. +type PublicationAdmission func(AssignmentAsk, func() error) error + +func WithPublicationAdmission(admit PublicationAdmission) PublisherOption { + return func(p *Publisher) { p.publicationAdmission = admit } +} + // PublisherOption configures a Publisher at construction. // Currently the only option is WithStore, but the variadic // shape is chosen so later slices can add options without @@ -416,6 +426,9 @@ func (p *Publisher) closeAllSubscriptions() { // non-zero Epoch. The structural non-forgeability test in // authority_test.go enforces this boundary at repo scope. func (p *Publisher) apply(ask AssignmentAsk) error { + if p.publicationAdmission != nil { + return p.publicationAdmission(ask, func() error { return p.applyWithWorkspaceMove(ask, nil) }) + } return p.applyWithWorkspaceMove(ask, nil) } diff --git a/seaweed-block/core/host/bootstrap/bootstrap.go b/seaweed-block/core/host/bootstrap/bootstrap.go index 2b6bf2c4a8..19e6a32dcb 100644 --- a/seaweed-block/core/host/bootstrap/bootstrap.go +++ b/seaweed-block/core/host/bootstrap/bootstrap.go @@ -43,7 +43,8 @@ type DurableAuthorityBootstrap struct { // Options customizes durable-authority bootstrap wiring. type Options struct { - PublishObserver authority.PublishObserver + PublishObserver authority.PublishObserver + PublicationAdmission authority.PublicationAdmission } // Bootstrap performs the durable-authority startup sequence and @@ -116,6 +117,7 @@ func bootstrapFromStoreLocked(storeDir string, lock *authority.StoreLock, store if opts.PublishObserver != nil { pubOpts = append(pubOpts, authority.WithPublishObserver(opts.PublishObserver)) } + pubOpts = append(pubOpts, authority.WithPublicationAdmission(opts.PublicationAdmission)) pub := authority.NewPublisher(directive, pubOpts...) // Publisher's LoadErrors is the canonical source; prefer it diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index 91c4da613a..a829f0a713 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -206,7 +206,8 @@ func New(cfg Config) (*Host, error) { } boot, err := bootstrap.BootstrapWithOptions(cfg.AuthorityStoreDir, ctrl, bootstrap.Options{ - PublishObserver: h.recordAuthorityPublishedEvent, + PublishObserver: h.recordAuthorityPublishedEvent, + PublicationAdmission: h.admitWorkspacePublication, }) if err != nil { return nil, fmt.Errorf("master.New: Bootstrap: %w", err) diff --git a/seaweed-block/core/host/master/product_loop_test.go b/seaweed-block/core/host/master/product_loop_test.go index 0b76bf1973..b8d9cbeed9 100644 --- a/seaweed-block/core/host/master/product_loop_test.go +++ b/seaweed-block/core/host/master/product_loop_test.go @@ -730,6 +730,7 @@ func TestG15c_ProductLoopReconcilesCreatedVolumeBeforePublishing(t *testing.T) { } func seedVerifiedExistingReplicaPlacement(t *testing.T, h *Host) { + ensureProductVolume(t, h, "vol-a", 1) t.Helper() stores := h.Lifecycle() if _, err := stores.Placements.ApplyPlan(lifecycle.PlacementPlan{ @@ -774,6 +775,7 @@ func seedRF2PlacementFor(t *testing.T, h *Host, volumeID string) { } func seedRF2PlacementForServers(t *testing.T, h *Host, volumeID, r1ServerID, r2ServerID string) { + ensureProductVolume(t, h, volumeID, 2) t.Helper() stores := h.Lifecycle() if _, err := stores.Placements.ApplyPlan(lifecycle.PlacementPlan{ @@ -855,6 +857,7 @@ func ingestRF2ObservationForServers(t *testing.T, h *Host, volumeID, r1ServerID, } func seedRF3PlacementForServers(t *testing.T, h *Host, volumeID, r1ServerID, r2ServerID, r3ServerID string) { + ensureProductVolume(t, h, volumeID, 3) t.Helper() stores := h.Lifecycle() if _, err := stores.Placements.ApplyPlan(lifecycle.PlacementPlan{ @@ -871,6 +874,7 @@ func seedRF3PlacementForServers(t *testing.T, h *Host, volumeID, r1ServerID, r2S } func seedRF3PlacementForServersWithAddrs(t *testing.T, h *Host, volumeID, r1ServerID, r2ServerID, r3ServerID string) { + ensureProductVolume(t, h, volumeID, 3) t.Helper() stores := h.Lifecycle() if _, err := stores.Placements.ApplyPlan(lifecycle.PlacementPlan{ @@ -994,3 +998,15 @@ func recvAssignmentInfo(t *testing.T, ch <-chan adapter.AssignmentInfo) adapter. return adapter.AssignmentInfo{} } } + +// Placement fixtures represent live lifecycle volumes, just as production +// CreateVolume/ReconcilePlacement do before asking Publisher to mint authority. +func ensureProductVolume(t *testing.T, h *Host, volume string, rf int) { + t.Helper() + if _, ok := h.Lifecycle().Volumes.GetVolume(volume); ok { + return + } + if _, err := h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: volume, SizeBytes: 1 << 20, ReplicationFactor: rf}); err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/core/host/master/workspace_binding.go b/seaweed-block/core/host/master/workspace_binding.go index e8a8462834..10bc3e57a8 100644 --- a/seaweed-block/core/host/master/workspace_binding.go +++ b/seaweed-block/core/host/master/workspace_binding.go @@ -4,6 +4,7 @@ import ( "context" "fmt" + "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/lifecycle" control "github.com/seaweedfs/seaweed-block/core/rpc/control" ) @@ -150,3 +151,50 @@ func (s *services) PlaceWorkspace(ctx context.Context, q *control.WorkspacePlace } return &control.WorkspaceEmpty{}, nil } + +// admitWorkspacePublication owns the last local boundary before an ordinary +// Publisher mint. Guarded Move already owns workspaceMu in its RPC path. +func (h *Host) admitWorkspacePublication(ask authority.AssignmentAsk, publish func() error) error { + if h.lifecycle == nil { + return publish() + } + h.workspaceMu.Lock() + defer h.workspaceMu.Unlock() + if _, alive := h.lifecycle.Volumes.GetVolume(ask.VolumeID); !alive { + return fmt.Errorf("workspace publication: volume no longer exists") + } + bindings, bound, err := h.lifecycle.WorkspaceBindings.Get(ask.VolumeID) + if err != nil { + return err + } + var epoch uint64 + if line, ok := h.Publisher().VolumeAuthorityLine(ask.VolumeID); ok { + epoch = line.Epoch + } + server := h.workspaceSourceHost(ask.VolumeID, ask.ReplicaID, epoch) + b := lifecycle.WorkspaceBinding{VolumeID: ask.VolumeID, ServerID: server, DataAddr: ask.DataAddr, CtrlAddr: ask.CtrlAddr} + if bound { + matched := false + for _, r := range bindings { + if !r.Retired && r.ServerID == server && r.DataAddr == ask.DataAddr && r.CtrlAddr == ask.CtrlAddr { + matched = true + break + } + } + if !matched { + return fmt.Errorf("workspace publication: no matching active binding") + } + } + if err := h.lifecycle.WorkspaceBindings.CheckAvailable(b); err != nil { + return err + } + // A supported snapshot and its direct promotion fallback may both be + // dequeued before either commits. Apply the product loop's existing + // already-current check again here, rather than advancing the epoch twice. + if ask.Intent == authority.IntentReassign && h.assignmentAskAlreadyCurrent(ask.VolumeID, ask.ReplicaID, ask.DataAddr, ask.CtrlAddr) { + return nil + } + // The same mutex covers Register/Delete. It stays held through the actual + // Publisher persistence and in-memory commit, not just queue admission. + return publish() +} diff --git a/seaweed-block/core/host/master/workspace_binding_review_test.go b/seaweed-block/core/host/master/workspace_binding_review_test.go index 1d6dcaa226..7a1fabe73e 100644 --- a/seaweed-block/core/host/master/workspace_binding_review_test.go +++ b/seaweed-block/core/host/master/workspace_binding_review_test.go @@ -21,11 +21,19 @@ func reviewBindingHost(t *testing.T) (*Host, *grpc.ClientConn, context.Context) } func reviewBindingHostWithReader(t *testing.T, reader func(context.Context, string) (authority.WorkspaceHead, error)) (*Host, *grpc.ClientConn, context.Context) { + t.Helper() + return reviewBindingHostBeforeStart(t, reader, nil) +} + +func reviewBindingHostBeforeStart(t *testing.T, reader func(context.Context, string) (authority.WorkspaceHead, error), before func(*Host)) (*Host, *grpc.ClientConn, context.Context) { t.Helper() h, e := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: reader}) if e != nil { t.Fatal(e) } + if before != nil { + before(h) + } h.Start() t.Cleanup(func() { closeTestMaster(t, h) }) c, e := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) @@ -116,6 +124,23 @@ func TestWorkspaceBindingDeleteCannotReleaseLiveAuthority(t *testing.T) { if _, bound, e := h.Lifecycle().WorkspaceBindings.Get("live"); e != nil || !bound { t.Fatal("refused deletion removed binding", bound, e) } + id := &control.WorkspaceIdentity{VolumeId: "live", ReplicaId: "r1", Epoch: 1} + if _, e := client.RevokeWorkspace(ctx, id); e != nil { + t.Fatal(e) + } + if _, e := client.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); e != nil { + t.Fatal(e) + } + if _, e := control.NewLifecycleServiceClient(c).DeleteVolume(ctx, &control.DeleteVolumeRequest{VolumeId: "live"}); e != nil { + t.Fatal("clean retired deletion positive", e) + } + reviewCreate(t, c, ctx, "reuse") + b.VolumeId = "reuse" + b.ServerId = "node-b" + if _, e := client.RegisterWorkspaceBinding(ctx, b); e != nil { + t.Fatal("retired pair not reusable after clean delete", e) + } + } func TestWorkspaceBindingCanceledQueuedDeleteDoesNotMutate(t *testing.T) { @@ -239,6 +264,9 @@ func TestWorkspaceBindingRemoteReadDoesNotBlockAck(t *testing.T) { done <- e }() } else { + if _, e := h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: "vol-rf3", SizeBytes: 1 << 20, ReplicationFactor: 3}); e != nil { + t.Fatal(e) + } seedRF3Placement(t, h) ingestRF3Observation(t, h, true, true, true) if _, e := h.RunLifecycleProductTick(); e != nil { @@ -277,3 +305,97 @@ func (p reviewHeldPromotion) ProbePromotionCandidates(string, authority.Authorit <-p.release return PromotionProbeResult{}, nil } + +// The real controller dequeues the admitted ask, then its Publisher is held +// before the production admission/mint boundary. Queue discard cannot pass this. +func TestWorkspaceBindingInFlightPublicationRechecksOwnershipAndLifetime(t *testing.T) { + for _, action := range []string{"register", "delete"} { + t.Run(action, func(t *testing.T) { + arrived, release := make(chan struct{}), make(chan struct{}) + finished := make(chan error, 1) + h, c, ctx := reviewBindingHostBeforeStart(t, func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }, func(h *Host) { + authority.WithPublicationAdmission(func(ask authority.AssignmentAsk, publish func() error) error { + if ask.VolumeID == "inflight" { + close(arrived) + select { + case <-release: + case <-time.After(5 * time.Second): + return context.DeadlineExceeded + } + } + err := h.admitWorkspacePublication(ask, publish) + if ask.VolumeID == "inflight" { + finished <- err + } + return err + })(h.Publisher()) + }) + reviewCreate(t, c, ctx, "inflight") + if _, e := h.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "inflight", DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{{VolumeID: "inflight", ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); e != nil { + t.Fatal(e) + } + reviewHeartbeat(t, c, ctx, "inflight", "node-a", "127.0.0.1:10000", "127.0.0.1:10001") + if _, e := h.RunLifecycleProductTick(); e != nil { + t.Fatal(e) + } + select { + case <-arrived: + case <-ctx.Done(): + t.Fatal("publisher did not dequeue ask", ctx.Err()) + } + defer func() { + select { + case <-release: + default: + close(release) + } + }() + if action == "delete" { + if _, e := control.NewLifecycleServiceClient(c).DeleteVolume(ctx, &control.DeleteVolumeRequest{VolumeId: "inflight"}); e != nil { + t.Fatal("unassigned legacy delete", e) + } + if _, ok := h.Lifecycle().Volumes.GetVolume("inflight"); ok { + t.Fatal("delete did not remove volume") + } + } + reviewCreate(t, c, ctx, "owner") + wc := control.NewWorkspaceServiceClient(c) + reserve := func() { + if _, e := wc.RegisterWorkspaceBinding(ctx, &control.WorkspaceBinding{VolumeId: "owner", ServerId: "node-b", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"}); e != nil { + t.Fatal("reservation", e) + } + } + if action == "register" { + reserve() + } + close(release) + select { + case e := <-finished: + if e == nil { + t.Error("held stale ask was published after competing " + action) + } + case <-ctx.Done(): + t.Fatal("publisher did not settle", ctx.Err()) + } + if line, ok := h.Publisher().VolumeAuthorityLine("inflight"); ok { + t.Fatal("stale or deleted ask minted authority", line) + } + if action == "delete" { + reserve() + } + st, e := wc.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "owner"}) + if e != nil || len(st.GetBindings()) != 1 { + t.Fatal("owner reservation lost", st, e) + } + // An unrelated, matching explicit owner can still reach the actual publisher. + if _, e = wc.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "owner", ServerId: "node-b", ReplicaId: "r1"}); e != nil { + t.Fatal(e) + } + reviewHeartbeat(t, c, ctx, "owner", "node-b", "127.0.0.1:10000", "127.0.0.1:10001") + if _, e = h.RunLifecycleProductTick(); e != nil { + t.Fatal(e) + } + waitAuthorityLine(t, h.Publisher(), "owner") + }) + } +} diff --git a/seaweed-block/core/host/master/workspace_protocol.md b/seaweed-block/core/host/master/workspace_protocol.md index b503342617..46f8971705 100644 --- a/seaweed-block/core/host/master/workspace_protocol.md +++ b/seaweed-block/core/host/master/workspace_protocol.md @@ -47,7 +47,15 @@ a crash between authority persistence and binding retirement is recoverable. Host workspace mutations serialize with `workspaceMu`. Remote HEAD reads and promotion probes run outside it; local intent, binding and reservation checks are -repeated under the lock before queueing or committing their results. +repeated under the lock before queueing or committing their results. Ordinary +Publisher mints also acquire that same host lock before checking the live volume, +current binding owner/pair and reservations, and retain it through authority +persistence/commit. The existing already-current product check is repeated for +ordinary Reassign asks here, so a snapshot plus its direct promotion fallback +cannot mint duplicate epochs after both were dequeued. Dequeued legacy asks therefore cannot bypass a later binding +or publish after successful deletion. Hosts without lifecycle stores retain their +static authority path. Guarded Move already holds this boundary and does not +recursively acquire it. Lock order is host workspace mutex, then Publisher or lifecycle-store locks. Initial placement persists under a Publisher unassigned guard; its callback must never call Publisher. Store reads do not hold their mutex while calling