diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index c8b7ce0c1c..fcc04b65de 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -15,6 +15,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/hostlimit" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -29,6 +30,7 @@ const ( ) type chunkFlags struct { + hostLimit hostlimit.Config filer string path string collection string @@ -44,10 +46,17 @@ type chunkFlags struct { func validateChunkFlags(f flags) error { c := f.chunk + if c.hostLimit.Directory != "" { + if err := c.hostLimit.Validate(); err != nil { + return err + } + } else if c.hostLimit != (hostlimit.Config{}) && c.hostLimit != hostlimit.DefaultConfig("") { + return errors.New("--host-limit-* settings require --host-limit-dir") + } if f.durableImpl != "walstore-chunk" { if c.filer != "" || c.collection != "" || c.replication != "" || c.path != defaultChunkPath || c.captureInterval != defaultChunkCaptureInterval || c.dirtyThreshold != defaultChunkDirtyThreshold || - c.uploadConcurrency != 8 || c.hydrationWorkers != 2 || c.hydrationQueueDepth != 64 || c.controlEndpoint { + c.uploadConcurrency != 8 || c.hydrationWorkers != 2 || c.hydrationQueueDepth != 64 || c.controlEndpoint || c.hostLimit.Directory != "" { return errors.New("--chunk-* flags require --durable-impl=walstore-chunk") } return nil @@ -101,7 +110,8 @@ type chunkWiring struct { close func() error } -// newChunkWiring dials the filer (lazily). +// newChunkWiring dials the filer and refuses unless it is the only filer of +// its group (chunkstore.CheckSingleFiler). func newChunkWiring(c chunkFlags) (chunkWiring, error) { client, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{ FilerGRPC: c.filer, @@ -112,6 +122,11 @@ func newChunkWiring(c chunkFlags) (chunkWiring, error) { if err != nil { return chunkWiring{}, err } + // Deployment rule: block metadata goes through exactly one filer. + if err := client.CheckSingleFiler(context.Background()); err != nil { + _ = client.Close() + return chunkWiring{}, err + } cat, err := chunkstore.NewCatalog(client, c.path) if err != nil { _ = client.Close() diff --git a/seaweed-block/cmd/blockvolume/host_limit.go b/seaweed-block/cmd/blockvolume/host_limit.go new file mode 100644 index 0000000000..7eba88af39 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/host_limit.go @@ -0,0 +1,20 @@ +package main + +import ( + "flag" + "github.com/seaweedfs/seaweed-block/core/hostlimit" +) + +func registerHostLimitFlags(fs *flag.FlagSet, c *hostlimit.Config) { + *c = hostlimit.DefaultConfig("") + fs.StringVar(&c.Directory, "host-limit-dir", "", "shared local directory for background-cut slots; empty disables shared slots") + fs.IntVar(&c.NormalSlots, "host-limit-normal-slots", c.NormalSlots, "host normal-cut slots; identical across processes") + fs.IntVar(&c.UrgentSlots, "host-limit-urgent-slots", c.UrgentSlots, "host reserved urgent-cut slots") + fs.IntVar(&c.FillSlots, "host-limit-fill-slots", c.FillSlots, "host background-fill slots; demand hydration bypasses them") + fs.IntVar(&c.IdleSlots, "host-limit-idle-slots", c.IdleSlots, "host idle-work slots") + fs.Int64Var(&c.PayloadBytes, "host-limit-payload-bytes", c.PayloadBytes, "maximum cut payload per slot") + fs.Int64Var(&c.COWBytes, "host-limit-cow-bytes", c.COWBytes, "maximum saved COW bytes per slot") + fs.Int64Var(&c.BytesPerSecond, "host-limit-upload-bytes-sec", c.BytesPerSecond, "pacing parameter divided per process by cut-slot count; not a host rate cap") + fs.IntVar(&c.FallbackVolumes, "host-limit-fallback-volumes", c.FallbackVolumes, "urgent-fallback per-process divisor; coordinated host cap is not enforced") + fs.DurationVar(&c.MaxHold, "host-limit-max-hold", c.MaxHold, "cut lease timeout; expiration aborts but waits for admitted I/O before release") +} diff --git a/seaweed-block/cmd/blockvolume/host_limit_test.go b/seaweed-block/cmd/blockvolume/host_limit_test.go new file mode 100644 index 0000000000..939050f42e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/host_limit_test.go @@ -0,0 +1,25 @@ +package main + +import ( + "path/filepath" + "testing" +) + +func TestHostCutLimitFlags(t *testing.T) { + base := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-impl=walstore-chunk", "--chunk-filer=x:1") + dir := t.TempDir() + args := append(append([]string{}, base...), "--host-limit-dir="+dir, "--host-limit-normal-slots=2", "--host-limit-urgent-slots=1") + f, e := parseFlags(args) + if e != nil { + t.Fatal(e) + } + if f.chunk.hostLimit.Directory != dir || f.chunk.hostLimit.NormalSlots != 2 || f.chunk.hostLimit.UrgentSlots != 1 { + t.Fatal("lost host limits") + } + for _, extra := range [][]string{{"--host-limit-normal-slots=2"}, {"--host-limit-dir=" + dir, "--host-limit-normal-slots=0"}, {"--host-limit-dir=" + dir, "--host-limit-max-hold=-1s"}, {"--host-limit-dir=" + filepath.Join("relative", "pool")}} { + a := append(append([]string{}, base...), extra...) + if _, e = parseFlags(a); e == nil { + t.Fatalf("accepted invalid limits: %v", extra) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index ad5126c180..b526388dbe 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -31,6 +31,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/ublk" "github.com/seaweedfs/seaweed-block/core/geometry" "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/hostlimit" "github.com/seaweedfs/seaweed-block/core/recovery" "github.com/seaweedfs/seaweed-block/core/replication" control "github.com/seaweedfs/seaweed-block/core/rpc/control" @@ -194,6 +195,7 @@ func parseFlags(args []string) (flags, error) { fs.IntVar(&f.ublkQueueDepth, "ublk-queue-depth", 0, "ublk in-flight requests per queue; 0 = default 64. Requires --ublk-device") fs.StringVar(&f.durableRoot, "durable-root", "", "directory for persistent storage files; empty = memback (non-durable)") fs.StringVar(&f.durableImpl, "durable-impl", "", "LogicalStorage impl: empty (default) = auto: an existing volume opens with its on-disk format (a walstore-chunk root needs the explicit walstore-chunk selector), a new volume is created as walstore; or walstore, smartwal (experimental), opt-in parallel-walstore, or opt-in walstore-chunk (walstore published to SeaweedFS; proof of concept); ignored unless --durable-root is set") + registerHostLimitFlags(fs, &f.chunk.hostLimit) fs.StringVar(&f.chunk.filer, "chunk-filer", "", "walstore-chunk: SeaweedFS filer gRPC address host:port") fs.StringVar(&f.chunk.path, "chunk-path", defaultChunkPath, "walstore-chunk: filer directory holding one directory per volume (HEAD and chunk key bindings)") fs.StringVar(&f.chunk.collection, "chunk-collection", "", "walstore-chunk: collection for chunk needles (empty = filer default / storage rule)") @@ -660,6 +662,18 @@ func run(f flags) int { cfg.ChunkHydrationWorkers = f.chunk.hydrationWorkers cfg.ChunkHydrationQueueDepth = f.chunk.hydrationQueueDepth cfg.ChunkHolder = chunkHolder(f) + cfg.ChunkStagger = true + if f.chunk.hostLimit.Directory != "" { + limiter, limitErr := hostlimit.New(f.chunk.hostLimit) + if limitErr != nil { + chunkErr = errors.Join(chunkErr, limitErr) + } else { + defer limiter.Close() + cfg.ChunkBudget = limiter + cfg.ChunkPayloadMemoryBudget = f.chunk.hostLimit.PayloadBytes + cfg.ChunkCOWSpillLimit = f.chunk.hostLimit.COWBytes + } + } if chunkErr == nil { cfg.ChunkRemoteFor = chunk.remoteFor workspaceRemoteFor = chunk.remoteFor diff --git a/seaweed-block/cmd/blockvolume/single_filer_test.go b/seaweed-block/cmd/blockvolume/single_filer_test.go new file mode 100644 index 0000000000..c4cc3ccbd8 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/single_filer_test.go @@ -0,0 +1,92 @@ +package main + +import ( + "context" + "errors" + "net" + "testing" + + "google.golang.org/grpc" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/masterpb" +) + +type groupFiler struct { + filerpb.UnimplementedSeaweedFilerServer + master string +} + +func (f *groupFiler) GetFilerConfiguration(context.Context, *filerpb.GetFilerConfigurationRequest) (*filerpb.GetFilerConfigurationResponse, error) { + return &filerpb.GetFilerConfigurationResponse{Masters: []string{f.master}}, nil +} + +type groupMaster struct { + masterpb.UnimplementedSeaweedServer + filers []string +} + +func (m *groupMaster) ListClusterNodes(context.Context, *masterpb.ListClusterNodesRequest) (*masterpb.ListClusterNodesResponse, error) { + r := &masterpb.ListClusterNodesResponse{} + for _, a := range m.filers { + r.ClusterNodes = append(r.ClusterNodes, &masterpb.ListClusterNodesResponse_ClusterNode{Address: a}) + } + return r, nil +} + +func serve(t *testing.T, register func(*grpc.Server)) string { + t.Helper() + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer() + register(srv) + go func() { _ = srv.Serve(lis) }() + t.Cleanup(srv.Stop) + return lis.Addr().String() +} + +// blockvolume's chunk wiring runs the single-filer check at startup: the +// configured filer listed as the one filer passes; a group with a second +// filer is refused. +func TestChunkWiringRefusesAMultiFilerGroup(t *testing.T) { + for _, c := range []struct { + name string + other []string + ok bool + }{ + {"one filer", nil, true}, + {"two filers", []string{"10.0.0.2:8888"}, false}, + } { + t.Run(c.name, func(t *testing.T) { + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + filer := lis.Addr().String() + _, fport, _ := net.SplitHostPort(filer) + self := "127.0.0.1:8888." + fport // the filer as a master lists it + m := serve(t, func(s *grpc.Server) { + masterpb.RegisterSeaweedServer(s, &groupMaster{filers: append([]string{self}, c.other...)}) + }) + _, mport, _ := net.SplitHostPort(m) + srv := grpc.NewServer() + filerpb.RegisterSeaweedFilerServer(srv, &groupFiler{master: "127.0.0.1:9333." + mport}) + go func() { _ = srv.Serve(lis) }() + t.Cleanup(srv.Stop) + w, err := newChunkWiring(chunkFlags{filer: filer, path: defaultChunkPath}) + if c.ok { + if err != nil { + t.Fatalf("one filer refused: %v", err) + } + _ = w.close() + return + } + if !errors.Is(err, chunkstore.ErrNotSingleFiler) { + t.Fatalf("two filers: %v; want chunkstore.ErrNotSingleFiler", err) + } + }) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/chunk_remote.go b/seaweed-block/core/frontend/chunkstore/chunk_remote.go index aff708783b..4c8dcc5da0 100644 --- a/seaweed-block/core/frontend/chunkstore/chunk_remote.go +++ b/seaweed-block/core/frontend/chunkstore/chunk_remote.go @@ -378,6 +378,11 @@ func (r *ChunkRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { return r.resolveManifest(ctx, h) } +// GetHeadRoot validates publication identity without reading segment bodies. +func (r *ChunkRemote) GetHeadRoot(ctx context.Context) (storage.ChunkHead, error) { + return r.getHeadRoot(ctx) +} + // getHeadRoot validates the root and its CAS attributes without reading any // immutable segment. CASHead only needs authority and lineage from this root. func (r *ChunkRemote) getHeadRoot(ctx context.Context) (storage.ChunkHead, error) { diff --git a/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.pb.go b/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.pb.go index d21579d389..fefdaee1fb 100644 --- a/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.pb.go +++ b/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.pb.go @@ -13,7 +13,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.36.6 -// protoc v7.34.1 +// protoc v3.12.4 // source: filer_subset.proto package filerpb @@ -1367,6 +1367,95 @@ func (x *LookupVolumeResponse) GetLocationsMap() map[string]*Locations { return nil } +type GetFilerConfigurationRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetFilerConfigurationRequest) Reset() { + *x = GetFilerConfigurationRequest{} + mi := &file_filer_subset_proto_msgTypes[19] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetFilerConfigurationRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetFilerConfigurationRequest) ProtoMessage() {} + +func (x *GetFilerConfigurationRequest) ProtoReflect() protoreflect.Message { + mi := &file_filer_subset_proto_msgTypes[19] + 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 GetFilerConfigurationRequest.ProtoReflect.Descriptor instead. +func (*GetFilerConfigurationRequest) Descriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{19} +} + +// Only the fields the single-filer startup check reads. +type GetFilerConfigurationResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Masters []string `protobuf:"bytes,1,rep,name=masters,proto3" json:"masters,omitempty"` + FilerGroup string `protobuf:"bytes,13,opt,name=filer_group,json=filerGroup,proto3" json:"filer_group,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetFilerConfigurationResponse) Reset() { + *x = GetFilerConfigurationResponse{} + mi := &file_filer_subset_proto_msgTypes[20] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetFilerConfigurationResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetFilerConfigurationResponse) ProtoMessage() {} + +func (x *GetFilerConfigurationResponse) ProtoReflect() protoreflect.Message { + mi := &file_filer_subset_proto_msgTypes[20] + 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 GetFilerConfigurationResponse.ProtoReflect.Descriptor instead. +func (*GetFilerConfigurationResponse) Descriptor() ([]byte, []int) { + return file_filer_subset_proto_rawDescGZIP(), []int{20} +} + +func (x *GetFilerConfigurationResponse) GetMasters() []string { + if x != nil { + return x.Masters + } + return nil +} + +func (x *GetFilerConfigurationResponse) GetFilerGroup() string { + if x != nil { + return x.FilerGroup + } + return "" +} + var File_filer_subset_proto protoreflect.FileDescriptor const file_filer_subset_proto_rawDesc = "" + @@ -1494,7 +1583,12 @@ const file_filer_subset_proto_rawDesc = "" + "\rlocations_map\x18\x01 \x03(\v20.filer_pb.LookupVolumeResponse.LocationsMapEntryR\flocationsMap\x1aT\n" + "\x11LocationsMapEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12)\n" + - "\x05value\x18\x02 \x01(\v2\x13.filer_pb.LocationsR\x05value:\x028\x01*\xb4\x01\n" + + "\x05value\x18\x02 \x01(\v2\x13.filer_pb.LocationsR\x05value:\x028\x01\"\x1e\n" + + "\x1cGetFilerConfigurationRequest\"Z\n" + + "\x1dGetFilerConfigurationResponse\x12\x18\n" + + "\amasters\x18\x01 \x03(\tR\amasters\x12\x1f\n" + + "\vfiler_group\x18\r \x01(\tR\n" + + "filerGroup*\xb4\x01\n" + "\n" + "FilerError\x12\x06\n" + "\x02OK\x10\x00\x12\x17\n" + @@ -1504,7 +1598,7 @@ const file_filer_subset_proto_rawDesc = "" + "\x10EXISTING_IS_FILE\x10\x04\x12\x18\n" + "\x14ENTRY_ALREADY_EXISTS\x10\x05\x12\x17\n" + "\x13PRECONDITION_FAILED\x10\x06\x12\r\n" + - "\tREAD_ONLY\x10\a2\xd3\x04\n" + + "\tREAD_ONLY\x10\a2\xbf\x05\n" + "\fSeaweedFiler\x12g\n" + "\x14LookupDirectoryEntry\x12%.filer_pb.LookupDirectoryEntryRequest\x1a&.filer_pb.LookupDirectoryEntryResponse\"\x00\x12N\n" + "\vListEntries\x12\x1c.filer_pb.ListEntriesRequest\x1a\x1d.filer_pb.ListEntriesResponse\"\x000\x01\x12L\n" + @@ -1512,7 +1606,8 @@ const file_filer_subset_proto_rawDesc = "" + "\vUpdateEntry\x12\x1c.filer_pb.UpdateEntryRequest\x1a\x1d.filer_pb.UpdateEntryResponse\"\x00\x12L\n" + "\vDeleteEntry\x12\x1c.filer_pb.DeleteEntryRequest\x1a\x1d.filer_pb.DeleteEntryResponse\"\x00\x12O\n" + "\fAssignVolume\x12\x1d.filer_pb.AssignVolumeRequest\x1a\x1e.filer_pb.AssignVolumeResponse\"\x00\x12O\n" + - "\fLookupVolume\x12\x1d.filer_pb.LookupVolumeRequest\x1a\x1e.filer_pb.LookupVolumeResponse\"\x00BEZCgithub.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpbb\x06proto3" + "\fLookupVolume\x12\x1d.filer_pb.LookupVolumeRequest\x1a\x1e.filer_pb.LookupVolumeResponse\"\x00\x12j\n" + + "\x15GetFilerConfiguration\x12&.filer_pb.GetFilerConfigurationRequest\x1a'.filer_pb.GetFilerConfigurationResponse\"\x00BEZCgithub.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpbb\x06proto3" var ( file_filer_subset_proto_rawDescOnce sync.Once @@ -1527,49 +1622,51 @@ func file_filer_subset_proto_rawDescGZIP() []byte { } var file_filer_subset_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_filer_subset_proto_msgTypes = make([]protoimpl.MessageInfo, 23) +var file_filer_subset_proto_msgTypes = make([]protoimpl.MessageInfo, 25) var file_filer_subset_proto_goTypes = []any{ - (FilerError)(0), // 0: filer_pb.FilerError - (*LookupDirectoryEntryRequest)(nil), // 1: filer_pb.LookupDirectoryEntryRequest - (*LookupDirectoryEntryResponse)(nil), // 2: filer_pb.LookupDirectoryEntryResponse - (*ListEntriesRequest)(nil), // 3: filer_pb.ListEntriesRequest - (*ListEntriesResponse)(nil), // 4: filer_pb.ListEntriesResponse - (*Entry)(nil), // 5: filer_pb.Entry - (*FileChunk)(nil), // 6: filer_pb.FileChunk - (*FuseAttributes)(nil), // 7: filer_pb.FuseAttributes - (*CreateEntryRequest)(nil), // 8: filer_pb.CreateEntryRequest - (*CreateEntryResponse)(nil), // 9: filer_pb.CreateEntryResponse - (*UpdateEntryRequest)(nil), // 10: filer_pb.UpdateEntryRequest - (*UpdateEntryResponse)(nil), // 11: filer_pb.UpdateEntryResponse - (*DeleteEntryRequest)(nil), // 12: filer_pb.DeleteEntryRequest - (*DeleteEntryResponse)(nil), // 13: filer_pb.DeleteEntryResponse - (*AssignVolumeRequest)(nil), // 14: filer_pb.AssignVolumeRequest - (*AssignVolumeResponse)(nil), // 15: filer_pb.AssignVolumeResponse - (*LookupVolumeRequest)(nil), // 16: filer_pb.LookupVolumeRequest - (*Locations)(nil), // 17: filer_pb.Locations - (*Location)(nil), // 18: filer_pb.Location - (*LookupVolumeResponse)(nil), // 19: filer_pb.LookupVolumeResponse - nil, // 20: filer_pb.Entry.ExtendedEntry - nil, // 21: filer_pb.UpdateEntryRequest.ExpectedExtendedEntry - nil, // 22: filer_pb.DeleteEntryRequest.ExpectedExtendedEntry - nil, // 23: filer_pb.LookupVolumeResponse.LocationsMapEntry + (FilerError)(0), // 0: filer_pb.FilerError + (*LookupDirectoryEntryRequest)(nil), // 1: filer_pb.LookupDirectoryEntryRequest + (*LookupDirectoryEntryResponse)(nil), // 2: filer_pb.LookupDirectoryEntryResponse + (*ListEntriesRequest)(nil), // 3: filer_pb.ListEntriesRequest + (*ListEntriesResponse)(nil), // 4: filer_pb.ListEntriesResponse + (*Entry)(nil), // 5: filer_pb.Entry + (*FileChunk)(nil), // 6: filer_pb.FileChunk + (*FuseAttributes)(nil), // 7: filer_pb.FuseAttributes + (*CreateEntryRequest)(nil), // 8: filer_pb.CreateEntryRequest + (*CreateEntryResponse)(nil), // 9: filer_pb.CreateEntryResponse + (*UpdateEntryRequest)(nil), // 10: filer_pb.UpdateEntryRequest + (*UpdateEntryResponse)(nil), // 11: filer_pb.UpdateEntryResponse + (*DeleteEntryRequest)(nil), // 12: filer_pb.DeleteEntryRequest + (*DeleteEntryResponse)(nil), // 13: filer_pb.DeleteEntryResponse + (*AssignVolumeRequest)(nil), // 14: filer_pb.AssignVolumeRequest + (*AssignVolumeResponse)(nil), // 15: filer_pb.AssignVolumeResponse + (*LookupVolumeRequest)(nil), // 16: filer_pb.LookupVolumeRequest + (*Locations)(nil), // 17: filer_pb.Locations + (*Location)(nil), // 18: filer_pb.Location + (*LookupVolumeResponse)(nil), // 19: filer_pb.LookupVolumeResponse + (*GetFilerConfigurationRequest)(nil), // 20: filer_pb.GetFilerConfigurationRequest + (*GetFilerConfigurationResponse)(nil), // 21: filer_pb.GetFilerConfigurationResponse + nil, // 22: filer_pb.Entry.ExtendedEntry + nil, // 23: filer_pb.UpdateEntryRequest.ExpectedExtendedEntry + nil, // 24: filer_pb.DeleteEntryRequest.ExpectedExtendedEntry + nil, // 25: filer_pb.LookupVolumeResponse.LocationsMapEntry } var file_filer_subset_proto_depIdxs = []int32{ 5, // 0: filer_pb.LookupDirectoryEntryResponse.entry:type_name -> filer_pb.Entry 5, // 1: filer_pb.ListEntriesResponse.entry:type_name -> filer_pb.Entry 6, // 2: filer_pb.Entry.chunks:type_name -> filer_pb.FileChunk 7, // 3: filer_pb.Entry.attributes:type_name -> filer_pb.FuseAttributes - 20, // 4: filer_pb.Entry.extended:type_name -> filer_pb.Entry.ExtendedEntry + 22, // 4: filer_pb.Entry.extended:type_name -> filer_pb.Entry.ExtendedEntry 5, // 5: filer_pb.CreateEntryRequest.entry:type_name -> filer_pb.Entry 0, // 6: filer_pb.CreateEntryResponse.error_code:type_name -> filer_pb.FilerError 5, // 7: filer_pb.UpdateEntryRequest.entry:type_name -> filer_pb.Entry - 21, // 8: filer_pb.UpdateEntryRequest.expected_extended:type_name -> filer_pb.UpdateEntryRequest.ExpectedExtendedEntry - 22, // 9: filer_pb.DeleteEntryRequest.expected_extended:type_name -> filer_pb.DeleteEntryRequest.ExpectedExtendedEntry + 23, // 8: filer_pb.UpdateEntryRequest.expected_extended:type_name -> filer_pb.UpdateEntryRequest.ExpectedExtendedEntry + 24, // 9: filer_pb.DeleteEntryRequest.expected_extended:type_name -> filer_pb.DeleteEntryRequest.ExpectedExtendedEntry 18, // 10: filer_pb.AssignVolumeResponse.location:type_name -> filer_pb.Location 18, // 11: filer_pb.AssignVolumeResponse.replicas:type_name -> filer_pb.Location 0, // 12: filer_pb.AssignVolumeResponse.error_code:type_name -> filer_pb.FilerError 18, // 13: filer_pb.Locations.locations:type_name -> filer_pb.Location - 23, // 14: filer_pb.LookupVolumeResponse.locations_map:type_name -> filer_pb.LookupVolumeResponse.LocationsMapEntry + 25, // 14: filer_pb.LookupVolumeResponse.locations_map:type_name -> filer_pb.LookupVolumeResponse.LocationsMapEntry 17, // 15: filer_pb.LookupVolumeResponse.LocationsMapEntry.value:type_name -> filer_pb.Locations 1, // 16: filer_pb.SeaweedFiler.LookupDirectoryEntry:input_type -> filer_pb.LookupDirectoryEntryRequest 3, // 17: filer_pb.SeaweedFiler.ListEntries:input_type -> filer_pb.ListEntriesRequest @@ -1578,15 +1675,17 @@ var file_filer_subset_proto_depIdxs = []int32{ 12, // 20: filer_pb.SeaweedFiler.DeleteEntry:input_type -> filer_pb.DeleteEntryRequest 14, // 21: filer_pb.SeaweedFiler.AssignVolume:input_type -> filer_pb.AssignVolumeRequest 16, // 22: filer_pb.SeaweedFiler.LookupVolume:input_type -> filer_pb.LookupVolumeRequest - 2, // 23: filer_pb.SeaweedFiler.LookupDirectoryEntry:output_type -> filer_pb.LookupDirectoryEntryResponse - 4, // 24: filer_pb.SeaweedFiler.ListEntries:output_type -> filer_pb.ListEntriesResponse - 9, // 25: filer_pb.SeaweedFiler.CreateEntry:output_type -> filer_pb.CreateEntryResponse - 11, // 26: filer_pb.SeaweedFiler.UpdateEntry:output_type -> filer_pb.UpdateEntryResponse - 13, // 27: filer_pb.SeaweedFiler.DeleteEntry:output_type -> filer_pb.DeleteEntryResponse - 15, // 28: filer_pb.SeaweedFiler.AssignVolume:output_type -> filer_pb.AssignVolumeResponse - 19, // 29: filer_pb.SeaweedFiler.LookupVolume:output_type -> filer_pb.LookupVolumeResponse - 23, // [23:30] is the sub-list for method output_type - 16, // [16:23] is the sub-list for method input_type + 20, // 23: filer_pb.SeaweedFiler.GetFilerConfiguration:input_type -> filer_pb.GetFilerConfigurationRequest + 2, // 24: filer_pb.SeaweedFiler.LookupDirectoryEntry:output_type -> filer_pb.LookupDirectoryEntryResponse + 4, // 25: filer_pb.SeaweedFiler.ListEntries:output_type -> filer_pb.ListEntriesResponse + 9, // 26: filer_pb.SeaweedFiler.CreateEntry:output_type -> filer_pb.CreateEntryResponse + 11, // 27: filer_pb.SeaweedFiler.UpdateEntry:output_type -> filer_pb.UpdateEntryResponse + 13, // 28: filer_pb.SeaweedFiler.DeleteEntry:output_type -> filer_pb.DeleteEntryResponse + 15, // 29: filer_pb.SeaweedFiler.AssignVolume:output_type -> filer_pb.AssignVolumeResponse + 19, // 30: filer_pb.SeaweedFiler.LookupVolume:output_type -> filer_pb.LookupVolumeResponse + 21, // 31: filer_pb.SeaweedFiler.GetFilerConfiguration:output_type -> filer_pb.GetFilerConfigurationResponse + 24, // [24:32] is the sub-list for method output_type + 16, // [16:24] is the sub-list for method input_type 16, // [16:16] is the sub-list for extension type_name 16, // [16:16] is the sub-list for extension extendee 0, // [0:16] is the sub-list for field type_name @@ -1603,7 +1702,7 @@ func file_filer_subset_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_filer_subset_proto_rawDesc), len(file_filer_subset_proto_rawDesc)), NumEnums: 1, - NumMessages: 23, + NumMessages: 25, NumExtensions: 0, NumServices: 1, }, diff --git a/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.proto b/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.proto index 5b3da5b992..e0fab4e1ef 100644 --- a/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.proto +++ b/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset.proto @@ -23,6 +23,7 @@ service SeaweedFiler { rpc DeleteEntry (DeleteEntryRequest) returns (DeleteEntryResponse) {} rpc AssignVolume (AssignVolumeRequest) returns (AssignVolumeResponse) {} rpc LookupVolume (LookupVolumeRequest) returns (LookupVolumeResponse) {} + rpc GetFilerConfiguration (GetFilerConfigurationRequest) returns (GetFilerConfigurationResponse) {} } message LookupDirectoryEntryRequest { @@ -167,3 +168,12 @@ message Location { message LookupVolumeResponse { map locations_map = 1; } + +message GetFilerConfigurationRequest { +} + +// Only the fields the single-filer startup check reads. +message GetFilerConfigurationResponse { + repeated string masters = 1; + string filer_group = 13; +} diff --git a/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset_grpc.pb.go b/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset_grpc.pb.go index 0e18f19a8e..26a7542dbd 100644 --- a/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset_grpc.pb.go +++ b/seaweed-block/core/frontend/chunkstore/filerpb/filer_subset_grpc.pb.go @@ -13,7 +13,7 @@ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: // - protoc-gen-go-grpc v1.6.2 -// - protoc v7.34.1 +// - protoc v3.12.4 // source: filer_subset.proto package filerpb @@ -31,13 +31,14 @@ import ( const _ = grpc.SupportPackageIsVersion9 const ( - SeaweedFiler_LookupDirectoryEntry_FullMethodName = "/filer_pb.SeaweedFiler/LookupDirectoryEntry" - SeaweedFiler_ListEntries_FullMethodName = "/filer_pb.SeaweedFiler/ListEntries" - SeaweedFiler_CreateEntry_FullMethodName = "/filer_pb.SeaweedFiler/CreateEntry" - SeaweedFiler_UpdateEntry_FullMethodName = "/filer_pb.SeaweedFiler/UpdateEntry" - SeaweedFiler_DeleteEntry_FullMethodName = "/filer_pb.SeaweedFiler/DeleteEntry" - SeaweedFiler_AssignVolume_FullMethodName = "/filer_pb.SeaweedFiler/AssignVolume" - SeaweedFiler_LookupVolume_FullMethodName = "/filer_pb.SeaweedFiler/LookupVolume" + SeaweedFiler_LookupDirectoryEntry_FullMethodName = "/filer_pb.SeaweedFiler/LookupDirectoryEntry" + SeaweedFiler_ListEntries_FullMethodName = "/filer_pb.SeaweedFiler/ListEntries" + SeaweedFiler_CreateEntry_FullMethodName = "/filer_pb.SeaweedFiler/CreateEntry" + SeaweedFiler_UpdateEntry_FullMethodName = "/filer_pb.SeaweedFiler/UpdateEntry" + SeaweedFiler_DeleteEntry_FullMethodName = "/filer_pb.SeaweedFiler/DeleteEntry" + SeaweedFiler_AssignVolume_FullMethodName = "/filer_pb.SeaweedFiler/AssignVolume" + SeaweedFiler_LookupVolume_FullMethodName = "/filer_pb.SeaweedFiler/LookupVolume" + SeaweedFiler_GetFilerConfiguration_FullMethodName = "/filer_pb.SeaweedFiler/GetFilerConfiguration" ) // SeaweedFilerClient is the client API for SeaweedFiler service. @@ -51,6 +52,7 @@ type SeaweedFilerClient interface { DeleteEntry(ctx context.Context, in *DeleteEntryRequest, opts ...grpc.CallOption) (*DeleteEntryResponse, error) AssignVolume(ctx context.Context, in *AssignVolumeRequest, opts ...grpc.CallOption) (*AssignVolumeResponse, error) LookupVolume(ctx context.Context, in *LookupVolumeRequest, opts ...grpc.CallOption) (*LookupVolumeResponse, error) + GetFilerConfiguration(ctx context.Context, in *GetFilerConfigurationRequest, opts ...grpc.CallOption) (*GetFilerConfigurationResponse, error) } type seaweedFilerClient struct { @@ -140,6 +142,16 @@ func (c *seaweedFilerClient) LookupVolume(ctx context.Context, in *LookupVolumeR return out, nil } +func (c *seaweedFilerClient) GetFilerConfiguration(ctx context.Context, in *GetFilerConfigurationRequest, opts ...grpc.CallOption) (*GetFilerConfigurationResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetFilerConfigurationResponse) + err := c.cc.Invoke(ctx, SeaweedFiler_GetFilerConfiguration_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + // SeaweedFilerServer is the server API for SeaweedFiler service. // All implementations must embed UnimplementedSeaweedFilerServer // for forward compatibility. @@ -151,6 +163,7 @@ type SeaweedFilerServer interface { DeleteEntry(context.Context, *DeleteEntryRequest) (*DeleteEntryResponse, error) AssignVolume(context.Context, *AssignVolumeRequest) (*AssignVolumeResponse, error) LookupVolume(context.Context, *LookupVolumeRequest) (*LookupVolumeResponse, error) + GetFilerConfiguration(context.Context, *GetFilerConfigurationRequest) (*GetFilerConfigurationResponse, error) mustEmbedUnimplementedSeaweedFilerServer() } @@ -182,6 +195,9 @@ func (UnimplementedSeaweedFilerServer) AssignVolume(context.Context, *AssignVolu func (UnimplementedSeaweedFilerServer) LookupVolume(context.Context, *LookupVolumeRequest) (*LookupVolumeResponse, error) { return nil, status.Error(codes.Unimplemented, "method LookupVolume not implemented") } +func (UnimplementedSeaweedFilerServer) GetFilerConfiguration(context.Context, *GetFilerConfigurationRequest) (*GetFilerConfigurationResponse, error) { + return nil, status.Error(codes.Unimplemented, "method GetFilerConfiguration not implemented") +} func (UnimplementedSeaweedFilerServer) mustEmbedUnimplementedSeaweedFilerServer() {} func (UnimplementedSeaweedFilerServer) testEmbeddedByValue() {} @@ -322,6 +338,24 @@ func _SeaweedFiler_LookupVolume_Handler(srv interface{}, ctx context.Context, de return interceptor(ctx, in, info, handler) } +func _SeaweedFiler_GetFilerConfiguration_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetFilerConfigurationRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SeaweedFilerServer).GetFilerConfiguration(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: SeaweedFiler_GetFilerConfiguration_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SeaweedFilerServer).GetFilerConfiguration(ctx, req.(*GetFilerConfigurationRequest)) + } + return interceptor(ctx, in, info, handler) +} + // SeaweedFiler_ServiceDesc is the grpc.ServiceDesc for SeaweedFiler service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) @@ -353,6 +387,10 @@ var SeaweedFiler_ServiceDesc = grpc.ServiceDesc{ MethodName: "LookupVolume", Handler: _SeaweedFiler_LookupVolume_Handler, }, + { + MethodName: "GetFilerConfiguration", + Handler: _SeaweedFiler_GetFilerConfiguration_Handler, + }, }, Streams: []grpc.StreamDesc{ { diff --git a/seaweed-block/core/frontend/chunkstore/head_cas_root_test.go b/seaweed-block/core/frontend/chunkstore/head_cas_root_test.go index d65183c90e..ed22ed0be0 100644 --- a/seaweed-block/core/frontend/chunkstore/head_cas_root_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_cas_root_test.go @@ -48,6 +48,10 @@ func TestManifest_CASReadsOnlyRoot(t *testing.T) { if gen != h.Gen+1 || tracked.roots != 1 || tracked.children != 0 { t.Fatalf("CAS gen=%d root reads=%d child reads=%d", gen, tracked.roots, tracked.children) } + root, err := r.GetHeadRoot(context.Background()) + if err != nil || root.Gen != gen || root.Epoch != h.Epoch || root.Holder != h.Holder || tracked.children != 0 { + t.Fatalf("confirmation resolved segments: root=%+v children=%d err=%v", root, tracked.children, err) + } if _, err := r.GetHead(context.Background()); err == nil { t.Fatal("GetHead skipped segment resolution") } diff --git a/seaweed-block/core/frontend/chunkstore/masterpb/master_subset.pb.go b/seaweed-block/core/frontend/chunkstore/masterpb/master_subset.pb.go new file mode 100644 index 0000000000..37ad2aa623 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/masterpb/master_subset.pb.go @@ -0,0 +1,253 @@ +// Minimal subset of SeaweedFS master.proto (seaweed-mono, weed/pb/master.proto) +// used by the single-filer startup check. +// +// Package, service, message names and field numbers are copied verbatim so +// the wire format and the gRPC method path (/master_pb.Seaweed/ListClusterNodes) +// match a real master. Fields the check never reads are omitted; protobuf +// keeps them as unknown fields on decode. +// +// Regenerate (from this directory): +// protoc --go_out=. --go_opt=paths=source_relative \ +// --go-grpc_out=. --go-grpc_opt=paths=source_relative master_subset.proto + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.6 +// protoc v3.12.4 +// source: master_subset.proto + +package masterpb + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type ListClusterNodesRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + ClientType string `protobuf:"bytes,1,opt,name=client_type,json=clientType,proto3" json:"client_type,omitempty"` + FilerGroup string `protobuf:"bytes,2,opt,name=filer_group,json=filerGroup,proto3" json:"filer_group,omitempty"` + Limit int32 `protobuf:"varint,4,opt,name=limit,proto3" json:"limit,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListClusterNodesRequest) Reset() { + *x = ListClusterNodesRequest{} + mi := &file_master_subset_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListClusterNodesRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListClusterNodesRequest) ProtoMessage() {} + +func (x *ListClusterNodesRequest) ProtoReflect() protoreflect.Message { + mi := &file_master_subset_proto_msgTypes[0] + 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 ListClusterNodesRequest.ProtoReflect.Descriptor instead. +func (*ListClusterNodesRequest) Descriptor() ([]byte, []int) { + return file_master_subset_proto_rawDescGZIP(), []int{0} +} + +func (x *ListClusterNodesRequest) GetClientType() string { + if x != nil { + return x.ClientType + } + return "" +} + +func (x *ListClusterNodesRequest) GetFilerGroup() string { + if x != nil { + return x.FilerGroup + } + return "" +} + +func (x *ListClusterNodesRequest) GetLimit() int32 { + if x != nil { + return x.Limit + } + return 0 +} + +type ListClusterNodesResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + ClusterNodes []*ListClusterNodesResponse_ClusterNode `protobuf:"bytes,1,rep,name=cluster_nodes,json=clusterNodes,proto3" json:"cluster_nodes,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListClusterNodesResponse) Reset() { + *x = ListClusterNodesResponse{} + mi := &file_master_subset_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListClusterNodesResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListClusterNodesResponse) ProtoMessage() {} + +func (x *ListClusterNodesResponse) ProtoReflect() protoreflect.Message { + mi := &file_master_subset_proto_msgTypes[1] + 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 ListClusterNodesResponse.ProtoReflect.Descriptor instead. +func (*ListClusterNodesResponse) Descriptor() ([]byte, []int) { + return file_master_subset_proto_rawDescGZIP(), []int{1} +} + +func (x *ListClusterNodesResponse) GetClusterNodes() []*ListClusterNodesResponse_ClusterNode { + if x != nil { + return x.ClusterNodes + } + return nil +} + +type ListClusterNodesResponse_ClusterNode struct { + state protoimpl.MessageState `protogen:"open.v1"` + Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListClusterNodesResponse_ClusterNode) Reset() { + *x = ListClusterNodesResponse_ClusterNode{} + mi := &file_master_subset_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListClusterNodesResponse_ClusterNode) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListClusterNodesResponse_ClusterNode) ProtoMessage() {} + +func (x *ListClusterNodesResponse_ClusterNode) ProtoReflect() protoreflect.Message { + mi := &file_master_subset_proto_msgTypes[2] + 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 ListClusterNodesResponse_ClusterNode.ProtoReflect.Descriptor instead. +func (*ListClusterNodesResponse_ClusterNode) Descriptor() ([]byte, []int) { + return file_master_subset_proto_rawDescGZIP(), []int{1, 0} +} + +func (x *ListClusterNodesResponse_ClusterNode) GetAddress() string { + if x != nil { + return x.Address + } + return "" +} + +var File_master_subset_proto protoreflect.FileDescriptor + +const file_master_subset_proto_rawDesc = "" + + "\n" + + "\x13master_subset.proto\x12\tmaster_pb\"q\n" + + "\x17ListClusterNodesRequest\x12\x1f\n" + + "\vclient_type\x18\x01 \x01(\tR\n" + + "clientType\x12\x1f\n" + + "\vfiler_group\x18\x02 \x01(\tR\n" + + "filerGroup\x12\x14\n" + + "\x05limit\x18\x04 \x01(\x05R\x05limit\"\x99\x01\n" + + "\x18ListClusterNodesResponse\x12T\n" + + "\rcluster_nodes\x18\x01 \x03(\v2/.master_pb.ListClusterNodesResponse.ClusterNodeR\fclusterNodes\x1a'\n" + + "\vClusterNode\x12\x18\n" + + "\aaddress\x18\x01 \x01(\tR\aaddress2h\n" + + "\aSeaweed\x12]\n" + + "\x10ListClusterNodes\x12\".master_pb.ListClusterNodesRequest\x1a#.master_pb.ListClusterNodesResponse\"\x00BFZDgithub.com/seaweedfs/seaweed-block/core/frontend/chunkstore/masterpbb\x06proto3" + +var ( + file_master_subset_proto_rawDescOnce sync.Once + file_master_subset_proto_rawDescData []byte +) + +func file_master_subset_proto_rawDescGZIP() []byte { + file_master_subset_proto_rawDescOnce.Do(func() { + file_master_subset_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_master_subset_proto_rawDesc), len(file_master_subset_proto_rawDesc))) + }) + return file_master_subset_proto_rawDescData +} + +var file_master_subset_proto_msgTypes = make([]protoimpl.MessageInfo, 3) +var file_master_subset_proto_goTypes = []any{ + (*ListClusterNodesRequest)(nil), // 0: master_pb.ListClusterNodesRequest + (*ListClusterNodesResponse)(nil), // 1: master_pb.ListClusterNodesResponse + (*ListClusterNodesResponse_ClusterNode)(nil), // 2: master_pb.ListClusterNodesResponse.ClusterNode +} +var file_master_subset_proto_depIdxs = []int32{ + 2, // 0: master_pb.ListClusterNodesResponse.cluster_nodes:type_name -> master_pb.ListClusterNodesResponse.ClusterNode + 0, // 1: master_pb.Seaweed.ListClusterNodes:input_type -> master_pb.ListClusterNodesRequest + 1, // 2: master_pb.Seaweed.ListClusterNodes:output_type -> master_pb.ListClusterNodesResponse + 2, // [2:3] is the sub-list for method output_type + 1, // [1:2] is the sub-list for method input_type + 1, // [1:1] is the sub-list for extension type_name + 1, // [1:1] is the sub-list for extension extendee + 0, // [0:1] is the sub-list for field type_name +} + +func init() { file_master_subset_proto_init() } +func file_master_subset_proto_init() { + if File_master_subset_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_master_subset_proto_rawDesc), len(file_master_subset_proto_rawDesc)), + NumEnums: 0, + NumMessages: 3, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_master_subset_proto_goTypes, + DependencyIndexes: file_master_subset_proto_depIdxs, + MessageInfos: file_master_subset_proto_msgTypes, + }.Build() + File_master_subset_proto = out.File + file_master_subset_proto_goTypes = nil + file_master_subset_proto_depIdxs = nil +} diff --git a/seaweed-block/core/frontend/chunkstore/masterpb/master_subset.proto b/seaweed-block/core/frontend/chunkstore/masterpb/master_subset.proto new file mode 100644 index 0000000000..4c4fe74852 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/masterpb/master_subset.proto @@ -0,0 +1,33 @@ +// Minimal subset of SeaweedFS master.proto (seaweed-mono, weed/pb/master.proto) +// used by the single-filer startup check. +// +// Package, service, message names and field numbers are copied verbatim so +// the wire format and the gRPC method path (/master_pb.Seaweed/ListClusterNodes) +// match a real master. Fields the check never reads are omitted; protobuf +// keeps them as unknown fields on decode. +// +// Regenerate (from this directory): +// protoc --go_out=. --go_opt=paths=source_relative \ +// --go-grpc_out=. --go-grpc_opt=paths=source_relative master_subset.proto +syntax = "proto3"; + +package master_pb; + +option go_package = "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/masterpb"; + +service Seaweed { + rpc ListClusterNodes (ListClusterNodesRequest) returns (ListClusterNodesResponse) {} +} + +message ListClusterNodesRequest { + string client_type = 1; + string filer_group = 2; + int32 limit = 4; +} + +message ListClusterNodesResponse { + message ClusterNode { + string address = 1; + } + repeated ClusterNode cluster_nodes = 1; +} diff --git a/seaweed-block/core/frontend/chunkstore/masterpb/master_subset_grpc.pb.go b/seaweed-block/core/frontend/chunkstore/masterpb/master_subset_grpc.pb.go new file mode 100644 index 0000000000..00821f8c1e --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/masterpb/master_subset_grpc.pb.go @@ -0,0 +1,133 @@ +// Minimal subset of SeaweedFS master.proto (seaweed-mono, weed/pb/master.proto) +// used by the single-filer startup check. +// +// Package, service, message names and field numbers are copied verbatim so +// the wire format and the gRPC method path (/master_pb.Seaweed/ListClusterNodes) +// match a real master. Fields the check never reads are omitted; protobuf +// keeps them as unknown fields on decode. +// +// Regenerate (from this directory): +// protoc --go_out=. --go_opt=paths=source_relative \ +// --go-grpc_out=. --go-grpc_opt=paths=source_relative master_subset.proto + +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.6.2 +// - protoc v3.12.4 +// source: master_subset.proto + +package masterpb + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + Seaweed_ListClusterNodes_FullMethodName = "/master_pb.Seaweed/ListClusterNodes" +) + +// SeaweedClient is the client API for Seaweed service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type SeaweedClient interface { + ListClusterNodes(ctx context.Context, in *ListClusterNodesRequest, opts ...grpc.CallOption) (*ListClusterNodesResponse, error) +} + +type seaweedClient struct { + cc grpc.ClientConnInterface +} + +func NewSeaweedClient(cc grpc.ClientConnInterface) SeaweedClient { + return &seaweedClient{cc} +} + +func (c *seaweedClient) ListClusterNodes(ctx context.Context, in *ListClusterNodesRequest, opts ...grpc.CallOption) (*ListClusterNodesResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ListClusterNodesResponse) + err := c.cc.Invoke(ctx, Seaweed_ListClusterNodes_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// SeaweedServer is the server API for Seaweed service. +// All implementations must embed UnimplementedSeaweedServer +// for forward compatibility. +type SeaweedServer interface { + ListClusterNodes(context.Context, *ListClusterNodesRequest) (*ListClusterNodesResponse, error) + mustEmbedUnimplementedSeaweedServer() +} + +// UnimplementedSeaweedServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedSeaweedServer struct{} + +func (UnimplementedSeaweedServer) ListClusterNodes(context.Context, *ListClusterNodesRequest) (*ListClusterNodesResponse, error) { + return nil, status.Error(codes.Unimplemented, "method ListClusterNodes not implemented") +} +func (UnimplementedSeaweedServer) mustEmbedUnimplementedSeaweedServer() {} +func (UnimplementedSeaweedServer) testEmbeddedByValue() {} + +// UnsafeSeaweedServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to SeaweedServer will +// result in compilation errors. +type UnsafeSeaweedServer interface { + mustEmbedUnimplementedSeaweedServer() +} + +func RegisterSeaweedServer(s grpc.ServiceRegistrar, srv SeaweedServer) { + // If the following call panics, it indicates UnimplementedSeaweedServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&Seaweed_ServiceDesc, srv) +} + +func _Seaweed_ListClusterNodes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ListClusterNodesRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SeaweedServer).ListClusterNodes(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Seaweed_ListClusterNodes_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SeaweedServer).ListClusterNodes(ctx, req.(*ListClusterNodesRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// Seaweed_ServiceDesc is the grpc.ServiceDesc for Seaweed service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var Seaweed_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "master_pb.Seaweed", + HandlerType: (*SeaweedServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "ListClusterNodes", + Handler: _Seaweed_ListClusterNodes_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "master_subset.proto", +} diff --git a/seaweed-block/core/frontend/chunkstore/single_filer.go b/seaweed-block/core/frontend/chunkstore/single_filer.go new file mode 100644 index 0000000000..7d21789c8e --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/single_filer.go @@ -0,0 +1,193 @@ +package chunkstore + +import ( + "context" + "errors" + "fmt" + "net" + "net/netip" + "strconv" + "strings" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/masterpb" +) + +// ErrNotSingleFiler: block metadata needs exactly one filer behind the +// configured address. Several filers in one group each serve the namespace +// from their own metadata store and catch up on each other's changes +// asynchronously, so a compare-and-swap on one filer does not exclude a +// concurrent writer on another. This is a startup census, not an ongoing +// fence: a filer added to the group later is not detected. +var ErrNotSingleFiler = errors.New("chunkstore: block metadata needs exactly one filer") + +// singleFilerWait bounds the whole check; singleFilerRetry spaces the +// rounds; singleFilerAttempt bounds one master call within the remaining +// time (vars for tests). A filer registers with the master only some +// seconds after it serves (14 s measured with a fresh filer), so "the +// target is not listed yet" is retried until the bound. +var ( + singleFilerWait = 60 * time.Second + singleFilerRetry = time.Second + singleFilerAttempt = 5 * time.Second +) + +// CheckSingleFiler asks the filer for its masters and filer group +// (filer_pb.SeaweedFiler/GetFilerConfiguration), then asks every master for +// the filers registered in that group (master_pb.Seaweed/ListClusterNodes, +// client_type "filer"). It passes when a master lists exactly one filer and +// that filer is the configured one. Any master listing another filer, or +// several, refuses at once, whichever master answers first. No master +// listing the target yet, or none answering, is retried until the bound and +// then refused (fail closed). +func (c *SWFS) CheckSingleFiler(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, singleFilerWait) + defer cancel() + // The dial is lazy and the filer may still be starting: wait for it, within the bound. + cfg, err := c.fc.GetFilerConfiguration(ctx, &filerpb.GetFilerConfigurationRequest{}, grpc.WaitForReady(true)) + if err != nil { + return fmt.Errorf("%w: filer %s configuration: %v", ErrNotSingleFiler, c.cfg.FilerGRPC, err) + } + if len(cfg.GetMasters()) == 0 { + return fmt.Errorf("%w: filer %s reports no master, cannot list its group", ErrNotSingleFiler, c.cfg.FilerGRPC) + } + var tried []string + for { + ok, err := c.singleFilerRound(ctx, cfg, &tried) + if ok || err != nil { + return err + } + select { + case <-ctx.Done(): + return fmt.Errorf("%w: could not confirm filer %s as the only filer within %s: %s", ErrNotSingleFiler, c.cfg.FilerGRPC, singleFilerWait, strings.Join(tried, "; ")) + case <-time.After(singleFilerRetry): + } + } +} + +// singleFilerRound asks every master once. It refuses when any master lists +// several filers or a filer other than the target; it passes when no master +// refuses and at least one lists exactly the target; otherwise it asks for +// another round (tried keeps each master's answer). +func (c *SWFS) singleFilerRound(ctx context.Context, cfg *filerpb.GetFilerConfigurationResponse, tried *[]string) (bool, error) { + *tried = (*tried)[:0] + group := cfg.GetFilerGroup() + sawTarget := false + for _, m := range cfg.GetMasters() { + addr, err := grpcAddress(m) + if err != nil { + *tried = append(*tried, fmt.Sprintf("%s: %v", m, err)) + continue + } + actx, cancel := context.WithTimeout(ctx, singleFilerAttempt) + nodes, err := listFilers(actx, addr, group) + cancel() + if err != nil { + *tried = append(*tried, fmt.Sprintf("%s: %v", addr, err)) + continue + } + switch { + case len(nodes) > 1: + return false, fmt.Errorf("%w: filer group %q has %d filers %v (master %s)", ErrNotSingleFiler, group, len(nodes), nodes, addr) + case len(nodes) == 1 && !c.isTarget(ctx, nodes[0]): + return false, fmt.Errorf("%w: master %s lists filer %s in group %q, not the configured %s", ErrNotSingleFiler, addr, nodes[0], group, c.cfg.FilerGRPC) + case len(nodes) == 1: + sawTarget = true + default: + *tried = append(*tried, addr+": lists no filer in group "+strconv.Quote(group)+" yet") + } + } + if ctx.Err() != nil { + // The bound passed while a later master was still being asked: + // its view is unknown, so an earlier favourable answer does not + // count. + return false, nil + } + return sawTarget, nil +} + +// isTarget reports whether a filer address listed by a master is the +// configured filer: the same gRPC port, and the same host or hosts that +// resolve to a common address. Addresses compare with their IPv6 zone; an +// address that does not parse never matches (fail closed). +func (c *SWFS) isTarget(ctx context.Context, listed string) bool { + got, err := grpcAddress(listed) + if err != nil { + return false + } + gh, gp, err1 := net.SplitHostPort(got) + wh, wp, err2 := net.SplitHostPort(c.cfg.FilerGRPC) + if err1 != nil || err2 != nil || gp != wp { + return false + } + if gh == wh { + return true + } + ga, err1 := net.DefaultResolver.LookupHost(ctx, gh) + wa, err2 := net.DefaultResolver.LookupHost(ctx, wh) + if err1 != nil || err2 != nil { + return false + } + for _, a := range ga { + pa, err := netip.ParseAddr(a) + if err != nil { + continue + } + for _, b := range wa { + if pb, err := netip.ParseAddr(b); err == nil && pa.Unmap() == pb.Unmap() { + return true + } + } + } + return false +} + +func listFilers(ctx context.Context, addr, group string) ([]string, error) { + conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + return nil, err + } + defer conn.Close() + resp, err := masterpb.NewSeaweedClient(conn).ListClusterNodes(ctx, &masterpb.ListClusterNodesRequest{ClientType: "filer", FilerGroup: group}) + if err != nil { + return nil, err + } + var out []string + for _, n := range resp.GetClusterNodes() { + out = append(out, n.GetAddress()) + } + return out, nil +} + +// grpcAddress turns a SeaweedFS server address into its gRPC address: +// "host:port.grpcPort" names the gRPC port; "host:port" uses port+10000 +// (SeaweedFS's convention). +func grpcAddress(a string) (string, error) { + host, port, err := net.SplitHostPort(a) + if err != nil { + // "host:port.grpcPort" does not parse as host:port; split it first. + i := strings.LastIndex(a, ":") + if i < 0 { + return "", fmt.Errorf("bad server address %q", a) + } + host, port = a[:i], a[i+1:] + } + if http, grpcPort, ok := strings.Cut(port, "."); ok { + if _, err := strconv.Atoi(http); err != nil { + return "", fmt.Errorf("bad server address %q", a) + } + if _, err := strconv.Atoi(grpcPort); err != nil { + return "", fmt.Errorf("bad server address %q", a) + } + return net.JoinHostPort(host, grpcPort), nil + } + p, err := strconv.Atoi(port) + if err != nil || p <= 0 || p+10000 > 65535 { + return "", fmt.Errorf("bad server address %q", a) + } + return net.JoinHostPort(host, strconv.Itoa(p+10000)), nil +} diff --git a/seaweed-block/core/frontend/chunkstore/single_filer_test.go b/seaweed-block/core/frontend/chunkstore/single_filer_test.go new file mode 100644 index 0000000000..e793c75cd3 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/single_filer_test.go @@ -0,0 +1,313 @@ +package chunkstore + +import ( + "context" + "errors" + "net" + "strings" + "sync" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/masterpb" +) + +type configFiler struct { + filerpb.UnimplementedSeaweedFilerServer + mu sync.Mutex + masters []string + group string + err error +} + +func (f *configFiler) GetFilerConfiguration(context.Context, *filerpb.GetFilerConfigurationRequest) (*filerpb.GetFilerConfigurationResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + if f.err != nil { + return nil, f.err + } + return &filerpb.GetFilerConfigurationResponse{Masters: f.masters, FilerGroup: f.group}, nil +} + +type nodesMaster struct { + masterpb.UnimplementedSeaweedServer + mu sync.Mutex + filers []string + emptyN int // the first emptyN calls list no filer (not registered yet) + stall bool // never answers (until the caller's deadline) + calls int + got *masterpb.ListClusterNodesRequest +} + +func (m *nodesMaster) ListClusterNodes(ctx context.Context, r *masterpb.ListClusterNodesRequest) (*masterpb.ListClusterNodesResponse, error) { + m.mu.Lock() + m.got = r + m.calls++ + calls, stall := m.calls, m.stall + filers := append([]string(nil), m.filers...) + m.mu.Unlock() + if stall { + <-ctx.Done() + return nil, ctx.Err() + } + resp := &masterpb.ListClusterNodesResponse{} + if calls <= m.emptyN { + return resp, nil + } + for _, a := range filers { + resp.ClusterNodes = append(resp.ClusterNodes, &masterpb.ListClusterNodesResponse_ClusterNode{Address: a}) + } + return resp, nil +} + +func (m *nodesMaster) callCount() int { + m.mu.Lock() + defer m.mu.Unlock() + return m.calls +} + +// startMaster serves a fake master and returns its address in SeaweedFS's +// "host:httpPort.grpcPort" form. +func startMaster(t *testing.T, m *nodesMaster) string { + t.Helper() + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer() + masterpb.RegisterSeaweedServer(srv, m) + go func() { _ = srv.Serve(lis) }() + t.Cleanup(srv.Stop) + _, port, _ := net.SplitHostPort(lis.Addr().String()) + return "127.0.0.1:9333." + port +} + +// deadAddress is a gRPC port nothing listens on. +func deadAddress(t *testing.T) string { + t.Helper() + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + _, port, _ := net.SplitHostPort(lis.Addr().String()) + _ = lis.Close() + return "127.0.0.1:9333." + port +} + +// startConfigFiler serves a fake filer and dials it. It returns the client +// and the filer's address as a master lists it ("host:httpPort.grpcPort"). +func startConfigFiler(t *testing.T, f *configFiler) (*SWFS, string) { + t.Helper() + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer() + filerpb.RegisterSeaweedFilerServer(srv, f) + go func() { _ = srv.Serve(lis) }() + t.Cleanup(srv.Stop) + c, err := DialSWFS(SWFSConfig{FilerGRPC: lis.Addr().String()}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = c.Close() }) + _, port, _ := net.SplitHostPort(lis.Addr().String()) + return c, "127.0.0.1:8888." + port +} + +// cluster starts a fake filer and one fake master per entry of masters; each +// master's listing is built from the filer's own listed address (self). +func cluster(t *testing.T, group string, masters ...func(self string) *nodesMaster) (*SWFS, []*nodesMaster) { + t.Helper() + f := &configFiler{group: group} + c, self := startConfigFiler(t, f) + var ms []*nodesMaster + var addrs []string + for _, mk := range masters { + m := mk(self) + ms = append(ms, m) + addrs = append(addrs, startMaster(t, m)) + } + f.mu.Lock() + f.masters = addrs + f.mu.Unlock() + return c, ms +} + +func lists(filers ...string) func(string) *nodesMaster { + return func(self string) *nodesMaster { + var out []string + for _, a := range filers { + if a == "self" { + a = self + } + out = append(out, a) + } + return &nodesMaster{filers: out} + } +} + +func shortBounds(t *testing.T) { + t.Helper() + w, r, a := singleFilerWait, singleFilerRetry, singleFilerAttempt + singleFilerWait, singleFilerRetry, singleFilerAttempt = 1500*time.Millisecond, 100*time.Millisecond, 300*time.Millisecond + t.Cleanup(func() { singleFilerWait, singleFilerRetry, singleFilerAttempt = w, r, a }) +} + +func refusedAtOnce(t *testing.T, what string, c *SWFS, want string) { + t.Helper() + start := time.Now() + err := c.CheckSingleFiler(context.Background()) + if !errors.Is(err, ErrNotSingleFiler) || !strings.Contains(err.Error(), want) || time.Since(start) > 700*time.Millisecond { + t.Fatalf("%s: %v after %s; want ErrNotSingleFiler naming %q, at once", what, err, time.Since(start), want) + } +} + +func refusedAtBound(t *testing.T, what string, c *SWFS) { + t.Helper() + start := time.Now() + err := c.CheckSingleFiler(context.Background()) + if !errors.Is(err, ErrNotSingleFiler) || time.Since(start) < singleFilerWait { + t.Fatalf("%s: %v after %s; want a refusal only at the %s bound", what, err, time.Since(start), singleFilerWait) + } +} + +// The configured filer passes only as the one filer of its group, listed by +// a master; also when it registers only after a few rounds. +func TestCheckSingleFilerPasses(t *testing.T) { + shortBounds(t) + c, ms := cluster(t, "g1", lists("self")) + if err := c.CheckSingleFiler(context.Background()); err != nil { + t.Fatalf("the target as the one filer: %v", err) + } + if ms[0].got.GetClientType() != "filer" || ms[0].got.GetFilerGroup() != "g1" { + t.Fatalf("master asked for %q in group %q; want filer in g1", ms[0].got.GetClientType(), ms[0].got.GetFilerGroup()) + } + c, ms = cluster(t, "", func(self string) *nodesMaster { return &nodesMaster{filers: []string{self}, emptyN: 3} }) + if err := c.CheckSingleFiler(context.Background()); err != nil || ms[0].callCount() != 4 { + t.Fatalf("target registered on the 4th round: %v after %d calls; want a pass", err, ms[0].callCount()) + } + // A dead or stalled first master does not hide a healthy second one, and + // a stalled call costs one attempt, not the whole bound. + c, _ = cluster(t, "", func(string) *nodesMaster { return &nodesMaster{stall: true} }, lists("self")) + start := time.Now() + if err := c.CheckSingleFiler(context.Background()); err != nil || time.Since(start) > 2*singleFilerAttempt { + t.Fatalf("stalled first master: %v after %s; want a pass within one attempt", err, time.Since(start)) + } + f := &configFiler{} + c, self := startConfigFiler(t, f) + f.mu.Lock() + f.masters = []string{deadAddress(t), startMaster(t, &nodesMaster{filers: []string{self}})} + f.mu.Unlock() + if err := c.CheckSingleFiler(context.Background()); err != nil { + t.Fatalf("dead first master: %v", err) + } +} + +// Refusals, in both master orders: several filers, or another filer listed +// as the sole filer while the target is not registered, refuse at once, +// whichever master answers first. +func TestCheckSingleFilerRefusesAnotherOrSeveralFilers(t *testing.T) { + shortBounds(t) + c, _ := cluster(t, "", lists("self", "10.0.0.2:8888")) + refusedAtOnce(t, "two filers", c, "10.0.0.2:8888") + c, _ = cluster(t, "", lists("10.9.9.9:8888")) + refusedAtOnce(t, "another sole filer, target not registered", c, "10.9.9.9:8888") + c, _ = cluster(t, "", lists("self"), lists("self", "10.0.0.2:8888")) + refusedAtOnce(t, "first master favourable, second lists two", c, "10.0.0.2:8888") + c, _ = cluster(t, "", lists("self", "10.0.0.2:8888"), lists("self")) + refusedAtOnce(t, "first master lists two, second favourable", c, "10.0.0.2:8888") + c, _ = cluster(t, "", lists("self"), lists("10.9.9.9:8888")) + refusedAtOnce(t, "masters disagree on the sole filer", c, "10.9.9.9:8888") + c, _ = cluster(t, "", lists("10.9.9.9:8888"), lists("self")) + refusedAtOnce(t, "masters disagree on the sole filer, reversed", c, "10.9.9.9:8888") +} + +// Distinct scoped IPv6 addresses are different filers; the zone counts, and +// an address that does not parse never matches. +func TestIsTargetComparesScopedAddresses(t *testing.T) { + for _, c := range []struct { + configured, listed string + want bool + }{ + {"[fe80::2%eth0]:18888", "[fe80::1%eth0]:8888.18888", false}, + {"[fe80::1%eth0]:18888", "[fe80::1%eth1]:8888.18888", false}, + {"[fe80::1%eth0]:18888", "[fe80::1%eth0]:8888.18888", true}, + {"127.0.0.1:18888", "127.0.0.1:8888", true}, + {"127.0.0.1:18888", "127.0.0.2:8888", false}, + {"127.0.0.1:18888", "127.0.0.1:8889", false}, + {"[::ffff:127.0.0.1]:18888", "127.0.0.1:8888", true}, + } { + s := &SWFS{cfg: SWFSConfig{FilerGRPC: c.configured}} + if got := s.isTarget(context.Background(), c.listed); got != c.want { + t.Errorf("configured %s, listed %s: isTarget %v, want %v", c.configured, c.listed, got, c.want) + } + } +} + +// A favourable first master does not pass once the bound has run out while +// a later master is still being asked: that master's view is unknown. +func TestCheckSingleFilerFavourableThenStalledRefuses(t *testing.T) { + w, r, a := singleFilerWait, singleFilerRetry, singleFilerAttempt + singleFilerWait, singleFilerRetry, singleFilerAttempt = 800*time.Millisecond, 100*time.Millisecond, 5*time.Second + t.Cleanup(func() { singleFilerWait, singleFilerRetry, singleFilerAttempt = w, r, a }) + c, _ := cluster(t, "", lists("self"), func(string) *nodesMaster { return &nodesMaster{stall: true} }) + start := time.Now() + err := c.CheckSingleFiler(context.Background()) + if !errors.Is(err, ErrNotSingleFiler) || time.Since(start) < singleFilerWait { + t.Fatalf("favourable then stalled past the bound: %v after %s; want a refusal at the bound", err, time.Since(start)) + } +} + +// Fail closed at the bound, after retrying: no filer listed, an unreachable +// master; and at once: a filer without configuration or without a master. +func TestCheckSingleFilerFailsClosed(t *testing.T) { + shortBounds(t) + c, ms := cluster(t, "", lists()) + refusedAtBound(t, "no filer listed", c) + if n := ms[0].callCount(); n < 3 { + t.Fatalf("no filer listed: %d rounds; want retries until the bound", n) + } + f := &configFiler{} + c, _ = startConfigFiler(t, f) + f.mu.Lock() + f.masters = []string{deadAddress(t)} + f.mu.Unlock() + refusedAtBound(t, "unreachable master", c) + c, _ = startConfigFiler(t, &configFiler{err: status.Error(codes.Unimplemented, "no")}) + if err := c.CheckSingleFiler(context.Background()); !errors.Is(err, ErrNotSingleFiler) { + t.Fatalf("filer without configuration: %v; want a refusal", err) + } + c, _ = startConfigFiler(t, &configFiler{}) + if err := c.CheckSingleFiler(context.Background()); !errors.Is(err, ErrNotSingleFiler) { + t.Fatalf("filer with no master: %v; want a refusal", err) + } +} + +func TestGRPCAddress(t *testing.T) { + for in, want := range map[string]string{ + "m1:9333": "m1:19333", + "m1:9333.19555": "m1:19555", + "10.0.0.5:9333": "10.0.0.5:19333", + "[::1]:9333": "[::1]:19333", + "m1:9333.notaport": "", + "m1": "", + "m1:60000": "", + } { + got, err := grpcAddress(in) + if want == "" { + if err == nil { + t.Errorf("%q: got %q, want an error", in, got) + } + continue + } + if err != nil || got != want { + t.Errorf("%q: got %q %v, want %q", in, got, err, want) + } + } +} diff --git a/seaweed-block/core/frontend/durable/cut_policy_test.go b/seaweed-block/core/frontend/durable/cut_policy_test.go index 510d3846ef..18ad8b8d3a 100644 --- a/seaweed-block/core/frontend/durable/cut_policy_test.go +++ b/seaweed-block/core/frontend/durable/cut_policy_test.go @@ -156,3 +156,28 @@ func TestCutPolicy_NothingDueWhileReconciling(t *testing.T) { t.Fatalf("after reconciliation: %q %v; want an immediate periodic cut", r, ok) } } + +func TestCutPolicy_StaggerPreservesExplicitTimerReset(t *testing.T) { + pol := testPolicy() + s := initialCutSchedule("v1", pol.interval, t0, true) + if !s.lastSuccess.Equal(t0) || !s.firstDue.After(t0) || s.firstDue.After(t0.Add(pol.interval)) { + t.Fatal("phase fabricated success or exceeded first period", s) + } + if _, ok := pol.dueNR(s, s.firstDue.Add(-time.Nanosecond)); ok { + t.Fatal("initial phase ignored") + } + if _, ok := pol.dueNR(s, s.firstDue); !ok { + t.Fatal("first phased cut not due") + } + explicit := t0.Add(s.firstDue.Sub(t0) / 2) + s = s.observe(explicit.UnixNano()) + if !s.lastSuccess.Equal(explicit) || !s.firstDue.IsZero() { + t.Fatal("stagger hid explicit success", s) + } + if _, ok := pol.dueNR(s, explicit.Add(pol.interval-time.Nanosecond)); ok { + t.Fatal("timer advanced before explicit success interval") + } + if _, ok := pol.dueNR(s, explicit.Add(pol.interval)); !ok { + t.Fatal("explicit success did not restart timer") + } +} diff --git a/seaweed-block/core/frontend/durable/head_belt_close_test.go b/seaweed-block/core/frontend/durable/head_belt_close_test.go new file mode 100644 index 0000000000..803a34531a --- /dev/null +++ b/seaweed-block/core/frontend/durable/head_belt_close_test.go @@ -0,0 +1,83 @@ +package durable_test + +import ( + "context" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" + "sync" + "testing" + "time" +) + +type beltClaimNotice struct { + storage.ChunkRemote + claimed chan struct{} + once sync.Once +} + +func (r *beltClaimNotice) CASHead(ctx context.Context, v storage.ChunkHeadVersion, h storage.ChunkHead) (uint64, error) { + gen, err := r.ChunkRemote.CASHead(ctx, v, h) + if err == nil { + r.once.Do(func() { close(r.claimed) }) + } + return gen, err +} + +func TestHeadBeltProviderCloseCancelsCooling(t *testing.T) { + r := &beltClaimNotice{ChunkRemote: seededRemote(t), claimed: make(chan struct{})} + view := newStubView(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2})) + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, + NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkHeadCoolingWindow: 3 * time.Second, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + backend := p.Backend("v1") + ctx, cancel := context.WithCancel(context.Background()) + recovered := make(chan error, 1) + closed := make(chan error, 1) + closeStarted := false + t.Cleanup(func() { + cancel() + if !closeStarted { + go func() { closed <- p.Close() }() + } + select { + case <-recovered: + case <-time.After(5 * time.Second): + t.Error("recovery did not join") + } + select { + case <-closed: + case <-time.After(5 * time.Second): + t.Error("provider close did not join") + } + }) + go func() { _, err := p.RecoverVolume(ctx, "v1"); recovered <- err }() + select { + case <-r.claimed: + case <-time.After(30 * time.Second): + t.Fatal("takeover did not reach cooling") + } + closeStarted = true + go func() { closed <- p.Close() }() + select { + case err := <-closed: + closed <- err // cleanup joins this completed owner too + if err != nil { + t.Fatal(err) + } + case <-time.After(time.Second): + t.Fatal("provider Close waited for takeover cooling instead of canceling it") + } + if _, err := backend.Read(context.Background(), 0, make([]byte, 4096)); err == nil { + t.Fatal("closed provider served I/O") + } +} diff --git a/seaweed-block/core/frontend/durable/host_limit_test.go b/seaweed-block/core/frontend/durable/host_limit_test.go new file mode 100644 index 0000000000..e4b38a628b --- /dev/null +++ b/seaweed-block/core/frontend/durable/host_limit_test.go @@ -0,0 +1,95 @@ +package durable_test + +import ( + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/hostlimit" + "github.com/seaweedfs/seaweed-block/core/storage" + "testing" +) + +func TestHostCutLimitDoesNotGateGuestIO(t *testing.T) { + c := hostlimit.DefaultConfig(t.TempDir()) + c.NormalSlots = 1 + c.UrgentSlots = 1 + holder, e := hostlimit.New(c) + if e != nil { + t.Fatal(e) + } + defer holder.Close() + x, e := holder.Admit(context.Background(), 1, nil) + if e != nil { + t.Fatal(e) + } + defer holder.Release(x) + lim, e := hostlimit.New(c) + if e != nil { + t.Fatal(e) + } + defer lim.Close() + r := storage.NewMemChunkRemote() + p, e := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: pcBlocks, BlockSize: 4096, ChunkBlocks: pcChunkBlocks, ChunkBudget: lim, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }}, v1View()) + if e != nil { + t.Fatal(e) + } + defer p.Close() + s := openRecovered(t, p) + if _, e = s.Write(0, block(0x72)); e != nil { + t.Fatal(e) + } + if _, e = s.Sync(); e != nil { + t.Fatal(e) + } + if _, e = p.CaptureVolume(context.Background(), "v1"); !errors.Is(e, storage.ErrChunkCaptureRefused) { + t.Fatalf("full cut pool: %v", e) + } + if _, e = s.Write(1, block(0x73)); e != nil { + t.Fatal("limiter blocked write", e) + } + if _, e = s.Sync(); e != nil { + t.Fatal("limiter blocked Flush", e) + } + if b, e := s.Read(0); e != nil || b[0] != 0x72 { + t.Fatal("limiter blocked read", e) + } + h, _ := r.GetHead(context.Background()) + if h.Gen != 0 { + t.Fatal("refused cut published") + } +} + +func TestHostUnusablePoolExplicitDurabilityUsesUrgent(t *testing.T) { + c := hostlimit.DefaultConfig(t.TempDir() + "/missing") + lim, err := hostlimit.New(c) + if err != nil { + t.Fatal(err) + } + defer lim.Close() + remote := storage.NewMemChunkRemote() + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: pcBlocks, BlockSize: 4096, ChunkBlocks: pcChunkBlocks, ChunkBudget: lim, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, v1View()) + if err != nil { + t.Fatal(err) + } + defer p.Close() + s := openRecovered(t, p) + if _, err = s.Write(0, block(0x6a)); err != nil { + t.Fatal(err) + } + if _, err = s.Sync(); err != nil { + t.Fatal(err) + } + if _, err = p.CaptureVolume(context.Background(), "v1"); !errors.Is(err, hostlimit.ErrBusy) { + t.Fatalf("background cut bypassed missing pool: %v", err) + } + if err = p.MakeVolumeRemoteDurable(context.Background(), "v1", 1); err != nil { + t.Fatalf("explicit durability was not urgent: %v", err) + } + head, err := remote.GetHead(context.Background()) + if err != nil || head.RemoteLSN < 1 { + t.Fatalf("explicit durability did not publish: %+v %v", head, err) + } + if st := lim.Snapshot().(hostlimit.Stats); st.Fallback != 1 || st.SkippedByClass[hostlimit.Normal] != 1 { + t.Fatalf("wrong durability/periodic policy: %+v", st) + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 2d4155d0b8..c5023e12a6 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -159,6 +159,9 @@ type ProviderConfig struct { // ChunkHolder names this node in HEAD; blockvolume sets // /. Zero: the replica ID (tests). ChunkHolder string + // Zero uses immediate HEAD confirmation for the supported single-filer + // topology. Nonzero cooling is reserved for explicit topology experiments. + ChunkHeadCoolingWindow time.Duration // ChunkReadMissTimeout bounds one remote fetch of an absent block. // Zero: the storage default. ChunkReadMissTimeout time.Duration @@ -188,7 +191,10 @@ type ProviderConfig struct { // ChunkPayloadMemoryBudget bounds one volume's cut payloads; zero uses the storage default. ChunkPayloadMemoryBudget int64 // ChunkBudget optionally admits cuts and accounts COW bytes through the host limiter. - ChunkBudget storage.Budget + ChunkBudget storage.Budget + ChunkCOWSpillLimit int64 + // ChunkStagger spreads automatic cuts by the stable volume-ID phase. + ChunkStagger bool } // DurableProvider is the production frontend.Provider implementation. @@ -295,6 +301,7 @@ type ChunkStatus struct { Fenced bool RemoteLSN uint64 Stats storage.ChunkLayerStats + HostBudget any `json:",omitempty"` } // NewDurableProvider constructs a provider. view is the ONLY @@ -561,6 +568,9 @@ func (p *DurableProvider) DurableStatuses() []VolumeStatus { if cv.layer != nil { cs.Attached, cs.Fenced, cs.RemoteLSN, cs.Stats = true, cv.layer.Fenced(), cv.layer.RemoteLSN(), cv.layer.Stats() } + if budget, ok := p.cfg.ChunkBudget.(interface{ Snapshot() any }); ok { + cs.HostBudget = budget.Snapshot() + } st.Chunk = cs } out = append(out, st) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index fed1eed93e..ea079fb7ef 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -15,6 +15,7 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/hostlimit" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -328,6 +329,10 @@ func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer st } func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h *volHandle) (storage.ChunkLayer, error) { + // Close cancels local takeover cooling as well as each bound remote RPC. + ctx, cancelAttach := context.WithCancel(ctx) + stopClose := context.AfterFunc(p.closeCtx, cancelAttach) + defer func() { stopClose(); cancelAttach() }() ws, ok := h.storage.(*storage.WALStore) if !ok { return nil, fmt.Errorf("durable: %s storage is %T, not a walstore", ImplWALStoreChunk, h.storage) @@ -357,6 +362,11 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h holder = proj.ReplicaID } bound := &closeBoundRemote{ChunkRemote: inner, done: p.closeCtx} + if pace, ok := p.cfg.ChunkBudget.(interface { + WaitUpload(context.Context, int) error + }); ok { + bound.waitUpload = pace.WaitUpload + } bound.setAttach(ctx) // the attach's calls also end with the caller's ctx defer bound.setAttach(nil) var remote storage.ChunkRemote = bound @@ -366,6 +376,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h cfg := storage.ChunkLayerConfig{ ChunkBlocks: p.cfg.ChunkBlocks, RestoreChunkBytes: uint64(ws.BlockSize()) * uint64(p.cfg.ChunkBlocks), + HeadCoolingWindow: p.cfg.ChunkHeadCoolingWindow, Epoch: lin.epoch, Holder: holder, FreshFromHead: h.fresh, @@ -376,6 +387,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h UploadConcurrency: p.cfg.ChunkUploadConcurrency, PayloadMemoryBudget: p.cfg.ChunkPayloadMemoryBudget, Budget: p.cfg.ChunkBudget, + COWSpillLimit: p.cfg.ChunkCOWSpillLimit, CaptureAllowed: func() error { cur := p.view.Projection() if !cur.Healthy || cur.VolumeID != volumeID || lin.volumeID != volumeID { @@ -462,7 +474,8 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h // attach runs, its calls also end with the attach caller's context. type closeBoundRemote struct { storage.ChunkRemote - done context.Context + done context.Context + waitUpload func(context.Context, int) error mu sync.Mutex attach context.Context @@ -499,6 +512,11 @@ func (r *closeBoundRemote) bind(ctx context.Context) (context.Context, func()) { func (r *closeBoundRemote) Put(ctx context.Context, key string, data []byte) error { c, end := r.bind(ctx) defer end() + if r.waitUpload != nil { + if err := r.waitUpload(c, len(data)); err != nil { + return err + } + } return r.ChunkRemote.Put(c, key, data) } @@ -514,6 +532,15 @@ func (r *closeBoundRemote) GetHead(ctx context.Context) (storage.ChunkHead, erro return r.ChunkRemote.GetHead(c) } +func (r *closeBoundRemote) GetHeadRoot(ctx context.Context) (storage.ChunkHead, error) { + c, end := r.bind(ctx) + defer end() + if reader, ok := r.ChunkRemote.(storage.ChunkHeadRootReader); ok { + return reader.GetHeadRoot(c) + } + return r.ChunkRemote.GetHead(c) +} + func (r *closeBoundRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { c, end := r.bind(ctx) defer end() @@ -629,6 +656,7 @@ type cutSchedule struct { failedAt time.Time // end of the last failed automatic cut retryAt time.Time // a failed automatic cut's backoff ends here backoff time.Duration + firstDue time.Time // startup phase only; never a fabricated success } // observe takes in a successful cut the layer reports (any trigger). A @@ -639,6 +667,7 @@ func (s cutSchedule) observe(lastCutNs int64) cutSchedule { c := time.Unix(0, lastCutNs) if c.After(s.lastSuccess) { s.lastSuccess = c + s.firstDue = time.Time{} } if !s.failedAt.IsZero() && c.After(s.failedAt) { s.backoff, s.retryAt, s.failedAt = 0, time.Time{}, time.Time{} @@ -657,7 +686,11 @@ func (pol cutPolicy) due(s cutSchedule, now time.Time, reconciling bool) (string if !s.lastAuto.IsZero() && now.Sub(s.lastAuto) < pol.minSpacing { return "", false } - if pol.interval > 0 && now.Sub(s.lastSuccess) >= pol.interval { + deadline := s.lastSuccess.Add(pol.interval) + if !s.firstDue.IsZero() { + deadline = s.firstDue + } + if pol.interval > 0 && !now.Before(deadline) { return "periodic", true } return "", false @@ -667,6 +700,7 @@ func (pol cutPolicy) due(s cutSchedule, now time.Time, reconciling bool) (string func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error) cutSchedule { s.lastAuto = start if err == nil { + s.firstDue = time.Time{} s.backoff, s.retryAt, s.failedAt = 0, time.Time{}, time.Time{} if end.After(s.lastSuccess) { s.lastSuccess = end @@ -685,6 +719,16 @@ func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error) cutSc return s } +func initialCutSchedule(volumeID string, interval time.Duration, now time.Time, stagger bool) cutSchedule { + s := cutSchedule{lastSuccess: now} + if stagger && interval > 0 { + phase := hostlimit.Phase(volumeID, interval) + startup := hostlimit.Phase(volumeID+":startup", min(interval, 10*time.Second)) + s.firstDue = now.Add(max(phase, startup)) + } + return s +} + // chunkLoop runs the volume's automatic cuts under cutPolicy. A refused // cut (not a healthy primary of this lineage, BASE install) is expected // and logged only when it is something else. A fenced layer can never @@ -697,7 +741,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer backoffMin: chunkCutBackoffMin, backoffMax: chunkCutBackoffMax, } - s := cutSchedule{lastSuccess: time.Now()} + s := initialCutSchedule(volumeID, pol.interval, time.Now(), p.cfg.ChunkStagger) t := time.NewTicker(chunkSchedulePoll) defer t.Stop() for { @@ -780,7 +824,7 @@ func (p *DurableProvider) MakeVolumeRemoteDurable(ctx context.Context, volumeID if err != nil { return err } - return layer.MakeRemoteDurable(ctx, lsn) + return layer.MakeRemoteDurable(hostlimit.WithClass(ctx, hostlimit.Urgent), lsn) } // chunkFenced refuses a volume whose layer attached fenced: HEAD belongs to @@ -811,6 +855,9 @@ func (p *DurableProvider) CutVolume(ctx context.Context, volumeID string, minLSN return storage.ChunkCutResult{}, fmt.Errorf("durable: cut of %s to LSN %d: that LSN was never written (last %d)", volumeID, minLSN, last) } } + if minLSN > 0 { + ctx = hostlimit.WithClass(ctx, hostlimit.Urgent) + } r, err := layer.Cut(ctx) if err != nil { return storage.ChunkCutResult{}, err @@ -876,7 +923,7 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st if err == nil { p.stopChunkLoop(h) var r storage.ChunkCutResult - if r, err = layer.Detach(cutCtx); err == nil { + if r, err = layer.Detach(hostlimit.WithClass(cutCtx, hostlimit.Urgent)); err == nil { return r, h.storage.NextLSN() - 1, nil } } diff --git a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go index e2278f7b30..97a1749e81 100644 --- a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go +++ b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go @@ -23,9 +23,29 @@ type heldTakeoverClaim struct { once, releaseOnce sync.Once holdFor time.Duration readRegistered chan struct{} + resolutionBlocked chan struct{} + resolutionOnce sync.Once } func (r *heldTakeoverClaim) unblock() { r.releaseOnce.Do(func() { close(r.release) }) } +func (r *heldTakeoverClaim) GetHead(ctx context.Context) (storage.ChunkHead, error) { + // The permanent-outage case must hold outcome resolution as well as the + // CAS reply: a committed CAS with readable HEAD can now settle after the + // per-operation deadline. Unbounded diagnostic reads still see the root. + if _, bounded := ctx.Deadline(); bounded && r.holdFor == 0 { + select { + case <-r.claimed: + r.resolutionOnce.Do(func() { close(r.resolutionBlocked) }) + select { + case <-r.release: + case <-ctx.Done(): + return storage.ChunkHead{}, ctx.Err() + } + default: + } + } + return r.ChunkRemote.GetHead(ctx) +} func (r *heldTakeoverClaim) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { gen, err := r.ChunkRemote.CASHead(ctx, expected, next) if err != nil || next.Epoch != 4 { @@ -57,7 +77,7 @@ func (r *heldTakeoverClaim) CASHead(ctx context.Context, expected storage.ChunkH func pendingTakeoverRead(t *testing.T, hold time.Duration) (*durable.DurableProvider, frontend.Backend, *nvme.IOHandler) { t.Helper() - remote := &heldTakeoverClaim{ChunkRemote: seededRemote(t), claimed: make(chan struct{}), release: make(chan struct{}), holdFor: hold, readRegistered: make(chan struct{})} + remote := &heldTakeoverClaim{ChunkRemote: seededRemote(t), claimed: make(chan struct{}), release: make(chan struct{}), holdFor: hold, readRegistered: make(chan struct{}), resolutionBlocked: make(chan struct{})} view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) p := chunkProvider(t, t.TempDir(), remote, view, 0) // Registered after provider cleanup, so release precedes its worker join. @@ -74,6 +94,13 @@ func pendingTakeoverRead(t *testing.T, hold time.Duration) (*durable.DurableProv case <-time.After(10 * time.Second): t.Fatal("takeover CAS never became visible") } + if hold == 0 { + select { + case <-remote.resolutionBlocked: + case <-time.After(30 * time.Second): + t.Fatal("permanent attach did not reach held outcome resolution") + } + } head, err := remote.GetHead(context.Background()) if err != nil || head.Epoch != 4 || head.Holder != "r1" { t.Fatalf("takeover HEAD: %+v, %v", head, err) @@ -91,7 +118,7 @@ func pendingTakeoverRead(t *testing.T, hold time.Duration) (*durable.DurableProv // Model Linux max_retries=5 and CRD=0: at most six attempts, no sleeps. // A status-only fix exhausts them during attachment and becomes guest EIO. func TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable(t *testing.T) { - _, _, handler := pendingTakeoverRead(t, 2500*time.Millisecond) + _, _, handler := pendingTakeoverRead(t, 1500*time.Millisecond) command := nvme.IOCommand{Opcode: 0x02, NSID: 1, SLBA: 33, NLB: 1} start := time.Now() for attempt := 0; attempt <= 5; attempt++ { @@ -141,7 +168,7 @@ func TestWALStoreChunk_PendingReadHonoursEarlierDeadline(t *testing.T) { } func TestWALStoreChunk_TakeoverWriteWaitsForAttach(t *testing.T) { - _, backend, _ := pendingTakeoverRead(t, 2500*time.Millisecond) + _, backend, _ := pendingTakeoverRead(t, 1500*time.Millisecond) start := time.Now() n, err := backend.Write(context.Background(), 33*4096, block(0x74)) if err != nil || n != 4096 { diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index e3024f6317..c762f4d5f1 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -19,6 +19,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/hostlimit" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -264,20 +265,22 @@ func chunkErrorCode(err error) (int, string, bool) { return http.StatusConflict, codeReconciling, true case errors.Is(err, storage.ErrChunkHeadPrecondition): return http.StatusConflict, codeHeadConflict, true - case errors.Is(err, storage.ErrChunkRemoteUnavailable): - return http.StatusServiceUnavailable, chunkstore.CodeRemoteUnavailable, true case errors.Is(err, storage.ErrChunkLayerDetached): return http.StatusConflict, codeClosing, false // stays closed until a new attach case errors.Is(err, storage.ErrChunkLayerClosed): return http.StatusServiceUnavailable, codeClosing, false // the process is shutting down + // A local window abort cancels its uploads; that cancellation is not + // a remote outage. Keep authority and uncertain-publication precedence. + case errors.Is(err, storage.ErrCutCOWAborted): + return http.StatusServiceUnavailable, "cut_aborted", true + case errors.Is(err, storage.ErrChunkRemoteUnavailable): + return http.StatusServiceUnavailable, chunkstore.CodeRemoteUnavailable, true case errors.Is(err, durable.ErrNotChunkVolume), errors.Is(err, durable.ErrVolumeNotOpen): return http.StatusConflict, chunkstore.CodeNotChunkVolume, false case errors.Is(err, context.DeadlineExceeded): return http.StatusServiceUnavailable, chunkstore.CodeDeadlineExceeded, true case errors.Is(err, storage.ErrChunkCaptureRefused): return http.StatusServiceUnavailable, "capture_refused", true - case errors.Is(err, storage.ErrCutCOWAborted): - return http.StatusServiceUnavailable, "cut_aborted", true default: return http.StatusInternalServerError, codeInternal, false } @@ -544,7 +547,8 @@ func (c *chunkControl) Snapshot(ctx context.Context, volumeID string, req ChunkS if info, replayed, err := c.cat.SnapshotReplay(ctx, volumeID, sreq); err != nil || replayed { return info, err } - r, err := c.p.CutVolume(ctx, volumeID, 0) + // A named seal is urgent even without a minimum LSN. + r, err := c.p.CutVolume(hostlimit.WithClass(ctx, hostlimit.Urgent), volumeID, 0) if err != nil { return chunkstore.SnapshotInfo{}, err } diff --git a/seaweed-block/core/host/volume/chunk_control_adapter_test.go b/seaweed-block/core/host/volume/chunk_control_adapter_test.go index 92ef54d65d..2f26ba2509 100644 --- a/seaweed-block/core/host/volume/chunk_control_adapter_test.go +++ b/seaweed-block/core/host/volume/chunk_control_adapter_test.go @@ -8,17 +8,20 @@ import ( "sync" "testing" + "errors" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/hostlimit" "github.com/seaweedfs/seaweed-block/core/storage" ) type fakeChunkProvider struct { - cut storage.ChunkCutResult - cutErr error - detach storage.ChunkCutResult - last uint64 - cuts int - lastMin uint64 + cut storage.ChunkCutResult + cutErr error + cutCheck func(context.Context) error + detach storage.ChunkCutResult + last uint64 + cuts int + lastMin uint64 } type adapterManifestFiler struct { @@ -45,9 +48,14 @@ func (f *adapterManifestFiler) Get(_ context.Context, id string) ([]byte, error) return append([]byte(nil), b...), nil } -func (f *fakeChunkProvider) CutVolume(_ context.Context, _ string, minLSN uint64) (storage.ChunkCutResult, error) { +func (f *fakeChunkProvider) CutVolume(ctx context.Context, _ string, minLSN uint64) (storage.ChunkCutResult, error) { f.cuts++ f.lastMin = minLSN + if f.cutCheck != nil { + if err := f.cutCheck(ctx); err != nil { + return storage.ChunkCutResult{}, err + } + } if f.cutErr != nil { return storage.ChunkCutResult{}, f.cutErr } @@ -201,3 +209,30 @@ func TestChunkControl_CutMinLSNAndDetach(t *testing.T) { t.Fatalf("detach: %+v %v", d, err) } } + +func TestChunkControl_NamedSnapshotUsesUrgentFallback(t *testing.T) { + fp, ctl := adapterFixture(t) + c := hostlimit.DefaultConfig(t.TempDir() + "/missing") + l, err := hostlimit.New(c) + if err != nil { + t.Fatal(err) + } + defer l.Close() + fp.cutCheck = func(ctx context.Context) error { + id, err := l.Admit(ctx, 1, nil) + if err == nil { + l.Release(id) + } + return err + } + if _, err = ctl.Cut(context.Background(), "v1", 0); !errors.Is(err, hostlimit.ErrBusy) { + t.Fatalf("ordinary cut bypassed missing pool: %v", err) + } + info, err := ctl.Snapshot(context.Background(), "v1", ChunkSnapshotRequest{Name: "named", RequestID: "named-r1"}) + if err != nil || info.Name != "named" { + t.Fatalf("named seal did not use urgent fallback: %+v %v", info, err) + } + if st := l.Snapshot().(hostlimit.Stats); st.Fallback != 1 || st.SkippedByClass[hostlimit.Normal] != 1 { + t.Fatalf("wrong named/normal policy: %+v", st) + } +} diff --git a/seaweed-block/core/host/volume/chunk_control_test.go b/seaweed-block/core/host/volume/chunk_control_test.go index 6c8c76722d..0d357c704a 100644 --- a/seaweed-block/core/host/volume/chunk_control_test.go +++ b/seaweed-block/core/host/volume/chunk_control_test.go @@ -219,8 +219,14 @@ func TestStatusServer_ChunkErrorBodyIsTyped(t *testing.T) { {fmt.Errorf("x: %w", storage.ErrChunkCASOutcomeUnknown), "outcome_unknown", 503, true}, {fmt.Errorf("x: %w", storage.ErrChunkHeadPrecondition), "head_conflict", 409, true}, {fmt.Errorf("save: %w", storage.ErrCutCOWAborted), "cut_aborted", 503, true}, + // Local capacity abort cancels the in-flight remote PUT. + {errors.Join(storage.ErrCutCOWAborted, storage.ErrChunkRemoteUnavailable, context.Canceled, errors.New("storage: saver capacity")), "cut_aborted", 503, true}, + {errors.Join(storage.ErrCutCOWAborted, storage.ErrChunkCASOutcomeUnknown, storage.ErrChunkRemoteUnavailable), "outcome_unknown", 503, true}, + {errors.Join(storage.ErrCutCOWAborted, storage.ErrChunkLayerFenced, storage.ErrChunkRemoteUnavailable), "fenced", 409, false}, {fmt.Errorf("x: %w", storage.ErrChunkRemoteUnavailable), "remote_unavailable", 503, true}, {fmt.Errorf("x: %w", storage.ErrChunkLayerClosed), "closing", 503, false}, + {errors.Join(storage.ErrCutCOWAborted, storage.ErrChunkLayerClosed, storage.ErrChunkRemoteUnavailable, context.Canceled), "closing", 503, false}, + {errors.Join(storage.ErrCutCOWAborted, storage.ErrChunkLayerDetached, storage.ErrChunkRemoteUnavailable, context.Canceled), "closing", 409, false}, {fmt.Errorf("x: %w", storage.ErrChunkLayerDetached), "closing", 409, false}, {fmt.Errorf("%w: %w", durable.ErrDetachAborted, storage.ErrChunkRemoteUnavailable), "detach_aborted", 409, true}, // The detach sentinels decide even over a catalog-error cause (which diff --git a/seaweed-block/core/hostlimit/limiter.go b/seaweed-block/core/hostlimit/limiter.go new file mode 100644 index 0000000000..3ab765d5e6 --- /dev/null +++ b/seaweed-block/core/hostlimit/limiter.go @@ -0,0 +1,478 @@ +// Package hostlimit coordinates background cuts across cooperating host processes. +// Guest I/O never acquires a slot. An unavailable pool skips background work; +// urgent seals may use explicitly uncoordinated per-process limits. +package hostlimit + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "hash/fnv" + "io" + "log" + "os" + "path/filepath" + "sync" + "time" +) + +var ErrBusy = errors.New("hostlimit: no background slot") +var ErrConfig = errors.New("hostlimit: incompatible host configuration") +var ErrRevoked = errors.New("hostlimit: cut budget revoked") + +type Class uint8 + +const ( + Normal Class = iota + Urgent + BackgroundFill + Idle +) + +type classKey struct{} + +func WithClass(ctx context.Context, c Class) context.Context { + return context.WithValue(ctx, classKey{}, c) +} + +type Config struct { + Directory string + NormalSlots, UrgentSlots int + FillSlots, IdleSlots int + PayloadBytes, COWBytes int64 + BytesPerSecond int64 + FallbackVolumes int + MaxHold time.Duration +} + +func DefaultConfig(dir string) Config { + return Config{Directory: dir, NormalSlots: 3, UrgentSlots: 1, FillSlots: 2, IdleSlots: 1, PayloadBytes: 64 << 20, COWBytes: 1 << 30, BytesPerSecond: 64 << 20, FallbackVolumes: 200, MaxHold: 5 * time.Minute} +} +func (c Config) Validate() error { + if !filepath.IsAbs(c.Directory) || c.NormalSlots < 1 || c.NormalSlots > 256 || c.UrgentSlots < 1 || c.UrgentSlots > 256 || c.FillSlots < 0 || c.FillSlots > 256 || c.IdleSlots < 0 || c.IdleSlots > 256 || c.NormalSlots+c.UrgentSlots+c.FillSlots+c.IdleSlots > 256 || c.PayloadBytes <= 0 || c.COWBytes <= 0 || c.BytesPerSecond <= 0 || c.FallbackVolumes < 1 || c.FallbackVolumes > 65536 || c.MaxHold <= 0 { + return errors.New("hostlimit: invalid configuration") + } + return nil +} + +type Stats struct { + Active int + PayloadReserved, COWReserved int64 + Admitted, Skipped, Fallback, Revoked, Released uint64 + FallbackActive bool + AdmissionNs, MaxHoldNs uint64 + SkippedByClass [4]uint64 + LastPoolError string +} +type lease struct { + file *os.File + started time.Time + class Class + fallback bool + payload, cow int64 + abort func(error) + timer *time.Timer + releasing bool + revoked bool +} +type Limiter struct { + testBeforeConfigWrite func() // test-only crash boundary; immutable before first admission + testBeforeConfigLock func(*os.File) // test-only fault boundary; immutable before first admission + cfg Config + mu sync.Mutex + admitWG sync.WaitGroup + next uint64 + live map[uint64]*lease + stats Stats + closed bool + wake chan struct{} + done chan struct{} + nextUpload time.Time + fallback bool +} + +func New(c Config) (*Limiter, error) { + if err := c.Validate(); err != nil { + return nil, err + } + l := &Limiter{cfg: c, live: map[uint64]*lease{}, wake: make(chan struct{}, 1), done: make(chan struct{})} + go l.releaseLoop() + return l, nil +} + +// Phase is stable across process restarts; it never delays guest readiness. +func Phase(volume string, period time.Duration) time.Duration { + if period <= 0 { + return 0 + } + h := fnv.New64a() + _, _ = h.Write([]byte(volume)) + return time.Duration(h.Sum64() % uint64(period)) +} + +// pool checks the immutable configuration under a separate OS lock. Slot files +// are never unlinked: replacing them could create a second set of live permits. +func (l *Limiter) pool(c Class) (*os.File, error) { + info, err := os.Lstat(l.cfg.Directory) + if err != nil { + return nil, err + } + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return nil, errors.New("hostlimit: pool must be a local directory") + } + open := func(name string) (*os.File, error) { + path := filepath.Join(l.cfg.Directory, name) + if i, e := os.Lstat(path); e == nil && !i.Mode().IsRegular() { + return nil, errors.New("hostlimit: nonregular pool file") + } + return os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600) + } + guard, err := open("configuration.lock") + if err != nil { + return nil, err + } + defer guard.Close() + if l.testBeforeConfigLock != nil { + l.testBeforeConfigLock(guard) + } + if err = tryLock(guard); err != nil { + return nil, err + } + expected, _ := json.Marshal(l.cfg) + path := filepath.Join(l.cfg.Directory, "configuration.json") + existing, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + err = l.publishConfig(path, expected) + existing = expected + } + if err != nil { + return nil, err + } + if string(existing) != string(expected) { + return nil, ErrConfig + } + names := []string{} + if c == BackgroundFill || c == Idle { + n, prefix := l.cfg.FillSlots, "fill" + if c == Idle { + n, prefix = l.cfg.IdleSlots, "idle" + } + for i := 0; i < n; i++ { + names = append(names, fmt.Sprintf("%s-%d", prefix, i)) + } + } else { + if c == Urgent { + for i := 0; i < l.cfg.UrgentSlots; i++ { + names = append(names, fmt.Sprintf("urgent-%d", i)) + } + } + for i := 0; i < l.cfg.NormalSlots; i++ { + names = append(names, fmt.Sprintf("normal-%d", i)) + } + } + for _, name := range names { + f, e := open(name) + if e != nil { + return nil, e + } + if e = tryLock(f); e == nil { + return f, nil + } + _ = f.Close() + if !errors.Is(e, ErrBusy) { + return nil, e + } + } + return nil, ErrBusy +} + +// publishConfig runs under the configuration OS lock. A killed initializer +// leaves an ignored temporary file, never a partially visible configuration. +func (l *Limiter) publishConfig(path string, data []byte) error { + f, err := os.CreateTemp(l.cfg.Directory, ".configuration-*") + if err != nil { + return err + } + defer os.Remove(f.Name()) + defer f.Close() + if l.testBeforeConfigWrite != nil { + l.testBeforeConfigWrite() + } + n, err := f.Write(data) + if err != nil { + return err + } + if n != len(data) { + return io.ErrShortWrite + } + if err = f.Sync(); err != nil { + return err + } + if err = f.Close(); err != nil { + return err + } + return os.Rename(f.Name(), path) +} + +// Acquire exposes background fill/idle permits to future background callers. +// Demand hydration must bypass this API; these permits carry no cut payload. +func (l *Limiter) Acquire(ctx context.Context, c Class, abort func(error)) (uint64, error) { + return l.Admit(WithClass(ctx, c), 0, abort) +} + +func (l *Limiter) Admit(ctx context.Context, payload int64, abort func(error)) (uint64, error) { + start := time.Now() + defer func() { l.mu.Lock(); l.stats.AdmissionNs += uint64(time.Since(start)); l.mu.Unlock() }() + l.mu.Lock() + if l.closed { + l.mu.Unlock() + return 0, ErrRevoked + } + l.admitWG.Add(1) + l.mu.Unlock() + defer l.admitWG.Done() + if err := ctx.Err(); err != nil { + return 0, err + } + if payload < 0 || payload > l.cfg.PayloadBytes { + return 0, ErrBusy + } + c, _ := ctx.Value(classKey{}).(Class) + if c > Idle || (c >= BackgroundFill && payload != 0) { + return 0, ErrBusy + } + f, err := l.pool(c) + if errors.Is(err, ErrBusy) { + l.mu.Lock() + l.stats.Skipped++ + l.stats.SkippedByClass[c]++ + l.mu.Unlock() + return 0, err + } + if errors.Is(err, ErrConfig) { + l.mu.Lock() + warn := l.stats.LastPoolError != err.Error() + l.stats.LastPoolError = err.Error() + l.stats.Skipped++ + l.stats.SkippedByClass[c]++ + l.mu.Unlock() + if warn { + log.Printf("hostlimit: shared pool configuration refused; background protection may lag: %v", err) + } + return 0, err + } + if err != nil && c != Urgent { + l.mu.Lock() + warn := l.stats.LastPoolError != err.Error() + l.stats.LastPoolError = err.Error() + l.stats.Skipped++ + l.stats.SkippedByClass[c]++ + l.mu.Unlock() + if warn { + log.Printf("hostlimit: shared pool unavailable; background work skipped: %v", err) + } + return 0, errors.Join(ErrBusy, err) + } + fallback := err != nil // Urgent fallback has no coordinated host resource/rate bound. + l.mu.Lock() + if l.closed || ctx.Err() != nil || len(l.live) >= l.cfg.NormalSlots+l.cfg.UrgentSlots+l.cfg.FillSlots+l.cfg.IdleSlots { + l.stats.Skipped++ + l.mu.Unlock() + if f != nil { + _ = f.Close() + } + if ctx.Err() != nil { + return 0, ctx.Err() + } + return 0, ErrBusy + } + l.next++ + id := l.next + x := &lease{file: f, started: time.Now(), class: c, fallback: fallback, payload: payload, abort: abort} + l.live[id] = x + l.stats.Admitted++ + l.stats.PayloadReserved += payload + l.stats.Active++ + l.fallback = fallback + for _, held := range l.live { + l.fallback = l.fallback || held.fallback + } + l.stats.FallbackActive = l.fallback + warnFallback := fallback && l.stats.Fallback == 0 + if fallback { + l.stats.LastPoolError = err.Error() + l.stats.Fallback++ + l.stats.FallbackActive = true + } + x.timer = time.AfterFunc(l.cfg.MaxHold, func() { l.revoke(id) }) + l.mu.Unlock() + if warnFallback { + log.Printf("hostlimit: shared cut pool unavailable (%v); using static fallback, shared memory/spill cap NOT enforced", err) + } + return id, nil +} +func (l *Limiter) revoke(id uint64) { + l.mu.Lock() + x := l.live[id] + var abort func(error) + if x != nil && !x.releasing && !x.revoked { + x.revoked = true + abort = x.abort + l.stats.Revoked++ + } + l.mu.Unlock() + if abort != nil { + abort(ErrRevoked) + } +} + +// ReserveCOW is guest-path accounting only: no OS calls, RPC or waiting for a slot. +func (l *Limiter) ReserveCOW(id uint64, n int64) error { + l.mu.Lock() + x := l.live[id] + if x == nil || x.releasing || x.revoked || n < 0 || (x.class >= BackgroundFill && n != 0) { + l.mu.Unlock() + return ErrRevoked + } + if n > l.cfg.COWBytes-x.cow { + x.revoked = true + abort := x.abort + l.stats.Revoked++ + l.mu.Unlock() + if abort != nil { + abort(ErrRevoked) + } + return ErrRevoked + } + x.cow += n + l.stats.COWReserved += n + l.mu.Unlock() + return nil +} + +// Release only marks settled work; one owned worker closes descriptors. Until +// then the kernel slot remains unavailable, conservatively retaining capacity. +func (l *Limiter) Release(id uint64) { + l.mu.Lock() + if x := l.live[id]; x != nil && !x.releasing { + x.releasing = true + x.timer.Stop() + } + l.mu.Unlock() + select { + case l.wake <- struct{}{}: + default: + } +} +func (l *Limiter) releaseLoop() { + defer close(l.done) + for range l.wake { + for { + l.mu.Lock() + var id uint64 + var x *lease + for k, v := range l.live { + if v.releasing { + id, x = k, v + break + } + } + if x == nil { + stop := l.closed && len(l.live) == 0 + l.mu.Unlock() + if stop { + return + } + break + } + l.mu.Unlock() + if x.file != nil { + _ = x.file.Close() + } + l.mu.Lock() + delete(l.live, id) + l.fallback = false + for _, held := range l.live { + l.fallback = l.fallback || held.fallback + } + l.stats.FallbackActive = l.fallback + l.stats.Active-- + l.stats.PayloadReserved -= x.payload + l.stats.COWReserved -= x.cow + l.stats.Released++ + l.stats.MaxHoldNs = max(l.stats.MaxHoldNs, uint64(time.Since(x.started))) + l.mu.Unlock() + } + } +} +func (l *Limiter) Snapshot() any { l.mu.Lock(); defer l.mu.Unlock(); return l.stats } + +// WaitUpload paces background payload PUTs, including parallel uploader workers. +// One process spaces reservations by the previous payload/rate. Its first +// payload is immediate; debt survives its leases but resets on a new process. +// For a constant share r and maximum payload B, one process reserves at most +// r*T+B bytes over T. Fresh processes each add a new B; neither process/slot +// churn nor uncoordinated fallback has a fixed host-rate bound. Wire overhead +// is excluded. Local WAL flushing, COW reads and demand hydration bypass it. +func (l *Limiter) WaitUpload(ctx context.Context, n int) error { + if n < 0 { + return ErrBusy + } + for { + if err := ctx.Err(); err != nil { + return err + } + l.mu.Lock() + if l.closed { + l.mu.Unlock() + return ErrRevoked + } + div := l.cfg.NormalSlots + l.cfg.UrgentSlots + if l.fallback { + div = l.cfg.FallbackVolumes + } + rate := l.cfg.BytesPerSecond / int64(div) + if rate < 1 { + rate = 1 + } + now := time.Now() + wait := time.Until(l.nextUpload) + if wait <= 0 { + l.nextUpload = now.Add(time.Duration(float64(n) / float64(rate) * float64(time.Second))) + l.mu.Unlock() + return ctx.Err() + } + l.mu.Unlock() + timer := time.NewTimer(wait) + select { + case <-ctx.Done(): + timer.Stop() + return ctx.Err() + case <-timer.C: + } + } +} + +// Close cancels cuts but cannot release their physical-I/O ownership. Callers +// must still settle their cuts and call Release; Close joins that settlement. +func (l *Limiter) Close() { + l.mu.Lock() + l.closed = true + callbacks := []func(error){} + for _, x := range l.live { + if !x.releasing && x.abort != nil { + callbacks = append(callbacks, x.abort) + } + } + l.mu.Unlock() + l.admitWG.Wait() + for _, a := range callbacks { + a(ErrRevoked) + } + select { + case l.wake <- struct{}{}: + default: + } + <-l.done +} diff --git a/seaweed-block/core/hostlimit/limiter_test.go b/seaweed-block/core/hostlimit/limiter_test.go new file mode 100644 index 0000000000..cbc5f3cdb5 --- /dev/null +++ b/seaweed-block/core/hostlimit/limiter_test.go @@ -0,0 +1,595 @@ +package hostlimit + +import ( + "bufio" + "context" + "errors" + "fmt" + "log" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +func testConfig(t *testing.T) Config { + t.Helper() + c := DefaultConfig(t.TempDir()) + c.NormalSlots = 1 + c.UrgentSlots = 1 + return c +} +func newTest(t *testing.T, c Config) *Limiter { + t.Helper() + l, e := New(c) + if e != nil { + t.Fatal(e) + } + t.Cleanup(func() { + l.mu.Lock() + ids := make([]uint64, 0, len(l.live)) + for id := range l.live { + ids = append(ids, id) + } + l.mu.Unlock() + for _, id := range ids { + l.Release(id) + } + l.Close() + }) + return l +} +func settled(t *testing.T, l *Limiter) { + t.Helper() + deadline := time.After(3 * time.Second) + tick := time.NewTicker(time.Millisecond) + defer tick.Stop() + for { + if l.Snapshot().(Stats).Active == 0 { + return + } + select { + case <-deadline: + t.Fatal("release did not settle") + case <-tick.C: + } + } +} +func TestSlotsUrgentAndJoinedRelease(t *testing.T) { + c := testConfig(t) + a, b, d := newTest(t, c), newTest(t, c), newTest(t, c) + x, e := a.Admit(context.Background(), c.PayloadBytes, nil) + if e != nil { + t.Fatal(e) + } + defer a.Release(x) + if _, e = b.Admit(context.Background(), 1, nil); !errors.Is(e, ErrBusy) { + t.Fatalf("normal bypass: %v", e) + } + y, e := b.Admit(WithClass(context.Background(), Urgent), 1, nil) + if e != nil { + t.Fatal(e) + } + defer b.Release(y) + if _, e = d.Admit(WithClass(context.Background(), Urgent), 1, nil); !errors.Is(e, ErrBusy) { + t.Fatalf("urgent bypass: %v", e) + } + a.Release(x) + a.Release(x) + settled(t, a) + z, e := d.Admit(context.Background(), 1, nil) + if e != nil { + t.Fatal(e) + } + d.Release(z) + settled(t, d) +} +func TestCOWAbortHoldsSlotUntilWorkerSettlement(t *testing.T) { + c := testConfig(t) + a, b := newTest(t, c), newTest(t, c) + revoked := make(chan struct{}, 1) + x, e := a.Admit(context.Background(), 1, func(error) { revoked <- struct{}{} }) + if e != nil { + t.Fatal(e) + } + defer a.Release(x) + if e = a.ReserveCOW(x, c.COWBytes); e != nil { + t.Fatal(e) + } + if e = a.ReserveCOW(x, 1); !errors.Is(e, ErrRevoked) { + t.Fatal(e) + } + select { + case <-revoked: + case <-time.After(time.Second): + t.Fatal("no abort") + } + if _, e = b.Admit(context.Background(), 1, nil); !errors.Is(e, ErrBusy) { + t.Fatalf("revocation released live I/O: %v", e) + } + a.Release(x) + settled(t, a) +} +func TestHoldExpiryAndCloseDoNotSteal(t *testing.T) { + c := testConfig(t) + c.MaxHold = 30 * time.Millisecond + a, b := newTest(t, c), newTest(t, c) + revoked := make(chan struct{}, 4) + x, e := a.Admit(context.Background(), 1, func(error) { revoked <- struct{}{} }) + if e != nil { + t.Fatal(e) + } + select { + case <-revoked: + case <-time.After(time.Second): + t.Fatal("no expiry") + } + done := make(chan struct{}) + go func() { a.Close(); close(done) }() + select { + case <-revoked: + case <-time.After(time.Second): + t.Fatal("Close did not cancel") + } + select { + case <-done: + t.Fatal("Close abandoned worker") + default: + } + if _, e = b.Admit(context.Background(), 1, nil); !errors.Is(e, ErrBusy) { + t.Fatal("lease stolen", e) + } + a.Release(x) + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("Close not joined") + } +} +func TestFallbackAndConfigMismatch(t *testing.T) { + c := testConfig(t) + a := newTest(t, c) + x, e := a.Admit(context.Background(), 1, nil) + if e != nil { + t.Fatal(e) + } + a.Release(x) + settled(t, a) + a.Close() + bad := c + bad.NormalSlots++ + b := newTest(t, bad) + for _, class := range []Class{Normal, Urgent} { + if _, e = b.Admit(WithClass(context.Background(), class), 1, nil); !errors.Is(e, ErrConfig) { + t.Fatalf("config mismatch bypassed cap: class=%d err=%v", class, e) + } + } + if st := b.Snapshot().(Stats); st.LastPoolError == "" || st.Skipped != 2 || st.Fallback != 0 { + t.Fatal("configuration refusal was silent", st) + } + c.Directory += "-missing" + f := newTest(t, c) + x, e = f.Admit(WithClass(context.Background(), Urgent), 1, nil) + if e != nil { + t.Fatal(e) + } + if !f.Snapshot().(Stats).FallbackActive { + t.Fatal("degraded cap hidden") + } + f.Release(x) + settled(t, f) + if st := f.Snapshot().(Stats); st.FallbackActive || st.Fallback != 1 { + t.Fatalf("settled fallback status: %+v", st) + } +} +func TestRateCancellationAndPhase(t *testing.T) { + c := testConfig(t) + c.BytesPerSecond = 1024 + l := newTest(t, c) + if e := l.WaitUpload(context.Background(), 2048); e != nil { + t.Fatal(e) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + if e := l.WaitUpload(ctx, 2048); !errors.Is(e, context.DeadlineExceeded) { + t.Fatal(e) + } + seen := map[time.Duration]bool{} + for i := 0; i < 200; i++ { + v := fmt.Sprint(i) + p := Phase(v, time.Minute) + if p < 0 || p >= time.Minute || p != Phase(v, time.Minute) { + t.Fatal("bad phase") + } + seen[p] = true + } + if len(seen) < 190 { + t.Fatal("phase collision", len(seen)) + } +} +func TestProcessSlotHelper(t *testing.T) { + dir := os.Getenv("SWBLOCK_TEST_LIMITER_DIR") + if dir == "" { + return + } + c := DefaultConfig(dir) + c.NormalSlots = 1 + c.UrgentSlots = 1 + l, e := New(c) + if e != nil { + t.Fatal(e) + } + if os.Getenv("SWBLOCK_TEST_LIMITER_INIT_GATE") == "1" { + l.testBeforeConfigWrite = func() { fmt.Println("CONFIG-WRITE"); _, _ = bufio.NewReader(os.Stdin).ReadByte() } + } + _, e = l.Admit(context.Background(), 1, nil) + if e != nil { + t.Fatal(e) + } + fmt.Println("HELD") + _, _ = bufio.NewReader(os.Stdin).ReadByte() +} +func TestKilledProcessReleasesButLiveHolderDoesNot(t *testing.T) { + c := testConfig(t) + cmd := exec.Command(os.Args[0], "-test.run=^TestProcessSlotHelper$") + cmd.Env = append(os.Environ(), "SWBLOCK_TEST_LIMITER_DIR="+c.Directory) + out, e := cmd.StdoutPipe() + if e != nil { + t.Fatal(e) + } + in, e := cmd.StdinPipe() + if e != nil { + t.Fatal(e) + } + defer in.Close() + if e = cmd.Start(); e != nil { + t.Fatal(e) + } + defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }() + ready := make(chan bool, 1) + go func() { + s := bufio.NewScanner(out) + for s.Scan() { + if s.Text() == "HELD" { + ready <- true + return + } + } + ready <- false + }() + select { + case ok := <-ready: + if !ok { + t.Fatal("child failed") + } + case <-time.After(15 * time.Second): + t.Fatal("child not ready") + } + l := newTest(t, c) + if _, e = l.Admit(context.Background(), 1, nil); !errors.Is(e, ErrBusy) { + t.Fatalf("live child not counted: %v", e) + } + if e = cmd.Process.Kill(); e != nil { + t.Fatal(e) + } + _ = cmd.Wait() + x, e := l.Admit(context.Background(), 1, nil) + if e != nil { + t.Fatal("dead child retained slot", e) + } + l.Release(x) + settled(t, l) +} + +func TestBackgroundPoolsDoNotBorrowCutReservations(t *testing.T) { + c := testConfig(t) + c.FillSlots = 1 + c.IdleSlots = 1 + l := newTest(t, c) + x, e := l.Admit(context.Background(), 1, nil) + if e != nil { + t.Fatal(e) + } + defer l.Release(x) + y, e := l.Acquire(context.Background(), BackgroundFill, nil) + if e != nil { + t.Fatal(e) + } + defer l.Release(y) + if _, e = l.Acquire(context.Background(), BackgroundFill, nil); !errors.Is(e, ErrBusy) { + t.Fatal("fill exceeded independent pool", e) + } + z, e := l.Acquire(context.Background(), Idle, nil) + if e != nil { + t.Fatal(e) + } + defer l.Release(z) + if e = l.ReserveCOW(y, 1); !errors.Is(e, ErrRevoked) { + t.Fatal("fill consumed cut spill", e) + } +} + +type heldLog struct { + entered, release chan struct{} + once sync.Once +} + +func (w *heldLog) Write(p []byte) (int, error) { + w.once.Do(func() { close(w.entered) }) + <-w.release + return len(p), nil +} +func TestFallbackLogDoesNotHoldCOWAccountingLock(t *testing.T) { + c := testConfig(t) + c.Directory += "-missing" + l := newTest(t, c) + gate := &heldLog{entered: make(chan struct{}), release: make(chan struct{})} + before := log.Writer() + log.SetOutput(gate) + defer log.SetOutput(before) + defer close(gate.release) + done := make(chan struct{}) + go func() { _, _ = l.Admit(WithClass(context.Background(), Urgent), 1, nil); close(done) }() + select { + case <-gate.entered: + case <-time.After(5 * time.Second): + t.Fatal("fallback log not reached") + } + if !l.mu.TryLock() { + t.Fatal("blocked log holds guest COW accounting lock") + } + l.mu.Unlock() +} + +func TestLastFallbackReleaseClearsActiveStatus(t *testing.T) { + c := testConfig(t) + c.Directory += "-missing" + l := newTest(t, c) + id, err := l.Acquire(context.Background(), Urgent, nil) + if err != nil { + t.Fatal(err) + } + if !l.Snapshot().(Stats).FallbackActive { + t.Fatal("fallback not reported while held") + } + l.Release(id) + settled(t, l) + st := l.Snapshot().(Stats) + if st.FallbackActive || st.PayloadReserved != 0 || st.COWReserved != 0 || st.Released != 1 { + t.Fatalf("last fallback release left stale status: %+v", st) + } +} + +func TestConfigurationLockFailurePreservesPoolPolicy(t *testing.T) { + for _, class := range []Class{Normal, Urgent} { + t.Run(fmt.Sprint(class), func(t *testing.T) { + l := newTest(t, testConfig(t)) + var lockErr error + l.testBeforeConfigLock = func(f *os.File) { + if err := f.Close(); err != nil { + t.Fatal(err) + } + lockErr = tryLock(f) + } + id, err := l.Acquire(context.Background(), class, nil) + if lockErr == nil || errors.Is(lockErr, ErrBusy) { + t.Fatalf("fault did not cause non-contention lock error: %v", lockErr) + } + st := l.Snapshot().(Stats) + if class == Normal { + if id != 0 || !errors.Is(err, ErrBusy) || !errors.Is(err, lockErr) || st.SkippedByClass[Normal] != 1 || st.Fallback != 0 { + t.Fatalf("configuration lock fault lost cause: id=%d err=%v stats=%+v", id, err, st) + } + } else { + if err != nil || id == 0 || st.Fallback != 1 || !st.FallbackActive { + t.Fatalf("configuration lock fault refused urgent fallback: id=%d err=%v stats=%+v", id, err, st) + } + l.Release(id) + } + if st.LastPoolError != lockErr.Error() { + t.Fatalf("configuration lock alarm lost cause: got %q want %q", st.LastPoolError, lockErr) + } + }) + } +} + +func TestConfigurationLockContentionRefusesAllClasses(t *testing.T) { + c := testConfig(t) + f, err := os.OpenFile(filepath.Join(c.Directory, "configuration.lock"), os.O_CREATE|os.O_RDWR, 0600) + if err != nil { + t.Fatal(err) + } + defer f.Close() + if err = tryLock(f); err != nil { + t.Fatal(err) + } + for _, class := range []Class{Normal, Urgent} { + l := newTest(t, c) + id, err := l.Acquire(context.Background(), class, nil) + st := l.Snapshot().(Stats) + if id != 0 || !errors.Is(err, ErrBusy) || st.Fallback != 0 || st.FallbackActive || st.LastPoolError != "" || st.SkippedByClass[class] != 1 { + t.Fatalf("configuration contention bypassed cap: class=%d id=%d err=%v stats=%+v", class, id, err, st) + } + } +} + +func TestHealthyAdmissionDoesNotHideOlderFallbackLease(t *testing.T) { + c := testConfig(t) + c.Directory = filepath.Join(c.Directory, "late-pool") + l := newTest(t, c) + x, e := l.Admit(WithClass(context.Background(), Urgent), 1, nil) + if e != nil { + t.Fatal(e) + } + if e = os.Mkdir(c.Directory, 0700); e != nil { + t.Fatal(e) + } + y, e := l.Acquire(context.Background(), BackgroundFill, nil) + if e != nil { + t.Fatal(e) + } + defer l.Release(y) + if !l.Snapshot().(Stats).FallbackActive { + t.Fatal("healthy admission hid an active uncoordinated lease") + } + l.Release(x) + deadline := time.After(3 * time.Second) + tick := time.NewTicker(time.Millisecond) + defer tick.Stop() + for l.Snapshot().(Stats).Active != 1 { + select { + case <-deadline: + t.Fatal("fallback lease not released") + case <-tick.C: + } + } + if l.Snapshot().(Stats).FallbackActive { + t.Fatal("settled fallback lease still degrades healthy owner") + } +} + +func TestKilledInitializerDoesNotPublishPartialConfiguration(t *testing.T) { + c := testConfig(t) + cmd := exec.Command(os.Args[0], "-test.run=^TestProcessSlotHelper$") + cmd.Env = append(os.Environ(), "SWBLOCK_TEST_LIMITER_DIR="+c.Directory, "SWBLOCK_TEST_LIMITER_INIT_GATE=1") + out, e := cmd.StdoutPipe() + if e != nil { + t.Fatal(e) + } + in, e := cmd.StdinPipe() + if e != nil { + t.Fatal(e) + } + defer in.Close() + if e = cmd.Start(); e != nil { + t.Fatal(e) + } + defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }() + ready := make(chan bool, 1) + go func() { + s := bufio.NewScanner(out) + for s.Scan() { + if s.Text() == "CONFIG-WRITE" { + ready <- true + return + } + } + ready <- false + }() + select { + case ok := <-ready: + if !ok { + t.Fatal("initializer did not reach write boundary") + } + case <-time.After(15 * time.Second): + t.Fatal("initializer boundary not reached") + } + if _, e = os.Stat(filepath.Join(c.Directory, "configuration.json")); !errors.Is(e, os.ErrNotExist) { + t.Fatal("unpublished configuration became visible", e) + } + if e = cmd.Process.Kill(); e != nil { + t.Fatal(e) + } + _ = cmd.Wait() + l := newTest(t, c) + x, e := l.Admit(context.Background(), 1, nil) + if e != nil { + t.Fatal("successor did not recover interrupted initialization", e) + } + defer l.Release(x) + if l.Snapshot().(Stats).FallbackActive { + t.Fatal("successor silently bypassed shared cap") + } +} + +func TestUnusablePoolClassPolicy(t *testing.T) { + for _, class := range []Class{Normal, Urgent, BackgroundFill, Idle} { + t.Run(fmt.Sprint(class), func(t *testing.T) { + c := testConfig(t) + c.Directory += "-missing" + l := newTest(t, c) + id, err := l.Acquire(context.Background(), class, nil) + st := l.Snapshot().(Stats) + if class == Urgent { + if err != nil || st.Fallback != 1 || !st.FallbackActive || st.LastPoolError == "" { + t.Fatalf("urgent fallback: id=%d err=%v stats=%+v", id, err, st) + } + l.Release(id) + } else if !errors.Is(err, ErrBusy) || id != 0 || st.Admitted != 0 || st.SkippedByClass[class] != 1 || st.Fallback != 0 || st.LastPoolError == "" { + t.Fatalf("background bypassed unavailable pool: class=%d id=%d err=%v stats=%+v", class, id, err, st) + } + }) + } +} + +func TestPacingDebtSurvivesOwnLeaseTurnover(t *testing.T) { + c := testConfig(t) + c.BytesPerSecond = 2 // one byte/second per coordinated cut slot + l := newTest(t, c) + first, err := l.Admit(context.Background(), 1, nil) + if err != nil { + t.Fatal(err) + } + if err = l.WaitUpload(context.Background(), 4<<20); err != nil { + t.Fatal(err) + } + l.Release(first) + settled(t, l) + next, err := l.Admit(context.Background(), 1, nil) + if err != nil { + t.Fatal(err) + } + defer l.Release(next) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + if err = l.WaitUpload(ctx, 1); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("same-process debt reset at lease turnover: %v", err) + } +} + +func TestPacingProcessHelper(t *testing.T) { + dir := os.Getenv("SWBLOCK_TEST_PACING_DIR") + if dir == "" { + return + } + c := DefaultConfig(dir) + c.NormalSlots, c.UrgentSlots, c.BytesPerSecond = 1, 1, 2 + l, err := New(c) + if err != nil { + t.Fatal(err) + } + id, err := l.Admit(context.Background(), 1, nil) + if err != nil { + t.Fatal(err) + } + defer func() { l.Release(id); l.Close() }() + // Start the pacing budget after process startup and slot admission. + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + if err = l.WaitUpload(ctx, 4<<20); err != nil { + t.Fatalf("fresh process inherited another process's pacing debt: %v", err) + } + fmt.Println("FRESH-PACING 4194304") +} + +func TestPacingFreshProcessesDoNotShareDebt(t *testing.T) { + dir := t.TempDir() + const starts = 6 + start := time.Now() + for i := 0; i < starts; i++ { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestPacingProcessHelper$") + cmd.Env = append(os.Environ(), "SWBLOCK_TEST_PACING_DIR="+dir) + out, err := cmd.CombinedOutput() + cancel() + if err != nil || !strings.Contains(string(out), "FRESH-PACING 4194304") { + t.Fatalf("fresh holder %d: %v\n%s", i, err, out) + } + } + // Each new process gets an immediate first reservation. Slot reuse does + // not preserve pacing debt, so these bytes cannot certify a host-rate cap. + t.Logf("fresh_processes=%d attempted_payload_bytes=%d elapsed=%s", starts, starts*(4<<20), time.Since(start)) +} diff --git a/seaweed-block/core/hostlimit/lock_unix.go b/seaweed-block/core/hostlimit/lock_unix.go new file mode 100644 index 0000000000..ff77b2a3da --- /dev/null +++ b/seaweed-block/core/hostlimit/lock_unix.go @@ -0,0 +1,17 @@ +//go:build !windows + +package hostlimit + +import ( + "errors" + "os" + "syscall" +) + +func tryLock(f *os.File) error { + err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) + if errors.Is(err, syscall.EWOULDBLOCK) || errors.Is(err, syscall.EAGAIN) { + return ErrBusy + } + return err +} diff --git a/seaweed-block/core/hostlimit/lock_windows.go b/seaweed-block/core/hostlimit/lock_windows.go new file mode 100644 index 0000000000..6cd06b16d9 --- /dev/null +++ b/seaweed-block/core/hostlimit/lock_windows.go @@ -0,0 +1,17 @@ +//go:build windows + +package hostlimit + +import ( + "errors" + "golang.org/x/sys/windows" + "os" +) + +func tryLock(f *os.File) error { + err := windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &windows.Overlapped{}) + if errors.Is(err, windows.ERROR_LOCK_VIOLATION) { + return ErrBusy + } + return err +} diff --git a/seaweed-block/core/storage/chunk_cut_cow.go b/seaweed-block/core/storage/chunk_cut_cow.go index b18c81dd49..c9fc09dc5c 100644 --- a/seaweed-block/core/storage/chunk_cut_cow.go +++ b/seaweed-block/core/storage/chunk_cut_cow.go @@ -272,6 +272,36 @@ func (w *cutCOWWindow) wait(ch <-chan struct{}) { w.waitNs.Add(time.Since(start).Nanoseconds()) } +// Saver admission is bounded independently of local physical I/O. Expiry +// drops only this cut; it never fails the guest mutation. +const cutSaverWaitLimit = 250 * time.Millisecond + +func (w *cutCOWWindow) acquireSaver() bool { + select { + case w.saverSlots <- struct{}{}: + return true + default: + } + start := time.Now() + timer := time.NewTimer(cutSaverWaitLimit) + defer timer.Stop() + defer func() { w.waitNs.Add(time.Since(start).Nanoseconds()) }() + if hook := w.layer.testCOWSaverWait; hook != nil { + hook() + } + select { + case w.saverSlots <- struct{}{}: + return true + case <-w.ended: + return false + case <-w.ctx.Done(): + return false + case <-timer.C: + w.abort(errors.Join(errCutCOWAborted, errCutSaverCapacity)) + return false + } +} + func (l *chunkLayerImpl) beforeCOWMutation(first, count uint64) { w := l.cowActive.Load() if w == nil || count == 0 { @@ -288,18 +318,10 @@ func (l *chunkLayerImpl) beforeCOWMutation(first, count uint64) { if e == nil { break } - // Never queue an unbounded number of full-chunk saver buffers behind - // local I/O. Refuse this cut, not the guest mutation, when its fixed - // saver slots are exhausted; no physical I/O has started for this owner. - acquired := false - select { - case w.saverSlots <- struct{}{}: - acquired = true - default: - w.abort(errors.Join(errCutCOWAborted, errCutSaverCapacity)) + // Wait briefly for an existing local saver, never for remote I/O. + // The claimed entry owns no payload until a slot becomes available. + if !w.acquireSaver() { w.refs.Done() - } - if !acquired { break } if w.status() != nil { diff --git a/seaweed-block/core/storage/chunk_cut_cow_lifetime_test.go b/seaweed-block/core/storage/chunk_cut_cow_lifetime_test.go index c60d4035e9..bf599c3ded 100644 --- a/seaweed-block/core/storage/chunk_cut_cow_lifetime_test.go +++ b/seaweed-block/core/storage/chunk_cut_cow_lifetime_test.go @@ -204,6 +204,9 @@ func TestCutCOWV3_RecoveryAndCloseDrainSavingOwner(t *testing.T) { if cutErr == nil { t.Fatal("terminal window published") } + if action == "LayerClose" && (!errors.Is(cutErr, ErrCutCOWAborted) || !errors.Is(cutErr, ErrChunkLayerClosed)) { + t.Fatalf("real Close lost terminal cut cause: %v", cutErr) + } if actionErr != nil && action != "Reset" { t.Fatal(actionErr) } diff --git a/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go b/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go index a4466f6e17..3adf5057c0 100644 --- a/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go +++ b/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go @@ -362,3 +362,72 @@ func TestCutCOWV3_RecentChunkUploadsFirst(t *testing.T) { } } } + +// Two guest saves exceed one slot; the second waits for local capacity and +// preserves the same cut point rather than aborting a transient burst. +func TestCutCOWV3_SaverBurstWaitsAndPublishes(t *testing.T) { + s, l, f, gate := cowFixture(t) + if _, err := s.Write(9, makeBlock(ctBlockSize, 9)); err != nil { + t.Fatal(err) + } + // Keep chunk 0 hottest, so the held copier precedes both unread saves. + if _, err := s.Write(1, makeBlock(ctBlockSize, 1)); err != nil { + t.Fatal(err) + } + entered, release, waiting := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var once, unblock sync.Once + free := func() { unblock.Do(func() { close(release) }) } + l.testCOWSave = func() error { once.Do(func() { close(entered); <-release }); return nil } + l.testCOWSaverWait = func() { close(waiting) } + done, errs := cowStartCut(t, l, gate) + l.cowActive.Load().saverSlots = make(chan struct{}, 1) + writers := make(chan error, 2) + firstDone, secondDone := make(chan struct{}), make(chan struct{}) + secondStarted := false + t.Cleanup(func() { + free() + gate.unblock() + // A timeout reports failure without skipping the other owner's join. + wait := func(done <-chan struct{}, name string) { + select { + case <-done: + case <-time.After(ctLocalBound): + t.Errorf("%s did not settle within %s", name, ctLocalBound) + } + } + wait(firstDone, "first burst writer cleanup") + if secondStarted { + wait(secondDone, "second burst writer cleanup") + } + }) + go func() { defer close(firstDone); _, e := s.Write(5, makeBlock(ctBlockSize, 0xa5)); writers <- e }() + cowWaitSignal(t, entered, "first saver held") + secondStarted = true + go func() { defer close(secondDone); _, e := s.Write(9, makeBlock(ctBlockSize, 0xa9)); writers <- e }() + cowWaitSignal(t, waiting, "second saver queued") + free() + for i := 0; i < 2; i++ { + select { + case e := <-writers: + if e != nil { + t.Fatal(e) + } + case <-time.After(ctLocalBound): + t.Fatal("writer did not settle") + } + } + gate.unblock() + cowWaitSignal(t, done, "burst cut") + if e := <-errs; e != nil { + t.Fatal(e) + } + image := f.imageOf(t, f.stats().head) + for _, lba := range []int{5, 9} { + if !bytes.Equal(image[lba*ctBlockSize:(lba+1)*ctBlockSize], makeBlock(ctBlockSize, byte(lba))) { + t.Fatalf("cut changed at block %d", lba) + } + } + if l.Stats().CutsAborted["saver_capacity"] != 0 { + t.Fatal("transient burst aborted cut") + } +} diff --git a/seaweed-block/core/storage/chunk_head_belt.go b/seaweed-block/core/storage/chunk_head_belt.go new file mode 100644 index 0000000000..1648d018e2 --- /dev/null +++ b/seaweed-block/core/storage/chunk_head_belt.go @@ -0,0 +1,108 @@ +package storage + +import ( + "context" + "fmt" + "log" + "time" +) + +const ( + chunkHeadOperationTimeout = 2 * time.Second + chunkHeadSettleTime = 100 * time.Millisecond +) + +func validateHeadCoolingWindow(window time.Duration) error { + if window != 0 && window < chunkHeadOperationTimeout+chunkHeadSettleTime { + return fmt.Errorf("storage: HEAD cooling window must be zero (single serialization point) or at least %s", chunkHeadOperationTimeout+chunkHeadSettleTime) + } + return nil +} + +func casChunkHead(ctx context.Context, remote chunkRemote, expected chunkHeadVersion, next chunkHead) (uint64, error) { + ctx, cancel := context.WithTimeout(ctx, chunkHeadOperationTimeout) + defer cancel() + return remote.CASHead(ctx, expected, next) +} + +func readChunkHead(ctx context.Context, remote chunkRemote) (chunkHead, error) { + ctx, cancel := context.WithTimeout(ctx, chunkHeadOperationTimeout) + defer cancel() + return remote.GetHead(ctx) +} + +// ChunkHeadRootReader confirms publication identity without resolving every +// immutable manifest. The returned Chunks need not be populated. +type ChunkHeadRootReader interface { + GetHeadRoot(context.Context) (ChunkHead, error) +} + +func confirmChunkHead(ctx context.Context, remote chunkRemote, want chunkHead) error { + ctx, cancel := context.WithTimeout(ctx, chunkHeadOperationTimeout) + defer cancel() + var got chunkHead + var err error + if reader, ok := remote.(ChunkHeadRootReader); ok { + got, err = reader.GetHeadRoot(ctx) + } else { + got, err = remote.GetHead(ctx) + } + if err != nil { + return fmt.Errorf("storage: HEAD publication confirmation: %w: %w", errChunkCASOutcomeUnknown, err) + } + if got.Gen != want.Gen || got.Epoch != want.Epoch || got.Holder != want.Holder { + log.Printf("ALARM: HEAD publication displaced: wanted gen=%d epoch=%d holder=%q, read gen=%d epoch=%d holder=%q", want.Gen, want.Epoch, want.Holder, got.Gen, got.Epoch, got.Holder) + return fmt.Errorf("%w: HEAD publication displaced", errChunkLayerFenced) + } + return nil +} + +// Every successful CAS is confirmed, including calls near or beyond a lease +// horizon. No lease renewal or guard lock is needed across these remote calls. +func casAndConfirmChunkHead(ctx context.Context, remote chunkRemote, expected chunkHeadVersion, next chunkHead) (uint64, error) { + gen, err := casChunkHead(ctx, remote, expected, next) + if err != nil { + return gen, err + } + next.Gen = gen + return gen, confirmChunkHead(ctx, remote, next) +} + +func confirmChunkTakeover(ctx context.Context, remote chunkRemote, head chunkHead, window time.Duration) error { + if window == 0 { + return confirmChunkHead(ctx, remote, head) + } + timer := time.NewTimer(window) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + } + return confirmChunkHead(ctx, remote, head) +} + +// A failed CAS must not retry over a different publication owner, even if a +// delayed write from another serialization point has lowered the remote epoch. +func (l *chunkLayerImpl) publicationOwnerChanged(cur chunkHead) bool { + l.stMu.Lock() + last := l.head + if last.Gen == 0 { + last.Epoch, last.Holder = l.cfg.Epoch, l.cfg.Holder + } + l.stMu.Unlock() + return l.supersededBy(cur) || (cur.Gen != 0 && (last.Epoch != cur.Epoch || last.Holder != cur.Holder)) +} + +func (l *chunkLayerImpl) fencePublication(cur chunkHead) { + l.stMu.Lock() + l.fenced = true + if cur.Gen != 0 { + // Preserve the existing hydration identity invalidation. This is not + // settlement of our cut: remoteLSN and captured-map dirt stay unchanged. + l.head = copyHead(cur) + } + l.stMu.Unlock() + log.Printf("ALARM: chunk publisher fenced: local epoch=%d holder=%q, observed gen=%d epoch=%d holder=%q; keeping local data and intents", l.cfg.Epoch, l.cfg.Holder, cur.Gen, cur.Epoch, cur.Holder) + l.abortCOW(errChunkLayerFenced) +} diff --git a/seaweed-block/core/storage/chunk_head_belt_test.go b/seaweed-block/core/storage/chunk_head_belt_test.go new file mode 100644 index 0000000000..bc7485a6c6 --- /dev/null +++ b/seaweed-block/core/storage/chunk_head_belt_test.go @@ -0,0 +1,256 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "testing" + "time" +) + +// The fake's direct root replacement models a delayed request accepted at a +// second serialization point; it deliberately bypasses the first filer's CAS. +func TestHeadBeltTakeoverRefusesLateOldCAS(t *testing.T) { + f := newFakeChunkRemote() + f.head = chunkHead{Gen: 1, Epoch: 1, Holder: "old", Chunks: map[uint64]chunkRef{}} + f.afterCAS = func(f *fakeChunkRemote) { + f.head = chunkHead{Gen: 2, Epoch: 1, Holder: "old", Chunks: map[uint64]chunkRef{}} + } + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + _, err := ClaimChunkHead(ctx, f, ChunkLayerConfig{Epoch: 2, Holder: "new"}) + if !errors.Is(err, ErrChunkLayerFenced) { + t.Fatalf("late old CAS allowed takeover to serve: %v", err) + } +} + +func TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + want := bytes.Repeat([]byte{0x67}, 4096) + if _, err := s.Write(0, want); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + f.afterCAS = func(f *fakeChunkRemote) { f.failGet = errors.New("confirmation unavailable near lease horizon") } + _, err := layer.Cut(ctTimeout(t)) + if err == nil { + t.Fatal("unconfirmed CAS returned success") + } + if layer.RemoteLSN() != 0 { + t.Fatal("unconfirmed CAS advanced remoteLSN", layer.RemoteLSN()) + } + if len(liveIntents(t, f)) == 0 { + t.Fatal("unconfirmed CAS removed its intent") + } + if got, err := s.Read(0); err != nil || !bytes.Equal(got, want) { + t.Fatalf("local acknowledged bytes changed: %v", err) + } + if err := layer.Close(); err != nil { + t.Fatal(err) + } + if len(liveIntents(t, f)) == 0 { + t.Fatal("Close removed unconfirmed publication roots") + } +} + +func TestHeadBeltLowerEpochConflictFencesWithoutCleanup(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(2)) + if _, err := s.Write(0, makeBlock(4096, 0x31)); err != nil { + t.Fatal(err) + } + if _, err := layer.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + frontier := layer.RemoteLSN() + if _, err := s.Write(1, makeBlock(4096, 0x32)); err != nil { + t.Fatal(err) + } + f.beforeCAS = func(f *fakeChunkRemote) { f.head.Gen++; f.head.Epoch = 1; f.head.Holder = "old" } + _, err := layer.Cut(ctTimeout(t)) + if !errors.Is(err, ErrChunkLayerFenced) || !layer.Fenced() { + t.Fatalf("different old owner not fenced: %v", err) + } + if layer.RemoteLSN() != frontier { + t.Fatal("refused cut advanced remote frontier") + } + if len(liveIntents(t, f)) == 0 { + t.Fatal("fenced cut removed its intent") + } + calls := f.stats().cas + if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, ErrChunkLayerFenced) || f.stats().cas != calls { + t.Fatalf("fenced owner retried publication: %v", err) + } + if err := layer.Close(); err != nil { + t.Fatal(err) + } + if len(liveIntents(t, f)) == 0 { + t.Fatal("Close removed fenced publication roots") + } +} + +func TestHeadBeltEmptyBaseForeignPublicationFences(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(2)) + if _, err := s.Write(0, makeBlock(4096, 0x51)); err != nil { + t.Fatal(err) + } + f.beforeCAS = func(f *fakeChunkRemote) { + f.head = chunkHead{Gen: 1, Epoch: 1, Holder: "old", Chunks: map[uint64]chunkRef{}} + } + if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, ErrChunkLayerFenced) || !layer.Fenced() { + t.Fatalf("empty-base foreign publication not fenced: %v", err) + } + if layer.RemoteLSN() != 0 || len(liveIntents(t, f)) == 0 { + t.Fatal("fenced first cut settled or deleted intents") + } + calls := f.stats().cas + if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, ErrChunkLayerFenced) || f.stats().cas != calls { + t.Fatal("fenced first cut published again", err) + } + if err := layer.Close(); err != nil { + t.Fatal(err) + } + if len(liveIntents(t, f)) == 0 { + t.Fatal("Close removed first-cut intents") + } +} + +func TestHeadBeltSinglePointHasNoCoolingDelay(t *testing.T) { + f := newFakeChunkRemote() + f.head = chunkHead{Gen: 1, Epoch: 1, Holder: "old", Chunks: map[uint64]chunkRef{}} + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + if _, err := ClaimChunkHead(ctx, f, ChunkLayerConfig{Epoch: 2, Holder: "new"}); err != nil { + t.Fatal("single-point takeover delayed", err) + } + if f.stats().getHeads != 2 { + t.Fatal("single-point claim skipped readback") + } +} + +type deadlineBeltRemote struct { + *fakeChunkRemote + casDeadline, readDeadline bool +} + +func (r *deadlineBeltRemote) CASHead(ctx context.Context, v ChunkHeadVersion, h ChunkHead) (uint64, error) { + d, ok := ctx.Deadline() + r.casDeadline = ok && time.Until(d) <= 2*time.Second + return r.fakeChunkRemote.CASHead(ctx, v, h) +} +func (r *deadlineBeltRemote) GetHeadRoot(ctx context.Context) (ChunkHead, error) { + d, ok := ctx.Deadline() + r.readDeadline = ok && time.Until(d) <= 2*time.Second + return r.fakeChunkRemote.GetHead(ctx) +} +func TestHeadBeltOperationsHaveOwnDeadline(t *testing.T) { + r := &deadlineBeltRemote{fakeChunkRemote: newFakeChunkRemote()} + r.head = chunkHead{Gen: 1, Epoch: 1, Holder: "old", Chunks: map[uint64]chunkRef{}} + if _, err := ClaimChunkHead(context.Background(), r, ChunkLayerConfig{Epoch: 2, Holder: "new"}); err != nil { + t.Fatal(err) + } + if !r.casDeadline || !r.readDeadline { + t.Fatalf("claim deadlines: CAS=%t read=%t", r.casDeadline, r.readDeadline) + } + r.casDeadline, r.readDeadline = false, false + head := r.stats().head + if _, err := casAndConfirmChunkHead(context.Background(), r, ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}, head); err != nil { + t.Fatal(err) + } + if !r.casDeadline || !r.readDeadline { + t.Fatalf("cut deadlines: CAS=%t read=%t", r.casDeadline, r.readDeadline) + } +} + +func TestHeadBeltTakeoverWaitsBeforeConfirmation(t *testing.T) { + f := newFakeChunkRemote() + f.head = chunkHead{Gen: 1, Epoch: 1, Holder: "old", Chunks: map[uint64]chunkRef{}} + var committedAt, confirmedAt time.Time + f.afterCAS = func(f *fakeChunkRemote) { committedAt = time.Now() } + f.onGetHead = func(f *fakeChunkRemote) { + if !committedAt.IsZero() { + confirmedAt = time.Now() + } + } + window := chunkHeadOperationTimeout + chunkHeadSettleTime + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + head, err := ClaimChunkHead(ctx, f, ChunkLayerConfig{Epoch: 2, Holder: "new", HeadCoolingWindow: window}) + if err != nil { + t.Fatal(err) + } + if committedAt.IsZero() || confirmedAt.IsZero() || confirmedAt.Sub(committedAt) < window || f.stats().getHeads != 2 { + t.Fatal("confirmation read preceded cooling", confirmedAt.Sub(committedAt)) + } + if head.Gen != 2 || head.Epoch != 2 || head.Holder != "new" { + t.Fatal("confirmed the wrong owner", head) + } +} + +func TestHeadBeltCoolingWindowCoversCASAndSettle(t *testing.T) { + for _, window := range []time.Duration{-1, time.Millisecond, chunkHeadOperationTimeout, chunkHeadOperationTimeout + chunkHeadSettleTime - 1} { + f := newFakeChunkRemote() + if _, err := ClaimChunkHead(context.Background(), f, ChunkLayerConfig{Epoch: 2, Holder: "new", HeadCoolingWindow: window}); err == nil || f.stats().getHeads != 0 { + t.Fatalf("unsafe cooling window %s admitted or touched remote: %v", window, err) + } + } +} + +type rootOnlyBeltRemote struct { + *fakeChunkRemote + rootReads int +} + +func (r *rootOnlyBeltRemote) GetHeadRoot(ctx context.Context) (ChunkHead, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.rootReads++ + return ChunkHead{Gen: r.head.Gen, Epoch: r.head.Epoch, Holder: r.head.Holder}, nil +} + +func TestHeadBeltConfirmationUsesOnlyRoot(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + r := &rootOnlyBeltRemote{fakeChunkRemote: f} + layer := mustAttach(t, s, r, ctConfig(1)) + if _, err := s.Write(0, makeBlock(4096, 0x42)); err != nil { + t.Fatal(err) + } + f.afterCAS = func(f *fakeChunkRemote) { f.failGet = errors.New("full manifest read unavailable") } + result, err := layer.Cut(ctTimeout(t)) + if err != nil { + t.Fatalf("root confirmation depended on full manifest read: %v", err) + } + if r.rootReads != 1 || result.H != 1 || layer.RemoteLSN() != 1 { + t.Fatalf("root confirmation reads=%d result=%d remote=%d", r.rootReads, result.H, layer.RemoteLSN()) + } + if got := f.imageOf(t, f.stats().head); !bytes.Equal(got[:4096], makeBlock(4096, 0x42)) { + t.Fatal("confirmed wrong image") + } +} + +func TestHeadBeltRetryOfUnconfirmedClaimStillCools(t *testing.T) { + f := newFakeChunkRemote() + f.head = chunkHead{Gen: 1, Epoch: 1, Holder: "old", Chunks: map[uint64]chunkRef{}} + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + if _, err := ClaimChunkHead(ctx, f, ChunkLayerConfig{Epoch: 2, Holder: "new", HeadCoolingWindow: chunkHeadOperationTimeout + chunkHeadSettleTime}); !errors.Is(err, context.DeadlineExceeded) || f.stats().cas != 1 { + t.Fatalf("claim did not stop inside cooling after CAS: %v, calls=%d", err, f.stats().cas) + } + retryCtx, retryCancel := context.WithTimeout(context.Background(), 8*time.Second) + defer retryCancel() + start := time.Now() + if _, err := ClaimChunkHead(retryCtx, f, ChunkLayerConfig{Epoch: 2, Holder: "new", HeadCoolingWindow: chunkHeadOperationTimeout + chunkHeadSettleTime}); err != nil { + t.Fatal(err) + } + if time.Since(start) < chunkHeadOperationTimeout+chunkHeadSettleTime || f.stats().cas != 1 { + t.Fatal("retry bypassed cooling or replayed a settled claim") + } +} diff --git a/seaweed-block/core/storage/chunk_host_budget_test.go b/seaweed-block/core/storage/chunk_host_budget_test.go new file mode 100644 index 0000000000..2fa955eccf --- /dev/null +++ b/seaweed-block/core/storage/chunk_host_budget_test.go @@ -0,0 +1,54 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/hostlimit" + "testing" +) + +func TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin(t *testing.T) { + s, l, f, gate := cowFixture(t) + c := hostlimit.DefaultConfig(t.TempDir()) + c.NormalSlots = 1 + c.UrgentSlots = 1 + c.COWBytes = ctChunkBytes - 1 + budget, err := hostlimit.New(c) + if err != nil { + t.Fatal(err) + } + contender, err := hostlimit.New(c) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { gate.unblock(); _ = l.Close(); budget.Close(); contender.Close() }) + l.cfg.Budget = budget + before := f.stats().head.Gen + done, errs := cowStartCut(t, l, gate) + if _, err = s.Write(5, makeBlock(ctBlockSize, 0xeb)); err != nil { + t.Fatal("host cap failed guest write:", err) + } + ticket, admitErr := contender.Admit(context.Background(), 1, nil) + if admitErr == nil { + contender.Release(ticket) + } + if !errors.Is(admitErr, hostlimit.ErrBusy) { + t.Fatalf("revoked but unjoined cut lost permit: %v", admitErr) + } + gate.unblock() + cowWaitSignal(t, done, "host-budget abort settlement") + if err = <-errs; !errors.Is(err, hostlimit.ErrRevoked) { + t.Fatalf("cut abort: %v", err) + } + if f.stats().head.Gen != before { + t.Fatal("host-cap aborted cut published") + } + b, err := s.Read(5) + if err != nil || !bytes.Equal(b, makeBlock(ctBlockSize, 0xeb)) { + t.Fatal("guest bytes lost after cut abort", err) + } + if l.Stats().CutsAborted["budget_revoked"] != 1 { + t.Fatal("host cap abort not reported") + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 6a96c8c875..355fcdb19f 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -122,6 +122,7 @@ type chunkLayerImpl struct { // Test-only scheduling hooks; nil in production. testHydrationWait func(uint64) // after promise registration, outside locks testCOWWait func() + testCOWSaverWait func() testCOWRead func(idx uint64, saved bool) testCOWSave func() error testPresenceSnapshotHook func() // after a presence snapshot, before it is written @@ -936,7 +937,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if !upgrade && !detach && len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 && !chunkHeadIsDetached(baseHead) { // A no-op cut still observes authority: a fresh host may have // claimed HEAD without uploading a single chunk since our last cut. - cur, err := l.remote.GetHead(ctx) + cur, err := readChunkHead(ctx, l.remote) if err != nil { l.abortCut(all) l.dropIntents(ctx, intents) @@ -944,11 +945,10 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } if cur.Gen != baseHead.Gen || !sameProposal(cur, baseHead) { l.abortCut(all) - l.dropIntents(ctx, intents) l.stMu.Lock() - l.fenced, l.head = true, copyHead(cur) + l.pendingIntents = append(l.pendingIntents, intents...) l.stMu.Unlock() - l.abortCOW(errChunkLayerFenced) + l.fencePublication(cur) return chunkCutResult{}, errChunkLayerFenced } l.finishCut(baseHead, h, nil, nil) // nothing new: no CAS @@ -972,7 +972,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } expected := chunkHeadVersion{Gen: baseHead.Gen, Epoch: baseHead.Epoch} casStart := time.Now() - gen, casErr := l.remote.CASHead(ctx, expected, next) + gen, casErr := casAndConfirmChunkHead(ctx, l.remote, expected, next) st.CASNs = time.Since(casStart).Nanoseconds() st.CASResult = "ok" if errors.Is(casErr, errChunkHeadPrecondition) { @@ -998,11 +998,21 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.stMu.Unlock() l.abortCut(all) } - cur, gerr := l.remote.GetHead(ctx) + if errors.Is(casErr, errChunkLayerFenced) { + keepPending() + l.fencePublication(chunkHead{}) // confirmChunkHead already logged the observed root. + return chunkCutResult{}, casErr + } + cur, gerr := readChunkHead(ctx, l.remote) if gerr != nil { keepPending() return chunkCutResult{}, fmt.Errorf("storage: capture CAS outcome unresolved (%v): %w: %w", casErr, errChunkCASOutcomeUnknown, gerr) } + if !sameProposal(cur, next) && l.publicationOwnerChanged(cur) { + keepPending() // Close must keep these roots as well. + l.fencePublication(cur) + return chunkCutResult{}, errors.Join(errChunkLayerFenced, casErr) + } if !errors.Is(casErr, errChunkHeadPrecondition) && !sameProposal(cur, next) && cur.Gen == expected.Gen && cur.Epoch == expected.Epoch { // HEAD is still the CAS's base and the server gave no definite // refusal: the CAS may still land. Settle it before any later @@ -1078,30 +1088,38 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (detachSettlement, ch // definitely refused (an unresolved ordinary cut settles as usual). return detachNotPublished, chunkCutResult{}, nil } - cur, err := l.remote.GetHead(ctx) + cur, err := readChunkHead(ctx, l.remote) if err != nil { return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved: %w: %w", errChunkCASOutcomeUnknown, err) } - if !sameProposal(cur, *pending) && !l.supersededBy(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { + if !sameProposal(cur, *pending) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { if err := l.admit(); err != nil { return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (%w); cancel refused: %w", errChunkCASOutcomeUnknown, err) } cancel := copyHead(baseHead) cancel.Epoch, cancel.Holder = l.cfg.Epoch, l.cfg.Holder cancel.State, cancel.DetachedBy = chunkHeadActive, nil - gen, casErr := l.remote.CASHead(ctx, base, cancel) + gen, casErr := casAndConfirmChunkHead(ctx, l.remote, base, cancel) if casErr == nil { cancel.Gen = gen cur = cancel - } else if cur, err = l.remote.GetHead(ctx); err != nil { + } else if errors.Is(casErr, errChunkLayerFenced) { + l.fencePublication(chunkHead{}) + return detachFenced, chunkCutResult{}, nil + } else if cur, err = readChunkHead(ctx, l.remote); err != nil { return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (cancel: %v): %w: %w", casErr, errChunkCASOutcomeUnknown, err) - } else if !sameProposal(cur, *pending) && !l.supersededBy(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { + } else if !sameProposal(cur, *pending) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (cancel: %v): HEAD unchanged: %w", casErr, errChunkCASOutcomeUnknown) } } + if !sameProposal(cur, *pending) && l.publicationOwnerChanged(cur) { + l.fencePublication(cur) + return detachFenced, chunkCutResult{}, nil + } // Settled: the detach landed, or it can never land. l.stMu.Lock() l.reusable = nil + l.pendingIntents = nil // settled here; allow deletion of these roots below. l.stMu.Unlock() l.dropIntents(ctx, intents) l.stMu.Lock() @@ -1194,11 +1212,11 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { if pending == nil { return nil } - cur, err := l.remote.GetHead(ctx) + cur, err := readChunkHead(ctx, l.remote) if err != nil { return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved: %w: %w", errChunkCASOutcomeUnknown, err) } - if !sameProposal(cur, *pending) && !l.supersededBy(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { + if !sameProposal(cur, *pending) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { // HEAD is still the unresolved CAS's base, so that CAS may still // land. Settle it by issuing the same proposal at the same base: // whichever lands first, HEAD ends at this proposal and the other @@ -1209,19 +1227,27 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { if err := l.admit(); err != nil { return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%w); re-proposal refused: %w", errChunkCASOutcomeUnknown, err) } - gen, casErr := l.remote.CASHead(ctx, base, copyHead(*pending)) + gen, casErr := casAndConfirmChunkHead(ctx, l.remote, base, copyHead(*pending)) if casErr == nil { cur = copyHead(*pending) cur.Gen = gen - } else if cur, err = l.remote.GetHead(ctx); err != nil { + } else if errors.Is(casErr, errChunkLayerFenced) { + l.fencePublication(chunkHead{}) + return errChunkLayerFenced + } else if cur, err = readChunkHead(ctx, l.remote); err != nil { return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%v): %w: %w", casErr, errChunkCASOutcomeUnknown, err) - } else if !sameProposal(cur, *pending) && !l.supersededBy(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { + } else if !sameProposal(cur, *pending) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%v): HEAD unchanged: %w", casErr, errChunkCASOutcomeUnknown) } } + if !sameProposal(cur, *pending) && l.publicationOwnerChanged(cur) { + l.fencePublication(cur) + return errChunkLayerFenced + } // Settled: the proposal landed or can never land. l.stMu.Lock() l.reusable = nil + l.pendingIntents = nil // settled here; allow deletion of these roots below. l.stMu.Unlock() l.dropIntents(ctx, intents) l.stMu.Lock() @@ -1371,6 +1397,9 @@ func (l *chunkLayerImpl) dropIntents(ctx context.Context, ids []string) { // once, rather than rescanning every cached chunk for each delete. l.stMu.Lock() keep := make(map[string]bool) + for _, id := range l.pendingIntents { + keep[id] = true + } for idx, sc := range l.reusable { if l.closed || l.fenced || sc.ver != l.chunkVersion(idx) || sc.headGen != l.head.Gen { delete(l.reusable, idx) @@ -1717,10 +1746,8 @@ func (l *chunkLayerImpl) Close() error { l.wg.Wait() l.stMu.Lock() protected := make(map[string]bool, len(l.pendingIntents)) - if l.pending != nil { - for _, id := range l.pendingIntents { - protected[id] = true - } + for _, id := range l.pendingIntents { + protected[id] = true } var settled []string for _, sc := range l.reusable { diff --git a/seaweed-block/core/storage/chunk_layer_intent_test.go b/seaweed-block/core/storage/chunk_layer_intent_test.go index c5d04f0b35..61730a7f89 100644 --- a/seaweed-block/core/storage/chunk_layer_intent_test.go +++ b/seaweed-block/core/storage/chunk_layer_intent_test.go @@ -167,8 +167,9 @@ func TestChunkIntent_FailedUploadDeletesIntent(t *testing.T) { } // HEAD is taken over before the CAS: the CAS is refused for good and the -// layer fences. Its uploads are orphans; its intent goes. -func TestChunkIntent_RefusedCASDeletesIntent(t *testing.T) { +// layer fences. Keep its roots for epoch-aware GC rather than cleaning over +// an independently serialized owner's publication. +func TestChunkIntent_ForeignOwnerRefusalKeepsIntent(t *testing.T) { s, _ := newChunkTestStore(t) f := newFakeChunkRemote() layer := mustAttach(t, s, f, ctConfig(1)) @@ -180,8 +181,8 @@ func TestChunkIntent_RefusedCASDeletesIntent(t *testing.T) { if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkLayerFenced) { t.Fatalf("cut against a taken-over HEAD: %v; want fenced", err) } - if live := liveIntents(t, f); len(live) != 0 { - t.Fatalf("intent left after a refused CAS: %+v", live) + if live := liveIntents(t, f); len(live) == 0 { + t.Fatal("foreign-owner refusal removed the cut's intent") } } diff --git a/seaweed-block/core/storage/chunk_restore.go b/seaweed-block/core/storage/chunk_restore.go index e34a11251b..9962198d17 100644 --- a/seaweed-block/core/storage/chunk_restore.go +++ b/seaweed-block/core/storage/chunk_restore.go @@ -15,6 +15,9 @@ func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfi if remote == nil || cfg.Epoch == 0 || cfg.Holder == "" { return ChunkHead{}, errors.New("storage: HEAD claim needs master epoch and holder") } + if err := validateHeadCoolingWindow(cfg.HeadCoolingWindow); err != nil { + return ChunkHead{}, err + } allowed := func() error { if err := ctx.Err(); err != nil { return err @@ -50,6 +53,11 @@ func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfi return head, nil } if head.Gen != 0 && head.Epoch == cfg.Epoch && head.Holder == cfg.Holder && !chunkHeadIsDetached(head) && head.DetachedBy == nil { + // A previous claim may have committed but timed out during cooling. + // An identical root alone does not prove that wait completed. + if err := confirmChunkTakeover(ctx, remote, head, cfg.HeadCoolingWindow); err != nil { + return ChunkHead{}, err + } return head, allowed() // idempotent restart or settled prior claim } next := copyHead(head) @@ -79,21 +87,38 @@ func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfi return ChunkHead{}, err } settled = false // an ambiguous CAS keeps its segment intents - gen, casErr := remote.CASHead(ctx, ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}, next) + gen, casErr := casChunkHead(ctx, remote, ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}, next) if casErr == nil { - settled = true next.Gen = gen - return next, allowed() + if err := confirmChunkTakeover(ctx, remote, next, cfg.HeadCoolingWindow); err != nil { + return ChunkHead{}, err + } + if err := allowed(); err != nil { + return ChunkHead{}, err + } + settled = true + return next, nil } // Never blindly replay a possibly committed takeover. A re-read must // prove the exact proposal; otherwise the volume remains nonoperational. - current, readErr := remote.GetHead(ctx) + current, readErr := readChunkHead(ctx, remote) if readErr != nil { return ChunkHead{}, fmt.Errorf("storage: HEAD claim unresolved: %w", errors.Join(casErr, readErr)) } - settled = errors.Is(casErr, ErrChunkHeadPrecondition) || current.Gen > head.Gen if current.Gen > head.Gen && sameProposal(current, next) { - return current, allowed() + if err := confirmChunkTakeover(ctx, remote, current, cfg.HeadCoolingWindow); err != nil { + return ChunkHead{}, err + } + if err := allowed(); err != nil { + return ChunkHead{}, err + } + settled = true + return current, nil } + // A foreign publication is a fence, not permission to clean our roots. + if current.Gen != 0 && (current.Epoch != head.Epoch || current.Holder != head.Holder) { + return ChunkHead{}, fmt.Errorf("storage: HEAD claim displaced: %w", ErrChunkLayerFenced) + } + settled = errors.Is(casErr, ErrChunkHeadPrecondition) || current.Gen > head.Gen return ChunkHead{}, fmt.Errorf("storage: HEAD claim not installed: %w", casErr) } diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 7318879fb6..90a8d87316 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -319,6 +319,10 @@ type chunkLayerConfig struct { // projection on every I/O. Epoch uint64 Holder string + // HeadCoolingWindow is zero for the supported single serialization point. + // Nonzero is reserved for explicit multi-filer experiments, must cover + // the HEAD operation deadline plus settling, and does not imply atomicity. + HeadCoolingWindow time.Duration // FreshFromHead says the local volume is new and empty and starts from // HEAD (every block absent, read lazily). False means an existing local // volume. Never inferred from the local contents. diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 97e3a0a084..8b1152d2cd 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -389,3 +389,17 @@ Native pre-copy streams logical reads directly to remote while remaining candida A cut does not pin WAL space or defer flushing. Local reads validate and re-resolve across dirty-map retirement and slot reuse. CopyFinish releases local chunk ownership; every PUT retry sends the same immutable slot, while lazy fills use the cut's fixed base HEAD. + + +### Host background-cut budget + +```mermaid +stateDiagram-v2 + Free --> Admitted: OS slot before staging/barrier + Admitted --> Draining: cancellation or lease expiry + Admitted --> Joined: workers settle + Draining --> Joined: workers settle + Joined --> Free: descriptor closed +``` + +Guest I/O never acquires a slot. An unavailable pool skips background cuts; urgent and named seals may use per-process fallback with an alarm. Active coordinated reservations exclude orphaned crash spill. Upload pacing debt survives leases in one process, but a new process starts fresh, so arbitrary process turnover has no fixed host-rate bound. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index a18ae9c755..52a68e66fa 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -158,7 +158,9 @@ stateDiagram-v2 Attaching --> Claiming: fresh local root Attaching --> Holder: existing root, HEAD is this holder's Attaching --> Refused: existing root, HEAD published by another holder - Claiming --> Holder: CAS to this epoch and holder, state active + Claiming --> Cooling: CAS to this epoch and holder, state active + Cooling --> Holder: configured window elapsed (zero for single filer), exact HEAD reread + Cooling --> HolderFenced: publication displaced Claiming --> HolderFenced: HEAD epoch higher, or another holder at this epoch Holder --> Detached: Detach final cut, state detached Holder --> HolderFenced: a superseding HEAD is seen @@ -171,11 +173,12 @@ stateDiagram-v2 | Valid | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, or the lease is revoking; a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `INV-WS-LEASE-001` | | Fenced | Drained, Acked | the stop callback succeeded; only then, and only when revoked, the acknowledgement is sent | `core/host/volume/workspace_lease.go` `drain` | `INV-WS-REVOKE-ACK-001` | | Attaching | Refused | an existing local root whose HEAD another holder has published (`ErrChunkStaleLocalRoot`) | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-STALE-LOCAL-ROOT-001` | -| Claiming | Holder | HEAD epoch not above the master-issued epoch, no other holder at the same epoch; the local frontier is seeded from HEAD before the CAS; I/O opens only after the claim | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-WS-HEAD-CAS-001` | +| (startup) | Refused | `--chunk-filer` is not the only filer of its group: a master lists another filer or several, or no master lists it within 60 s (`ErrNotSingleFiler`) | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `INV-WS-SINGLE-FILER-001` | +| Claiming | Holder | HEAD epoch not above the master-issued epoch, no other holder at the same epoch; the local frontier is seeded from HEAD before the CAS; I/O opens only after the configured cooling window (zero at one serialization point) and an exact generation/epoch/holder readback | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-WS-HEAD-CAS-001` | | Claiming | Holder, or not installed | unknown CAS outcome: success only if a re-read shows the exact proposal; never a blind replay | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CAS-UNKNOWN-001` | | Holder | Holder | every publish is a cut (M5) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | | Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` | -| Holder | HolderFenced | a HEAD with a higher epoch, or another holder at the same epoch | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | +| Holder | HolderFenced | a conflicting HEAD owner (including a regressed epoch) or a displaced publication is observed; local data and unresolved cut intents remain | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | | Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | | Holder | (hydration wait) | one request deadline covers all missing chunks; callers may detach, but bounded per-layer workers retain and join each shared fill; HEAD/generation/local-write checks still govern installation | `core/storage/chunk_hydration.go`; `core/frontend/durable/storage_adapter.go` `readStorageBlock` | `INV-CUT-HYDRATION-WAIT-001`, `INV-CUT-READMISS-001` | @@ -308,6 +311,10 @@ snapshot lifetime; local persistence does not bypass it. and refusal after Recover. Missing map coverage still forbids checkpoint advancement; the earlier unmapped dark fixture is not a production geometry. +### M7. Host background-cut admission + +`free -> admitted -> draining -> joined -> released`; process death releases its OS slot. Configuration is published by temporary-file sync and rename under its OS lock; a killed initializer leaves no partially visible configuration. Admission precedes staging/barrier; expiry cancels the cut but keeps its slot until workers join. Urgent can borrow normal slots; normal cannot borrow urgent. Unavailable pools skip background work with an alarm; urgent move-final and named seals may use per-process fallback with no coordinated host-cap claim. Guest COW only accounts locally; guest I/O and WAL reclamation never acquire slots. + ## Part B. Invariant ledger 81 rows: 70 ACTIVE, 11 STUB; 15 kept from the internal ledger, 66 new. @@ -420,11 +427,13 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-WS-HEAD-CAS-001` | Every HEAD publish is a conditional update on `{gen, epoch}`, so only one holder can publish each HEAD generation; a holder that sees a superseding HEAD fences itself. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE | -| `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`); `TestNativeReplacementCutBehindHEADRefuses` (`core/storage/legacy_replacement_v3_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE | +| `INV-WS-HEAD-BELT-001` | A takeover confirms its exact HEAD before serving. The supported single-serialization-point mode has W=0; explicit experimental cooling requires W >= the 2 s HEAD operation deadline plus 100 ms settling. Each CAS and confirmation has its own 2 s deadline. A successful cut CAS requires readback before remoteLSN/map settlement and intent cleanup. Unconfirmed roots remain protected through Close; an observed different publication owner fences without retry, even after epoch regression or when the original HEAD was empty. | M4 Claiming → Cooling → Holder; M5 CAS → Confirmed or Pending/Fenced | `core/storage/chunk_head_belt.go`; `chunk_restore.go` `ClaimChunkHead`; `chunk_layer.go` `captureLocked`, `resolvePending`, `SettleDetach`, `dropIntents`, `Close` | `TestHeadBeltTakeoverRefusesLateOldCAS`; `TestHeadBeltTakeoverWaitsBeforeConfirmation`; `TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier`; `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`; `TestHeadBeltEmptyBaseForeignPublicationFences`; `TestHeadBeltSinglePointHasNoCoolingDelay`; `TestHeadBeltOperationsHaveOwnDeadline`; `TestHeadBeltCoolingWindowCoversCASAndSettle` (`core/storage/chunk_head_belt_test.go`) | `WorkspaceTakeover` belt extension pending | ACTIVE | +| `INV-WS-HEAD-CAS-001` | Every HEAD publish is conditional on `{gen, epoch}` at one serialization point. A conflicting observed owner fences the publisher. Multiple independent filer serialization points are not made atomic by readback. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE | +| `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkCut_RemoteLSNNeverDecreases` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`); `TestNativeReplacementCutBehindHEADRefuses` (`core/storage/legacy_replacement_v3_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE | | `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE | | `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | | `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | +| `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`) | — | ACTIVE | | `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | | `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | @@ -453,7 +462,9 @@ Notes: | `INV-CUT-HOOK-BEFORE-APPEND` | The COW hook owns/saves the at-H image before a read-visible WAL mutation, under shared capture admission. | M1 Write / M5 Save | `walstore.go` `Write`, `WriteBatch`; `chunk_cut_cow.go` `beforeChunkMutation` | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 SaveStart before Write | ACTIVE | | `INV-CUT-FILL-FROM-BASE` | Lazily absent blocks are filled from this cut's fixed base HEAD, never a newer remote HEAD. Remote fetch runs after releasing local ownership. | M5 Copy / lazy fill | `chunk_cut_cow.go` `readCOWChunk`, `fillMissing` | `TestCutCOWV3_LazySaverSpillImageIsExact`, `TestCutCOWV3_SaverUsesValidatedWALBatchAndLazyHEAD` | Remote fill not modelled; native byte-image controls | ACTIVE | | `PROGRESS-DESTRUCTIVE` | Supported guest zero-data writes use ordinary COW and do not abort every update. Unsupported DSM/discard/write-zeroes opcodes reach no storage mutation. Administrative Recover/reset/BASE still invalidate and drain; progress assumes these lifecycle transitions eventually stop. | M1 Write / M5 Save | `chunk_cut_cow.go` `beforeCOWMutation`; frontend dispatch | `TestCutCOWV3_ZeroWritesDoNotAbortUpdates` (`core/storage/chunk_cut_alignment_test.go`); `TestDispatch_UnsupportedOperations` (`core/frontend/ublk/dispatch_test.go`); `TestT2Batch11a_IdentifyController_ONCSAllZero` (`core/frontend/nvme/identify_test.go`) | Guest/lifecycle distinction not modelled; native controls | ACTIVE | -| `INV-CUT-PAYLOAD-BOUNDED-001` | Upload workers, active savers and cached saves share a configurable per-volume payload byte bound independent of candidate count; an explicit budget below six chunks is refused. An optional Budget admits before staging/barrier and accounts each COW save without a window lock; revocation aborts only the cut and its ticket is released after worker joins. Host-wide policy is a separate limiter module. WAL batch validation uses block-sized scratch even when a record spans many chunks. Pre-copy streams one chunk per worker; native at-H reads protect unsent candidates with COW. Only guest overwrites consume side-file bytes. A full side-file cap aborts the update, retains its dirty set and allows guest writes to proceed. Uploads join before cleanup. | M5 Stage / Copy / Upload | `chunk_cut_payload.go`; `chunk_cut_cow.go`; `chunk_upload.go` | `TestCutBudgetRefusesBeforeBarrier`, `TestCutBudgetCOWRefusalAbortsOnlyCut`, `TestCutBudgetRevocationJoinsBeforeRelease` (`core/storage/chunk_cut_budget_test.go`); `TestV3ReadLargeBatchScratchIsBlockBounded`, `TestCutAbortReasonsAreCountedAndCopied`, `TestCutPayloadBudgetBoundsSlots`, `TestChunkLayerPayloadBudgetRejectsUndersized` (`core/storage/chunk_cut_payload_budget_test.go`); `TestWALStoreChunk_InitialWriteAnonymousMemory` (isolated Linux RSS arms, `core/frontend/durable/provider_initial_memory_linux_test.go`); `TestCutCOWV3_ChangedImageExceedsSpillCap`, `TestChunkStageV3_ChangedImageExceedsSpillCap`, `TestCutCOWV3_OverwriteStormAbortsAndRetries`, `TestCutCOWV3_RemoteUploadDoesNotParkCopiedChunk` (`core/storage/chunk_cut_cow_spillcap_test.go`); `TestChunkUploads_FailureJoinsBeforeIntentCleanup` (`core/storage/chunk_upload_parallel_test.go`) | `CutPipeline` `AbortPoint` covers refused-point stutter; byte counts and filesystem/transport resource costs are not modelled | ACTIVE | +| `INV-CUT-PAYLOAD-BOUNDED-001` | Saver-slot admission waits at most 250 ms without a window lock or remote call before aborting only the cut; physical local I/O remains joined. Upload workers, active savers and cached saves share a configurable per-volume payload byte bound independent of candidate count; an explicit budget below six chunks is refused. An optional Budget admits before staging/barrier and accounts each COW save without a window lock; revocation aborts only the cut and its ticket is released after worker joins. Host-wide policy is a separate limiter module. WAL batch validation uses block-sized scratch even when a record spans many chunks. Pre-copy streams one chunk per worker; native at-H reads protect unsent candidates with COW. Only guest overwrites consume side-file bytes. A full side-file cap aborts the update, retains its dirty set and allows guest writes to proceed. Uploads join before cleanup. | M5 Stage / Copy / Upload | `chunk_cut_payload.go`; `chunk_cut_cow.go`; `chunk_upload.go` | `TestCutBudgetRefusesBeforeBarrier`, `TestCutBudgetCOWRefusalAbortsOnlyCut`, `TestCutBudgetRevocationJoinsBeforeRelease` (`core/storage/chunk_cut_budget_test.go`); `TestV3ReadLargeBatchScratchIsBlockBounded`, `TestCutCOWV3_SaverBurstWaitsAndPublishes`; `TestStatusServer_ChunkErrorBodyIsTyped` (local cut abort wins over its cancelled upload; uncertain CAS, fencing and terminal Closed/Detached keep precedence), `TestCutAbortReasonsAreCountedAndCopied`, `TestCutPayloadBudgetBoundsSlots`, `TestChunkLayerPayloadBudgetRejectsUndersized` (`core/storage/chunk_cut_payload_budget_test.go`); `TestWALStoreChunk_InitialWriteAnonymousMemory` (isolated Linux RSS arms, `core/frontend/durable/provider_initial_memory_linux_test.go`); `TestCutCOWV3_ChangedImageExceedsSpillCap`, `TestChunkStageV3_ChangedImageExceedsSpillCap`, `TestCutCOWV3_OverwriteStormAbortsAndRetries`, `TestCutCOWV3_RemoteUploadDoesNotParkCopiedChunk` (`core/storage/chunk_cut_cow_spillcap_test.go`); `TestChunkUploads_FailureJoinsBeforeIntentCleanup` (`core/storage/chunk_upload_parallel_test.go`) | `CutPipeline` `AbortPoint` covers refused-point stutter; byte counts and filesystem/transport resource costs are not modelled | ACTIVE | +| `INV-HOST-CUT-BUDGET-001` | Cooperating cut processes hold an OS slot before staging/barrier; payload and side caps are reserved per slot, including urgent slots. Cancellation never frees a slot before actual worker settlement. Active coordinated reservations exclude retained crash spill, fallback and RSS. Unavailable pools refuse ordinary background work; urgent/named fallback is explicitly degraded and cannot claim a host resource/rate bound. Pacing debt persists within one process, not across process turnover. | M7 admission/drain/release | `core/hostlimit`; durable `ChunkBudget`; blockvolume host-limit flags | `TestSlotsUrgentAndJoinedRelease`, `TestCOWAbortHoldsSlotUntilWorkerSettlement`, `TestHoldExpiryAndCloseDoNotSteal`, `TestKilledProcessReleasesButLiveHolderDoesNot`, `TestHostCutLimitDoesNotGateGuestIO`, `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin`, `TestCutPolicy_StaggerPreservesExplicitTimerReset`, `TestKilledInitializerDoesNotPublishPartialConfiguration`, `TestUnusablePoolClassPolicy`, `TestPacingDebtSurvivesOwnLeaseTurnover`, `TestPacingFreshProcessesDoNotShareDebt`, `TestChunkControl_NamedSnapshotUsesUrgentFallback`, `TestLastFallbackReleaseClearsActiveStatus`, `TestConfigurationLockFailurePreservesPoolPolicy`, `TestConfigurationLockContentionRefusesAllClasses` | `HostBudget` HeldUntilJoined/PayloadBound/SpillBound (bounded OS-lock abstraction; fallback excluded) | ACTIVE | +| `INV-HOST-POOL-CONFIG-001` | A pool configuration is invisible until its complete synced temporary file is atomically renamed under the OS configuration lock. A killed initializer cannot leave a partial visible configuration that strands successors. | M7 configuration preparation/publication | `core/hostlimit` `publishConfig` | `TestKilledInitializerDoesNotPublishPartialConfiguration` | `HostBudget` NoPartialConfig/ConfigBeforeAdmission (filesystem atomicity checked natively) | ACTIVE | | `INV-CUT-INTENT-FIRST-001` | Before the first upload of a cut or staging round, one intent names every preallocated candidate key (unused keys are harmless), independent of upload wave count. Known-aborted reusable roots are removed at clean Close; unresolved CAS roots remain protected. Intent removal follows a known CAS outcome. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestCutPayloadReadsOverlapEarlierUploadsWithinBudget`, `TestCutPayloadIntentCountIndependentOfCandidates`, `TestChunkCloseDropsReusableButKeepsUnknownCASRoots`, `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | | `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | | `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | ACTIVE | diff --git a/seaweed-block/docs/spec/HostBudget.tla b/seaweed-block/docs/spec/HostBudget.tla new file mode 100644 index 0000000000..bae8554b27 --- /dev/null +++ b/seaweed-block/docs/spec/HostBudget.tla @@ -0,0 +1,66 @@ +----------------------------- MODULE HostBudget ----------------------------- +\* Active coordinated reservations only: fallback, pacing, RSS and retained +\* crash scratch bytes are outside this abstraction. Crash frees active slots. +EXTENDS Integers, FiniteSets, TLC +CONSTANTS N, SlotCount, Payload, Spill, EarlyRelease, AtomicConfig +Owners == 1..N +Slots == 1..SlotCount +VARIABLES phase, owner, slot, saved, cfg, initializer +vars == <> +Init == /\ cfg = "absent" + /\ initializer = 0 + /\ phase = [o \in Owners |-> "free"] + /\ owner = [s \in Slots |-> 0] + /\ slot = [o \in Owners |-> 0] + /\ saved = [o \in Owners |-> 0] +Admit(o,s) == /\ cfg = "ready" + /\ phase[o] = "free" /\ owner[s] = 0 + /\ (o = N \/ s < SlotCount) + /\ phase' = [phase EXCEPT ![o] = "active"] + /\ owner' = [owner EXCEPT ![s] = o] + /\ slot' = [slot EXCEPT ![o] = s] + /\ UNCHANGED <> +Save(o) == /\ phase[o] = "active" /\ saved[o] < Spill + /\ saved' = [saved EXCEPT ![o] = @ + 1] + /\ UNCHANGED <> +Abort(o) == /\ phase[o] = "active" + /\ phase' = [phase EXCEPT ![o] = "draining"] + /\ owner' = IF EarlyRelease THEN [owner EXCEPT ![slot[o]] = 0] ELSE owner + /\ UNCHANGED <> +Join(o) == /\ phase[o] \in {"active","draining"} + /\ phase' = [phase EXCEPT ![o] = "joined"] + /\ UNCHANGED <> +Release(o) == /\ phase[o] = "joined" + /\ owner' = [owner EXCEPT ![slot[o]] = 0] + /\ phase' = [phase EXCEPT ![o] = "free"] + /\ slot' = [slot EXCEPT ![o] = 0] + /\ saved' = [saved EXCEPT ![o] = 0] + /\ UNCHANGED <> +Crash(o) == /\ phase[o] # "free" + /\ owner' = [owner EXCEPT ![slot[o]] = 0] + /\ phase' = [phase EXCEPT ![o] = "free"] + /\ slot' = [slot EXCEPT ![o] = 0] + /\ saved' = [saved EXCEPT ![o] = 0] + /\ UNCHANGED <> +BeginConfig(o) == /\ cfg = "absent" + /\ cfg' = IF AtomicConfig THEN "writing" ELSE "partial" + /\ initializer' = o + /\ UNCHANGED <> +PublishConfig == /\ cfg \in {"writing","partial"} + /\ cfg' = "ready" /\ initializer' = 0 + /\ UNCHANGED <> +CrashInitializer == /\ cfg \in {"writing","partial"} + /\ cfg' = "absent" /\ initializer' = 0 + /\ UNCHANGED <> +Next == (\E o \in Owners: BeginConfig(o)) \/ PublishConfig \/ CrashInitializer \/ + (\E o \in Owners,s \in Slots: Admit(o,s)) \/ + (\E o \in Owners: Save(o) \/ Abort(o) \/ Join(o) \/ Release(o) \/ Crash(o)) +Spec == Init /\ [][Next]_vars +NoPartialConfig == cfg # "partial" +ConfigBeforeAdmission == (\E o \in Owners: phase[o] # "free") => cfg = "ready" +HeldUntilJoined == \A o \in Owners: phase[o] # "free" => owner[slot[o]] = o +RECURSIVE Total(_) +Total(n) == IF n=0 THEN 0 ELSE saved[n]+Total(n-1) +PayloadBound == Cardinality({o \in Owners: phase[o] # "free"})*Payload <= SlotCount*Payload +SpillBound == Total(N) <= SlotCount*Spill +============================================================================= diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index ae3adb124e..98c2c668f4 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -311,3 +311,9 @@ TLC. This is an abstraction: physical fsync success, byte layout, crash recovery both-slot retirement, timing and multiple writers remain covered by their other models and actual Go controls. Do not treat finite liveness checking as an end-to-end wall-clock latency guarantee. Keep long model runs off tp04. + +## HostBudget + +`HostBudget.tla` abstracts cooperating process slots, COW reservation and joined release. Config `HostBudget.cfg` checks three owners/two slots; `HostBudget_early_release.cfg` must violate HeldUntilJoined. It excludes degraded static fallback and does not prove filesystem locks, rates or physical-I/O deadlines. Native subprocess tests cover lock lifetime. + +HostBudget also models guarded configuration initialization: staged bytes are invisible until atomic publication; an initializer crash permits a successor. `HostBudget_partial_config.cfg` must violate NoPartialConfig. The syscall-level crash boundary is covered by TestKilledInitializerDoesNotPublishPartialConfiguration. diff --git a/seaweed-block/docs/spec/cfg/HostBudget.cfg b/seaweed-block/docs/spec/cfg/HostBudget.cfg new file mode 100644 index 0000000000..37f2082ee0 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/HostBudget.cfg @@ -0,0 +1,9 @@ +CONSTANTS +N=3 +SlotCount=2 +Payload=1 +Spill=2 +EarlyRelease=FALSE +AtomicConfig=TRUE +SPECIFICATION Spec +INVARIANTS NoPartialConfig ConfigBeforeAdmission HeldUntilJoined PayloadBound SpillBound diff --git a/seaweed-block/docs/spec/cfg/HostBudget_early_release.cfg b/seaweed-block/docs/spec/cfg/HostBudget_early_release.cfg new file mode 100644 index 0000000000..6cf3a12ea2 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/HostBudget_early_release.cfg @@ -0,0 +1,9 @@ +CONSTANTS +N=3 +SlotCount=2 +Payload=1 +Spill=2 +EarlyRelease=TRUE +AtomicConfig=TRUE +SPECIFICATION Spec +INVARIANTS NoPartialConfig ConfigBeforeAdmission HeldUntilJoined PayloadBound SpillBound diff --git a/seaweed-block/docs/spec/cfg/HostBudget_partial_config.cfg b/seaweed-block/docs/spec/cfg/HostBudget_partial_config.cfg new file mode 100644 index 0000000000..f0e304be5b --- /dev/null +++ b/seaweed-block/docs/spec/cfg/HostBudget_partial_config.cfg @@ -0,0 +1,9 @@ +CONSTANTS +N=3 +SlotCount=2 +Payload=1 +Spill=2 +EarlyRelease=FALSE +AtomicConfig=FALSE +SPECIFICATION Spec +INVARIANTS NoPartialConfig ConfigBeforeAdmission HeldUntilJoined PayloadBound SpillBound diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 49539b774d..c2c8f5abb4 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -132,6 +132,15 @@ the example units, which turn them into flags. blockvolume itself reads only The `--chunk-*` and `--workspace-lease` flags are refused unless `--durable-impl=walstore-chunk`; leave them at their defaults otherwise. +`--chunk-filer` must name the only filer of its filer group. At startup +blockvolume asks that filer for its masters, then every master for the +filers in the group. It starts only when a master lists exactly that filer. +Any master listing another filer, or several, refuses at once. If no master +lists it yet (a fresh filer registers with its master some seconds after it +serves), or none answers, blockvolume asks again every second until 60 s, +then refuses. This is checked at startup only; do not add filers to the +group while volumes run. + ## Notes - The control plane, the status endpoint and the NVMe/TCP target have no