gunk-dev/the-valley

lingering.go

sourcecaaa5bee5e11main's published tip history
7.8 KiB
1package cmd
2
3import (
4 "errors"
5 "fmt"
6 "io/fs"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "sort"
11 "strconv"
12 "strings"
13)
14
15// lingeringProcesses names the commands still running with a working directory
16// inside dir: background work a worker left when its turn ended. Workers'
17// tools often start commands in a new session, so the worktree, not the
18// process group, ties them to the run. This process, its ancestors (the
19// pane's shell), and processes attached to another terminal (someone's
20// interactive shell) are skipped. It reads /proc where there is one, as on
21// Linux, and asks ps and lsof where there is none, as on macOS. An error
22// says some or all processes could not be read, which is not the same as
23// none running. A worktree that is gone holds nothing.
24func lingeringProcesses(dir string) ([]string, error) {
25 root, err := filepath.EvalSymlinks(dir)
26 if errors.Is(err, fs.ErrNotExist) {
27 return nil, nil
28 }
29 if err != nil {
30 return nil, err
31 }
32 read := procProcesses
33 if _, err := os.Stat("/proc/self/stat"); err != nil {
34 read = psProcesses
35 }
36 procs, err := read()
37 if err != nil {
38 return nil, err
39 }
40 return lingering(root, os.Getpid(), procs)
41}
42
43// process is what lingering weighs of a process: its parent, its
44// controlling terminal ("" for none), its command name, and its working
45// directory ("" where it cannot be read). Where cwdPart is set, cwd holds
46// only the start of the working directory, as far as lsofName could read it
47// for certain.
48type process struct {
49 ppid int
50 tty string
51 comm string
52 cwd string
53 cwdPart bool
54}
55
56// lingering names the commands in procs running with a working directory at
57// or under root, other than self, its ancestors, and processes attached to a
58// terminal that is not self's. A process whose working directory may or may
59// not be under root is an error, which says the processes could not all be
60// read; the commands known to be under root are named beside it.
61func lingering(root string, self int, procs map[int]process) ([]string, error) {
62 skip := map[int]bool{}
63 for pid := self; pid > 1 && !skip[pid]; pid = procs[pid].ppid {
64 skip[pid] = true
65 }
66 ownTTY := procs[self].tty
67 under := root + string(filepath.Separator)
68 seen := map[string]bool{}
69 var names, unclear []string
70 for pid, p := range procs {
71 if skip[pid] || p.comm == "" {
72 continue
73 }
74 if p.tty != "" && p.tty != ownTTY {
75 continue
76 }
77 inside := strings.HasPrefix(p.cwd, under) || !p.cwdPart && p.cwd == root
78 if !inside {
79 // The start of a directory that could still continue into
80 // root is unknown; any other is outside it.
81 if p.cwdPart && strings.HasPrefix(under, p.cwd) {
82 unclear = append(unclear, fmt.Sprintf("%s (pid %d)", p.comm, pid))
83 }
84 continue
85 }
86 if seen[p.comm] {
87 continue
88 }
89 seen[p.comm] = true
90 names = append(names, p.comm)
91 }
92 sort.Strings(names)
93 if len(unclear) > 0 {
94 sort.Strings(unclear)
95 return names, fmt.Errorf("lsof's listing leaves unclear whether these work under %s: %s", root, strings.Join(unclear, ", "))
96 }
97 return names, nil
98}
99
100// procProcesses reads every process in /proc.
101func procProcesses() (map[int]process, error) {
102 entries, err := os.ReadDir("/proc")
103 if err != nil {
104 return nil, err
105 }
106 procs := map[int]process{}
107 for _, e := range entries {
108 pid, err := strconv.Atoi(e.Name())
109 if err != nil {
110 continue
111 }
112 data, err := os.ReadFile(filepath.Join("/proc", e.Name(), "stat"))
113 if err != nil {
114 continue
115 }
116 ppid, tty, ok := parseProcStat(string(data))
117 if !ok {
118 continue
119 }
120 cwd, _ := os.Readlink(filepath.Join("/proc", e.Name(), "cwd"))
121 comm, _ := os.ReadFile(filepath.Join("/proc", e.Name(), "comm"))
122 procs[pid] = process{ppid: ppid, tty: tty, comm: strings.TrimSpace(string(comm)), cwd: cwd}
123 }
124 return procs, nil
125}
126
127// parseProcStat returns a process's parent PID and controlling terminal
128// ("" for none) from its /proc/<pid>/stat line.
129func parseProcStat(s string) (ppid int, tty string, ok bool) {
130 // The command name may contain spaces and parentheses; fields resume
131 // after the last ')': state, ppid, pgrp, session, tty_nr, ...
132 f := strings.Fields(s[strings.LastIndexByte(s, ')')+1:])
133 if len(f) < 5 {
134 return 0, "", false
135 }
136 ppid, _ = strconv.Atoi(f[1])
137 if f[4] != "0" {
138 tty = f[4]
139 }
140 return ppid, tty, true
141}
142
143// psProcesses asks ps for every process's parent, terminal and command name,
144// and lsof for the working directories it can read. Each -o takes one
145// keyword: BSD ps reads the rest of an argument after "=" as the header.
146func psProcesses() (map[int]process, error) {
147 out, err := exec.Command("ps", "-A", "-o", "pid=", "-o", "ppid=", "-o", "tty=", "-o", "ucomm=").Output()
148 if err != nil {
149 return nil, fmt.Errorf("ps: %w", err)
150 }
151 // lsof exits 1 when some process's directory could not be read, and
152 // still lists the rest. It lists this process's own directory, so a run
153 // that lists nothing failed, as does one that ends any other way. In the
154 // C locale it prints every byte outside printable ASCII as an escape, so
155 // what it prints does not hang on the locale's idea of printable.
156 lsof := exec.Command("lsof", "-w", "-n", "-P", "-d", "cwd", "-F", "pn")
157 lsof.Env = append(os.Environ(), "LC_ALL=C")
158 cwds, err := lsof.Output()
159 var exit *exec.ExitError
160 if err != nil && !(errors.As(err, &exit) && exit.ExitCode() == 1 && len(cwds) > 0) {
161 return nil, fmt.Errorf("lsof: %w", err)
162 }
163 return fromPSAndLsof(string(out), string(cwds)), nil
164}
165
166// fromPSAndLsof reads ps's pid, ppid, tty and ucomm columns, and lsof's -F
167// pn listing of cwd descriptors, in which a p line names a process and the
168// n line after it its working directory, escaped as lsofName reads it. A
169// terminal of "?" (Linux) or "??" (macOS) is none.
170func fromPSAndLsof(ps, lsof string) map[int]process {
171 procs := map[int]process{}
172 for _, line := range strings.Split(ps, "\n") {
173 f := strings.Fields(line)
174 if len(f) < 4 {
175 continue
176 }
177 pid, err := strconv.Atoi(f[0])
178 if err != nil {
179 continue
180 }
181 ppid, err := strconv.Atoi(f[1])
182 if err != nil {
183 continue
184 }
185 tty := f[2]
186 if strings.Trim(tty, "?") == "" {
187 tty = ""
188 }
189 procs[pid] = process{ppid: ppid, tty: tty, comm: strings.Join(f[3:], " ")}
190 }
191 pid := 0
192 for _, line := range strings.Split(lsof, "\n") {
193 if line == "" {
194 continue
195 }
196 switch line[0] {
197 case 'p':
198 pid, _ = strconv.Atoi(line[1:])
199 case 'n':
200 if p, ok := procs[pid]; ok {
201 p.cwd, p.cwdPart = lsofName(line[1:])
202 procs[pid] = p
203 }
204 }
205 }
206 return procs
207}
208
209// lsofName decodes a name as lsof prints it: \\ for a backslash; \b, \f, \n,
210// \r and \t; ^ and the character 0x40 above it for any other control (^A for
211// 0x01); ^? for 0xff where char is unsigned; and \xNN for any other byte the
212// locale cannot print (safepup and safestrprt in lsof's lib/misc.c, alike in
213// the 4.91 macOS ships and in 4.99). lsof prints ^ as itself, so ^A may be a
214// control or ^ and A, and an escape lsof never prints has no reading. The
215// name stops at the first of either: part is set, and name holds what
216// precedes it.
217func lsofName(s string) (name string, part bool) {
218 escaped := map[byte]byte{'\\': '\\', 'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t'}
219 var b strings.Builder
220 for i := 0; i < len(s); i++ {
221 c := s[i]
222 if c == '^' && i+1 < len(s) && caretControl(s[i+1]) {
223 return b.String(), true
224 }
225 if c != '\\' {
226 b.WriteByte(c)
227 continue
228 }
229 if i+1 == len(s) {
230 return b.String(), true
231 }
232 i++
233 if e, ok := escaped[s[i]]; ok {
234 b.WriteByte(e)
235 continue
236 }
237 if s[i] != 'x' || i+3 > len(s) {
238 return b.String(), true
239 }
240 v, err := strconv.ParseUint(s[i+1:i+3], 16, 8)
241 if err != nil {
242 return b.String(), true
243 }
244 b.WriteByte(byte(v))
245 i += 2
246 }
247 return b.String(), false
248}
249
250// caretControl says whether lsof prints a control as ^ and c. ^H, ^I, ^J, ^L
251// and ^M are not among them: those controls print as \b, \t, \n, \f and \r.
252func caretControl(c byte) bool {
253 return c == '?' || c > '@' && c <= '_' && !strings.ContainsRune("HIJLM", rune(c))
254}