Merge branch 'main' of https://github.com/seaweedfs/seaweed-block into feat/retire-v2-local-format

This commit is contained in:
pingqiu committed 2026-11-20 00:35:32 -08:00
commit c02464ad44
6 files changed
+366

No files matched your search

@@ -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
// <dir>/blockvolume-<pid>-<n>.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
}
@@ -0,0 +1,15 @@
//go:build !unix
package main
import "errors"
// cpuProfileSupported: no SIGUSR1 on this platform.
const cpuProfileSupported = false
func startCPUProfileSignal(dir string) (stop func(), err error) {
if dir == "" {
return func() {}, nil
}
return nil, errors.New("--cpu-profile-dir needs SIGUSR1 (unix only)")
}
@@ -0,0 +1,58 @@
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)
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)
}
if errx != nil || fx.cpuProfileDir != other {
t.Fatalf("explicit flag: %q %v; want %q", fx.cpuProfileDir, errx, 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)
}
// 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")
}
}
@@ -0,0 +1,56 @@
//go:build unix
package main
import (
"log"
"os"
"os/signal"
"syscall"
)
// 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
}
if err := checkCPUProfileDir(dir); err != nil {
return nil, err
}
p := &cpuProfiler{dir: dir}
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGUSR1)
quit, done := make(chan struct{}), make(chan struct{})
go func() {
defer close(done)
for {
select {
case <-quit:
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)
close(quit)
<-done
p.stop()
}, nil
}
@@ -0,0 +1,144 @@
//go:build unix
package main
import (
"bytes"
"compress/gzip"
"io"
"os"
"path/filepath"
"runtime/pprof"
"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
}
// 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 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()
stop, err := startCPUProfileSignal(dir)
if err != nil {
t.Fatal(err)
}
stopped := false
defer func() {
if !stopped {
stop()
}
}()
for cycle := 1; cycle <= 2; cycle++ {
usr1(t)
waitUntil(t, "profile file created", func() bool { return len(profiles(t, dir)) == cycle })
burn(200 * time.Millisecond)
usr1(t)
path := profiles(t, dir)[cycle-1]
waitUntil(t, "profile "+path+" written", func() bool { return complete(path) })
}
usr1(t)
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)
}
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("")
if err != nil || stop == nil {
t.Fatalf("off: %v", err)
}
stop()
}
+18
View File
@@ -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=<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")
@@ -253,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
}
@@ -567,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))