| 1 | package jobs |
| 2 | |
| 3 | import ( |
| 4 | "os" |
| 5 | "os/exec" |
| 6 | "runtime" |
| 7 | "testing" |
| 8 | "time" |
| 9 | ) |
| 10 | |
| 11 | // A running record reads as died once its process is gone, or once its PID |
| 12 | // names a process that started at another time (a reused PID). |
| 13 | func TestRunningRecordDiesWithItsProcess(t *testing.T) { |
| 14 | if runtime.GOOS != "linux" { |
| 15 | t.Skip("start times come from /proc") |
| 16 | } |
| 17 | s := NewStore(t.TempDir()) |
| 18 | live := &Job{ID: "consult-live", Kind: KindConsult, Backend: "codex"} |
| 19 | if err := s.Start(live); err != nil { |
| 20 | t.Fatal(err) |
| 21 | } |
| 22 | if live.PID != os.Getpid() || live.PIDStart == "" { |
| 23 | t.Fatalf("start didn't record this process: %+v", live) |
| 24 | } |
| 25 | |
| 26 | exited := exec.Command("true") |
| 27 | if err := exited.Run(); err != nil { |
| 28 | t.Fatal(err) |
| 29 | } |
| 30 | gone := &Job{ID: "consult-gone", Kind: KindConsult, Status: Running, StartedAt: time.Now(), PID: exited.Process.Pid, PIDStart: "1"} |
| 31 | reused := &Job{ID: "consult-reused", Kind: KindConsult, Status: Running, StartedAt: time.Now(), PID: os.Getpid(), PIDStart: live.PIDStart + "0"} |
| 32 | for _, j := range []*Job{gone, reused} { |
| 33 | if err := s.Save(j); err != nil { |
| 34 | t.Fatal(err) |
| 35 | } |
| 36 | } |
| 37 | for id, want := range map[string]Status{"consult-live": Running, "consult-gone": Died, "consult-reused": Died} { |
| 38 | j, err := s.Load(id) |
| 39 | if err != nil { |
| 40 | t.Fatal(err) |
| 41 | } |
| 42 | if j.Status != want { |
| 43 | t.Errorf("%s reads %q, want %q", id, j.Status, want) |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | // The command name in /proc/<pid>/stat may hold spaces and parentheses; the |
| 49 | // fields are counted after the last ")". A zombie has exited. |
| 50 | func TestParseStatSkipsTheCommandName(t *testing.T) { |
| 51 | const tail = " 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 777 19 20" |
| 52 | for stat, want := range map[string]string{ |
| 53 | "4242 (klaus) S" + tail: "777", |
| 54 | "4242 (a b) (c) ) S" + tail: "777", |
| 55 | "4242 (klaus) Z" + tail: "", |
| 56 | "4242 (klaus) S 1 2": "", |
| 57 | "garbage without a paren S 1 2": "", |
| 58 | } { |
| 59 | got, ok := parseStat(stat) |
| 60 | if got != want || ok != (want != "") { |
| 61 | t.Errorf("parseStat(%q) = %q, %v; want %q", stat, got, ok, want) |
| 62 | } |
| 63 | } |
| 64 | } |