From ffa660897267289fddaaefeb33b234b32d853276 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 30 Nov 2026 13:08:56 -0800 Subject: [PATCH] Serve lab heap profiles on the existing status listener --- .../.github/scripts/lab-tag-check.sh | 11 ++-- .../cmd/blockvolume/heapprofile_lab.go | 31 --------- .../cmd/blockvolume/heapprofile_lab_other.go | 12 ---- .../cmd/blockvolume/heapprofile_lab_test.go | 59 ----------------- .../cmd/blockvolume/heapprofile_lab_unix.go | 44 ------------- .../blockvolume/heapprofile_lab_unix_test.go | 54 ---------------- .../cmd/blockvolume/heapprofile_release.go | 9 --- .../blockvolume/heapprofile_release_test.go | 15 ----- seaweed-block/cmd/blockvolume/main.go | 8 --- .../core/host/volume/status_heap_lab.go | 21 +++++++ .../core/host/volume/status_heap_lab_test.go | 63 +++++++++++++++++++ .../core/host/volume/status_heap_release.go | 7 +++ .../host/volume/status_heap_release_test.go | 34 ++++++++++ .../core/host/volume/status_server.go | 1 + seaweed-block/docs/lab-heap-profiles.md | 26 ++++---- 15 files changed, 145 insertions(+), 250 deletions(-) delete mode 100644 seaweed-block/cmd/blockvolume/heapprofile_lab.go delete mode 100644 seaweed-block/cmd/blockvolume/heapprofile_lab_other.go delete mode 100644 seaweed-block/cmd/blockvolume/heapprofile_lab_test.go delete mode 100644 seaweed-block/cmd/blockvolume/heapprofile_lab_unix.go delete mode 100644 seaweed-block/cmd/blockvolume/heapprofile_lab_unix_test.go delete mode 100644 seaweed-block/cmd/blockvolume/heapprofile_release.go delete mode 100644 seaweed-block/cmd/blockvolume/heapprofile_release_test.go create mode 100644 seaweed-block/core/host/volume/status_heap_lab.go create mode 100644 seaweed-block/core/host/volume/status_heap_lab_test.go create mode 100644 seaweed-block/core/host/volume/status_heap_release.go create mode 100644 seaweed-block/core/host/volume/status_heap_release_test.go diff --git a/seaweed-block/.github/scripts/lab-tag-check.sh b/seaweed-block/.github/scripts/lab-tag-check.sh index 87dfea5f09..c2b2215195 100644 --- a/seaweed-block/.github/scripts/lab-tag-check.sh +++ b/seaweed-block/.github/scripts/lab-tag-check.sh @@ -16,13 +16,10 @@ tag=swblock_lab_bigvol allowed='.github/scripts/lab-tag-check-test.sh .github/scripts/lab-tag-check.sh .github/workflows/test.yml -cmd/blockvolume/heapprofile_lab.go -cmd/blockvolume/heapprofile_lab_other.go -cmd/blockvolume/heapprofile_lab_test.go -cmd/blockvolume/heapprofile_lab_unix.go -cmd/blockvolume/heapprofile_lab_unix_test.go -cmd/blockvolume/heapprofile_release.go -cmd/blockvolume/heapprofile_release_test.go +core/host/volume/status_heap_lab.go +core/host/volume/status_heap_lab_test.go +core/host/volume/status_heap_release.go +core/host/volume/status_heap_release_test.go core/frontend/durable/headroom.go core/frontend/durable/headroom_lab_test.go core/geometry/volume_size.go diff --git a/seaweed-block/cmd/blockvolume/heapprofile_lab.go b/seaweed-block/cmd/blockvolume/heapprofile_lab.go deleted file mode 100644 index 70deb7a035..0000000000 --- a/seaweed-block/cmd/blockvolume/heapprofile_lab.go +++ /dev/null @@ -1,31 +0,0 @@ -//go:build swblock_lab_bigvol - -package main - -import ( - "flag" - "fmt" - "os" - "path/filepath" - "runtime" - "runtime/pprof" -) - -func registerHeapProfileFlag(fs *flag.FlagSet, f *flags) { - fs.StringVar(&f.heapProfileDir, "heap-profile-dir", "", "lab only: existing directory for SIGUSR2 heap snapshots after GC; empty disables; profiling pauses and perturbs the workload") -} - -func writeHeapProfile(dir string) (string, error) { - f, err := os.CreateTemp(dir, fmt.Sprintf("blockvolume-%d-heap-*.pprof", os.Getpid())) - if err != nil { - return "", err - } - path := filepath.Clean(f.Name()) - runtime.GC() - writeErr := pprof.WriteHeapProfile(f) - closeErr := f.Close() - if writeErr != nil { - return path, writeErr - } - return path, closeErr -} diff --git a/seaweed-block/cmd/blockvolume/heapprofile_lab_other.go b/seaweed-block/cmd/blockvolume/heapprofile_lab_other.go deleted file mode 100644 index 6ad4dc4aac..0000000000 --- a/seaweed-block/cmd/blockvolume/heapprofile_lab_other.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build swblock_lab_bigvol && !unix - -package main - -import "fmt" - -func startHeapProfileSignal(dir string) (func(), error) { - if dir != "" { - return nil, fmt.Errorf("--heap-profile-dir requires SIGUSR2 on Unix") - } - return func() {}, nil -} diff --git a/seaweed-block/cmd/blockvolume/heapprofile_lab_test.go b/seaweed-block/cmd/blockvolume/heapprofile_lab_test.go deleted file mode 100644 index 939e02c42e..0000000000 --- a/seaweed-block/cmd/blockvolume/heapprofile_lab_test.go +++ /dev/null @@ -1,59 +0,0 @@ -//go:build swblock_lab_bigvol - -package main - -import ( - "compress/gzip" - "flag" - "io" - "os" - "path/filepath" - "testing" -) - -func TestHeapProfileLabFlag(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"} - dir := t.TempDir() - f, err := parseFlags(append(base, "--heap-profile-dir", dir)) - if err != nil || f.heapProfileDir != dir { - t.Fatalf("flag: %q, %v", f.heapProfileDir, err) - } - fs := flag.NewFlagSet("test", flag.ContinueOnError) - registerHeapProfileFlag(fs, &f) - if err := fs.Parse(nil); err != nil || f.heapProfileDir != "" { - t.Fatalf("default must be off: %q, %v", f.heapProfileDir, err) - } -} - -func TestHeapProfileWritesDistinctCompleteSnapshots(t *testing.T) { - dir := t.TempDir() - var previous string - for i := 0; i < 2; i++ { - path, err := writeHeapProfile(dir) - if err != nil { - t.Fatal(err) - } - if path == previous { - t.Fatal("snapshot overwritten") - } - previous = path - f, err := os.Open(path) - if err != nil { - t.Fatal(err) - } - zr, err := gzip.NewReader(f) - if err != nil { - f.Close() - t.Fatal(err) - } - data, err := io.ReadAll(zr) - zr.Close() - f.Close() - if err != nil || len(data) == 0 { - t.Fatalf("incomplete profile: %v", err) - } - } - if _, err := writeHeapProfile(filepath.Join(dir, "missing")); err == nil { - t.Fatal("missing directory accepted") - } -} diff --git a/seaweed-block/cmd/blockvolume/heapprofile_lab_unix.go b/seaweed-block/cmd/blockvolume/heapprofile_lab_unix.go deleted file mode 100644 index d766cec12f..0000000000 --- a/seaweed-block/cmd/blockvolume/heapprofile_lab_unix.go +++ /dev/null @@ -1,44 +0,0 @@ -//go:build swblock_lab_bigvol && unix - -package main - -import ( - "fmt" - "log" - "os" - "os/signal" - "syscall" -) - -func startHeapProfileSignal(dir string) (func(), error) { - if dir == "" { - return func() {}, nil - } - fi, err := os.Stat(dir) - if err != nil { - return nil, fmt.Errorf("--heap-profile-dir: %w", err) - } - if !fi.IsDir() { - return nil, fmt.Errorf("--heap-profile-dir: not a directory") - } - sig := make(chan os.Signal, 1) - signal.Notify(sig, syscall.SIGUSR2) - quit, done := make(chan struct{}), make(chan struct{}) - go func() { - defer close(done) - for { - select { - case <-quit: - return - case <-sig: - path, err := writeHeapProfile(dir) - if err != nil { - log.Printf("blockvolume: heap profile %s: %v", path, err) - } else { - log.Printf("blockvolume: heap profile written: %s", path) - } - } - } - }() - return func() { signal.Stop(sig); close(quit); <-done }, nil -} diff --git a/seaweed-block/cmd/blockvolume/heapprofile_lab_unix_test.go b/seaweed-block/cmd/blockvolume/heapprofile_lab_unix_test.go deleted file mode 100644 index 1f342b4cac..0000000000 --- a/seaweed-block/cmd/blockvolume/heapprofile_lab_unix_test.go +++ /dev/null @@ -1,54 +0,0 @@ -//go:build swblock_lab_bigvol && unix - -package main - -import ( - "os" - "path/filepath" - "syscall" - "testing" -) - -func TestHeapProfileSIGUSR2AndStop(t *testing.T) { - dir := t.TempDir() - stop, err := startHeapProfileSignal(dir) - if err != nil { - t.Fatal(err) - } - defer stop() - for i := 1; i <= 2; i++ { - if err := syscall.Kill(os.Getpid(), syscall.SIGUSR2); err != nil { - t.Fatal(err) - } - waitUntil(t, "complete heap snapshot", func() bool { - paths, _ := filepath.Glob(filepath.Join(dir, "*-heap-*.pprof")) - if len(paths) != i { - return false - } - for _, p := range paths { - if !complete(p) { - return false - } - } - return true - }) - } -} - -func TestHeapProfileDirectoryAndOff(t *testing.T) { - stop, err := startHeapProfileSignal("") - if err != nil { - t.Fatal(err) - } - stop() - if _, err := startHeapProfileSignal(filepath.Join(t.TempDir(), "missing")); err == nil { - t.Fatal("missing directory accepted") - } - path := filepath.Join(t.TempDir(), "file") - if err := os.WriteFile(path, nil, 0600); err != nil { - t.Fatal(err) - } - if _, err := startHeapProfileSignal(path); err == nil { - t.Fatal("file accepted as directory") - } -} diff --git a/seaweed-block/cmd/blockvolume/heapprofile_release.go b/seaweed-block/cmd/blockvolume/heapprofile_release.go deleted file mode 100644 index 461897b6b1..0000000000 --- a/seaweed-block/cmd/blockvolume/heapprofile_release.go +++ /dev/null @@ -1,9 +0,0 @@ -//go:build !swblock_lab_bigvol - -package main - -import "flag" - -func registerHeapProfileFlag(_ *flag.FlagSet, _ *flags) {} - -func startHeapProfileSignal(_ string) (func(), error) { return func() {}, nil } diff --git a/seaweed-block/cmd/blockvolume/heapprofile_release_test.go b/seaweed-block/cmd/blockvolume/heapprofile_release_test.go deleted file mode 100644 index d68a570e1e..0000000000 --- a/seaweed-block/cmd/blockvolume/heapprofile_release_test.go +++ /dev/null @@ -1,15 +0,0 @@ -//go:build !swblock_lab_bigvol - -package main - -import ( - "strings" - "testing" -) - -func TestHeapProfileFlagAbsentFromRelease(t *testing.T) { - _, err := parseFlags([]string{"--heap-profile-dir", t.TempDir()}) - if err == nil || !strings.Contains(err.Error(), "flag provided but not defined") { - t.Fatalf("release accepted lab flag: %v", err) - } -} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index ba43c263ac..504b30ac57 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -46,7 +46,6 @@ import ( type flags struct { logLevel string cpuProfileDir string - heapProfileDir string memoryLimitMiB int64 masterAddr string serverID string @@ -204,7 +203,6 @@ func parseFlags(args []string) (flags, error) { 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)") - registerHeapProfileFlag(fs, &f) 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") @@ -652,12 +650,6 @@ func runVolume(f flags, exits *processExit) int { return 1 } defer stopProfile() - stopHeap, err := startHeapProfileSignal(f.heapProfileDir) - if err != nil { - fmt.Fprintln(os.Stderr, "blockvolume:", err) - return 1 - } - defer stopHeap() readyCh := make(chan adapter.AssignmentInfo, 16) dialTLS, err := masterDialTLS(f) diff --git a/seaweed-block/core/host/volume/status_heap_lab.go b/seaweed-block/core/host/volume/status_heap_lab.go new file mode 100644 index 0000000000..6fc6e22f7b --- /dev/null +++ b/seaweed-block/core/host/volume/status_heap_lab.go @@ -0,0 +1,21 @@ +//go:build swblock_lab_bigvol + +package volume + +import ( + "net/http" + "net/http/pprof" +) + +// registerLabHeapProfile uses the existing listener, but never exposes heap +// contents to a non-loopback client, even when status has an external bind. +func registerLabHeapProfile(mux *http.ServeMux) { + handler := pprof.Handler("heap") + mux.HandleFunc("GET /debug/pprof/heap", func(w http.ResponseWriter, r *http.Request) { + if !isLoopbackRemote(r.RemoteAddr) { + http.Error(w, "heap profile restricted to loopback", http.StatusForbidden) + return + } + handler.ServeHTTP(w, r) + }) +} diff --git a/seaweed-block/core/host/volume/status_heap_lab_test.go b/seaweed-block/core/host/volume/status_heap_lab_test.go new file mode 100644 index 0000000000..d48c3f7ac5 --- /dev/null +++ b/seaweed-block/core/host/volume/status_heap_lab_test.go @@ -0,0 +1,63 @@ +//go:build swblock_lab_bigvol + +package volume + +import ( + "compress/gzip" + "context" + "io" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func TestLabHeapProfileGET(t *testing.T) { + s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil)) + addr, err := s.Start("127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + _ = s.Close(ctx) + }) + client := &http.Client{Timeout: 10 * time.Second} + resp, err := client.Get("http://" + addr + "/debug/pprof/heap?gc=1") + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != 200 { + t.Fatalf("heap GET status %d", resp.StatusCode) + } + zr, err := gzip.NewReader(resp.Body) + if err != nil { + t.Fatal(err) + } + defer zr.Close() + data, err := io.ReadAll(zr) + if err != nil || len(data) == 0 { + t.Fatalf("profile: bytes=%d err=%v", len(data), err) + } +} + +func TestLabHeapProfileRejectsRemoteAndPOST(t *testing.T) { + mux := http.NewServeMux() + registerLabHeapProfile(mux) + remote := httptest.NewRequest(http.MethodGet, "/debug/pprof/heap?gc=1", nil) + remote.RemoteAddr = "192.0.2.1:1234" + denied := httptest.NewRecorder() + mux.ServeHTTP(denied, remote) + if denied.Code != http.StatusForbidden { + t.Fatalf("remote heap status %d", denied.Code) + } + post := httptest.NewRequest(http.MethodPost, "/debug/pprof/heap", nil) + post.RemoteAddr = "127.0.0.1:1234" + rr := httptest.NewRecorder() + mux.ServeHTTP(rr, post) + if rr.Code != http.StatusMethodNotAllowed { + t.Fatalf("POST heap status %d", rr.Code) + } +} diff --git a/seaweed-block/core/host/volume/status_heap_release.go b/seaweed-block/core/host/volume/status_heap_release.go new file mode 100644 index 0000000000..b15d2036ec --- /dev/null +++ b/seaweed-block/core/host/volume/status_heap_release.go @@ -0,0 +1,7 @@ +//go:build !swblock_lab_bigvol + +package volume + +import "net/http" + +func registerLabHeapProfile(_ *http.ServeMux) {} diff --git a/seaweed-block/core/host/volume/status_heap_release_test.go b/seaweed-block/core/host/volume/status_heap_release_test.go new file mode 100644 index 0000000000..587b78819f --- /dev/null +++ b/seaweed-block/core/host/volume/status_heap_release_test.go @@ -0,0 +1,34 @@ +//go:build !swblock_lab_bigvol + +package volume + +import ( + "context" + "net/http" + "testing" + "time" +) + +func TestHeapProfileRouteAbsentFromRelease(t *testing.T) { + s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil)) + addr, err := s.Start("127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + _ = s.Close(ctx) + }) + client := &http.Client{Timeout: 5 * time.Second} + for _, path := range []string{"/debug/pprof/heap", "/debug/pprof/", "/debug/pprof/profile"} { + resp, err := client.Get("http://" + addr + path) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusNotFound { + t.Fatalf("release route %s returned %d, want 404", path, resp.StatusCode) + } + } +} diff --git a/seaweed-block/core/host/volume/status_server.go b/seaweed-block/core/host/volume/status_server.go index 7e82cf51a3..4dd71e8ff0 100644 --- a/seaweed-block/core/host/volume/status_server.go +++ b/seaweed-block/core/host/volume/status_server.go @@ -390,6 +390,7 @@ func (s *StatusServer) Start(addr string) (string, error) { s.addr = ln.Addr().String() mux := http.NewServeMux() + registerLabHeapProfile(mux) mux.HandleFunc("/status", s.handleStatus) mux.HandleFunc("/status/peers", s.handleStatusPeers) mux.HandleFunc("/status/durable", s.handleStatusDurable) diff --git a/seaweed-block/docs/lab-heap-profiles.md b/seaweed-block/docs/lab-heap-profiles.md index 61501c3396..d418f14bb8 100644 --- a/seaweed-block/docs/lab-heap-profiles.md +++ b/seaweed-block/docs/lab-heap-profiles.md @@ -1,14 +1,18 @@ # Lab heap profiles -Only a blockvolume built with `-tags swblock_lab_bigvol` exposes -`--heap-profile-dir `. Release builds reject the flag. -The default is disabled; it does not install a signal handler or write files. +Only a holder built with `-tags swblock_lab_bigvol` serves +`GET /debug/pprof/heap` on its existing `--status-addr` listener. +Release builds return 404. There is no additional flag, signal handler or +listener. The route always refuses non-loopback clients, including when the +status listener was explicitly allowed to bind externally. -On Unix, send `kill -USR2 ` to collect one heap snapshot. -Each signal handled runs a full GC, then writes a distinct -`blockvolume--heap-*.pprof` file with owner-only permissions. The daemon -logs the completed path or the write error. Inspect it with -`go tool pprof -top `. SIGUSR1 retains its separate CPU-profile -behavior. Heap collection pauses and perturbs the workload; record the sample -time in performance evidence. The handler joins on shutdown. Non-Unix lab -builds refuse a nonempty heap-profile directory at startup. +For current live allocations, fetch `/debug/pprof/heap?gc=1`: the standard +Go heap handler runs a full GC first and returns a binary pprof profile. +For example, save the response using `curl --fail --max-time 30 http://127.0.0.1:9181/debug/pprof/heap?gc=1 -o heap.pprof`, substituting the +holder's actual status address. Inspect it with +`go tool pprof -sample_index=inuse_space -top -cum heap.pprof`. + +GC and collection pause and perturb the workload; record the sample time in +performance evidence. This small diagnostic smoke does not measure large-volume +memory use. The standard handler's `debug` and `gc` query options retain their +normal meaning. CPU profiling via SIGUSR1 remains independent.