From 39f011555ac4375bdd2dfc1de0e6d42ee0509b5f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 23:36:05 -0800 Subject: [PATCH 01/12] blockvolume: opt-in CPU profile toggled by SIGUSR1 --cpu-profile-dir (default $SWBLOCK_CPU_PROFILE_DIR) names an existing directory; SIGUSR1 then starts a CPU profile written there as blockvolume--.pprof and the next SIGUSR1 stops it. Shutdown writes out a running profile. Unset (the default), nothing is installed and blockvolume is unchanged. No port is opened, so a harness can profile any running volume with kill -USR1. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/cpuprofile.go | 75 ++++++++++++++ .../cmd/blockvolume/cpuprofile_other.go | 15 +++ .../cmd/blockvolume/cpuprofile_test.go | 44 +++++++++ .../cmd/blockvolume/cpuprofile_unix.go | 51 ++++++++++ .../cmd/blockvolume/cpuprofile_unix_test.go | 97 +++++++++++++++++++ seaweed-block/cmd/blockvolume/main.go | 8 ++ 6 files changed, 290 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/cpuprofile.go create mode 100644 seaweed-block/cmd/blockvolume/cpuprofile_other.go create mode 100644 seaweed-block/cmd/blockvolume/cpuprofile_test.go create mode 100644 seaweed-block/cmd/blockvolume/cpuprofile_unix.go create mode 100644 seaweed-block/cmd/blockvolume/cpuprofile_unix_test.go 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..05fde43c6e --- /dev/null +++ b/seaweed-block/cmd/blockvolume/cpuprofile_other.go @@ -0,0 +1,15 @@ +//go:build !unix + +package main + +import ( + "context" + "errors" +) + +func startCPUProfileSignal(_ context.Context, 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..3e5a4a672d --- /dev/null +++ b/seaweed-block/cmd/blockvolume/cpuprofile_test.go @@ -0,0 +1,44 @@ +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) + if f, err := parseFlags(base); err != nil || f.cpuProfileDir != dir { + t.Fatalf("from env: %q %v; want %q", f.cpuProfileDir, err, dir) + } + other := t.TempDir() + if f, err := parseFlags(append(append([]string{}, base...), "--cpu-profile-dir", other)); err != nil || f.cpuProfileDir != other { + t.Fatalf("explicit flag: %q %v; want %q", f.cpuProfileDir, err, 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) + } +} diff --git a/seaweed-block/cmd/blockvolume/cpuprofile_unix.go b/seaweed-block/cmd/blockvolume/cpuprofile_unix.go new file mode 100644 index 0000000000..ee85312e42 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/cpuprofile_unix.go @@ -0,0 +1,51 @@ +//go:build unix + +package main + +import ( + "context" + "log" + "os" + "os/signal" + "syscall" +) + +// startCPUProfileSignal makes SIGUSR1 toggle a CPU profile into dir until ctx +// ends; the returned stop ends a running profile and removes the handler. +// dir "" installs nothing. +func startCPUProfileSignal(ctx context.Context, 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) + done := make(chan struct{}) + go func() { + defer close(done) + for { + select { + case <-ctx.Done(): + 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) + 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..6565d4ab61 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/cpuprofile_unix_test.go @@ -0,0 +1,97 @@ +//go:build unix + +package main + +import ( + "bytes" + "context" + "os" + "path/filepath" + "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 +} + +// With a profile directory, SIGUSR1 starts a CPU profile and the next +// SIGUSR1 writes it out (a gzip pprof); a second pair writes a second file. +// Stopping the handler ends a running profile and keeps what it recorded. +func TestCPUProfileSIGUSR1TogglesAProfile(t *testing.T) { + dir := t.TempDir() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + stop, err := startCPUProfileSignal(ctx, dir) + if err != nil { + t.Fatal(err) + } + stopped := false + defer func() { + if !stopped { + stop() + } + }() + usr1 := func() { + if err := syscall.Kill(os.Getpid(), syscall.SIGUSR1); err != nil { + t.Fatal(err) + } + } + complete := func(path string) bool { + b, err := os.ReadFile(path) + return err == nil && len(b) > 2 && bytes.HasPrefix(b, []byte{0x1f, 0x8b}) + } + for cycle := 1; cycle <= 2; cycle++ { + usr1() + waitUntil(t, "profile file created", func() bool { return len(profiles(t, dir)) == cycle }) + burn(200 * time.Millisecond) + usr1() + path := profiles(t, dir)[cycle-1] + waitUntil(t, "profile "+path+" written", func() bool { return complete(path) }) + } + // A third profile left running is written out by stop. + usr1() + 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) + } +} + +// Off (no directory): nothing is installed and nothing is written. +func TestCPUProfileOffInstallsNothing(t *testing.T) { + stop, err := startCPUProfileSignal(context.Background(), "") + 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 a07ae34efc..396eb99c55 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -40,6 +40,7 @@ import ( ) type flags struct { + cpuProfileDir string memoryLimitMiB int64 masterAddr string serverID string @@ -170,6 +171,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") @@ -1196,6 +1198,12 @@ func run(f flags) int { shutdownCtx, stopSignals := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stopSignals() + stopProfile, err := startCPUProfileSignal(shutdownCtx, f.cpuProfileDir) + if err != nil { + fmt.Fprintf(os.Stderr, "blockvolume: %v\n", err) + return 1 + } + defer stopProfile() var leaseRequests <-chan workspaceStopRequest var leaseDone <-chan error if f.workspaceLease { From fb939adb8af4e16e794b4e3e48c69fef87dc95be Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 23:47:25 -0800 Subject: [PATCH 02/12] blockvolume: validate the profile dir before startup; stop joins the worker parseFlags refuses an unusable --cpu-profile-dir (and a platform without SIGUSR1) before run() activates anything; the handler is installed at the top of run(). stop removes the handler, stops and joins the signal worker, then writes out a running profile, so a buffered SIGUSR1 cannot start a profile after it. Tests decompress the whole profile and check that no profile runs after stop. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/cpuprofile_other.go | 10 +-- .../cmd/blockvolume/cpuprofile_test.go | 5 ++ .../cmd/blockvolume/cpuprofile_unix.go | 19 ++-- .../cmd/blockvolume/cpuprofile_unix_test.go | 87 ++++++++++++++----- seaweed-block/cmd/blockvolume/main.go | 22 +++-- 5 files changed, 105 insertions(+), 38 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/cpuprofile_other.go b/seaweed-block/cmd/blockvolume/cpuprofile_other.go index 05fde43c6e..b90c365ff1 100644 --- a/seaweed-block/cmd/blockvolume/cpuprofile_other.go +++ b/seaweed-block/cmd/blockvolume/cpuprofile_other.go @@ -2,12 +2,12 @@ package main -import ( - "context" - "errors" -) +import "errors" -func startCPUProfileSignal(_ context.Context, dir string) (stop func(), err error) { +// cpuProfileSupported: no SIGUSR1 on this platform. +const cpuProfileSupported = false + +func startCPUProfileSignal(dir string) (stop func(), err error) { if dir == "" { return func() {}, nil } diff --git a/seaweed-block/cmd/blockvolume/cpuprofile_test.go b/seaweed-block/cmd/blockvolume/cpuprofile_test.go index 3e5a4a672d..9c375477d9 100644 --- a/seaweed-block/cmd/blockvolume/cpuprofile_test.go +++ b/seaweed-block/cmd/blockvolume/cpuprofile_test.go @@ -41,4 +41,9 @@ func TestCPUProfileDirMustBeAnExistingDirectory(t *testing.T) { 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 index ee85312e42..6d182b80ce 100644 --- a/seaweed-block/cmd/blockvolume/cpuprofile_unix.go +++ b/seaweed-block/cmd/blockvolume/cpuprofile_unix.go @@ -3,17 +3,20 @@ package main import ( - "context" "log" "os" "os/signal" "syscall" ) -// startCPUProfileSignal makes SIGUSR1 toggle a CPU profile into dir until ctx -// ends; the returned stop ends a running profile and removes the handler. -// dir "" installs nothing. -func startCPUProfileSignal(ctx context.Context, dir string) (stop func(), err error) { +// 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 } @@ -23,12 +26,12 @@ func startCPUProfileSignal(ctx context.Context, dir string) (stop func(), err er p := &cpuProfiler{dir: dir} sig := make(chan os.Signal, 1) signal.Notify(sig, syscall.SIGUSR1) - done := make(chan struct{}) + quit, done := make(chan struct{}), make(chan struct{}) go func() { defer close(done) for { select { - case <-ctx.Done(): + case <-quit: return case <-sig: path, running, err := p.toggle() @@ -46,6 +49,8 @@ func startCPUProfileSignal(ctx context.Context, dir string) (stop func(), err er 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 index 6565d4ab61..1c965f79d4 100644 --- a/seaweed-block/cmd/blockvolume/cpuprofile_unix_test.go +++ b/seaweed-block/cmd/blockvolume/cpuprofile_unix_test.go @@ -4,9 +4,11 @@ package main import ( "bytes" - "context" + "compress/gzip" + "io" "os" "path/filepath" + "runtime/pprof" "sort" "syscall" "testing" @@ -42,14 +44,44 @@ func burn(d time.Duration) { _ = 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 (a gzip pprof); a second pair writes a second file. -// Stopping the handler ends a running profile and keeps what it recorded. +// 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() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - stop, err := startCPUProfileSignal(ctx, dir) + stop, err := startCPUProfileSignal(dir) if err != nil { t.Fatal(err) } @@ -59,25 +91,15 @@ func TestCPUProfileSIGUSR1TogglesAProfile(t *testing.T) { stop() } }() - usr1 := func() { - if err := syscall.Kill(os.Getpid(), syscall.SIGUSR1); err != nil { - t.Fatal(err) - } - } - complete := func(path string) bool { - b, err := os.ReadFile(path) - return err == nil && len(b) > 2 && bytes.HasPrefix(b, []byte{0x1f, 0x8b}) - } for cycle := 1; cycle <= 2; cycle++ { - usr1() + usr1(t) waitUntil(t, "profile file created", func() bool { return len(profiles(t, dir)) == cycle }) burn(200 * time.Millisecond) - usr1() + usr1(t) path := profiles(t, dir)[cycle-1] waitUntil(t, "profile "+path+" written", func() bool { return complete(path) }) } - // A third profile left running is written out by stop. - usr1() + usr1(t) waitUntil(t, "third profile file created", func() bool { return len(profiles(t, dir)) == 3 }) burn(100 * time.Millisecond) stop() @@ -85,11 +107,36 @@ func TestCPUProfileSIGUSR1TogglesAProfile(t *testing.T) { 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(context.Background(), "") + stop, err := startCPUProfileSignal("") if err != nil || stop == nil { t.Fatalf("off: %v", err) } diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 396eb99c55..ad5126c180 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -255,6 +255,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 +577,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)) @@ -1198,12 +1214,6 @@ func run(f flags) int { shutdownCtx, stopSignals := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stopSignals() - stopProfile, err := startCPUProfileSignal(shutdownCtx, f.cpuProfileDir) - if err != nil { - fmt.Fprintf(os.Stderr, "blockvolume: %v\n", err) - return 1 - } - defer stopProfile() var leaseRequests <-chan workspaceStopRequest var leaseDone <-chan error if f.workspaceLease { From 26e34b6b9a66728839020b941ff7425c021ec349 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 23:57:18 -0800 Subject: [PATCH 03/12] test: expect the profile dir refused where SIGUSR1 is missing On platforms without SIGUSR1 a set --cpu-profile-dir is refused in flag parsing; the default (off) stays common to all platforms. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/cpuprofile_test.go | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/cpuprofile_test.go b/seaweed-block/cmd/blockvolume/cpuprofile_test.go index 9c375477d9..aac5a77d11 100644 --- a/seaweed-block/cmd/blockvolume/cpuprofile_test.go +++ b/seaweed-block/cmd/blockvolume/cpuprofile_test.go @@ -16,12 +16,21 @@ func TestCPUProfileDirFlagDefaultsFromEnv(t *testing.T) { } dir := t.TempDir() t.Setenv(cpuProfileEnv, dir) - if f, err := parseFlags(base); err != nil || f.cpuProfileDir != 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) } - other := t.TempDir() - if f, err := parseFlags(append(append([]string{}, base...), "--cpu-profile-dir", other)); err != nil || f.cpuProfileDir != other { - t.Fatalf("explicit flag: %q %v; want %q", f.cpuProfileDir, err, other) + if errx != nil || fx.cpuProfileDir != other { + t.Fatalf("explicit flag: %q %v; want %q", fx.cpuProfileDir, errx, other) } } From a5785ff68861fa5d10c72d6be2140f4f8d5d9e48 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 00:20:10 -0800 Subject: [PATCH 04/12] blockvolume: refuse to start unless the chunk filer is the only filer Block metadata needs exactly one filer behind --chunk-filer. At startup the chunk wiring asks that filer for its masters and filer group (filer_pb.SeaweedFiler/GetFilerConfiguration), then the masters for the filers of that group (master_pb.Seaweed/ListClusterNodes). It refuses unless a master lists exactly one, and when it cannot get that answer within 15 s. The filer subset gains GetFilerConfiguration and a master subset carries ListClusterNodes, generated with the committed plugin versions. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/chunk_remote.go | 8 +- .../cmd/blockvolume/single_filer_test.go | 81 ++++++ .../chunkstore/filerpb/filer_subset.pb.go | 185 ++++++++++--- .../chunkstore/filerpb/filer_subset.proto | 10 + .../filerpb/filer_subset_grpc.pb.go | 54 +++- .../chunkstore/masterpb/master_subset.pb.go | 253 ++++++++++++++++++ .../chunkstore/masterpb/master_subset.proto | 33 +++ .../masterpb/master_subset_grpc.pb.go | 133 +++++++++ .../core/frontend/chunkstore/single_filer.go | 114 ++++++++ .../frontend/chunkstore/single_filer_test.go | 169 ++++++++++++ seaweed-block/docs/standalone-deployment.md | 5 + 11 files changed, 993 insertions(+), 52 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/single_filer_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/masterpb/master_subset.pb.go create mode 100644 seaweed-block/core/frontend/chunkstore/masterpb/master_subset.proto create mode 100644 seaweed-block/core/frontend/chunkstore/masterpb/master_subset_grpc.pb.go create mode 100644 seaweed-block/core/frontend/chunkstore/single_filer.go create mode 100644 seaweed-block/core/frontend/chunkstore/single_filer_test.go diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index c8b7ce0c1c..4a312fa1bf 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -101,7 +101,8 @@ type chunkWiring struct { close func() error } -// newChunkWiring dials the filer (lazily). +// newChunkWiring dials the filer and refuses unless it is the only filer of +// its group (chunkstore.CheckSingleFiler). func newChunkWiring(c chunkFlags) (chunkWiring, error) { client, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{ FilerGRPC: c.filer, @@ -112,6 +113,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/single_filer_test.go b/seaweed-block/cmd/blockvolume/single_filer_test.go new file mode 100644 index 0000000000..df6540be0b --- /dev/null +++ b/seaweed-block/cmd/blockvolume/single_filer_test.go @@ -0,0 +1,81 @@ +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: a filer +// group with two filers is refused, one filer passes. +func TestChunkWiringRefusesAMultiFilerGroup(t *testing.T) { + for _, c := range []struct { + name string + filers []string + ok bool + }{ + {"one filer", []string{"10.0.0.1:8888"}, true}, + {"two filers", []string{"10.0.0.1:8888", "10.0.0.2:8888"}, false}, + } { + t.Run(c.name, func(t *testing.T) { + m := serve(t, func(s *grpc.Server) { masterpb.RegisterSeaweedServer(s, &groupMaster{filers: c.filers}) }) + _, mport, _ := net.SplitHostPort(m) + filer := serve(t, func(s *grpc.Server) { + filerpb.RegisterSeaweedFilerServer(s, &groupFiler{master: "127.0.0.1:9333." + mport}) + }) + 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..0c0bd532ae --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/single_filer.go @@ -0,0 +1,114 @@ +package chunkstore + +import ( + "context" + "errors" + "fmt" + "net" + "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. +var ErrNotSingleFiler = errors.New("chunkstore: block metadata needs exactly one filer") + +// singleFilerWait bounds the whole check (a var for tests). +var singleFilerWait = 15 * time.Second + +// CheckSingleFiler asks the filer for its masters and filer group +// (filer_pb.SeaweedFiler/GetFilerConfiguration), then asks the masters for +// the filers registered in that group (master_pb.Seaweed/ListClusterNodes, +// client_type "filer"). It passes only when a master answers with exactly +// one filer. More than one filer is refused; so is an answer it cannot get +// or confirm (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 _, m := range cfg.GetMasters() { + addr, err := masterGRPCAddress(m) + if err != nil { + tried = append(tried, fmt.Sprintf("%s: %v", m, err)) + continue + } + nodes, err := listFilers(ctx, addr, cfg.GetFilerGroup()) + if err != nil { + tried = append(tried, fmt.Sprintf("%s: %v", addr, err)) + continue + } + switch len(nodes) { + case 1: + return nil + case 0: + tried = append(tried, addr+": lists no filer in group "+strconv.Quote(cfg.GetFilerGroup())) + default: + return fmt.Errorf("%w: filer group %q has %d filers %v (master %s)", ErrNotSingleFiler, cfg.GetFilerGroup(), len(nodes), nodes, addr) + } + } + return fmt.Errorf("%w: could not confirm a single filer: %s", ErrNotSingleFiler, strings.Join(tried, "; ")) +} + +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 +} + +// masterGRPCAddress 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 masterGRPCAddress(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 master 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 master address %q", a) + } + if _, err := strconv.Atoi(grpcPort); err != nil { + return "", fmt.Errorf("bad master 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 master 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..d1648aa61c --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/single_filer_test.go @@ -0,0 +1,169 @@ +package chunkstore + +import ( + "context" + "errors" + "net" + "strings" + "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 + masters []string + group string + err error +} + +func (f *configFiler) GetFilerConfiguration(context.Context, *filerpb.GetFilerConfigurationRequest) (*filerpb.GetFilerConfigurationResponse, error) { + if f.err != nil { + return nil, f.err + } + return &filerpb.GetFilerConfigurationResponse{Masters: f.masters, FilerGroup: f.group}, nil +} + +type nodesMaster struct { + masterpb.UnimplementedSeaweedServer + filers []string + got *masterpb.ListClusterNodesRequest +} + +func (m *nodesMaster) ListClusterNodes(_ context.Context, r *masterpb.ListClusterNodesRequest) (*masterpb.ListClusterNodesResponse, error) { + m.got = r + resp := &masterpb.ListClusterNodesResponse{} + for _, a := range m.filers { + resp.ClusterNodes = append(resp.ClusterNodes, &masterpb.ListClusterNodesResponse_ClusterNode{Address: a}) + } + return resp, nil +} + +// 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 +} + +func startConfigFiler(t *testing.T, f *configFiler) *SWFS { + 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() }) + return c +} + +// Block metadata needs exactly one filer: a group with one filer passes; two +// filers, no filer, an unreachable master or a filer that cannot report its +// configuration are refused (fail closed), each within the bound. +func TestCheckSingleFiler(t *testing.T) { + old := singleFilerWait + singleFilerWait = 3 * time.Second + t.Cleanup(func() { singleFilerWait = old }) + ctx := context.Background() + + one := &nodesMaster{filers: []string{"10.0.0.1:8888"}} + c := startConfigFiler(t, &configFiler{masters: []string{startMaster(t, one)}, group: "g1"}) + if err := c.CheckSingleFiler(ctx); err != nil { + t.Fatalf("one filer refused: %v", err) + } + if one.got.GetClientType() != "filer" || one.got.GetFilerGroup() != "g1" { + t.Fatalf("master asked for %q in group %q; want filer in g1", one.got.GetClientType(), one.got.GetFilerGroup()) + } + + two := &nodesMaster{filers: []string{"10.0.0.1:8888", "10.0.0.2:8888"}} + c = startConfigFiler(t, &configFiler{masters: []string{startMaster(t, two)}}) + err := c.CheckSingleFiler(ctx) + if !errors.Is(err, ErrNotSingleFiler) || !strings.Contains(err.Error(), "10.0.0.2:8888") { + t.Fatalf("two filers: %v; want ErrNotSingleFiler naming both", err) + } + + none := &nodesMaster{} + c = startConfigFiler(t, &configFiler{masters: []string{startMaster(t, none)}}) + if err := c.CheckSingleFiler(ctx); !errors.Is(err, ErrNotSingleFiler) { + t.Fatalf("no filer listed: %v; want a refusal", err) + } + + start := time.Now() + c = startConfigFiler(t, &configFiler{masters: []string{deadAddress(t)}}) + if err := c.CheckSingleFiler(ctx); !errors.Is(err, ErrNotSingleFiler) || time.Since(start) > 5*time.Second { + t.Fatalf("unreachable master: %v after %s; want a bounded refusal", err, time.Since(start)) + } + + c = startConfigFiler(t, &configFiler{err: status.Error(codes.Unimplemented, "no")}) + if err := c.CheckSingleFiler(ctx); !errors.Is(err, ErrNotSingleFiler) { + t.Fatalf("filer without configuration: %v; want a refusal", err) + } + + c = startConfigFiler(t, &configFiler{}) + if err := c.CheckSingleFiler(ctx); !errors.Is(err, ErrNotSingleFiler) { + t.Fatalf("filer with no master: %v; want a refusal", err) + } + + // An unreachable first master does not hide the answer of the next one. + c = startConfigFiler(t, &configFiler{masters: []string{deadAddress(t), startMaster(t, &nodesMaster{filers: []string{"10.0.0.1:8888"}})}}) + if err := c.CheckSingleFiler(ctx); err != nil { + t.Fatalf("second master answers one filer: %v", err) + } +} + +func TestMasterGRPCAddress(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 := masterGRPCAddress(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/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 49539b774d..dbf8ba1422 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -132,6 +132,11 @@ 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 the masters for the filers +in the group, and refuses to start unless exactly one is listed. It also +refuses when it cannot get that answer within 15 s. + ## Notes - The control plane, the status endpoint and the NVMe/TCP target have no From 7578b34095213f5f9ad131929a82e62f842c608b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 00:28:23 -0800 Subject: [PATCH 05/12] chunkstore: wait for the filer to register before refusing A fresh filer registers with its master some seconds after it serves (14 s in the swap smoke), so "no filer listed" is asked again every second until a 60 s bound and refused only then. Several filers are still refused at once; an unreachable master is retried the same way. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/single_filer.go | 45 ++++++++++++++----- .../frontend/chunkstore/single_filer_test.go | 38 +++++++++++----- seaweed-block/docs/standalone-deployment.md | 6 ++- 3 files changed, 66 insertions(+), 23 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/single_filer.go b/seaweed-block/core/frontend/chunkstore/single_filer.go index 0c0bd532ae..b43a60cacf 100644 --- a/seaweed-block/core/frontend/chunkstore/single_filer.go +++ b/seaweed-block/core/frontend/chunkstore/single_filer.go @@ -23,15 +23,22 @@ import ( // concurrent writer on another. var ErrNotSingleFiler = errors.New("chunkstore: block metadata needs exactly one filer") -// singleFilerWait bounds the whole check (a var for tests). -var singleFilerWait = 15 * time.Second +// singleFilerWait bounds the whole check; singleFilerRetry spaces the +// rounds (vars for tests). A filer registers with the master only some +// seconds after it serves (14 s measured with a fresh filer), so "no filer +// listed yet" is retried until the bound. +var ( + singleFilerWait = 60 * time.Second + singleFilerRetry = time.Second +) // CheckSingleFiler asks the filer for its masters and filer group // (filer_pb.SeaweedFiler/GetFilerConfiguration), then asks the masters for // the filers registered in that group (master_pb.Seaweed/ListClusterNodes, // client_type "filer"). It passes only when a master answers with exactly -// one filer. More than one filer is refused; so is an answer it cannot get -// or confirm (fail closed). +// one filer. More than one filer is refused at once. No filer listed yet, or +// no master 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() @@ -44,27 +51,45 @@ func (c *SWFS) CheckSingleFiler(ctx context.Context) error { 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 a single filer within %s: %s", ErrNotSingleFiler, singleFilerWait, strings.Join(tried, "; ")) + case <-time.After(singleFilerRetry): + } + } +} + +// singleFilerRound asks each master once: ok when one lists exactly one +// filer, an error when one lists several, else (false, nil) to retry; tried +// keeps the last answer of each master. +func (c *SWFS) singleFilerRound(ctx context.Context, cfg *filerpb.GetFilerConfigurationResponse, tried *[]string) (bool, error) { + *tried = (*tried)[:0] for _, m := range cfg.GetMasters() { addr, err := masterGRPCAddress(m) if err != nil { - tried = append(tried, fmt.Sprintf("%s: %v", m, err)) + *tried = append(*tried, fmt.Sprintf("%s: %v", m, err)) continue } nodes, err := listFilers(ctx, addr, cfg.GetFilerGroup()) if err != nil { - tried = append(tried, fmt.Sprintf("%s: %v", addr, err)) + *tried = append(*tried, fmt.Sprintf("%s: %v", addr, err)) continue } switch len(nodes) { case 1: - return nil + return true, nil case 0: - tried = append(tried, addr+": lists no filer in group "+strconv.Quote(cfg.GetFilerGroup())) + *tried = append(*tried, addr+": lists no filer in group "+strconv.Quote(cfg.GetFilerGroup())+" yet") default: - return fmt.Errorf("%w: filer group %q has %d filers %v (master %s)", ErrNotSingleFiler, cfg.GetFilerGroup(), len(nodes), nodes, addr) + return false, fmt.Errorf("%w: filer group %q has %d filers %v (master %s)", ErrNotSingleFiler, cfg.GetFilerGroup(), len(nodes), nodes, addr) } } - return fmt.Errorf("%w: could not confirm a single filer: %s", ErrNotSingleFiler, strings.Join(tried, "; ")) + return false, nil } func listFilers(ctx context.Context, addr, group string) ([]string, error) { diff --git a/seaweed-block/core/frontend/chunkstore/single_filer_test.go b/seaweed-block/core/frontend/chunkstore/single_filer_test.go index d1648aa61c..21274a2ea1 100644 --- a/seaweed-block/core/frontend/chunkstore/single_filer_test.go +++ b/seaweed-block/core/frontend/chunkstore/single_filer_test.go @@ -33,12 +33,18 @@ func (f *configFiler) GetFilerConfiguration(context.Context, *filerpb.GetFilerCo type nodesMaster struct { masterpb.UnimplementedSeaweedServer filers []string + emptyN int // the first emptyN calls list no filer (not registered yet) + calls int got *masterpb.ListClusterNodesRequest } func (m *nodesMaster) ListClusterNodes(_ context.Context, r *masterpb.ListClusterNodesRequest) (*masterpb.ListClusterNodesResponse, error) { m.got = r + m.calls++ resp := &masterpb.ListClusterNodesResponse{} + if m.calls <= m.emptyN { + return resp, nil + } for _, a := range m.filers { resp.ClusterNodes = append(resp.ClusterNodes, &masterpb.ListClusterNodesResponse_ClusterNode{Address: a}) } @@ -91,13 +97,14 @@ func startConfigFiler(t *testing.T, f *configFiler) *SWFS { return c } -// Block metadata needs exactly one filer: a group with one filer passes; two -// filers, no filer, an unreachable master or a filer that cannot report its -// configuration are refused (fail closed), each within the bound. +// Block metadata needs exactly one filer: a group with one filer passes, also +// when the filer registers with the master only after a few rounds; two +// filers are refused at once; no filer, an unreachable master or a filer that +// cannot report its configuration are refused at the bound (fail closed). func TestCheckSingleFiler(t *testing.T) { - old := singleFilerWait - singleFilerWait = 3 * time.Second - t.Cleanup(func() { singleFilerWait = old }) + oldW, oldR := singleFilerWait, singleFilerRetry + singleFilerWait, singleFilerRetry = 1500*time.Millisecond, 100*time.Millisecond + t.Cleanup(func() { singleFilerWait, singleFilerRetry = oldW, oldR }) ctx := context.Background() one := &nodesMaster{filers: []string{"10.0.0.1:8888"}} @@ -109,20 +116,29 @@ func TestCheckSingleFiler(t *testing.T) { t.Fatalf("master asked for %q in group %q; want filer in g1", one.got.GetClientType(), one.got.GetFilerGroup()) } + // A fresh filer registers with the master only after it serves. + late := &nodesMaster{filers: []string{"10.0.0.1:8888"}, emptyN: 3} + c = startConfigFiler(t, &configFiler{masters: []string{startMaster(t, late)}}) + if err := c.CheckSingleFiler(ctx); err != nil || late.calls != 4 { + t.Fatalf("filer listed on the 4th round: %v after %d calls; want a pass", err, late.calls) + } + two := &nodesMaster{filers: []string{"10.0.0.1:8888", "10.0.0.2:8888"}} c = startConfigFiler(t, &configFiler{masters: []string{startMaster(t, two)}}) + start := time.Now() err := c.CheckSingleFiler(ctx) - if !errors.Is(err, ErrNotSingleFiler) || !strings.Contains(err.Error(), "10.0.0.2:8888") { - t.Fatalf("two filers: %v; want ErrNotSingleFiler naming both", err) + if !errors.Is(err, ErrNotSingleFiler) || !strings.Contains(err.Error(), "10.0.0.2:8888") || time.Since(start) > 500*time.Millisecond { + t.Fatalf("two filers: %v after %s; want ErrNotSingleFiler naming both, at once", err, time.Since(start)) } none := &nodesMaster{} c = startConfigFiler(t, &configFiler{masters: []string{startMaster(t, none)}}) - if err := c.CheckSingleFiler(ctx); !errors.Is(err, ErrNotSingleFiler) { - t.Fatalf("no filer listed: %v; want a refusal", err) + start = time.Now() + if err := c.CheckSingleFiler(ctx); !errors.Is(err, ErrNotSingleFiler) || time.Since(start) < singleFilerWait || none.calls < 3 { + t.Fatalf("no filer listed: %v after %s and %d calls; want retries, then a refusal at the bound", err, time.Since(start), none.calls) } - start := time.Now() + start = time.Now() c = startConfigFiler(t, &configFiler{masters: []string{deadAddress(t)}}) if err := c.CheckSingleFiler(ctx); !errors.Is(err, ErrNotSingleFiler) || time.Since(start) > 5*time.Second { t.Fatalf("unreachable master: %v after %s; want a bounded refusal", err, time.Since(start)) diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index dbf8ba1422..29d400c32f 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -134,8 +134,10 @@ The `--chunk-*` and `--workspace-lease` flags are refused unless `--chunk-filer` must name the only filer of its filer group. At startup blockvolume asks that filer for its masters, then the masters for the filers -in the group, and refuses to start unless exactly one is listed. It also -refuses when it cannot get that answer within 15 s. +in the group, and refuses to start unless exactly one is listed: several +filers are refused at once; a filer not listed yet (a fresh filer registers +with its master some seconds after it serves) is asked again until 60 s, then +refused. ## Notes From 94aface4392eb1c60dfc2a4c8ff5f0383384e6e5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 00:33:50 -0800 Subject: [PATCH 06/12] fix(volume): report local cut abort before cancelled upload --- seaweed-block/core/host/volume/chunk_control.go | 6 ++++-- seaweed-block/core/host/volume/chunk_control_test.go | 4 ++++ seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index e3024f6317..9f7bec134b 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -264,6 +264,10 @@ func chunkErrorCode(err error) (int, string, bool) { return http.StatusConflict, codeReconciling, true case errors.Is(err, storage.ErrChunkHeadPrecondition): return http.StatusConflict, codeHeadConflict, true + // 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, storage.ErrChunkLayerDetached): @@ -276,8 +280,6 @@ func chunkErrorCode(err error) (int, string, bool) { 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..c5ba31f693 100644 --- a/seaweed-block/core/host/volume/chunk_control_test.go +++ b/seaweed-block/core/host/volume/chunk_control_test.go @@ -219,6 +219,10 @@ 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}, {fmt.Errorf("x: %w", storage.ErrChunkLayerDetached), "closing", 409, false}, diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9068b36a7b..4451fea4cf 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -453,7 +453,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` | 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`, `TestStatusServer_ChunkErrorBodyIsTyped` (local cut abort wins over its cancelled upload; uncertain CAS and fencing 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-CUT-INTENT-FIRST-001` | Before the first upload of a cut or staging round, one intent names every preallocated candidate key (unused keys are harmless), independent of upload wave count. Known-aborted reusable roots are removed at clean Close; unresolved CAS roots remain protected. Intent removal follows a known CAS outcome. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestCutPayloadReadsOverlapEarlierUploadsWithinBudget`, `TestCutPayloadIntentCountIndependentOfCandidates`, `TestChunkCloseDropsReusableButKeepsUnknownCASRoots`, `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | | `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | | `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | ACTIVE | From 782505510a03d6910ec9a81274c3efbe60ab0bd5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 00:36:47 -0800 Subject: [PATCH 07/12] fix(storage): allow bounded saver admission for write bursts --- seaweed-block/core/storage/chunk_cut_cow.go | 44 ++++++++++++----- .../storage/chunk_cut_cow_spillcap_test.go | 47 +++++++++++++++++++ seaweed-block/core/storage/chunk_layer.go | 1 + seaweed-block/docs/design/invariants.md | 2 +- 4 files changed, 82 insertions(+), 12 deletions(-) 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_spillcap_test.go b/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go index a4466f6e17..8e46682507 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,50 @@ 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) + } + 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) + t.Cleanup(func() { free(); gate.unblock() }) + go func() { _, e := s.Write(5, makeBlock(ctBlockSize, 0xa5)); writers <- e }() + cowWaitSignal(t, entered, "first saver held") + go func() { _, 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 4451fea4cf..d33d5f1b25 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -453,7 +453,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`, `TestStatusServer_ChunkErrorBodyIsTyped` (local cut abort wins over its cancelled upload; uncertain CAS and fencing 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-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 and fencing 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-CUT-INTENT-FIRST-001` | Before the first upload of a cut or staging round, one intent names every preallocated candidate key (unused keys are harmless), independent of upload wave count. Known-aborted reusable roots are removed at clean Close; unresolved CAS roots remain protected. Intent removal follows a known CAS outcome. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestCutPayloadReadsOverlapEarlierUploadsWithinBudget`, `TestCutPayloadIntentCountIndependentOfCandidates`, `TestChunkCloseDropsReusableButKeepsUnknownCASRoots`, `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | | `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | | `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | ACTIVE | From 2f6cf84c04dd66980de023d588e6b10d442ea5b4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 00:39:11 -0800 Subject: [PATCH 08/12] test(storage): witness unread candidates after hot-first ordering --- seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go | 4 ++++ 1 file changed, 4 insertions(+) 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 8e46682507..1c226ec934 100644 --- a/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go +++ b/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go @@ -370,6 +370,10 @@ func TestCutCOWV3_SaverBurstWaitsAndPublishes(t *testing.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) }) } From cfd2a8332c834542f271562697ddc62279e11fd0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 00:49:09 -0800 Subject: [PATCH 09/12] fix(volume): retain terminal close precedence for aborted cuts --- seaweed-block/core/host/volume/chunk_control.go | 8 ++++---- .../core/host/volume/chunk_control_test.go | 2 ++ .../core/storage/chunk_cut_cow_lifetime_test.go | 3 +++ .../core/storage/chunk_cut_cow_spillcap_test.go | 16 +++++++++++++--- seaweed-block/docs/design/invariants.md | 2 +- 5 files changed, 23 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 9f7bec134b..43db86794e 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -264,16 +264,16 @@ 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.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, 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 case errors.Is(err, durable.ErrNotChunkVolume), errors.Is(err, durable.ErrVolumeNotOpen): return http.StatusConflict, chunkstore.CodeNotChunkVolume, false case errors.Is(err, context.DeadlineExceeded): diff --git a/seaweed-block/core/host/volume/chunk_control_test.go b/seaweed-block/core/host/volume/chunk_control_test.go index c5ba31f693..0d357c704a 100644 --- a/seaweed-block/core/host/volume/chunk_control_test.go +++ b/seaweed-block/core/host/volume/chunk_control_test.go @@ -225,6 +225,8 @@ func TestStatusServer_ChunkErrorBodyIsTyped(t *testing.T) { {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_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 1c226ec934..039e991478 100644 --- a/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go +++ b/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go @@ -382,10 +382,20 @@ func TestCutCOWV3_SaverBurstWaitsAndPublishes(t *testing.T) { done, errs := cowStartCut(t, l, gate) l.cowActive.Load().saverSlots = make(chan struct{}, 1) writers := make(chan error, 2) - t.Cleanup(func() { free(); gate.unblock() }) - go func() { _, e := s.Write(5, makeBlock(ctBlockSize, 0xa5)); writers <- e }() + firstDone, secondDone := make(chan struct{}), make(chan struct{}) + secondStarted := false + t.Cleanup(func() { + free() + gate.unblock() + cowWaitSignal(t, firstDone, "first burst writer cleanup") + if secondStarted { + cowWaitSignal(t, 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") - go func() { _, e := s.Write(9, makeBlock(ctBlockSize, 0xa9)); writers <- e }() + 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++ { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d33d5f1b25..3a51e5aacf 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -453,7 +453,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` | 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 and fencing 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-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-CUT-INTENT-FIRST-001` | Before the first upload of a cut or staging round, one intent names every preallocated candidate key (unused keys are harmless), independent of upload wave count. Known-aborted reusable roots are removed at clean Close; unresolved CAS roots remain protected. Intent removal follows a known CAS outcome. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestCutPayloadReadsOverlapEarlierUploadsWithinBudget`, `TestCutPayloadIntentCountIndependentOfCandidates`, `TestChunkCloseDropsReusableButKeepsUnknownCASRoots`, `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | | `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | | `INV-CUT-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | ACTIVE | From 961f08f66e1aa0f37af294405152cf2a2ea50143 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 00:53:13 -0800 Subject: [PATCH 10/12] chunkstore: the single filer must be the configured one, on every master A pass now needs a master listing exactly the configured filer (same gRPC port, same or co-resolving host). Every master is asked: any master listing another filer or several refuses at once, whichever answers first. Each master call is bounded within the remaining time, so a stalled master no longer consumes the whole bound. Startup census only; invariant INV-WS-SINGLE-FILER-001 and its M6 row record it. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/single_filer_test.go | 33 ++- .../core/frontend/chunkstore/single_filer.go | 102 ++++++--- .../frontend/chunkstore/single_filer_test.go | 202 +++++++++++++----- seaweed-block/docs/design/invariants.md | 2 + seaweed-block/docs/standalone-deployment.md | 12 +- 5 files changed, 250 insertions(+), 101 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/single_filer_test.go b/seaweed-block/cmd/blockvolume/single_filer_test.go index df6540be0b..c4cc3ccbd8 100644 --- a/seaweed-block/cmd/blockvolume/single_filer_test.go +++ b/seaweed-block/cmd/blockvolume/single_filer_test.go @@ -48,23 +48,34 @@ func serve(t *testing.T, register func(*grpc.Server)) string { return lis.Addr().String() } -// blockvolume's chunk wiring runs the single-filer check at startup: a filer -// group with two filers is refused, one filer passes. +// 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 - filers []string - ok bool + name string + other []string + ok bool }{ - {"one filer", []string{"10.0.0.1:8888"}, true}, - {"two filers", []string{"10.0.0.1:8888", "10.0.0.2:8888"}, false}, + {"one filer", nil, true}, + {"two filers", []string{"10.0.0.2:8888"}, false}, } { t.Run(c.name, func(t *testing.T) { - m := serve(t, func(s *grpc.Server) { masterpb.RegisterSeaweedServer(s, &groupMaster{filers: c.filers}) }) - _, mport, _ := net.SplitHostPort(m) - filer := serve(t, func(s *grpc.Server) { - filerpb.RegisterSeaweedFilerServer(s, &groupFiler{master: "127.0.0.1:9333." + mport}) + 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 { diff --git a/seaweed-block/core/frontend/chunkstore/single_filer.go b/seaweed-block/core/frontend/chunkstore/single_filer.go index b43a60cacf..f5b33e75f0 100644 --- a/seaweed-block/core/frontend/chunkstore/single_filer.go +++ b/seaweed-block/core/frontend/chunkstore/single_filer.go @@ -20,25 +20,29 @@ import ( // 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. +// 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 (vars for tests). A filer registers with the master only some -// seconds after it serves (14 s measured with a fresh filer), so "no filer -// listed yet" is retried until the bound. +// 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 + 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 the masters for +// (filer_pb.SeaweedFiler/GetFilerConfiguration), then asks every master for // the filers registered in that group (master_pb.Seaweed/ListClusterNodes, -// client_type "filer"). It passes only when a master answers with exactly -// one filer. More than one filer is refused at once. No filer listed yet, or -// no master answering, is retried until the bound and then refused (fail -// closed). +// 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() @@ -58,38 +62,76 @@ func (c *SWFS) CheckSingleFiler(ctx context.Context) error { } select { case <-ctx.Done(): - return fmt.Errorf("%w: could not confirm a single filer within %s: %s", ErrNotSingleFiler, singleFilerWait, strings.Join(tried, "; ")) + 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 each master once: ok when one lists exactly one -// filer, an error when one lists several, else (false, nil) to retry; tried -// keeps the last answer of each master. +// 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 := masterGRPCAddress(m) + addr, err := grpcAddress(m) if err != nil { *tried = append(*tried, fmt.Sprintf("%s: %v", m, err)) continue } - nodes, err := listFilers(ctx, addr, cfg.GetFilerGroup()) + 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 len(nodes) { - case 1: - return true, nil - case 0: - *tried = append(*tried, addr+": lists no filer in group "+strconv.Quote(cfg.GetFilerGroup())+" yet") + 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: - return false, fmt.Errorf("%w: filer group %q has %d filers %v (master %s)", ErrNotSingleFiler, cfg.GetFilerGroup(), len(nodes), nodes, addr) + *tried = append(*tried, addr+": lists no filer in group "+strconv.Quote(group)+" yet") } } - 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. +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 { + for _, b := range wa { + if net.ParseIP(a).Equal(net.ParseIP(b)) { + return true + } + } + } + return false } func listFilers(ctx context.Context, addr, group string) ([]string, error) { @@ -109,31 +151,31 @@ func listFilers(ctx context.Context, addr, group string) ([]string, error) { return out, nil } -// masterGRPCAddress turns a SeaweedFS server address into its gRPC address: +// 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 masterGRPCAddress(a string) (string, error) { +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 master address %q", a) + 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 master address %q", a) + return "", fmt.Errorf("bad server address %q", a) } if _, err := strconv.Atoi(grpcPort); err != nil { - return "", fmt.Errorf("bad master address %q", a) + 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 master address %q", a) + 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 index 21274a2ea1..35f5e04aa0 100644 --- a/seaweed-block/core/frontend/chunkstore/single_filer_test.go +++ b/seaweed-block/core/frontend/chunkstore/single_filer_test.go @@ -5,6 +5,7 @@ import ( "errors" "net" "strings" + "sync" "testing" "time" @@ -18,12 +19,15 @@ import ( 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 } @@ -32,25 +36,41 @@ func (f *configFiler) GetFilerConfiguration(context.Context, *filerpb.GetFilerCo type nodesMaster struct { masterpb.UnimplementedSeaweedServer + mu sync.Mutex filers []string - emptyN int // the first emptyN calls list no filer (not registered yet) + 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(_ context.Context, r *masterpb.ListClusterNodesRequest) (*masterpb.ListClusterNodesResponse, error) { +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 m.calls <= m.emptyN { + if calls <= m.emptyN { return resp, nil } - for _, a := range m.filers { + 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 { @@ -79,7 +99,9 @@ func deadAddress(t *testing.T) string { return "127.0.0.1:9333." + port } -func startConfigFiler(t *testing.T, f *configFiler) *SWFS { +// 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 { @@ -94,74 +116,144 @@ func startConfigFiler(t *testing.T, f *configFiler) *SWFS { t.Fatal(err) } t.Cleanup(func() { _ = c.Close() }) - return c + _, port, _ := net.SplitHostPort(lis.Addr().String()) + return c, "127.0.0.1:8888." + port } -// Block metadata needs exactly one filer: a group with one filer passes, also -// when the filer registers with the master only after a few rounds; two -// filers are refused at once; no filer, an unreachable master or a filer that -// cannot report its configuration are refused at the bound (fail closed). -func TestCheckSingleFiler(t *testing.T) { - oldW, oldR := singleFilerWait, singleFilerRetry - singleFilerWait, singleFilerRetry = 1500*time.Millisecond, 100*time.Millisecond - t.Cleanup(func() { singleFilerWait, singleFilerRetry = oldW, oldR }) - ctx := context.Background() - - one := &nodesMaster{filers: []string{"10.0.0.1:8888"}} - c := startConfigFiler(t, &configFiler{masters: []string{startMaster(t, one)}, group: "g1"}) - if err := c.CheckSingleFiler(ctx); err != nil { - t.Fatalf("one filer refused: %v", err) - } - if one.got.GetClientType() != "filer" || one.got.GetFilerGroup() != "g1" { - t.Fatalf("master asked for %q in group %q; want filer in g1", one.got.GetClientType(), one.got.GetFilerGroup()) +// 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 +} - // A fresh filer registers with the master only after it serves. - late := &nodesMaster{filers: []string{"10.0.0.1:8888"}, emptyN: 3} - c = startConfigFiler(t, &configFiler{masters: []string{startMaster(t, late)}}) - if err := c.CheckSingleFiler(ctx); err != nil || late.calls != 4 { - t.Fatalf("filer listed on the 4th round: %v after %d calls; want a pass", err, late.calls) +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} } +} - two := &nodesMaster{filers: []string{"10.0.0.1:8888", "10.0.0.2:8888"}} - c = startConfigFiler(t, &configFiler{masters: []string{startMaster(t, two)}}) +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(ctx) - if !errors.Is(err, ErrNotSingleFiler) || !strings.Contains(err.Error(), "10.0.0.2:8888") || time.Since(start) > 500*time.Millisecond { - t.Fatalf("two filers: %v after %s; want ErrNotSingleFiler naming both, at once", err, time.Since(start)) + 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) } +} - none := &nodesMaster{} - c = startConfigFiler(t, &configFiler{masters: []string{startMaster(t, none)}}) - start = time.Now() - if err := c.CheckSingleFiler(ctx); !errors.Is(err, ErrNotSingleFiler) || time.Since(start) < singleFilerWait || none.calls < 3 { - t.Fatalf("no filer listed: %v after %s and %d calls; want retries, then a refusal at the bound", err, time.Since(start), none.calls) +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) } +} - start = time.Now() - c = startConfigFiler(t, &configFiler{masters: []string{deadAddress(t)}}) - if err := c.CheckSingleFiler(ctx); !errors.Is(err, ErrNotSingleFiler) || time.Since(start) > 5*time.Second { - t.Fatalf("unreachable master: %v after %s; want a bounded refusal", err, time.Since(start)) +// 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) + } +} - c = startConfigFiler(t, &configFiler{err: status.Error(codes.Unimplemented, "no")}) - if err := c.CheckSingleFiler(ctx); !errors.Is(err, ErrNotSingleFiler) { +// 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") +} + +// 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(ctx); !errors.Is(err, ErrNotSingleFiler) { + 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) } - - // An unreachable first master does not hide the answer of the next one. - c = startConfigFiler(t, &configFiler{masters: []string{deadAddress(t), startMaster(t, &nodesMaster{filers: []string{"10.0.0.1:8888"}})}}) - if err := c.CheckSingleFiler(ctx); err != nil { - t.Fatalf("second master answers one filer: %v", err) - } } -func TestMasterGRPCAddress(t *testing.T) { +func TestGRPCAddress(t *testing.T) { for in, want := range map[string]string{ "m1:9333": "m1:19333", "m1:9333.19555": "m1:19555", @@ -171,7 +263,7 @@ func TestMasterGRPCAddress(t *testing.T) { "m1": "", "m1:60000": "", } { - got, err := masterGRPCAddress(in) + got, err := grpcAddress(in) if want == "" { if err == nil { t.Errorf("%q: got %q, want an error", in, got) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9068b36a7b..9b135530f8 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` | @@ -425,6 +426,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. | M6 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `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 | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 29d400c32f..c2c8f5abb4 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -133,11 +133,13 @@ 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 the masters for the filers -in the group, and refuses to start unless exactly one is listed: several -filers are refused at once; a filer not listed yet (a fresh filer registers -with its master some seconds after it serves) is asked again until 60 s, then -refused. +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 From 3d850aa2369c1bbf8f5b4b4d88a399972432a70e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 01:10:15 -0800 Subject: [PATCH 11/12] chunkstore: compare filer addresses with their zone; recheck the deadline isTarget compares resolved addresses with netip (IPv6 zone included); an address that does not parse never matches. A round whose bound ran out while a later master was still being asked does not pass on an earlier favourable answer. The ledger row maps to the M4 table. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/single_filer.go | 16 +++++++-- .../frontend/chunkstore/single_filer_test.go | 36 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 51 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/single_filer.go b/seaweed-block/core/frontend/chunkstore/single_filer.go index f5b33e75f0..7d21789c8e 100644 --- a/seaweed-block/core/frontend/chunkstore/single_filer.go +++ b/seaweed-block/core/frontend/chunkstore/single_filer.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "net" + "net/netip" "strconv" "strings" "time" @@ -100,12 +101,19 @@ func (c *SWFS) singleFilerRound(ctx context.Context, cfg *filerpb.GetFilerConfig *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. +// 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 { @@ -125,8 +133,12 @@ func (c *SWFS) isTarget(ctx context.Context, listed string) bool { return false } for _, a := range ga { + pa, err := netip.ParseAddr(a) + if err != nil { + continue + } for _, b := range wa { - if net.ParseIP(a).Equal(net.ParseIP(b)) { + if pb, err := netip.ParseAddr(b); err == nil && pa.Unmap() == pb.Unmap() { return true } } diff --git a/seaweed-block/core/frontend/chunkstore/single_filer_test.go b/seaweed-block/core/frontend/chunkstore/single_filer_test.go index 35f5e04aa0..e793c75cd3 100644 --- a/seaweed-block/core/frontend/chunkstore/single_filer_test.go +++ b/seaweed-block/core/frontend/chunkstore/single_filer_test.go @@ -228,6 +228,42 @@ func TestCheckSingleFilerRefusesAnotherOrSeveralFilers(t *testing.T) { 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) { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9b135530f8..331d11ee26 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -426,7 +426,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. | M6 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_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 | From dd759ed0748a5f9910b9c86d13eed83d5cb83872 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 01:12:03 -0800 Subject: [PATCH 12/12] test(storage): join both burst writers after cleanup timeout --- .../core/storage/chunk_cut_cow_spillcap_test.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) 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 039e991478..3adf5057c0 100644 --- a/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go +++ b/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go @@ -387,9 +387,17 @@ func TestCutCOWV3_SaverBurstWaitsAndPublishes(t *testing.T) { t.Cleanup(func() { free() gate.unblock() - cowWaitSignal(t, firstDone, "first burst writer cleanup") + // 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 { - cowWaitSignal(t, secondDone, "second burst writer cleanup") + wait(secondDone, "second burst writer cleanup") } }) go func() { defer close(firstDone); _, e := s.Write(5, makeBlock(ctBlockSize, 0xa5)); writers <- e }()