//go:build linux package pause import ( "bytes" "encoding/json" "errors" "fmt" "os" "os/exec" "path/filepath" "regexp" "strconv" "strings" "sync" "syscall" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" "golang.org/x/sys/unix" ) // writerBody appends a counter to $DIR/$0 about every millisecond, each // pass forking a sleep: a writer that also keeps making new processes. const writerBody = `i=0; while :; do i=$((i+1)); echo $i >> "$DIR/$0"; sleep 0.001; done` // writers are the files the sandbox's writers append to: one a child of // the sandbox's first process, one inside a nested user and pid namespace // made by unshare, one inside a nested bubblewrap sandbox. var writers = []string{"direct", "unshare", "bwrap"} // A nested start that fails (a busy shared host) is tried again. const writersScript = `sh -c "$W" direct & until unshare --user --pid --fork sh -c "$W" unshare; do sleep 0.1; done & until bwrap --dev-bind / / --unshare-user --unshare-pid --die-with-parent sh -c "$W" bwrap; do sleep 0.1; done & wait` // sandbox starts script as the first process of a bubblewrap sandbox made // with the step sandbox's namespace arguments (provider.NamespaceArguments: // --unshare-pid, --new-session, --as-pid-1, --json-status-fd 3), and // returns that process as containment records it. The sandbox is killed // when the test ends. func sandbox(t *testing.T, dir, script string) Process { t.Helper() bwrap, err := exec.LookPath("bwrap") if err != nil { t.Skip("no bwrap") } for _, tool := range []string{"sh", "unshare", "sleep"} { if _, err := exec.LookPath(tool); err != nil { t.Skipf("no %s", tool) } } status, statusW, err := os.Pipe() if err != nil { t.Fatal(err) } defer status.Close() // A /proc of the sandbox's own pid namespace, as the step sandbox has: // the nested bwrap reads its own pid there. args := append([]string{"--dev-bind", "/", "/", "--proc", "/proc"}, provider.NamespaceArguments()...) cmd := exec.Command(bwrap, append(args, "sh", "-c", script)...) cmd.Env = []string{"PATH=/usr/bin:/bin", "DIR=" + dir, "W=" + writerBody} cmd.ExtraFiles = []*os.File{statusW} stderr := &lockedBuffer{} cmd.Stderr = stderr t.Cleanup(func() { if t.Failed() { t.Logf("sandbox stderr: %s", stderr.String()) } }) if err := cmd.Start(); err != nil { t.Fatal(err) } statusW.Close() var msg struct { PID int `json:"child-pid"` } status.SetReadDeadline(time.Now().Add(10 * time.Second)) if err := json.NewDecoder(status).Decode(&msg); err != nil || msg.PID <= 1 { cmd.Process.Kill() cmd.Wait() t.Skipf("bwrap did not start a sandbox here: %v", err) } fd, err := unix.PidfdOpen(msg.PID, 0) if err != nil { t.Fatal(err) } t.Cleanup(func() { // SIGKILL to the namespace's init ends every process in it and in // the namespaces nested inside, stopped or not. unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0) unix.Close(fd) cmd.Process.Kill() cmd.Wait() }) _, _, start, err := readStat(fmt.Sprintf("/proc/%d/stat", msg.PID)) if err != nil { t.Fatal(err) } ns, err := os.Readlink(fmt.Sprintf("/proc/%d/ns/pid", msg.PID)) if err != nil { t.Fatal(err) } return Process{PID: msg.PID, StartTicks: start, Namespace: ns} } type lockedBuffer struct { mu sync.Mutex b bytes.Buffer } func (l *lockedBuffer) Write(p []byte) (int, error) { l.mu.Lock() defer l.mu.Unlock() if l.b.Len() > 64<<10 { return len(p), nil } return l.b.Write(p) } func (l *lockedBuffer) String() string { l.mu.Lock() defer l.mu.Unlock() return l.b.String() } func sizes(dir string, names ...string) map[string]int64 { if len(names) == 0 { names = writers } out := map[string]int64{} for _, w := range names { if info, err := os.Stat(filepath.Join(dir, w)); err == nil { out[w] = info.Size() } } return out } // allGrowing waits until every writer's file grows, and fails the test // with the ones that did not. func allGrowing(t *testing.T, dir string, within time.Duration) { t.Helper() before := sizes(dir) deadline := time.Now().Add(within) for { now := sizes(dir) var still []string for _, w := range writers { if now[w] == 0 || now[w] == before[w] { still = append(still, w) } } if len(still) == 0 { return } if time.Now().After(deadline) { t.Fatalf("writers made no progress in %s: %v (sizes %v)", within, still, now) } time.Sleep(5 * time.Millisecond) } } // movedOver reports the writers (names; all of writers when none) whose // files changed over d. func movedOver(dir string, d time.Duration, names ...string) []string { if len(names) == 0 { names = writers } before := sizes(dir, names...) time.Sleep(d) after := sizes(dir, names...) var moved []string for _, w := range names { if after[w] != before[w] { moved = append(moved, fmt.Sprintf("%s %d->%d", w, before[w], after[w])) } } return moved } // growingFile waits until dir/name exists and grows. func growingFile(t *testing.T, dir, name string, within time.Duration) { t.Helper() before := sizes(dir, name)[name] for deadline := time.Now().Add(within); ; { if now := sizes(dir, name)[name]; now > 0 && now != before { return } if time.Now().After(deadline) { t.Fatalf("%s made no progress in %s", name, within) } time.Sleep(5 * time.Millisecond) } } // join starts the writer named name inside the sandbox's user and pid // namespaces with nsenter, from outside: a member by namespace whose // parent (nsenter) is not one. func join(t *testing.T, p Process, dir, name string) { t.Helper() nsenter, err := exec.LookPath("nsenter") if err != nil { t.Skip("no nsenter") } cmd := exec.Command(nsenter, "--target", strconv.Itoa(p.PID), "--user", "--pid", "--preserve-credentials", "--", "sh", "-c", writerBody, name) cmd.Env = []string{"PATH=/usr/bin:/bin", "DIR=" + dir} if err := cmd.Start(); err != nil { t.Fatal(err) } t.Cleanup(func() { cmd.Process.Kill(); cmd.Wait() }) } func writerSandbox(t *testing.T) (Process, string) { dir := t.TempDir() p := sandbox(t, dir, writersScript) allGrowing(t, dir, 10*time.Second) return p, dir } // Plan task 9: a writer that appends a counter every millisecond, from a // nested namespace too, makes no progress between pause and resume, and // all of them go on after. func TestHoldStopsEveryWriter(t *testing.T) { p, dir := writerSandbox(t) var moved []string called := false err := holdAmid(p, Bound, func(deadline time.Time) error { called = true if time.Until(deadline) <= 0 || time.Until(deadline) > Bound { t.Errorf("deadline %s away", time.Until(deadline)) } moved = movedOver(dir, 300*time.Millisecond) return nil }) if err != nil || !called { t.Fatalf("Hold: %v (called %v)", err, called) } if len(moved) > 0 { t.Fatalf("writers ran while paused: %v", moved) } allGrowing(t, dir, 2*time.Second) } // fn's error comes back as Hold's, after everything is resumed. func TestHoldReturnsWorkError(t *testing.T) { p, dir := writerSandbox(t) want := errors.New("work failed") if err := holdAmid(p, Bound, func(time.Time) error { return want }); err != want { t.Fatalf("Hold: %v", err) } allGrowing(t, dir, 2*time.Second) } // A panic inside the pause resumes every process before it goes on up. func TestHoldResumesAfterPanic(t *testing.T) { p, dir := writerSandbox(t) var moved []string func() { defer func() { if r := recover(); r != "injected" { t.Fatalf("recovered %v", r) } }() holdAmid(p, Bound, func(time.Time) error { moved = movedOver(dir, 100*time.Millisecond) panic("injected") }) t.Fatal("Hold returned past the panic") }() if len(moved) > 0 { t.Fatalf("writers ran while paused: %v", moved) } allGrowing(t, dir, 2*time.Second) } // Past the bound the sandbox is resumed even while the work still runs, // and Hold refuses with ErrBusy once the work returns. func TestHoldResumesAtTheBound(t *testing.T) { p, dir := writerSandbox(t) var early, late []string start := time.Now() err := holdAmid(p, 800*time.Millisecond, func(time.Time) error { early = movedOver(dir, 200*time.Millisecond) time.Sleep(time.Until(start.Add(900 * time.Millisecond))) // The work is still running here, past the bound. late = movedOver(dir, 300*time.Millisecond) return nil }) if !errors.Is(err, ErrBusy) { t.Fatalf("Hold past its bound: %v", err) } if len(early) > 0 { t.Fatalf("writers ran while paused: %v", early) } if len(late) != len(writers) { t.Fatalf("writers not resumed at the bound while the work ran on: moved %v", late) } allGrowing(t, dir, 2*time.Second) } // A bound too short to stop the sandbox refuses with ErrBusy without // calling the work, and leaves nothing stopped. func TestHoldBusyWhenStoppingRunsOut(t *testing.T) { p, dir := writerSandbox(t) called := false err := holdAmid(p, time.Nanosecond, func(time.Time) error { called = true; return nil }) if !errors.Is(err, ErrBusy) || called { t.Fatalf("Hold: %v (called %v)", err, called) } allGrowing(t, dir, 2*time.Second) if s := stoppedIn(t, p); len(s) > 0 { t.Fatalf("left stopped: %v", s) } } // A recorded process that is not the one at that pid (another start // time, another namespace, or none) is refused with ErrGone, and nothing // is stopped. func TestHoldRefusesAnotherProcess(t *testing.T) { p, dir := writerSandbox(t) for name, q := range map[string]Process{ "start time": {PID: p.PID, StartTicks: p.StartTicks + 1, Namespace: p.Namespace}, "namespace": {PID: p.PID, StartTicks: p.StartTicks, Namespace: "pid:[1]"}, "no process": {PID: 1 << 30, StartTicks: p.StartTicks}, "zero": {}, } { called := false err := holdAmid(q, Bound, func(time.Time) error { called = true; return nil }) if !errors.Is(err, ErrGone) || called { t.Errorf("%s: Hold %v (called %v)", name, err, called) } } allGrowing(t, dir, 2*time.Second) } // After Hold, no process of the sandbox is left stopped. func TestHoldLeavesNothingStopped(t *testing.T) { p, _ := writerSandbox(t) if err := holdAmid(p, Bound, func(time.Time) error { return nil }); err != nil { t.Fatal(err) } // SIGCONT is delivered at once; give the scheduler a moment. deadline := time.Now().Add(2 * time.Second) for { s := stoppedIn(t, p) if len(s) == 0 { return } if time.Now().After(deadline) { t.Fatalf("left stopped: %v", s) } time.Sleep(10 * time.Millisecond) } } // membersOf lists the pids Hold counts as the sandbox's. func membersOf(t *testing.T, p Process) []int { t.Helper() h := newHeld() defer h.closeNamespaces() fd, _, err := h.pin(p) if err != nil { t.Fatal(err) } unix.Close(fd) d, err := os.Open("/proc") if err != nil { t.Fatal(err) } names, _ := d.Readdirnames(-1) d.Close() var out []int for _, name := range names { pid, err := strconv.Atoi(name) if err != nil { continue } inside, err := h.inSandbox(pid) if errors.Is(err, errVanished) { continue } if err != nil { t.Fatalf("placing %d: %v", pid, err) } if inside { out = append(out, pid) } } return out } // stoppedIn lists the sandbox's tasks that read stopped. func stoppedIn(t *testing.T, p Process) []string { t.Helper() var out []string for _, pid := range membersOf(t, p) { tasks, _ := os.ReadDir(fmt.Sprintf("/proc/%d/task", pid)) for _, task := range tasks { state, _, _, err := readStat(fmt.Sprintf("/proc/%d/task/%s/stat", pid, task.Name())) if err == nil && (state == 'T' || state == 't') { out = append(out, strconv.Itoa(pid)+"/"+task.Name()) } } } return out } // readStat parses the fields Hold reads from a stat file. func TestReadStat(t *testing.T) { dir := t.TempDir() // A command name may hold spaces and parentheses. line := "4242 (a) b (c) S 17 4242 4242 0 -1 4194560 1 0 0 0 0 0 0 0 20 0 1 0 987654 1 1" path := filepath.Join(dir, "stat") if err := os.WriteFile(path, []byte(line+"\n"), 0o600); err != nil { t.Fatal(err) } state, ppid, start, err := readStat(path) if err != nil || state != 'S' || ppid != 17 || start != 987654 { t.Fatalf("readStat: %c %d %d %v", state, ppid, start, err) } for _, bad := range []string{"", "1 (x", "1 (x) S", "1 (x) S 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 notanumber"} { os.WriteFile(path, []byte(bad), 0o600) if _, _, _, err := readStat(path); err == nil { t.Errorf("readStat accepted %q", bad) } } } // A pass is settled only once every member reads stopped: a member still // running (here one held but never signalled) keeps it unsettled and is // sent SIGSTOP again, and a sleeping process does not count as stopped. func TestPassWaitsForStopped(t *testing.T) { cmd := exec.Command("sleep", "30") if err := cmd.Start(); err != nil { t.Skip("no sleep") } defer func() { cmd.Process.Kill(); cmd.Wait() }() pid := cmd.Process.Pid var start uint64 for deadline := time.Now().Add(2 * time.Second); ; { state, _, s, err := readStat(fmt.Sprintf("/proc/%d/stat", pid)) if err == nil && state == 'S' { start = s break } if time.Now().After(deadline) { t.Fatalf("sleep never slept: %c %v", state, err) } time.Sleep(time.Millisecond) } fd, err := unix.PidfdOpen(pid, 0) if err != nil { t.Fatal(err) } m := member{pid, start} h := plainHeld(t) h.members[m] = fd defer h.resume() if settled, err := h.pass(); err != nil || settled { t.Fatalf("a sleeping member settled the pass: %v %v", settled, err) } for deadline := time.Now().Add(2 * time.Second); ; { settled, err := h.pass() if err != nil { t.Fatal(err) } if settled { break } if time.Now().After(deadline) { t.Fatal("the member never read stopped") } time.Sleep(time.Millisecond) } if state, _, _, _ := readStat(fmt.Sprintf("/proc/%d/stat", pid)); state != 'T' { t.Fatalf("settled with the member in state %c", state) } h.resume() for deadline := time.Now().Add(2 * time.Second); ; { if state, _, _, _ := readStat(fmt.Sprintf("/proc/%d/stat", pid)); state == 'S' { return } if time.Now().After(deadline) { t.Fatal("not resumed") } time.Sleep(time.Millisecond) } } // F2: a process that joined the sandbox's namespaces from outside (its // parent is not in the sandbox) is a member and is stopped. func TestHoldStopsANamespaceJoiner(t *testing.T) { p, dir := writerSandbox(t) join(t, p, dir, "joiner") growingFile(t, dir, "joiner", 10*time.Second) var moved []string if err := holdAmid(p, Bound, func(time.Time) error { moved = movedOver(dir, 300*time.Millisecond, append([]string{"joiner"}, writers...)...) return nil }); err != nil { t.Fatal(err) } if len(moved) > 0 { t.Fatalf("writers ran while paused: %v", moved) } growingFile(t, dir, "joiner", 2*time.Second) } // F2, forced: the first process is held but still running when a pass // starts; after the pass lists /proc it gains a new member (as a fork // finishing late would) and stops. The listing that pass made cannot have // seen the new member, so the pass must not settle: the member is found // by a later listing and is stopped before the pause settles. func TestPassForkAfterListing(t *testing.T) { dir := t.TempDir() p := sandbox(t, dir, "exec sleep 1000") h := newHeld() defer h.closeNamespaces() fd, start, err := h.pin(p) if err != nil { t.Fatal(err) } h.members[member{p.PID, start}] = fd // held, not yet signalled defer h.resume() fired := false testHook = func(point string, _ int) { if point != "scanned" || fired { return } fired = true join(t, p, dir, "late") growingFile(t, dir, "late", 10*time.Second) unix.PidfdSendSignal(fd, unix.SIGSTOP, nil, 0) for deadline := time.Now().Add(2 * time.Second); ; { if state, _, _, _ := readStat(fmt.Sprintf("/proc/%d/stat", p.PID)); state == 'T' { break } if time.Now().After(deadline) { t.Fatal("the first process never stopped") } time.Sleep(time.Millisecond) } } defer func() { testHook = nil }() for deadline := time.Now().Add(5 * time.Second); ; { settled, err := h.pass() if err != nil { t.Fatal(err) } if settled { break } if time.Now().After(deadline) { t.Fatal("never settled") } time.Sleep(time.Millisecond) } if !fired { t.Fatal("the hook never ran") } if moved := movedOver(dir, 300*time.Millisecond, "late"); len(moved) > 0 { t.Fatalf("a member made after the listing ran while settled: %v", moved) } h.resume() growingFile(t, dir, "late", 2*time.Second) } // F2, forced: a daemon whose parent is killed while a pass lists /proc // (so it is reparented mid-scan) is still a member and is stopped. The // first process outlives the parent (a plain wait would return when the // parent is killed and end the namespace, the daemon with it). func TestHoldStopsAReparentedDaemon(t *testing.T) { dir := t.TempDir() p := sandbox(t, dir, `sh -c 'sh -c "$W" daemon & exec sleep 1000' & while :; do wait; sleep 0.1; done`) growingFile(t, dir, "daemon", 10*time.Second) parent := 0 for _, pid := range membersOf(t, p) { if cl, _ := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid)); string(cl) == "sleep\x001000\x00" { parent = pid } } if parent == 0 { t.Fatal("no intermediate parent") } fired := false testHook = func(point string, _ int) { if point == "scanned" && !fired { fired = true syscall.Kill(parent, syscall.SIGKILL) } } defer func() { testHook = nil }() var moved []string if err := holdAmid(p, Bound, func(time.Time) error { moved = movedOver(dir, 300*time.Millisecond, "daemon") return nil }); err != nil { t.Fatal(err) } if !fired || len(moved) > 0 { t.Fatalf("hook fired %v; the reparented daemon ran while paused: %v", fired, moved) } growingFile(t, dir, "daemon", 2*time.Second) } // F3: the watchdog resumes (and closes every pidfd) between a member's // running read and its retry SIGSTOP, and the descriptor number is reused // by a fresh pidfd for the same process. The retry must not signal: the // member keeps running. func TestRetryAfterTheWatchdogDoesNotStop(t *testing.T) { cmd := exec.Command("sleep", "30") if err := cmd.Start(); err != nil { t.Skip("no sleep") } defer func() { cmd.Process.Kill(); cmd.Wait() }() pid := cmd.Process.Pid var start uint64 for deadline := time.Now().Add(2 * time.Second); ; { state, _, s, err := readStat(fmt.Sprintf("/proc/%d/stat", pid)) if err == nil && state == 'S' { start = s break } if time.Now().After(deadline) { t.Fatalf("sleep never slept: %c %v", state, err) } time.Sleep(time.Millisecond) } fd, err := unix.PidfdOpen(pid, 0) if err != nil { t.Fatal(err) } h := plainHeld(t) h.members[member{pid, start}] = fd reused := -1 testHook = func(point string, _ int) { if point == "retry" { h.resume() reused, _ = unix.PidfdOpen(pid, 0) } } defer func() { testHook = nil; unix.Close(reused) }() if _, err := h.pass(); !errors.Is(err, ErrBusy) { t.Fatalf("pass after resume: %v", err) } time.Sleep(50 * time.Millisecond) if state, _, _, _ := readStat(fmt.Sprintf("/proc/%d/stat", pid)); state == 'T' { t.Fatalf("stopped after the sandbox was resumed (reused descriptor %d, first %d)", reused, fd) } } // F5: a copy that runs past the deadline while the watchdog has not run // (delayed here) is still refused, and the sandbox is resumed. func TestHoldBusyWhenTheWatchdogIsLate(t *testing.T) { p, dir := writerSandbox(t) afterFunc = func(time.Duration, func()) *time.Timer { return time.AfterFunc(time.Hour, func() {}) } defer func() { afterFunc = time.AfterFunc }() err := holdAmid(p, 300*time.Millisecond, func(deadline time.Time) error { time.Sleep(time.Until(deadline) + 50*time.Millisecond) return nil }) if !errors.Is(err, ErrBusy) { t.Fatalf("an overdue copy: %v", err) } allGrowing(t, dir, 2*time.Second) } // plainHeld is a held for members outside any sandbox (plain test // processes): no namespace counts as the sandbox's, so a pass's listing // adds nothing and only its retained members matter. func plainHeld(t *testing.T) *held { t.Helper() h := newHeld() self, err := unix.Open("/proc/self/ns/pid", unix.O_RDONLY|unix.O_CLOEXEC, 0) if err != nil { t.Fatal(err) } h.ours, _ = inode(self) unix.Close(self) h.rootDepth = 1 << 20 t.Cleanup(h.closeNamespaces) return h } // descendant: pid is root or one of its descendants (by parent pid). func descendant(pid, root int) bool { for range 64 { if pid == root { return true } _, ppid, _, err := readStat(fmt.Sprintf("/proc/%d/stat", pid)) if err != nil || ppid <= 1 { return false } pid = ppid } return false } // unreadableWhile makes the pid namespace of every process unreadable for // which is returns true, as another user's or a non-dumpable process's is // (hosted CI's other sandboxes: containment's namespace helper). func unreadableWhile(t *testing.T, is func(pid int) bool) { t.Helper() testUnreadable = is t.Cleanup(func() { testUnreadable = nil }) } // refusedUnreadable: Hold refuses (ErrBusy, naming the unreadable // process) without calling the work, and every writer of dirs goes on. func refusedUnreadable(t *testing.T, p Process, dirs ...string) { t.Helper() called := false err := Hold(p, Bound, func(time.Time) error { called = true; return nil }) if !errors.Is(err, ErrBusy) || called || !strings.Contains(err.Error(), "pid namespace is unreadable") { t.Fatalf("Hold: %v (called %v)", err, called) } for _, dir := range dirs { allGrowing(t, dir, 2*time.Second) } } // Another sandbox of ours, as deep, whose processes' namespaces cannot be // read cannot be told from this one's members: the pause refuses rather // than guess, and leaves both running. (Placing such a process by its // parent needs validated ancestry: discussion 105.) func TestHoldRefusesAnUnreadableSandbox(t *testing.T) { p, dir := writerSandbox(t) other, otherDir := writerSandbox(t) unreadableWhile(t, func(pid int) bool { return descendant(pid, other.PID) }) refusedUnreadable(t, p, dir, otherDir) } // Members whose namespaces cannot be read (the first process's can: it // is pinned) refuse the pause too, and nothing is left stopped. func TestHoldRefusesUnreadableMembers(t *testing.T) { p, dir := writerSandbox(t) unreadableWhile(t, func(pid int) bool { return pid != p.PID && descendant(pid, p.PID) }) refusedUnreadable(t, p, dir) } // foreignUnreadable is Hold's refusal naming a process whose namespace // cannot be read. var foreignUnreadable = regexp.MustCompile(`: (\d+) \(.*\) is ours but its pid namespace is unreadable`) // holdAmid is Hold on a host where other tests' sandboxes come and go: // a refusal naming an unreadable process outside p's sandbox (another // test's) is tried again, for up to 20 seconds, and anything else is // Hold's own result. The pause refuses rather than guess (discussion // 105); what these tests prove is what a pause that holds does. func holdAmid(p Process, bound time.Duration, fn func(time.Time) error) error { for deadline := time.Now().Add(20 * time.Second); ; { err := Hold(p, bound, fn) m := foreignUnreadable.FindStringSubmatch(fmt.Sprint(err)) if m == nil || time.Now().After(deadline) { return err } if pid, _ := strconv.Atoi(m[1]); descendant(pid, p.PID) { return err } time.Sleep(200 * time.Millisecond) } }