diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index 6721fc1a84..fcc04b65de 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -110,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, @@ -121,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/cpuprofile.go b/seaweed-block/cmd/blockvolume/cpuprofile.go new file mode 100644 index 0000000000..24656f7b47 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/cpuprofile.go @@ -0,0 +1,75 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "runtime/pprof" + "sync" +) + +// cpuProfileEnv names the directory for on-demand CPU profiles (diagnostics). +// Empty (the default) leaves blockvolume unchanged: no signal handler is +// installed and nothing is written. Set, SIGUSR1 starts a CPU profile into +// /blockvolume--.pprof and the next SIGUSR1 stops it, so a +// harness can profile a running volume without a port or a restart. +const cpuProfileEnv = "SWBLOCK_CPU_PROFILE_DIR" + +// cpuProfiler toggles one CPU profile at a time. +type cpuProfiler struct { + dir string + mu sync.Mutex + f *os.File + n int +} + +// toggle starts a profile when none runs, else stops the running one. It +// returns the profile's path and whether a profile now runs. +func (p *cpuProfiler) toggle() (string, bool, error) { + p.mu.Lock() + defer p.mu.Unlock() + if p.f != nil { + path := p.f.Name() + pprof.StopCPUProfile() + err := p.f.Close() + p.f = nil + return path, false, err + } + p.n++ + path := filepath.Join(p.dir, fmt.Sprintf("blockvolume-%d-%d.pprof", os.Getpid(), p.n)) + f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) + if err != nil { + return path, false, err + } + if err := pprof.StartCPUProfile(f); err != nil { + _ = f.Close() + _ = os.Remove(path) + return path, false, err + } + p.f = f + return path, true, nil +} + +// stop ends a running profile (at shutdown), keeping what it recorded. +func (p *cpuProfiler) stop() { + p.mu.Lock() + defer p.mu.Unlock() + if p.f != nil { + pprof.StopCPUProfile() + _ = p.f.Close() + p.f = nil + } +} + +// checkCPUProfileDir refuses a profile directory that is not an existing +// directory, at startup rather than at the first signal. +func checkCPUProfileDir(dir string) error { + fi, err := os.Stat(dir) + if err != nil { + return fmt.Errorf("--cpu-profile-dir %s: %w", dir, err) + } + if !fi.IsDir() { + return fmt.Errorf("--cpu-profile-dir %s: not a directory", dir) + } + return nil +} diff --git a/seaweed-block/cmd/blockvolume/cpuprofile_other.go b/seaweed-block/cmd/blockvolume/cpuprofile_other.go new file mode 100644 index 0000000000..b90c365ff1 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/cpuprofile_other.go @@ -0,0 +1,15 @@ +//go:build !unix + +package main + +import "errors" + +// cpuProfileSupported: no SIGUSR1 on this platform. +const cpuProfileSupported = false + +func startCPUProfileSignal(dir string) (stop func(), err error) { + if dir == "" { + return func() {}, nil + } + return nil, errors.New("--cpu-profile-dir needs SIGUSR1 (unix only)") +} diff --git a/seaweed-block/cmd/blockvolume/cpuprofile_test.go b/seaweed-block/cmd/blockvolume/cpuprofile_test.go new file mode 100644 index 0000000000..aac5a77d11 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/cpuprofile_test.go @@ -0,0 +1,58 @@ +package main + +import ( + "os" + "path/filepath" + "testing" +) + +// The profile directory comes from --cpu-profile-dir, defaulting to +// $SWBLOCK_CPU_PROFILE_DIR; unset means off. +func TestCPUProfileDirFlagDefaultsFromEnv(t *testing.T) { + base := []string{"--master", "127.0.0.1:1", "--server-id", "h1", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", "127.0.0.1:2", "--ctrl-addr", "127.0.0.1:3"} + t.Setenv(cpuProfileEnv, "") + if f, err := parseFlags(base); err != nil || f.cpuProfileDir != "" { + t.Fatalf("default: %q %v; want off", f.cpuProfileDir, err) + } + dir := t.TempDir() + t.Setenv(cpuProfileEnv, dir) + f, err := parseFlags(base) + other := t.TempDir() + fx, errx := parseFlags(append(append([]string{}, base...), "--cpu-profile-dir", other)) + if !cpuProfileSupported { + // No SIGUSR1 here: a set directory is refused in flag parsing. + if err == nil || errx == nil { + t.Fatalf("unsupported platform accepted a profile dir: env %v, flag %v", err, errx) + } + return + } + if err != nil || f.cpuProfileDir != dir { + t.Fatalf("from env: %q %v; want %q", f.cpuProfileDir, err, dir) + } + if errx != nil || fx.cpuProfileDir != other { + t.Fatalf("explicit flag: %q %v; want %q", fx.cpuProfileDir, errx, other) + } +} + +// A profile directory that is not an existing directory is refused before +// any signal arrives. +func TestCPUProfileDirMustBeAnExistingDirectory(t *testing.T) { + if err := checkCPUProfileDir(filepath.Join(t.TempDir(), "missing")); err == nil { + t.Fatal("a missing directory was accepted") + } + file := filepath.Join(t.TempDir(), "file") + if err := os.WriteFile(file, nil, 0o644); err != nil { + t.Fatal(err) + } + if err := checkCPUProfileDir(file); err == nil { + t.Fatal("a file was accepted as the profile directory") + } + if err := checkCPUProfileDir(t.TempDir()); err != nil { + t.Fatalf("an existing directory was refused: %v", err) + } + // The refusal happens in parseFlags, before run() activates anything. + base := []string{"--master", "127.0.0.1:1", "--server-id", "h1", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", "127.0.0.1:2", "--ctrl-addr", "127.0.0.1:3"} + if _, err := parseFlags(append(append([]string{}, base...), "--cpu-profile-dir", file)); err == nil { + t.Fatal("parseFlags accepted a file as the profile directory") + } +} diff --git a/seaweed-block/cmd/blockvolume/cpuprofile_unix.go b/seaweed-block/cmd/blockvolume/cpuprofile_unix.go new file mode 100644 index 0000000000..6d182b80ce --- /dev/null +++ b/seaweed-block/cmd/blockvolume/cpuprofile_unix.go @@ -0,0 +1,56 @@ +//go:build unix + +package main + +import ( + "log" + "os" + "os/signal" + "syscall" +) + +// cpuProfileSupported: SIGUSR1 exists here. +const cpuProfileSupported = true + +// startCPUProfileSignal makes SIGUSR1 toggle a CPU profile into dir. The +// returned stop removes the handler, stops and joins the worker (so no +// buffered signal can start a profile after it), then writes out a running +// profile. dir "" installs nothing. +func startCPUProfileSignal(dir string) (stop func(), err error) { + if dir == "" { + return func() {}, nil + } + if err := checkCPUProfileDir(dir); err != nil { + return nil, err + } + p := &cpuProfiler{dir: dir} + sig := make(chan os.Signal, 1) + signal.Notify(sig, syscall.SIGUSR1) + quit, done := make(chan struct{}), make(chan struct{}) + go func() { + defer close(done) + for { + select { + case <-quit: + return + case <-sig: + path, running, err := p.toggle() + switch { + case err != nil: + log.Printf("blockvolume: cpu profile %s: %v", path, err) + case running: + log.Printf("blockvolume: cpu profile started: %s (SIGUSR1 again stops it)", path) + default: + log.Printf("blockvolume: cpu profile written: %s", path) + } + } + } + }() + log.Printf("blockvolume: SIGUSR1 toggles a CPU profile into %s", dir) + return func() { + signal.Stop(sig) + close(quit) + <-done + p.stop() + }, nil +} diff --git a/seaweed-block/cmd/blockvolume/cpuprofile_unix_test.go b/seaweed-block/cmd/blockvolume/cpuprofile_unix_test.go new file mode 100644 index 0000000000..1c965f79d4 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/cpuprofile_unix_test.go @@ -0,0 +1,144 @@ +//go:build unix + +package main + +import ( + "bytes" + "compress/gzip" + "io" + "os" + "path/filepath" + "runtime/pprof" + "sort" + "syscall" + "testing" + "time" +) + +func profiles(t *testing.T, dir string) []string { + t.Helper() + m, err := filepath.Glob(filepath.Join(dir, "blockvolume-*.pprof")) + if err != nil { + t.Fatal(err) + } + sort.Strings(m) + return m +} + +func waitUntil(t *testing.T, what string, ok func() bool) { + t.Helper() + end := time.Now().Add(10 * time.Second) + for !ok() { + if time.Now().After(end) { + t.Fatalf("timed out waiting for %s", what) + } + time.Sleep(20 * time.Millisecond) + } +} + +func burn(d time.Duration) { + x := 0 + for end := time.Now().Add(d); time.Now().Before(end); { + x++ + } + _ = x +} + +// complete reports whether path holds a whole gzip stream (a written-out +// pprof profile): a truncated or still-open profile fails to decompress. +func complete(path string) bool { + b, err := os.ReadFile(path) + if err != nil || len(b) == 0 { + return false + } + zr, err := gzip.NewReader(bytes.NewReader(b)) + if err != nil { + return false + } + out, err := io.ReadAll(zr) + return err == nil && len(out) > 0 +} + +// noProfileRunning reports whether no CPU profile is active in this process. +func noProfileRunning(t *testing.T) bool { + t.Helper() + if err := pprof.StartCPUProfile(io.Discard); err != nil { + return false + } + pprof.StopCPUProfile() + return true +} + +func usr1(t *testing.T) { + t.Helper() + if err := syscall.Kill(os.Getpid(), syscall.SIGUSR1); err != nil { + t.Fatal(err) + } +} + +// With a profile directory, SIGUSR1 starts a CPU profile and the next +// SIGUSR1 writes it out as a complete pprof; a second pair writes a second +// file. stop writes out a profile still running. +func TestCPUProfileSIGUSR1TogglesAProfile(t *testing.T) { + dir := t.TempDir() + stop, err := startCPUProfileSignal(dir) + if err != nil { + t.Fatal(err) + } + stopped := false + defer func() { + if !stopped { + stop() + } + }() + for cycle := 1; cycle <= 2; cycle++ { + usr1(t) + waitUntil(t, "profile file created", func() bool { return len(profiles(t, dir)) == cycle }) + burn(200 * time.Millisecond) + usr1(t) + path := profiles(t, dir)[cycle-1] + waitUntil(t, "profile "+path+" written", func() bool { return complete(path) }) + } + usr1(t) + waitUntil(t, "third profile file created", func() bool { return len(profiles(t, dir)) == 3 }) + burn(100 * time.Millisecond) + stop() + stopped = true + if p := profiles(t, dir)[2]; !complete(p) { + t.Fatalf("stop did not write out the running profile %s", p) + } + if !noProfileRunning(t) { + t.Fatal("a CPU profile is still running after stop") + } +} + +// A SIGUSR1 delivered just before stop cannot leave a profile running after +// it: stop joins the worker before the final write-out. +func TestCPUProfileStopJoinsTheWorker(t *testing.T) { + for i := 0; i < 20; i++ { + dir := t.TempDir() + stop, err := startCPUProfileSignal(dir) + if err != nil { + t.Fatal(err) + } + usr1(t) + stop() + if !noProfileRunning(t) { + t.Fatalf("round %d: a profile was running after stop returned", i) + } + for _, p := range profiles(t, dir) { + if !complete(p) { + t.Fatalf("round %d: %s left incomplete after stop", i, p) + } + } + } +} + +// Off (no directory): nothing is installed and nothing is written. +func TestCPUProfileOffInstallsNothing(t *testing.T) { + stop, err := startCPUProfileSignal("") + if err != nil || stop == nil { + t.Fatalf("off: %v", err) + } + stop() +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index e3eac2712b..b526388dbe 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -41,6 +41,7 @@ import ( ) type flags struct { + cpuProfileDir string memoryLimitMiB int64 masterAddr string serverID string @@ -171,6 +172,7 @@ func parseFlags(args []string) (flags, error) { fs.BoolVar(&f.printReadyLine, "t0-print-ready", false, "internal test-only: emit one structured JSON line on stdout on first assignment") fs.BoolVar(&f.enableT1Readiness, "t1-readiness", false, "enable readiness bridge (HealthyPathExecutor) so adapter projection reaches Healthy") fs.StringVar(&f.statusAddr, "status-addr", "", "address for the status HTTP endpoint (e.g. 127.0.0.1:0); empty disables") + fs.StringVar(&f.cpuProfileDir, "cpu-profile-dir", os.Getenv(cpuProfileEnv), "diagnostics: an existing directory; SIGUSR1 then toggles a CPU profile written there (default $"+cpuProfileEnv+"; empty disables)") fs.BoolVar(&f.statusRecovery, "status-recovery", false, "expose /status/recovery?volume= with engine.ReplicaProjection (Mode/R/S/H/RecoveryDecision); off by default; loopback-only; intended for hardware test orchestration") fs.BoolVar(&f.allowExternalStatusBind, "allow-external-status-bind", false, "allow the unauthenticated status endpoint to bind and serve non-loopback addresses; intended only for explicit Kubernetes node-loss gates") fs.BoolVar(&f.runtimeRebuildEndpoint, "runtime-rebuild-endpoint", false, "expose POST /runtime/rebuild on the status HTTP listener; off by default; starts primary-side rebuild/catch-up traffic only after request lineage validation") @@ -255,6 +257,14 @@ func parseFlags(args []string) (flags, error) { if f.memoryLimitMiB < 0 || f.memoryLimitMiB > math.MaxInt64>>20 { return flags{}, fmt.Errorf("--memory-limit-mib out of range") } + if f.cpuProfileDir != "" { // before anything starts: run() has no side effect yet + if !cpuProfileSupported { + return flags{}, fmt.Errorf("--cpu-profile-dir needs SIGUSR1 (unix only)") + } + if err := checkCPUProfileDir(f.cpuProfileDir); err != nil { + return flags{}, err + } + } if f.version { return f, nil } @@ -569,6 +579,14 @@ func durableCreateGeometry(f flags) (uint32, int, error) { } func run(f flags) int { + // Diagnostics first: parseFlags validated the directory, and nothing + // has been activated yet, so a failure here leaves nothing to clean up. + stopProfile, err := startCPUProfileSignal(f.cpuProfileDir) + if err != nil { + fmt.Fprintln(os.Stderr, "blockvolume:", err) + return 1 + } + defer stopProfile() readyCh := make(chan adapter.AssignmentInfo, 16) h, err := volume.New(hostConfig(f, readyCh)) 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/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/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/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index e3024f6317..43db86794e 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -264,20 +264,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 } 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/storage/chunk_cut_cow.go b/seaweed-block/core/storage/chunk_cut_cow.go index 63281469e6..f732f9cf05 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_layer.go b/seaweed-block/core/storage/chunk_layer.go index c886d84022..5a5056c49d 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -132,6 +132,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 diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index bd895ebb89..9b846e4bac 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -171,6 +171,7 @@ 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` | +| (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 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` | | 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` | @@ -429,6 +430,7 @@ Notes: | `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 | @@ -457,7 +459,7 @@ 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. Missing-pool fallback is explicitly degraded and cannot claim the shared bound. | M7 admission/drain/release | `core/hostlimit`; durable `ChunkBudget`; blockvolume host-limit flags | `TestSlotsUrgentAndJoinedRelease`, `TestCOWAbortHoldsSlotUntilWorkerSettlement`, `TestHoldExpiryAndCloseDoNotSteal`, `TestKilledProcessReleasesButLiveHolderDoesNot`, `TestHostCutLimitDoesNotGateGuestIO`, `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin`, `TestCutPolicy_StaggerPreservesExplicitTimerReset`, `TestKilledInitializerDoesNotPublishPartialConfiguration` | `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 | 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