Add lab-only on-demand heap profiles for blockvolume

This commit is contained in:
pingqiu committed 2026-11-30 12:41:25 -08:00
1 parent 51984cefac
commit aacf77535b
9 files changed
+246

No files matched your search

@@ -0,0 +1,31 @@
//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
}
@@ -0,0 +1,12 @@
//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
}
@@ -0,0 +1,59 @@
//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")
}
}
@@ -0,0 +1,44 @@
//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
}
@@ -0,0 +1,54 @@
//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")
}
}
@@ -0,0 +1,9 @@
//go:build !swblock_lab_bigvol
package main
import "flag"
func registerHeapProfileFlag(_ *flag.FlagSet, _ *flags) {}
func startHeapProfileSignal(_ string) (func(), error) { return func() {}, nil }
@@ -0,0 +1,15 @@
//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)
}
}
+8
View File
@@ -46,6 +46,7 @@ import (
type flags struct {
logLevel string
cpuProfileDir string
heapProfileDir string
memoryLimitMiB int64
masterAddr string
serverID string
@@ -203,6 +204,7 @@ 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=<id> 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")
@@ -650,6 +652,12 @@ 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)
+14
View File
@@ -0,0 +1,14 @@
# Lab heap profiles
Only a blockvolume built with `-tags swblock_lab_bigvol` exposes
`--heap-profile-dir <existing-directory>`. Release builds reject the flag.
The default is disabled; it does not install a signal handler or write files.
On Unix, send `kill -USR2 <blockvolume-pid>` to collect one heap snapshot.
Each signal handled runs a full GC, then writes a distinct
`blockvolume-<pid>-heap-*.pprof` file with owner-only permissions. The daemon
logs the completed path or the write error. Inspect it with
`go tool pprof -top <profile-path>`. 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.