diff --git a/seaweed-block/cmd/blockvolume/mini_process_linux_test.go b/seaweed-block/cmd/blockvolume/mini_process_linux_test.go index ec5e4cdc3b..6192b1d0e2 100644 --- a/seaweed-block/cmd/blockvolume/mini_process_linux_test.go +++ b/seaweed-block/cmd/blockvolume/mini_process_linux_test.go @@ -6,15 +6,19 @@ import ( "bytes" "context" "errors" + "fmt" "os" "os/exec" "path/filepath" "strconv" "strings" "sync" + "sync/atomic" "syscall" "testing" "time" + + "golang.org/x/sys/unix" ) // Preconditions are assertions: a privileged run is not non-root evidence. @@ -58,108 +62,275 @@ func (b *miniOutput) Write(p []byte) (int, error) { } func (b *miniOutput) String() string { b.mu.Lock(); defer b.mu.Unlock(); return b.b.String() } -type ownedMini struct { - cmd *exec.Cmd - done chan struct{} - err error - output miniOutput - stopOnce sync.Once +const miniFailStopExit = 86 + +func miniFailStop(t *testing.T, why string) { + fmt.Fprintf(os.Stderr, "%s: %s; stopping tests before directory cleanup\n", t.Name(), why) + os.Exit(miniFailStopExit) } -// All descendants inherit this dedicated group. Cleanup is registered before -// any assertion can fail; TERM, bounded join, KILL, bounded join. No name kill. +type ownedMini struct { + cmd *exec.Cmd + done chan struct{} + err error + output miniOutput + stopOnce sync.Once + mu sync.Mutex + settled bool + leaderFD int + leaderKey string + dispatches atomic.Int64 + // Only the isolated fail-stop controls replace the census or its window. + census func() []int + censusWait time.Duration +} + +// Open the leader pidfd before starting Wait: even an already-exited child is +// still unreaped here, so its numeric PID cannot have been reused. func startOwnedMini(t *testing.T, ctx context.Context, bin string, args ...string) *ownedMini { t.Helper() - p := &ownedMini{cmd: exec.CommandContext(ctx, bin, args...), done: make(chan struct{})} + p := &ownedMini{cmd: exec.CommandContext(ctx, bin, args...), done: make(chan struct{}), leaderFD: -1} p.cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} p.cmd.Stdout, p.cmd.Stderr = &p.output, &p.output p.cmd.WaitDelay = 3 * time.Second - p.cmd.Cancel = func() error { return syscall.Kill(-p.cmd.Process.Pid, syscall.SIGTERM) } + p.cmd.Cancel = func() error { return p.signalLeader(unix.SIGTERM) } + p.mu.Lock() // a context cancellation cannot observe the unopened pidfd if err := p.cmd.Start(); err != nil { + p.mu.Unlock() t.Fatal(err) } + fd, err := unix.PidfdOpen(p.cmd.Process.Pid, 0) + if err != nil { + miniFailStop(t, fmt.Sprintf("cannot own leader incarnation: %v", err)) + } + p.leaderFD = fd + info, err := miniProc(p.cmd.Process.Pid) + if err != nil { + miniFailStop(t, fmt.Sprintf("cannot record leader incarnation: %v", err)) + } + p.leaderKey = info.key + p.mu.Unlock() go func() { p.err = p.cmd.Wait(); close(p.done) }() t.Cleanup(func() { p.stop(t) }) return p } +func (p *ownedMini) signalFD(fd int, sig unix.Signal) error { + p.dispatches.Add(1) + return unix.PidfdSendSignal(fd, sig, nil, 0) +} +func (p *ownedMini) signalLeader(sig unix.Signal) error { + p.mu.Lock() + defer p.mu.Unlock() + if p.settled { + return os.ErrProcessDone + } + return p.signalFD(p.leaderFD, sig) +} +func (p *ownedMini) isSettled() bool { p.mu.Lock(); defer p.mu.Unlock(); return p.settled } +func (p *ownedMini) settle() { + p.mu.Lock() + defer p.mu.Unlock() + if !p.settled { + p.settled = true + if p.leaderFD >= 0 { + _ = unix.Close(p.leaderFD) + p.leaderFD = -1 + } + } +} func (p *ownedMini) join(t *testing.T, bound time.Duration) error { t.Helper() select { case <-p.done: return p.err case <-time.After(bound): - t.Fatalf("owned process did not join in %s", bound) + miniFailStop(t, fmt.Sprintf("owned process did not join in %s", bound)) return nil } } -func (p *ownedMini) stop(t *testing.T) { - p.stopOnce.Do(func() { p.stopGroup(t) }) -} +func (p *ownedMini) stop(t *testing.T) { p.stopOnce.Do(func() { p.stopGroup(t) }) } + +// Never signal a numeric PGID. While the original leader is stopped, its +// group identity cannot disappear; capture and stop each member by pidfd. +// After resuming, TERM/KILL use those immutable references even if a PID is +// recycled. Unknown late members or an exited leader with live residue cause +// fail-stop rather than guessing ownership and signaling an unrelated group. func (p *ownedMini) stopGroup(t *testing.T) { t.Helper() - pgid := p.cmd.Process.Pid - if pgid <= 1 { - t.Error("invalid owned process group") + if p.isSettled() { return } - _ = syscall.Kill(-pgid, syscall.SIGTERM) + select { + case <-p.done: + p.assertStopped(t) + return + default: + } + if err := p.signalLeader(unix.SIGSTOP); err != nil { + select { + case <-p.done: + p.assertStopped(t) + return + default: + miniFailStop(t, fmt.Sprintf("cannot stop owned leader: %v", err)) + } + } + pgid := p.cmd.Process.Pid + leaderFD := p.leaderFD + refs := map[string]int{} + defer func() { + for _, fd := range refs { + if fd != leaderFD { + _ = unix.Close(fd) + } + } + }() + deadline := time.Now().Add(time.Second) + for { + leader, err := miniProc(pgid) + if err != nil || leader.key != p.leaderKey || (leader.state != "T" && leader.state != "t") || unix.PidfdSendSignal(leaderFD, 0, nil, 0) != nil { + if time.Now().After(deadline) { + miniFailStop(t, "leader incarnation not held during member capture") + } + time.Sleep(5 * time.Millisecond) + continue + } + refs[leader.key] = leaderFD + members := miniGroupMembers(t, pgid) + stopped := true + for _, m := range members { + fd, ok := refs[m.key] + if !ok { + fd, err = unix.PidfdOpen(m.pid, 0) + if err != nil { + if errors.Is(err, unix.ESRCH) { + stopped = false + continue + } + miniFailStop(t, fmt.Sprintf("cannot own descendant: %v", err)) + } + current, err := miniProc(m.pid) + if err != nil || current.key != m.key || current.group != pgid { + _ = unix.Close(fd) + stopped = false + continue + } + refs[m.key] = fd + } + if m.state != "T" && m.state != "t" { + stopped = false + if err := p.signalFD(fd, unix.SIGSTOP); err != nil && !errors.Is(err, unix.ESRCH) { + miniFailStop(t, fmt.Sprintf("cannot stop descendant: %v", err)) + } + } + } + if stopped { + break + } + if time.Now().After(deadline) { + miniFailStop(t, "descendant capture did not quiesce") + } + time.Sleep(5 * time.Millisecond) + } + for _, fd := range refs { + _ = p.signalFD(fd, unix.SIGTERM) + } + for _, fd := range refs { + _ = p.signalFD(fd, unix.SIGCONT) + } select { case <-p.done: case <-time.After(2 * time.Second): } - _ = syscall.Kill(-pgid, syscall.SIGKILL) + for _, fd := range refs { + _ = p.signalFD(fd, unix.SIGKILL) + } _ = p.join(t, 5*time.Second) p.assertStopped(t) } func (p *ownedMini) assertStopped(t *testing.T) { t.Helper() - deadline := time.Now().Add(5 * time.Second) + wait := p.censusWait + if wait == 0 { + wait = 5 * time.Second + } + deadline := time.Now().Add(wait) for { - live := miniGroupLive(t, p.cmd.Process.Pid) + var live []int + if p.census != nil { + live = p.census() + } else { + live = miniGroupLive(t, p.cmd.Process.Pid) + } if len(live) == 0 { - return + select { + case <-p.done: + p.settle() + return + default: + miniFailStop(t, "empty group but leader not joined") + } } if time.Now().After(deadline) { - t.Fatalf("owned group %d still has live descendants %v", p.cmd.Process.Pid, live) + miniFailStop(t, fmt.Sprintf("owned group has live residue %v", live)) } - time.Sleep(20 * time.Millisecond) + time.Sleep(5 * time.Millisecond) } } -func miniGroupLive(t *testing.T, pgid int) []int { - t.Helper() + +type miniProcInfo struct { + pid, group int + state, key string +} + +func miniProc(pid int) (miniProcInfo, error) { + b, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat")) + if err != nil { + return miniProcInfo{}, err + } + end := strings.LastIndexByte(string(b), ')') + if end < 0 { + return miniProcInfo{}, fmt.Errorf("invalid proc stat") + } + fields := strings.Fields(string(b[end+1:])) + if len(fields) < 20 { + return miniProcInfo{}, fmt.Errorf("short proc stat") + } + group, err := strconv.Atoi(fields[2]) + if err != nil { + return miniProcInfo{}, err + } + return miniProcInfo{pid: pid, group: group, state: fields[0], key: strconv.Itoa(pid) + ":" + fields[19]}, nil +} +func miniGroupMembers(t *testing.T, pgid int) []miniProcInfo { entries, err := os.ReadDir("/proc") if err != nil { - t.Fatal(err) + miniFailStop(t, err.Error()) } - var live []int + var members []miniProcInfo for _, entry := range entries { pid, err := strconv.Atoi(entry.Name()) if err != nil { continue } - b, err := os.ReadFile(filepath.Join("/proc", entry.Name(), "stat")) - if errors.Is(err, os.ErrNotExist) { + info, err := miniProc(pid) + if errors.Is(err, os.ErrNotExist) || errors.Is(err, unix.ESRCH) { continue } if err != nil { - t.Fatal(err) + miniFailStop(t, err.Error()) } - end := strings.LastIndexByte(string(b), ')') - if end < 0 { - t.Fatalf("invalid proc stat for %d", pid) - } - fields := strings.Fields(string(b[end+1:])) - if len(fields) < 3 { - t.Fatal("short proc stat") - } - group, err := strconv.Atoi(fields[2]) - if err != nil { - t.Fatal(err) - } - if group == pgid && fields[0] != "Z" && fields[0] != "X" { - live = append(live, pid) + if info.group == pgid && info.state != "Z" && info.state != "X" { + members = append(members, info) } } + return members +} +func miniGroupLive(t *testing.T, pgid int) []int { + var live []int + for _, m := range miniGroupMembers(t, pgid) { + live = append(live, m.pid) + } return live } @@ -185,3 +356,76 @@ func TestMiniOwnedGroupCleanupStopsDescendants(t *testing.T) { t.Fatal("leader not joined") } } + +// This real process settles normally before its registered cleanup runs. A +// later cleanup must not dispatch anything to its old group or descriptor. +func TestMiniSettledCleanupDoesNotSignal(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + p := startOwnedMini(t, ctx, "/bin/true") + if err := p.join(t, 3*time.Second); err != nil { + t.Fatal(err) + } + p.assertStopped(t) + before := p.dispatches.Load() + p.stop(t) + if got := p.dispatches.Load(); got != before { + t.Fatalf("settled cleanup dispatched %d signals", got-before) + } +} + +func TestMiniCleanupFailStopAndSettlement(t *testing.T) { + for _, mode := range []string{"join", "residue", "settled"} { + t.Run(mode, func(t *testing.T) { + marker := filepath.Join(t.TempDir(), "cleanup-ran") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + t.Setenv("MINI_CLEANUP_CONTROL", mode) + t.Setenv("MINI_CLEANUP_MARKER", marker) + p := startOwnedMini(t, ctx, self, "-test.run=^TestMiniCleanupFailStopHelper$") + err = p.join(t, 3*time.Second) + p.assertStopped(t) + _, statErr := os.Stat(marker) + if mode == "settled" { + if err != nil || statErr != nil { + t.Fatalf("positive cleanup twin: err=%v marker=%v", err, statErr) + } + } else { + var exit *exec.ExitError + if !errors.As(err, &exit) || exit.ExitCode() != miniFailStopExit || !errors.Is(statErr, os.ErrNotExist) { + t.Fatalf("fail-stop %s: err=%v marker=%v output=%s", mode, err, statErr, p.output.String()) + } + } + }) + } +} +func TestMiniCleanupFailStopHelper(t *testing.T) { + mode := os.Getenv("MINI_CLEANUP_CONTROL") + if mode == "" { + t.Skip("isolated fail-stop helper") + } + t.Cleanup(func() { + if err := os.WriteFile(os.Getenv("MINI_CLEANUP_MARKER"), []byte("cleanup ran"), 0o600); err != nil { + t.Error(err) + } + }) + p := &ownedMini{done: make(chan struct{}), leaderFD: -1, censusWait: 10 * time.Millisecond} + switch mode { + case "join": + p.join(t, 10*time.Millisecond) + case "residue": + close(p.done) + p.census = func() []int { return []int{1234} } + p.assertStopped(t) + case "settled": + close(p.done) + p.census = func() []int { return nil } + p.assertStopped(t) + default: + t.Fatal("invalid control") + } +} diff --git a/seaweed-block/cmd/sw-block/mini_test.go b/seaweed-block/cmd/sw-block/mini_test.go index 4f69443895..f246a5c156 100644 --- a/seaweed-block/cmd/sw-block/mini_test.go +++ b/seaweed-block/cmd/sw-block/mini_test.go @@ -853,6 +853,9 @@ func TestMiniPrintedResumeRunsOnASpacedDir(t *testing.T) { // terminal server) inherits INVOCATION_ID; blockvolume refuses the lock-dir // override under it, so mini's children must start without it. func TestMiniChildrenStartWithoutInvocationID(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Unix child environment and signals") + } t.Setenv("INVOCATION_ID", "0123456789abcdef") dir := t.TempDir() r := &miniRun{cfg: miniConfig{Dir: dir}, out: io.Discard, log: io.Discard} @@ -860,7 +863,35 @@ func TestMiniChildrenStartWithoutInvocationID(t *testing.T) { if err != nil { t.Fatal(err) } - <-c.done + joined := false + stop := func() { + if joined { + return + } + _ = c.cmd.Process.Signal(syscall.SIGTERM) + select { + case <-c.done: + joined = true + return + case <-time.After(2 * time.Second): + } + _ = c.cmd.Process.Kill() + select { + case <-c.done: + joined = true + case <-time.After(2 * time.Second): + fmt.Fprintln(os.Stderr, "mini child did not join; stopping tests before directory cleanup") + os.Exit(86) + } + } + t.Cleanup(stop) + select { + case <-c.done: + joined = true + case <-time.After(2 * time.Second): + stop() + t.Fatal("mini environment child did not finish") + } b, err := os.ReadFile(filepath.Join(dir, "env.log")) if err != nil { t.Fatal(err)