| 1 | //go:build linux |
| 2 | |
| 3 | package pause |
| 4 | |
| 5 | import ( |
| 6 | "bytes" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "path/filepath" |
| 13 | "regexp" |
| 14 | "strconv" |
| 15 | "strings" |
| 16 | "sync" |
| 17 | "syscall" |
| 18 | "testing" |
| 19 | "time" |
| 20 | |
| 21 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 22 | "golang.org/x/sys/unix" |
| 23 | ) |
| 24 | |
| 25 | // writerBody appends a counter to $DIR/$0 about every millisecond, each |
| 26 | // pass forking a sleep: a writer that also keeps making new processes. |
| 27 | const writerBody = `i=0; while :; do i=$((i+1)); echo $i >> "$DIR/$0"; sleep 0.001; done` |
| 28 | |
| 29 | // writers are the files the sandbox's writers append to: one a child of |
| 30 | // the sandbox's first process, one inside a nested user and pid namespace |
| 31 | // made by unshare, one inside a nested bubblewrap sandbox. |
| 32 | var writers = []string{"direct", "unshare", "bwrap"} |
| 33 | |
| 34 | // A nested start that fails (a busy shared host) is tried again. |
| 35 | const writersScript = `sh -c "$W" direct & |
| 36 | until unshare --user --pid --fork sh -c "$W" unshare; do sleep 0.1; done & |
| 37 | until bwrap --dev-bind / / --unshare-user --unshare-pid --die-with-parent sh -c "$W" bwrap; do sleep 0.1; done & |
| 38 | wait` |
| 39 | |
| 40 | // sandbox starts script as the first process of a bubblewrap sandbox made |
| 41 | // with the step sandbox's namespace arguments (provider.NamespaceArguments: |
| 42 | // --unshare-pid, --new-session, --as-pid-1, --json-status-fd 3), and |
| 43 | // returns that process as containment records it. The sandbox is killed |
| 44 | // when the test ends. |
| 45 | func sandbox(t *testing.T, dir, script string) Process { |
| 46 | t.Helper() |
| 47 | bwrap, err := exec.LookPath("bwrap") |
| 48 | if err != nil { |
| 49 | t.Skip("no bwrap") |
| 50 | } |
| 51 | for _, tool := range []string{"sh", "unshare", "sleep"} { |
| 52 | if _, err := exec.LookPath(tool); err != nil { |
| 53 | t.Skipf("no %s", tool) |
| 54 | } |
| 55 | } |
| 56 | status, statusW, err := os.Pipe() |
| 57 | if err != nil { |
| 58 | t.Fatal(err) |
| 59 | } |
| 60 | defer status.Close() |
| 61 | // A /proc of the sandbox's own pid namespace, as the step sandbox has: |
| 62 | // the nested bwrap reads its own pid there. |
| 63 | args := append([]string{"--dev-bind", "/", "/", "--proc", "/proc"}, provider.NamespaceArguments()...) |
| 64 | cmd := exec.Command(bwrap, append(args, "sh", "-c", script)...) |
| 65 | cmd.Env = []string{"PATH=/usr/bin:/bin", "DIR=" + dir, "W=" + writerBody} |
| 66 | cmd.ExtraFiles = []*os.File{statusW} |
| 67 | stderr := &lockedBuffer{} |
| 68 | cmd.Stderr = stderr |
| 69 | t.Cleanup(func() { |
| 70 | if t.Failed() { |
| 71 | t.Logf("sandbox stderr: %s", stderr.String()) |
| 72 | } |
| 73 | }) |
| 74 | if err := cmd.Start(); err != nil { |
| 75 | t.Fatal(err) |
| 76 | } |
| 77 | statusW.Close() |
| 78 | var msg struct { |
| 79 | PID int `json:"child-pid"` |
| 80 | } |
| 81 | status.SetReadDeadline(time.Now().Add(10 * time.Second)) |
| 82 | if err := json.NewDecoder(status).Decode(&msg); err != nil || msg.PID <= 1 { |
| 83 | cmd.Process.Kill() |
| 84 | cmd.Wait() |
| 85 | t.Skipf("bwrap did not start a sandbox here: %v", err) |
| 86 | } |
| 87 | fd, err := unix.PidfdOpen(msg.PID, 0) |
| 88 | if err != nil { |
| 89 | t.Fatal(err) |
| 90 | } |
| 91 | t.Cleanup(func() { |
| 92 | // SIGKILL to the namespace's init ends every process in it and in |
| 93 | // the namespaces nested inside, stopped or not. |
| 94 | unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0) |
| 95 | unix.Close(fd) |
| 96 | cmd.Process.Kill() |
| 97 | cmd.Wait() |
| 98 | }) |
| 99 | _, _, start, err := readStat(fmt.Sprintf("/proc/%d/stat", msg.PID)) |
| 100 | if err != nil { |
| 101 | t.Fatal(err) |
| 102 | } |
| 103 | ns, err := os.Readlink(fmt.Sprintf("/proc/%d/ns/pid", msg.PID)) |
| 104 | if err != nil { |
| 105 | t.Fatal(err) |
| 106 | } |
| 107 | return Process{PID: msg.PID, StartTicks: start, Namespace: ns} |
| 108 | } |
| 109 | |
| 110 | type lockedBuffer struct { |
| 111 | mu sync.Mutex |
| 112 | b bytes.Buffer |
| 113 | } |
| 114 | |
| 115 | func (l *lockedBuffer) Write(p []byte) (int, error) { |
| 116 | l.mu.Lock() |
| 117 | defer l.mu.Unlock() |
| 118 | if l.b.Len() > 64<<10 { |
| 119 | return len(p), nil |
| 120 | } |
| 121 | return l.b.Write(p) |
| 122 | } |
| 123 | |
| 124 | func (l *lockedBuffer) String() string { |
| 125 | l.mu.Lock() |
| 126 | defer l.mu.Unlock() |
| 127 | return l.b.String() |
| 128 | } |
| 129 | |
| 130 | func sizes(dir string, names ...string) map[string]int64 { |
| 131 | if len(names) == 0 { |
| 132 | names = writers |
| 133 | } |
| 134 | out := map[string]int64{} |
| 135 | for _, w := range names { |
| 136 | if info, err := os.Stat(filepath.Join(dir, w)); err == nil { |
| 137 | out[w] = info.Size() |
| 138 | } |
| 139 | } |
| 140 | return out |
| 141 | } |
| 142 | |
| 143 | // allGrowing waits until every writer's file grows, and fails the test |
| 144 | // with the ones that did not. |
| 145 | func allGrowing(t *testing.T, dir string, within time.Duration) { |
| 146 | t.Helper() |
| 147 | before := sizes(dir) |
| 148 | deadline := time.Now().Add(within) |
| 149 | for { |
| 150 | now := sizes(dir) |
| 151 | var still []string |
| 152 | for _, w := range writers { |
| 153 | if now[w] == 0 || now[w] == before[w] { |
| 154 | still = append(still, w) |
| 155 | } |
| 156 | } |
| 157 | if len(still) == 0 { |
| 158 | return |
| 159 | } |
| 160 | if time.Now().After(deadline) { |
| 161 | t.Fatalf("writers made no progress in %s: %v (sizes %v)", within, still, now) |
| 162 | } |
| 163 | time.Sleep(5 * time.Millisecond) |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | // movedOver reports the writers (names; all of writers when none) whose |
| 168 | // files changed over d. |
| 169 | func movedOver(dir string, d time.Duration, names ...string) []string { |
| 170 | if len(names) == 0 { |
| 171 | names = writers |
| 172 | } |
| 173 | before := sizes(dir, names...) |
| 174 | time.Sleep(d) |
| 175 | after := sizes(dir, names...) |
| 176 | var moved []string |
| 177 | for _, w := range names { |
| 178 | if after[w] != before[w] { |
| 179 | moved = append(moved, fmt.Sprintf("%s %d->%d", w, before[w], after[w])) |
| 180 | } |
| 181 | } |
| 182 | return moved |
| 183 | } |
| 184 | |
| 185 | // growingFile waits until dir/name exists and grows. |
| 186 | func growingFile(t *testing.T, dir, name string, within time.Duration) { |
| 187 | t.Helper() |
| 188 | before := sizes(dir, name)[name] |
| 189 | for deadline := time.Now().Add(within); ; { |
| 190 | if now := sizes(dir, name)[name]; now > 0 && now != before { |
| 191 | return |
| 192 | } |
| 193 | if time.Now().After(deadline) { |
| 194 | t.Fatalf("%s made no progress in %s", name, within) |
| 195 | } |
| 196 | time.Sleep(5 * time.Millisecond) |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | // join starts the writer named name inside the sandbox's user and pid |
| 201 | // namespaces with nsenter, from outside: a member by namespace whose |
| 202 | // parent (nsenter) is not one. |
| 203 | func join(t *testing.T, p Process, dir, name string) { |
| 204 | t.Helper() |
| 205 | nsenter, err := exec.LookPath("nsenter") |
| 206 | if err != nil { |
| 207 | t.Skip("no nsenter") |
| 208 | } |
| 209 | cmd := exec.Command(nsenter, "--target", strconv.Itoa(p.PID), "--user", "--pid", "--preserve-credentials", "--", "sh", "-c", writerBody, name) |
| 210 | cmd.Env = []string{"PATH=/usr/bin:/bin", "DIR=" + dir} |
| 211 | if err := cmd.Start(); err != nil { |
| 212 | t.Fatal(err) |
| 213 | } |
| 214 | t.Cleanup(func() { cmd.Process.Kill(); cmd.Wait() }) |
| 215 | } |
| 216 | |
| 217 | func writerSandbox(t *testing.T) (Process, string) { |
| 218 | dir := t.TempDir() |
| 219 | p := sandbox(t, dir, writersScript) |
| 220 | allGrowing(t, dir, 10*time.Second) |
| 221 | return p, dir |
| 222 | } |
| 223 | |
| 224 | // Plan task 9: a writer that appends a counter every millisecond, from a |
| 225 | // nested namespace too, makes no progress between pause and resume, and |
| 226 | // all of them go on after. |
| 227 | func TestHoldStopsEveryWriter(t *testing.T) { |
| 228 | p, dir := writerSandbox(t) |
| 229 | var moved []string |
| 230 | called := false |
| 231 | err := holdAmid(p, Bound, func(deadline time.Time) error { |
| 232 | called = true |
| 233 | if time.Until(deadline) <= 0 || time.Until(deadline) > Bound { |
| 234 | t.Errorf("deadline %s away", time.Until(deadline)) |
| 235 | } |
| 236 | moved = movedOver(dir, 300*time.Millisecond) |
| 237 | return nil |
| 238 | }) |
| 239 | if err != nil || !called { |
| 240 | t.Fatalf("Hold: %v (called %v)", err, called) |
| 241 | } |
| 242 | if len(moved) > 0 { |
| 243 | t.Fatalf("writers ran while paused: %v", moved) |
| 244 | } |
| 245 | allGrowing(t, dir, 2*time.Second) |
| 246 | } |
| 247 | |
| 248 | // fn's error comes back as Hold's, after everything is resumed. |
| 249 | func TestHoldReturnsWorkError(t *testing.T) { |
| 250 | p, dir := writerSandbox(t) |
| 251 | want := errors.New("work failed") |
| 252 | if err := holdAmid(p, Bound, func(time.Time) error { return want }); err != want { |
| 253 | t.Fatalf("Hold: %v", err) |
| 254 | } |
| 255 | allGrowing(t, dir, 2*time.Second) |
| 256 | } |
| 257 | |
| 258 | // A panic inside the pause resumes every process before it goes on up. |
| 259 | func TestHoldResumesAfterPanic(t *testing.T) { |
| 260 | p, dir := writerSandbox(t) |
| 261 | var moved []string |
| 262 | func() { |
| 263 | defer func() { |
| 264 | if r := recover(); r != "injected" { |
| 265 | t.Fatalf("recovered %v", r) |
| 266 | } |
| 267 | }() |
| 268 | holdAmid(p, Bound, func(time.Time) error { |
| 269 | moved = movedOver(dir, 100*time.Millisecond) |
| 270 | panic("injected") |
| 271 | }) |
| 272 | t.Fatal("Hold returned past the panic") |
| 273 | }() |
| 274 | if len(moved) > 0 { |
| 275 | t.Fatalf("writers ran while paused: %v", moved) |
| 276 | } |
| 277 | allGrowing(t, dir, 2*time.Second) |
| 278 | } |
| 279 | |
| 280 | // Past the bound the sandbox is resumed even while the work still runs, |
| 281 | // and Hold refuses with ErrBusy once the work returns. |
| 282 | func TestHoldResumesAtTheBound(t *testing.T) { |
| 283 | p, dir := writerSandbox(t) |
| 284 | var early, late []string |
| 285 | start := time.Now() |
| 286 | err := holdAmid(p, 800*time.Millisecond, func(time.Time) error { |
| 287 | early = movedOver(dir, 200*time.Millisecond) |
| 288 | time.Sleep(time.Until(start.Add(900 * time.Millisecond))) |
| 289 | // The work is still running here, past the bound. |
| 290 | late = movedOver(dir, 300*time.Millisecond) |
| 291 | return nil |
| 292 | }) |
| 293 | if !errors.Is(err, ErrBusy) { |
| 294 | t.Fatalf("Hold past its bound: %v", err) |
| 295 | } |
| 296 | if len(early) > 0 { |
| 297 | t.Fatalf("writers ran while paused: %v", early) |
| 298 | } |
| 299 | if len(late) != len(writers) { |
| 300 | t.Fatalf("writers not resumed at the bound while the work ran on: moved %v", late) |
| 301 | } |
| 302 | allGrowing(t, dir, 2*time.Second) |
| 303 | } |
| 304 | |
| 305 | // A bound too short to stop the sandbox refuses with ErrBusy without |
| 306 | // calling the work, and leaves nothing stopped. |
| 307 | func TestHoldBusyWhenStoppingRunsOut(t *testing.T) { |
| 308 | p, dir := writerSandbox(t) |
| 309 | called := false |
| 310 | err := holdAmid(p, time.Nanosecond, func(time.Time) error { called = true; return nil }) |
| 311 | if !errors.Is(err, ErrBusy) || called { |
| 312 | t.Fatalf("Hold: %v (called %v)", err, called) |
| 313 | } |
| 314 | allGrowing(t, dir, 2*time.Second) |
| 315 | if s := stoppedIn(t, p); len(s) > 0 { |
| 316 | t.Fatalf("left stopped: %v", s) |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | // A recorded process that is not the one at that pid (another start |
| 321 | // time, another namespace, or none) is refused with ErrGone, and nothing |
| 322 | // is stopped. |
| 323 | func TestHoldRefusesAnotherProcess(t *testing.T) { |
| 324 | p, dir := writerSandbox(t) |
| 325 | for name, q := range map[string]Process{ |
| 326 | "start time": {PID: p.PID, StartTicks: p.StartTicks + 1, Namespace: p.Namespace}, |
| 327 | "namespace": {PID: p.PID, StartTicks: p.StartTicks, Namespace: "pid:[1]"}, |
| 328 | "no process": {PID: 1 << 30, StartTicks: p.StartTicks}, |
| 329 | "zero": {}, |
| 330 | } { |
| 331 | called := false |
| 332 | err := holdAmid(q, Bound, func(time.Time) error { called = true; return nil }) |
| 333 | if !errors.Is(err, ErrGone) || called { |
| 334 | t.Errorf("%s: Hold %v (called %v)", name, err, called) |
| 335 | } |
| 336 | } |
| 337 | allGrowing(t, dir, 2*time.Second) |
| 338 | } |
| 339 | |
| 340 | // After Hold, no process of the sandbox is left stopped. |
| 341 | func TestHoldLeavesNothingStopped(t *testing.T) { |
| 342 | p, _ := writerSandbox(t) |
| 343 | if err := holdAmid(p, Bound, func(time.Time) error { return nil }); err != nil { |
| 344 | t.Fatal(err) |
| 345 | } |
| 346 | // SIGCONT is delivered at once; give the scheduler a moment. |
| 347 | deadline := time.Now().Add(2 * time.Second) |
| 348 | for { |
| 349 | s := stoppedIn(t, p) |
| 350 | if len(s) == 0 { |
| 351 | return |
| 352 | } |
| 353 | if time.Now().After(deadline) { |
| 354 | t.Fatalf("left stopped: %v", s) |
| 355 | } |
| 356 | time.Sleep(10 * time.Millisecond) |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | // membersOf lists the pids Hold counts as the sandbox's. |
| 361 | func membersOf(t *testing.T, p Process) []int { |
| 362 | t.Helper() |
| 363 | h := newHeld() |
| 364 | defer h.closeNamespaces() |
| 365 | fd, _, err := h.pin(p) |
| 366 | if err != nil { |
| 367 | t.Fatal(err) |
| 368 | } |
| 369 | unix.Close(fd) |
| 370 | d, err := os.Open("/proc") |
| 371 | if err != nil { |
| 372 | t.Fatal(err) |
| 373 | } |
| 374 | names, _ := d.Readdirnames(-1) |
| 375 | d.Close() |
| 376 | var out []int |
| 377 | for _, name := range names { |
| 378 | pid, err := strconv.Atoi(name) |
| 379 | if err != nil { |
| 380 | continue |
| 381 | } |
| 382 | inside, err := h.inSandbox(pid) |
| 383 | if errors.Is(err, errVanished) { |
| 384 | continue |
| 385 | } |
| 386 | if err != nil { |
| 387 | t.Fatalf("placing %d: %v", pid, err) |
| 388 | } |
| 389 | if inside { |
| 390 | out = append(out, pid) |
| 391 | } |
| 392 | } |
| 393 | return out |
| 394 | } |
| 395 | |
| 396 | // stoppedIn lists the sandbox's tasks that read stopped. |
| 397 | func stoppedIn(t *testing.T, p Process) []string { |
| 398 | t.Helper() |
| 399 | var out []string |
| 400 | for _, pid := range membersOf(t, p) { |
| 401 | tasks, _ := os.ReadDir(fmt.Sprintf("/proc/%d/task", pid)) |
| 402 | for _, task := range tasks { |
| 403 | state, _, _, err := readStat(fmt.Sprintf("/proc/%d/task/%s/stat", pid, task.Name())) |
| 404 | if err == nil && (state == 'T' || state == 't') { |
| 405 | out = append(out, strconv.Itoa(pid)+"/"+task.Name()) |
| 406 | } |
| 407 | } |
| 408 | } |
| 409 | return out |
| 410 | } |
| 411 | |
| 412 | // readStat parses the fields Hold reads from a stat file. |
| 413 | func TestReadStat(t *testing.T) { |
| 414 | dir := t.TempDir() |
| 415 | // A command name may hold spaces and parentheses. |
| 416 | 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" |
| 417 | path := filepath.Join(dir, "stat") |
| 418 | if err := os.WriteFile(path, []byte(line+"\n"), 0o600); err != nil { |
| 419 | t.Fatal(err) |
| 420 | } |
| 421 | state, ppid, start, err := readStat(path) |
| 422 | if err != nil || state != 'S' || ppid != 17 || start != 987654 { |
| 423 | t.Fatalf("readStat: %c %d %d %v", state, ppid, start, err) |
| 424 | } |
| 425 | 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"} { |
| 426 | os.WriteFile(path, []byte(bad), 0o600) |
| 427 | if _, _, _, err := readStat(path); err == nil { |
| 428 | t.Errorf("readStat accepted %q", bad) |
| 429 | } |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | // A pass is settled only once every member reads stopped: a member still |
| 434 | // running (here one held but never signalled) keeps it unsettled and is |
| 435 | // sent SIGSTOP again, and a sleeping process does not count as stopped. |
| 436 | func TestPassWaitsForStopped(t *testing.T) { |
| 437 | cmd := exec.Command("sleep", "30") |
| 438 | if err := cmd.Start(); err != nil { |
| 439 | t.Skip("no sleep") |
| 440 | } |
| 441 | defer func() { cmd.Process.Kill(); cmd.Wait() }() |
| 442 | pid := cmd.Process.Pid |
| 443 | var start uint64 |
| 444 | for deadline := time.Now().Add(2 * time.Second); ; { |
| 445 | state, _, s, err := readStat(fmt.Sprintf("/proc/%d/stat", pid)) |
| 446 | if err == nil && state == 'S' { |
| 447 | start = s |
| 448 | break |
| 449 | } |
| 450 | if time.Now().After(deadline) { |
| 451 | t.Fatalf("sleep never slept: %c %v", state, err) |
| 452 | } |
| 453 | time.Sleep(time.Millisecond) |
| 454 | } |
| 455 | fd, err := unix.PidfdOpen(pid, 0) |
| 456 | if err != nil { |
| 457 | t.Fatal(err) |
| 458 | } |
| 459 | m := member{pid, start} |
| 460 | h := plainHeld(t) |
| 461 | h.members[m] = fd |
| 462 | defer h.resume() |
| 463 | if settled, err := h.pass(); err != nil || settled { |
| 464 | t.Fatalf("a sleeping member settled the pass: %v %v", settled, err) |
| 465 | } |
| 466 | for deadline := time.Now().Add(2 * time.Second); ; { |
| 467 | settled, err := h.pass() |
| 468 | if err != nil { |
| 469 | t.Fatal(err) |
| 470 | } |
| 471 | if settled { |
| 472 | break |
| 473 | } |
| 474 | if time.Now().After(deadline) { |
| 475 | t.Fatal("the member never read stopped") |
| 476 | } |
| 477 | time.Sleep(time.Millisecond) |
| 478 | } |
| 479 | if state, _, _, _ := readStat(fmt.Sprintf("/proc/%d/stat", pid)); state != 'T' { |
| 480 | t.Fatalf("settled with the member in state %c", state) |
| 481 | } |
| 482 | h.resume() |
| 483 | for deadline := time.Now().Add(2 * time.Second); ; { |
| 484 | if state, _, _, _ := readStat(fmt.Sprintf("/proc/%d/stat", pid)); state == 'S' { |
| 485 | return |
| 486 | } |
| 487 | if time.Now().After(deadline) { |
| 488 | t.Fatal("not resumed") |
| 489 | } |
| 490 | time.Sleep(time.Millisecond) |
| 491 | } |
| 492 | } |
| 493 | |
| 494 | // F2: a process that joined the sandbox's namespaces from outside (its |
| 495 | // parent is not in the sandbox) is a member and is stopped. |
| 496 | func TestHoldStopsANamespaceJoiner(t *testing.T) { |
| 497 | p, dir := writerSandbox(t) |
| 498 | join(t, p, dir, "joiner") |
| 499 | growingFile(t, dir, "joiner", 10*time.Second) |
| 500 | var moved []string |
| 501 | if err := holdAmid(p, Bound, func(time.Time) error { |
| 502 | moved = movedOver(dir, 300*time.Millisecond, append([]string{"joiner"}, writers...)...) |
| 503 | return nil |
| 504 | }); err != nil { |
| 505 | t.Fatal(err) |
| 506 | } |
| 507 | if len(moved) > 0 { |
| 508 | t.Fatalf("writers ran while paused: %v", moved) |
| 509 | } |
| 510 | growingFile(t, dir, "joiner", 2*time.Second) |
| 511 | } |
| 512 | |
| 513 | // F2, forced: the first process is held but still running when a pass |
| 514 | // starts; after the pass lists /proc it gains a new member (as a fork |
| 515 | // finishing late would) and stops. The listing that pass made cannot have |
| 516 | // seen the new member, so the pass must not settle: the member is found |
| 517 | // by a later listing and is stopped before the pause settles. |
| 518 | func TestPassForkAfterListing(t *testing.T) { |
| 519 | dir := t.TempDir() |
| 520 | p := sandbox(t, dir, "exec sleep 1000") |
| 521 | h := newHeld() |
| 522 | defer h.closeNamespaces() |
| 523 | fd, start, err := h.pin(p) |
| 524 | if err != nil { |
| 525 | t.Fatal(err) |
| 526 | } |
| 527 | h.members[member{p.PID, start}] = fd // held, not yet signalled |
| 528 | defer h.resume() |
| 529 | fired := false |
| 530 | testHook = func(point string, _ int) { |
| 531 | if point != "scanned" || fired { |
| 532 | return |
| 533 | } |
| 534 | fired = true |
| 535 | join(t, p, dir, "late") |
| 536 | growingFile(t, dir, "late", 10*time.Second) |
| 537 | unix.PidfdSendSignal(fd, unix.SIGSTOP, nil, 0) |
| 538 | for deadline := time.Now().Add(2 * time.Second); ; { |
| 539 | if state, _, _, _ := readStat(fmt.Sprintf("/proc/%d/stat", p.PID)); state == 'T' { |
| 540 | break |
| 541 | } |
| 542 | if time.Now().After(deadline) { |
| 543 | t.Fatal("the first process never stopped") |
| 544 | } |
| 545 | time.Sleep(time.Millisecond) |
| 546 | } |
| 547 | } |
| 548 | defer func() { testHook = nil }() |
| 549 | for deadline := time.Now().Add(5 * time.Second); ; { |
| 550 | settled, err := h.pass() |
| 551 | if err != nil { |
| 552 | t.Fatal(err) |
| 553 | } |
| 554 | if settled { |
| 555 | break |
| 556 | } |
| 557 | if time.Now().After(deadline) { |
| 558 | t.Fatal("never settled") |
| 559 | } |
| 560 | time.Sleep(time.Millisecond) |
| 561 | } |
| 562 | if !fired { |
| 563 | t.Fatal("the hook never ran") |
| 564 | } |
| 565 | if moved := movedOver(dir, 300*time.Millisecond, "late"); len(moved) > 0 { |
| 566 | t.Fatalf("a member made after the listing ran while settled: %v", moved) |
| 567 | } |
| 568 | h.resume() |
| 569 | growingFile(t, dir, "late", 2*time.Second) |
| 570 | } |
| 571 | |
| 572 | // F2, forced: a daemon whose parent is killed while a pass lists /proc |
| 573 | // (so it is reparented mid-scan) is still a member and is stopped. The |
| 574 | // first process outlives the parent (a plain wait would return when the |
| 575 | // parent is killed and end the namespace, the daemon with it). |
| 576 | func TestHoldStopsAReparentedDaemon(t *testing.T) { |
| 577 | dir := t.TempDir() |
| 578 | p := sandbox(t, dir, `sh -c 'sh -c "$W" daemon & exec sleep 1000' & while :; do wait; sleep 0.1; done`) |
| 579 | growingFile(t, dir, "daemon", 10*time.Second) |
| 580 | parent := 0 |
| 581 | for _, pid := range membersOf(t, p) { |
| 582 | if cl, _ := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid)); string(cl) == "sleep\x001000\x00" { |
| 583 | parent = pid |
| 584 | } |
| 585 | } |
| 586 | if parent == 0 { |
| 587 | t.Fatal("no intermediate parent") |
| 588 | } |
| 589 | fired := false |
| 590 | testHook = func(point string, _ int) { |
| 591 | if point == "scanned" && !fired { |
| 592 | fired = true |
| 593 | syscall.Kill(parent, syscall.SIGKILL) |
| 594 | } |
| 595 | } |
| 596 | defer func() { testHook = nil }() |
| 597 | var moved []string |
| 598 | if err := holdAmid(p, Bound, func(time.Time) error { |
| 599 | moved = movedOver(dir, 300*time.Millisecond, "daemon") |
| 600 | return nil |
| 601 | }); err != nil { |
| 602 | t.Fatal(err) |
| 603 | } |
| 604 | if !fired || len(moved) > 0 { |
| 605 | t.Fatalf("hook fired %v; the reparented daemon ran while paused: %v", fired, moved) |
| 606 | } |
| 607 | growingFile(t, dir, "daemon", 2*time.Second) |
| 608 | } |
| 609 | |
| 610 | // F3: the watchdog resumes (and closes every pidfd) between a member's |
| 611 | // running read and its retry SIGSTOP, and the descriptor number is reused |
| 612 | // by a fresh pidfd for the same process. The retry must not signal: the |
| 613 | // member keeps running. |
| 614 | func TestRetryAfterTheWatchdogDoesNotStop(t *testing.T) { |
| 615 | cmd := exec.Command("sleep", "30") |
| 616 | if err := cmd.Start(); err != nil { |
| 617 | t.Skip("no sleep") |
| 618 | } |
| 619 | defer func() { cmd.Process.Kill(); cmd.Wait() }() |
| 620 | pid := cmd.Process.Pid |
| 621 | var start uint64 |
| 622 | for deadline := time.Now().Add(2 * time.Second); ; { |
| 623 | state, _, s, err := readStat(fmt.Sprintf("/proc/%d/stat", pid)) |
| 624 | if err == nil && state == 'S' { |
| 625 | start = s |
| 626 | break |
| 627 | } |
| 628 | if time.Now().After(deadline) { |
| 629 | t.Fatalf("sleep never slept: %c %v", state, err) |
| 630 | } |
| 631 | time.Sleep(time.Millisecond) |
| 632 | } |
| 633 | fd, err := unix.PidfdOpen(pid, 0) |
| 634 | if err != nil { |
| 635 | t.Fatal(err) |
| 636 | } |
| 637 | h := plainHeld(t) |
| 638 | h.members[member{pid, start}] = fd |
| 639 | reused := -1 |
| 640 | testHook = func(point string, _ int) { |
| 641 | if point == "retry" { |
| 642 | h.resume() |
| 643 | reused, _ = unix.PidfdOpen(pid, 0) |
| 644 | } |
| 645 | } |
| 646 | defer func() { testHook = nil; unix.Close(reused) }() |
| 647 | if _, err := h.pass(); !errors.Is(err, ErrBusy) { |
| 648 | t.Fatalf("pass after resume: %v", err) |
| 649 | } |
| 650 | time.Sleep(50 * time.Millisecond) |
| 651 | if state, _, _, _ := readStat(fmt.Sprintf("/proc/%d/stat", pid)); state == 'T' { |
| 652 | t.Fatalf("stopped after the sandbox was resumed (reused descriptor %d, first %d)", reused, fd) |
| 653 | } |
| 654 | } |
| 655 | |
| 656 | // F5: a copy that runs past the deadline while the watchdog has not run |
| 657 | // (delayed here) is still refused, and the sandbox is resumed. |
| 658 | func TestHoldBusyWhenTheWatchdogIsLate(t *testing.T) { |
| 659 | p, dir := writerSandbox(t) |
| 660 | afterFunc = func(time.Duration, func()) *time.Timer { return time.AfterFunc(time.Hour, func() {}) } |
| 661 | defer func() { afterFunc = time.AfterFunc }() |
| 662 | err := holdAmid(p, 300*time.Millisecond, func(deadline time.Time) error { |
| 663 | time.Sleep(time.Until(deadline) + 50*time.Millisecond) |
| 664 | return nil |
| 665 | }) |
| 666 | if !errors.Is(err, ErrBusy) { |
| 667 | t.Fatalf("an overdue copy: %v", err) |
| 668 | } |
| 669 | allGrowing(t, dir, 2*time.Second) |
| 670 | } |
| 671 | |
| 672 | // plainHeld is a held for members outside any sandbox (plain test |
| 673 | // processes): no namespace counts as the sandbox's, so a pass's listing |
| 674 | // adds nothing and only its retained members matter. |
| 675 | func plainHeld(t *testing.T) *held { |
| 676 | t.Helper() |
| 677 | h := newHeld() |
| 678 | self, err := unix.Open("/proc/self/ns/pid", unix.O_RDONLY|unix.O_CLOEXEC, 0) |
| 679 | if err != nil { |
| 680 | t.Fatal(err) |
| 681 | } |
| 682 | h.ours, _ = inode(self) |
| 683 | unix.Close(self) |
| 684 | h.rootDepth = 1 << 20 |
| 685 | t.Cleanup(h.closeNamespaces) |
| 686 | return h |
| 687 | } |
| 688 | |
| 689 | // descendant: pid is root or one of its descendants (by parent pid). |
| 690 | func descendant(pid, root int) bool { |
| 691 | for range 64 { |
| 692 | if pid == root { |
| 693 | return true |
| 694 | } |
| 695 | _, ppid, _, err := readStat(fmt.Sprintf("/proc/%d/stat", pid)) |
| 696 | if err != nil || ppid <= 1 { |
| 697 | return false |
| 698 | } |
| 699 | pid = ppid |
| 700 | } |
| 701 | return false |
| 702 | } |
| 703 | |
| 704 | // unreadableWhile makes the pid namespace of every process unreadable for |
| 705 | // which is returns true, as another user's or a non-dumpable process's is |
| 706 | // (hosted CI's other sandboxes: containment's namespace helper). |
| 707 | func unreadableWhile(t *testing.T, is func(pid int) bool) { |
| 708 | t.Helper() |
| 709 | testUnreadable = is |
| 710 | t.Cleanup(func() { testUnreadable = nil }) |
| 711 | } |
| 712 | |
| 713 | // refusedUnreadable: Hold refuses (ErrBusy, naming the unreadable |
| 714 | // process) without calling the work, and every writer of dirs goes on. |
| 715 | func refusedUnreadable(t *testing.T, p Process, dirs ...string) { |
| 716 | t.Helper() |
| 717 | called := false |
| 718 | err := Hold(p, Bound, func(time.Time) error { called = true; return nil }) |
| 719 | if !errors.Is(err, ErrBusy) || called || !strings.Contains(err.Error(), "pid namespace is unreadable") { |
| 720 | t.Fatalf("Hold: %v (called %v)", err, called) |
| 721 | } |
| 722 | for _, dir := range dirs { |
| 723 | allGrowing(t, dir, 2*time.Second) |
| 724 | } |
| 725 | } |
| 726 | |
| 727 | // Another sandbox of ours, as deep, whose processes' namespaces cannot be |
| 728 | // read cannot be told from this one's members: the pause refuses rather |
| 729 | // than guess, and leaves both running. (Placing such a process by its |
| 730 | // parent needs validated ancestry: discussion 105.) |
| 731 | func TestHoldRefusesAnUnreadableSandbox(t *testing.T) { |
| 732 | p, dir := writerSandbox(t) |
| 733 | other, otherDir := writerSandbox(t) |
| 734 | unreadableWhile(t, func(pid int) bool { return descendant(pid, other.PID) }) |
| 735 | refusedUnreadable(t, p, dir, otherDir) |
| 736 | } |
| 737 | |
| 738 | // Members whose namespaces cannot be read (the first process's can: it |
| 739 | // is pinned) refuse the pause too, and nothing is left stopped. |
| 740 | func TestHoldRefusesUnreadableMembers(t *testing.T) { |
| 741 | p, dir := writerSandbox(t) |
| 742 | unreadableWhile(t, func(pid int) bool { return pid != p.PID && descendant(pid, p.PID) }) |
| 743 | refusedUnreadable(t, p, dir) |
| 744 | } |
| 745 | |
| 746 | // foreignUnreadable is Hold's refusal naming a process whose namespace |
| 747 | // cannot be read. |
| 748 | var foreignUnreadable = regexp.MustCompile(`: (\d+) \(.*\) is ours but its pid namespace is unreadable`) |
| 749 | |
| 750 | // holdAmid is Hold on a host where other tests' sandboxes come and go: |
| 751 | // a refusal naming an unreadable process outside p's sandbox (another |
| 752 | // test's) is tried again, for up to 20 seconds, and anything else is |
| 753 | // Hold's own result. The pause refuses rather than guess (discussion |
| 754 | // 105); what these tests prove is what a pause that holds does. |
| 755 | func holdAmid(p Process, bound time.Duration, fn func(time.Time) error) error { |
| 756 | for deadline := time.Now().Add(20 * time.Second); ; { |
| 757 | err := Hold(p, bound, fn) |
| 758 | m := foreignUnreadable.FindStringSubmatch(fmt.Sprint(err)) |
| 759 | if m == nil || time.Now().After(deadline) { |
| 760 | return err |
| 761 | } |
| 762 | if pid, _ := strconv.Atoi(m[1]); descendant(pid, p.PID) { |
| 763 | return err |
| 764 | } |
| 765 | time.Sleep(200 * time.Millisecond) |
| 766 | } |
| 767 | } |
| 768 | |