mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 19:17:28 +01:00
* seaweed-block: sw-block mini starts as any user with no sudo blockvolume gets --volume-lock-dir, a trial-run override of the host volume lock directory (refused under systemd and together with the test override). sw-block mini passes <dir>/locks to its holder, so it starts as any user on a host without /run/sw-block. mini also runs v1 with no scheduled snapshot (it prints the command that takes one), names sw-block and weed by their absolute paths in every command it prints, and after a failed start stops what it started and prints the --reuse command for the same --dir. The release archive carries sw-block.tmpfiles.conf for the units' lock directory. The README Quick Start drops its sudo lines, and the v1.1.1 known issue reads fixed in v1.1.2. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * seaweed-block: mini under a systemd process tree, and no new lock-dir flag (on #13421) (#13425) * seaweed-block: mini starts its children without INVOCATION_ID Run from a systemd service's process tree (a CI runner unit, a terminal server), mini passed INVOCATION_ID to blockvolume, which then refused mini's lock directory and the run stopped at startup. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * seaweed-block: mini's interrupt test expects the resume command with mini's own path mini prints the resume command with os.Executable(), so the in-process test saw the test binary's path, not a bare sw-block, and failed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * seaweed-block: mini uses the existing hidden lock-dir override, no new flag --volume-lock-dir set the same field as the hidden --volume-lock-dir-test-only with the same systemd refusal, and mini was its only caller. Keep one hidden override so operators are not offered a documented knob that drops the one-holder-per-volume guarantee outside systemd (containers, hand-run hosts). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> * docs: track mini resolve helper time bounds * Test active release assets and relative mini paths * Complete mini release assets and bounded process checks * Terminate owned mini groups before checking for residue * Accept inaccessible host locks as a non-root precondition * Harden mini test ownership and fail-stop cleanup * test: reproduce empty filtered mini child environment * fix(block): complete mini startup and cleanup proof * test(block): claim the mini test's ports host-wide The pid-derived --port-shift put mini's 13 ports inside the handoff and weed pair ranges the other process-level harnesses claim, unclaimed, so a parallel CI shard could bind one of them. Pick a shift whose every port is claimed and free, as handoffAddress does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(block): claim the failed-start mini launch's ports too The second launch ran at shift+1, whose ports were neither claimed nor checked, so a parallel shard could take one and fail the launch before it reached the deliberate blockvolume refusal. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(block): exercise production mini hint with quoted paths * docs(block): explain mini local data lock scope * fix(block): preserve mini executable and cleanup proof * test(block): settle a leader that exits as member capture expires stopGroup checked done only at the top of each capture iteration. A leader that exited after that check, once the one-second window had passed, made the next failed read fail-stop even though the group had settled. Both capture deadlines now defer to assertStopped when done has closed, so live residue still fail-stops. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(block): refuse a PATH weed found through the current directory exec.LookPath reports exec.ErrDot for a weed found only through . in PATH. Making that name absolute let exec.Command start it, where it refused before; mini now refuses it and names --weed ./weed as the explicit choice. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(block): accept a reused --weed that names the recorded executable A relative --weed made absolute from another working directory names the same file through a different path; mini compared the strings and refused the retry. Compare file identity when the paths differ, so a different executable is still refused. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(block): prove the selected weed ran in the mini startup tests A start failure and the fixture weed's exit both return 1, and the printed command and the record exist either way. The dying fixture weed now writes a marker file, and both startup tests require it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(block): name the mini trial lock in the M4 start arrows The table already says a mini trial's blockvolume locks the run's --dir/locks; the diagram's start arrows still named only the host lock. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(block): shell-quote mini's startup trace Making --weed absolute can put a space from the working directory into the printed command. Quote the executable and each argument with shQuote, as mini's other printed commands already are, so the trace runs as printed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(block): count the mini group again when it is gone after a census A member listed by the census can exit before the signal-0 query reports ESRCH. On the iteration that crosses the deadline that stale count fail-stopped a settled group. Count again when the group is absent, so only a member still listed holds the settlement; the residue control still fail-stops. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(block): name the empty-census case in the mini group fail-stop A group that still exists while the census lists no live member failed with "live residue []". Say what it can be: a member the census missed, or zombies their new parent does not reap. Both stay fail-stops. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(block): match the quoted failed-start trace in the non-root mini test The startup trace is shell-quoted now, and this test's weed path has a quote in it, so match each binary through miniHintWord. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(block): let --reuse take its recorded run past a weed found through . The exec.ErrDot refusal ran before the record was read, so a reuse of a recorded run failed whenever . in PATH found a ./weed, although the reuse would use the recorded weed (or none for a walstore run). A reuse now ignores that weed; a fresh start still refuses it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(block): match the shell-quoted start trace in the mini unit tests mini shell-quotes each word of its "+" trace, so a TMPDIR holding a space prints the blockmaster, blockvolume and weed paths quoted, and three unit tests looked for them bare. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(block): pin that a normal start keeps the host volume lock A start under systemd (INVOCATION_ID set, as every shipped unit runs) gets no lock directory of its own, so the provider uses the host one, and the hidden test-only override is refused, naming the host lock directory. The test is listed under INV-WS-ONE-PROCESS-PER-HOST-001. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(block): mini quotes the --weed path in its dot-in-PATH hint Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
616 lines
18 KiB
Go
616 lines
18 KiB
Go
//go:build linux && subprocess && chunkstore_integration
|
|
|
|
package main_test
|
|
|
|
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.
|
|
func assertMiniUnprivileged(t *testing.T) {
|
|
t.Helper()
|
|
if os.Getuid() == 0 || os.Geteuid() == 0 {
|
|
t.Fatal("non-root qualification must run without uid 0")
|
|
}
|
|
p := "/run/sw-block/locks"
|
|
// A read-only existing file can still be flocked without a directory write.
|
|
// Refuse qualification if it can even be opened; never mutate the host path.
|
|
lock, err := os.Open(filepath.Join(p, "v1.lock"))
|
|
if err == nil {
|
|
_ = lock.Close()
|
|
t.Fatal("existing host lock is readable; old host-lock path is usable")
|
|
}
|
|
if !errors.Is(err, os.ErrNotExist) && !errors.Is(err, syscall.EACCES) && !errors.Is(err, syscall.EPERM) {
|
|
t.Fatalf("host lock file preflight: %v", err)
|
|
}
|
|
for {
|
|
_, err := os.Stat(p)
|
|
if err == nil {
|
|
break
|
|
}
|
|
if errors.Is(err, syscall.EACCES) || errors.Is(err, syscall.EPERM) {
|
|
t.Logf("non-root uid=%d euid=%d; host lock path %s is inaccessible: %v", os.Getuid(), os.Geteuid(), p, err)
|
|
return
|
|
}
|
|
if !errors.Is(err, os.ErrNotExist) {
|
|
t.Fatalf("host lock preflight: %v", err)
|
|
}
|
|
p = filepath.Dir(p)
|
|
}
|
|
if err := syscall.Access(p, 3); err == nil {
|
|
t.Fatalf("host lock path/ancestor %s is writable; non-root precondition is unproved", p)
|
|
} else if !errors.Is(err, syscall.EACCES) && !errors.Is(err, syscall.EPERM) {
|
|
t.Fatalf("host lock access preflight: %v", err)
|
|
}
|
|
t.Logf("non-root uid=%d euid=%d; host lock ancestor %s is not writable", os.Getuid(), os.Geteuid(), p)
|
|
}
|
|
|
|
type miniOutput struct {
|
|
mu sync.Mutex
|
|
b bytes.Buffer
|
|
}
|
|
|
|
func (b *miniOutput) Write(p []byte) (int, error) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
return b.b.Write(p)
|
|
}
|
|
func (b *miniOutput) String() string { b.mu.Lock(); defer b.mu.Unlock(); return b.b.String() }
|
|
|
|
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)
|
|
}
|
|
|
|
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
|
|
watchdog atomic.Bool
|
|
// Only the isolated fail-stop controls replace the census or its window.
|
|
groupExists func() bool
|
|
census func() []int
|
|
censusWait time.Duration
|
|
captureLeader func(int) (miniProcInfo, error)
|
|
}
|
|
|
|
const miniShutdownGrace = 35 * time.Second // three 10-second child stops plus margin
|
|
|
|
// Probe before starting any workload. CLONE_PIDFD then obtains the child's
|
|
// immutable reference atomically with creation, before a cancellation can run.
|
|
func miniPidfdSupport() error {
|
|
fd, err := unix.PidfdOpen(os.Getpid(), 0)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer unix.Close(fd)
|
|
return unix.PidfdSendSignal(fd, 0, nil, 0)
|
|
}
|
|
func startOwnedMini(t *testing.T, ctx context.Context, bin string, args ...string) *ownedMini {
|
|
t.Helper()
|
|
if err := miniPidfdSupport(); err != nil {
|
|
t.Fatalf("pidfd ownership unavailable before start: %v", err)
|
|
}
|
|
p := &ownedMini{cmd: exec.CommandContext(ctx, bin, args...), done: make(chan struct{}), leaderFD: -1}
|
|
p.cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true, PidFD: &p.leaderFD}
|
|
p.cmd.Stdout, p.cmd.Stderr = &p.output, &p.output
|
|
// os/exec must not kill only the leader after a short WaitDelay. Our
|
|
// watchdog grants the full product shutdown window, then owns group cleanup.
|
|
p.cmd.Cancel = func() error { p.watchdog.Store(true); go p.stop(t); return nil }
|
|
p.mu.Lock() // a context cancellation cannot observe the unopened pidfd
|
|
if err := p.cmd.Start(); err != nil {
|
|
p.mu.Unlock()
|
|
t.Fatal(err)
|
|
}
|
|
if p.leaderFD < 0 {
|
|
p.mu.Unlock()
|
|
p.ownershipFailed(t, "atomic leader pidfd missing")
|
|
}
|
|
info, err := miniProc(p.cmd.Process.Pid)
|
|
if err != nil {
|
|
p.mu.Unlock()
|
|
p.ownershipFailed(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
|
|
}
|
|
|
|
// No Wait goroutine exists yet: the unreaped direct child cannot have its
|
|
// PID recycled. Stop and reap it before failing closed with directories kept.
|
|
func (p *ownedMini) ownershipFailed(t *testing.T, why string) {
|
|
_ = p.cmd.Process.Kill()
|
|
p.cmd.WaitDelay = time.Second
|
|
reaped := make(chan struct{})
|
|
go func() { _ = p.cmd.Wait(); close(reaped) }()
|
|
select {
|
|
case <-reaped:
|
|
case <-time.After(5 * time.Second):
|
|
}
|
|
miniFailStop(t, why)
|
|
}
|
|
func (p *ownedMini) signalFD(fd int, sig unix.Signal) error {
|
|
p.mu.Lock()
|
|
defer p.mu.Unlock()
|
|
if p.settled {
|
|
return os.ErrProcessDone
|
|
}
|
|
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
|
|
}
|
|
p.dispatches.Add(1)
|
|
return unix.PidfdSendSignal(p.leaderFD, sig, nil, 0)
|
|
}
|
|
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):
|
|
miniFailStop(t, fmt.Sprintf("owned process did not join in %s", bound))
|
|
return nil
|
|
}
|
|
}
|
|
func (p *ownedMini) assertNaturalExit(t *testing.T) {
|
|
t.Helper()
|
|
if p.watchdog.Load() {
|
|
t.Fatal("watchdog intervened; failed-start cleanup was not completed by mini")
|
|
}
|
|
}
|
|
func (p *ownedMini) stop(t *testing.T) {
|
|
p.stopOnce.Do(func() {
|
|
if p.isSettled() {
|
|
return
|
|
}
|
|
_ = p.signalLeader(unix.SIGTERM)
|
|
select {
|
|
case <-p.done:
|
|
p.assertStopped(t)
|
|
return
|
|
case <-time.After(miniShutdownGrace):
|
|
}
|
|
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()
|
|
if p.isSettled() {
|
|
return
|
|
}
|
|
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 {
|
|
select {
|
|
case <-p.done:
|
|
p.assertStopped(t)
|
|
return
|
|
default:
|
|
}
|
|
readLeader := miniProc
|
|
if p.captureLeader != nil {
|
|
readLeader = p.captureLeader
|
|
}
|
|
leader, err := readLeader(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) {
|
|
p.captureExpired(t, "leader incarnation not held during member capture")
|
|
return
|
|
}
|
|
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) {
|
|
p.captureExpired(t, "descendant capture did not quiesce")
|
|
return
|
|
}
|
|
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):
|
|
}
|
|
for _, fd := range refs {
|
|
_ = p.signalFD(fd, unix.SIGKILL)
|
|
}
|
|
_ = p.join(t, 5*time.Second)
|
|
p.assertStopped(t)
|
|
}
|
|
|
|
// A leader that exits as the capture window closes settles through assertStopped.
|
|
func (p *ownedMini) captureExpired(t *testing.T, why string) {
|
|
t.Helper()
|
|
select {
|
|
case <-p.done:
|
|
p.assertStopped(t)
|
|
default:
|
|
miniFailStop(t, why)
|
|
}
|
|
}
|
|
func (p *ownedMini) assertStopped(t *testing.T) {
|
|
t.Helper()
|
|
wait := p.censusWait
|
|
if wait == 0 {
|
|
wait = 5 * time.Second
|
|
}
|
|
deadline := time.Now().Add(wait)
|
|
census := func() []int {
|
|
if p.census != nil {
|
|
return p.census()
|
|
}
|
|
return miniGroupLive(t, p.cmd.Process.Pid)
|
|
}
|
|
for {
|
|
live := census()
|
|
// A /proc listing is not atomic: a member can fork then disappear
|
|
// between list and stat. Signal 0 is only an existence query (never a
|
|
// numeric effect signal); ESRCH proves the entire group is now absent.
|
|
absent := false
|
|
if p.groupExists != nil {
|
|
absent = !p.groupExists()
|
|
} else {
|
|
err := unix.Kill(-p.cmd.Process.Pid, 0)
|
|
absent = errors.Is(err, unix.ESRCH)
|
|
}
|
|
// A member counted before ESRCH may have exited in between: count
|
|
// again, so only a member still listed holds the settlement.
|
|
if len(live) != 0 && absent {
|
|
live = census()
|
|
}
|
|
if len(live) == 0 && absent {
|
|
select {
|
|
case <-p.done:
|
|
p.settle()
|
|
return
|
|
default:
|
|
miniFailStop(t, "empty group but leader not joined")
|
|
}
|
|
}
|
|
if time.Now().After(deadline) {
|
|
if len(live) == 0 {
|
|
miniFailStop(t, "owned group still exists with no live member listed: a member the census missed, or zombies its new parent does not reap")
|
|
}
|
|
miniFailStop(t, fmt.Sprintf("owned group has live residue %v", live))
|
|
}
|
|
time.Sleep(5 * time.Millisecond)
|
|
}
|
|
}
|
|
|
|
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 {
|
|
miniFailStop(t, err.Error())
|
|
}
|
|
var members []miniProcInfo
|
|
for _, entry := range entries {
|
|
pid, err := strconv.Atoi(entry.Name())
|
|
if err != nil {
|
|
continue
|
|
}
|
|
info, err := miniProc(pid)
|
|
if errors.Is(err, os.ErrNotExist) || errors.Is(err, unix.ESRCH) {
|
|
continue
|
|
}
|
|
if err != nil {
|
|
miniFailStop(t, err.Error())
|
|
}
|
|
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
|
|
}
|
|
|
|
// An intentionally TERM-ignoring descendant exercises the safety net itself.
|
|
func TestMiniOwnedGroupCleanupStopsDescendants(t *testing.T) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
defer cancel()
|
|
p := startOwnedMini(t, ctx, "/bin/sh", "-c", "trap '' TERM; sleep 60 & echo ready; wait")
|
|
deadline := time.Now().Add(5 * time.Second)
|
|
for !strings.Contains(p.output.String(), "ready") {
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("fixture did not start")
|
|
}
|
|
time.Sleep(10 * time.Millisecond)
|
|
}
|
|
if live := miniGroupLive(t, p.cmd.Process.Pid); len(live) < 2 {
|
|
t.Fatalf("descendant fixture not reached: %v", live)
|
|
}
|
|
p.stop(t)
|
|
select {
|
|
case <-p.done:
|
|
default:
|
|
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", "missed-member", "settled", "late-exit-settled", "capture-settled", "capture-residue", "capture-expired-settled", "capture-expired-residue", "natural", "watchdog"} {
|
|
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" || mode == "late-exit-settled" || mode == "capture-settled" || mode == "capture-expired-settled" || mode == "natural" {
|
|
if err != nil || statErr != nil {
|
|
t.Fatalf("positive cleanup twin: err=%v marker=%v", err, statErr)
|
|
}
|
|
} else if mode == "watchdog" {
|
|
var exit *exec.ExitError
|
|
if !errors.As(err, &exit) || exit.ExitCode() != 1 || !strings.Contains(p.output.String(), "watchdog intervened") || statErr != nil {
|
|
t.Fatalf("watchdog cannot prove natural cleanup: err=%v marker=%v output=%s", err, statErr, p.output.String())
|
|
}
|
|
} 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, groupExists: func() bool { return false }}
|
|
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 "missed-member":
|
|
close(p.done)
|
|
p.census = func() []int { return nil }
|
|
p.groupExists = func() bool { return true }
|
|
p.assertStopped(t)
|
|
case "settled":
|
|
close(p.done)
|
|
p.census = func() []int { return nil }
|
|
p.assertStopped(t)
|
|
case "late-exit-settled":
|
|
close(p.done)
|
|
counted := false
|
|
p.census = func() []int {
|
|
if counted {
|
|
return nil
|
|
}
|
|
counted = true
|
|
time.Sleep(2 * p.censusWait) // the member exits as the window closes
|
|
return []int{1234}
|
|
}
|
|
p.assertStopped(t)
|
|
case "capture-settled", "capture-residue", "capture-expired-settled", "capture-expired-residue":
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
p := startOwnedMini(t, ctx, "/bin/sleep", "60")
|
|
p.censusWait = 10 * time.Millisecond
|
|
if strings.HasSuffix(mode, "-residue") {
|
|
p.census = func() []int { return []int{1234} }
|
|
p.groupExists = func() bool { return true }
|
|
}
|
|
p.captureLeader = func(int) (miniProcInfo, error) {
|
|
if strings.HasPrefix(mode, "capture-expired") {
|
|
time.Sleep(1100 * time.Millisecond) // past the one-second capture window
|
|
}
|
|
_ = p.signalLeader(unix.SIGKILL)
|
|
_ = p.join(t, time.Second)
|
|
return miniProcInfo{}, os.ErrNotExist
|
|
}
|
|
p.stopGroup(t)
|
|
case "natural", "watchdog":
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
defer cancel()
|
|
bin, args := "/bin/false", []string{}
|
|
if mode == "watchdog" {
|
|
bin, args = "/bin/sleep", []string{"60"}
|
|
}
|
|
p := startOwnedMini(t, ctx, bin, args...)
|
|
if mode == "watchdog" {
|
|
cancel()
|
|
}
|
|
_ = p.join(t, time.Second)
|
|
p.assertStopped(t)
|
|
p.assertNaturalExit(t)
|
|
default:
|
|
t.Fatal("invalid control")
|
|
}
|
|
}
|
|
|
|
// A four-second shutdown exceeds the old WaitDelay. The context watchdog
|
|
// must let it finish rather than kill its leader before children are stopped.
|
|
func TestMiniContextAllowsChildShutdownGrace(t *testing.T) {
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
defer cancel()
|
|
p := startOwnedMini(t, ctx, "/bin/sh", "-c", "trap 'sleep 4; echo graceful; exit 0' TERM; echo ready; while :; do sleep .05; done")
|
|
deadline := time.Now().Add(5 * time.Second)
|
|
for !strings.Contains(p.output.String(), "ready") {
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("shutdown fixture not ready")
|
|
}
|
|
time.Sleep(10 * time.Millisecond)
|
|
}
|
|
cancel()
|
|
_ = p.join(t, miniShutdownGrace+10*time.Second)
|
|
p.assertStopped(t)
|
|
if !strings.Contains(p.output.String(), "graceful") {
|
|
t.Fatalf("shutdown killed prematurely: %s", p.output.String())
|
|
}
|
|
}
|