From fb939adb8af4e16e794b4e3e48c69fef87dc95be Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 23:47:25 -0800 Subject: [PATCH] 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 {