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 {