@kaynooo/cli-proc 0.8.3 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/manage.ts ADDED
@@ -0,0 +1,333 @@
1
+ import type { ExitRow } from '@kaynooo/cli-kit'
2
+ import type { ProcInfo } from './read'
3
+ import process from 'node:process'
4
+ import { badUsage, duration, fail, formatFileSize, formatSeconds, jsonOption, paint, parse, printJson, problem, table, truncate, watching, watchOption, wholeNumber, withoutWatch } from '@kaynooo/cli-kit'
5
+ import { confirm } from '@kaynooo/cli-kit/prompt'
6
+ import { protectionOf, terminate } from './kill'
7
+ import { maskArgs } from './mask'
8
+ import { ancestry, fdCount, snapshot } from './read'
9
+
10
+ const DIGITS = /^\d+$/
11
+
12
+ function commandOf(proc: ProcInfo): string {
13
+ return maskArgs(proc.args).join(' ') || `[${proc.comm}]`
14
+ }
15
+
16
+ const LS_USAGE = `proc ls [pattern]: lists processes matching an optional pattern (substring or regex) on command, comm or cwd`
17
+ const LS_EXITS: ExitRow[] = [[0, 'listed matching processes'], [1, 'no process matched'], [2, 'a usage error']]
18
+ const LS_OPTIONS = {
19
+ all: { type: 'boolean', short: 'a', description: 'include processes of other users (default: calling user only)' },
20
+ sort: { type: 'string', short: 's', choices: ['rss', 'pid', 'age'] as const, description: 'sort order: rss (default), pid, or age' },
21
+ limit: { type: 'string', short: 'n', description: 'maximum rows to print (50)' },
22
+ json: jsonOption('[{pid, ppid, comm, command, cwd, rss, ageSeconds}]'),
23
+ } as const
24
+
25
+ export async function lsCmd(args: string[]): Promise<number> {
26
+ const { values, positionals } = parse(args, LS_USAGE, LS_OPTIONS, {
27
+ exits: LS_EXITS,
28
+ positionals: ['[pattern]'],
29
+ examples: ['proc ls', 'proc ls vite', 'proc find bun --sort age'],
30
+ })
31
+ const [pattern] = positionals
32
+ let regex: RegExp | undefined
33
+
34
+ if (pattern !== undefined) {
35
+ try {
36
+ regex = new RegExp(pattern, 'i')
37
+ }
38
+ catch (error) {
39
+ badUsage(`invalid pattern: ${error instanceof Error ? error.message : String(error)}`)
40
+ }
41
+ }
42
+
43
+ const uid = process.getuid?.() ?? -1
44
+ const all = await snapshot('/proc', owner => values.all === true || owner === uid)
45
+ const now = Date.now()
46
+ const filtered = all
47
+ .filter(proc => (values.all === true || proc.uid === uid) && proc.pid !== process.pid)
48
+ .filter((proc) => {
49
+ if (regex === undefined)
50
+ return true
51
+
52
+ return regex.test(commandOf(proc)) || regex.test(proc.comm) || (proc.cwd !== undefined && regex.test(proc.cwd))
53
+ })
54
+
55
+ const sortBy = values.sort ?? 'rss'
56
+
57
+ filtered.sort((a, b) => {
58
+ if (sortBy === 'pid')
59
+ return a.pid - b.pid
60
+
61
+ return sortBy === 'age' ? a.startMs - b.startMs : b.rss - a.rss || a.pid - b.pid
62
+ })
63
+
64
+ if (pattern !== undefined && filtered.length === 0) {
65
+ if (values.json === true)
66
+ printJson([])
67
+ else
68
+ problem(`no process matched ${pattern}`)
69
+
70
+ return 1
71
+ }
72
+
73
+ const limit = wholeNumber(values.limit, 'limit', 50, 1)
74
+ const shown = filtered.slice(0, limit)
75
+
76
+ if (values.json === true) {
77
+ printJson(shown.map(proc => ({ pid: proc.pid, ppid: proc.ppid, comm: proc.comm, command: commandOf(proc), cwd: proc.cwd, rss: proc.rss, ageSeconds: Math.max(0, Math.round((now - proc.startMs) / 1000)) })))
78
+
79
+ return 0
80
+ }
81
+
82
+ const colors = paint(process.stdout)
83
+
84
+ console.log(table([
85
+ ['PID', 'PPID', 'RSS', 'AGE', 'COMMAND', 'CWD'],
86
+ ...shown.map(proc => [
87
+ colors.cyan(String(proc.pid)),
88
+ colors.dim(String(proc.ppid)),
89
+ formatFileSize(proc.rss),
90
+ formatSeconds(Math.max(0, (now - proc.startMs) / 1000)),
91
+ truncate(commandOf(proc), 60),
92
+ colors.dim(proc.cwd ?? '-'),
93
+ ]),
94
+ ], { header: true, align: ['right', 'right', 'right', 'right', 'left', 'left'] }))
95
+
96
+ return 0
97
+ }
98
+
99
+ const TREE_USAGE = `proc tree [pid]: prints the process hierarchy rooted at pid (or the calling user's top-level processes)`
100
+ const TREE_EXITS: ExitRow[] = [[0, 'printed process tree'], [1, 'no process has this pid'], [2, 'a usage error']]
101
+ const TREE_OPTIONS = {
102
+ all: { type: 'boolean', short: 'a', description: 'include processes of all users when no pid is given' },
103
+ json: jsonOption('[{pid, ppid, comm, command, rss, children: [...]}]'),
104
+ } as const
105
+
106
+ interface TreeNode {
107
+ pid: number
108
+ ppid: number
109
+ comm: string
110
+ command: string
111
+ rss: number
112
+ children: TreeNode[]
113
+ }
114
+
115
+ export async function treeCmd(args: string[]): Promise<number> {
116
+ const { values, positionals } = parse(args, TREE_USAGE, TREE_OPTIONS, {
117
+ exits: TREE_EXITS,
118
+ positionals: ['[pid]'],
119
+ examples: ['proc tree', 'proc tree 1234'],
120
+ })
121
+ const [given] = positionals
122
+
123
+ if (given !== undefined && !DIGITS.test(given))
124
+ fail(`the pid takes a number, not ${given}`, 2)
125
+
126
+ const uid = process.getuid?.() ?? -1
127
+ const all = await snapshot('/proc', owner => owner === uid)
128
+ const byPid = new Map(all.map(proc => [proc.pid, proc]))
129
+ const childrenByPid = new Map<number, ProcInfo[]>()
130
+
131
+ for (const proc of all)
132
+ childrenByPid.set(proc.ppid, [...(childrenByPid.get(proc.ppid) ?? []), proc])
133
+
134
+ for (const list of childrenByPid.values())
135
+ list.sort((a, b) => a.pid - b.pid)
136
+
137
+ const build = (proc: ProcInfo, seen = new Set<number>()): TreeNode => {
138
+ seen.add(proc.pid)
139
+
140
+ return {
141
+ pid: proc.pid,
142
+ ppid: proc.ppid,
143
+ comm: proc.comm,
144
+ command: commandOf(proc),
145
+ rss: proc.rss,
146
+ children: (childrenByPid.get(proc.pid) ?? []).filter(child => !seen.has(child.pid)).map(child => build(child, seen)),
147
+ }
148
+ }
149
+
150
+ let roots: TreeNode[]
151
+
152
+ if (given !== undefined) {
153
+ const rootProc = byPid.get(Number(given))
154
+
155
+ if (rootProc === undefined)
156
+ return fail(`no process with pid ${given}`, 1)
157
+
158
+ roots = [build(rootProc)]
159
+ }
160
+ else {
161
+ const visible = all.filter(proc => values.all === true || proc.uid === uid)
162
+ const visiblePids = new Set(visible.map(proc => proc.pid))
163
+
164
+ roots = visible.filter(proc => !visiblePids.has(proc.ppid)).sort((a, b) => a.pid - b.pid).map(proc => build(proc))
165
+ }
166
+
167
+ if (values.json === true) {
168
+ printJson(roots)
169
+
170
+ return 0
171
+ }
172
+
173
+ const colors = paint(process.stdout)
174
+ const renderNode = (node: TreeNode, prefix: string, isLast: boolean, isRoot: boolean): void => {
175
+ let branch = ''
176
+
177
+ if (!isRoot)
178
+ branch = isLast ? '└─ ' : '├─ '
179
+
180
+ console.log(`${prefix}${branch}${colors.cyan(String(node.pid))} ${node.comm} ${colors.dim(formatFileSize(node.rss))} ${colors.dim(truncate(node.command, 70))}`)
181
+
182
+ const nextPrefix = isRoot ? '' : `${prefix}${isLast ? ' ' : '│ '}`
183
+
184
+ for (const [idx, child] of node.children.entries())
185
+ renderNode(child, nextPrefix, idx === node.children.length - 1, false)
186
+ }
187
+
188
+ for (const root of roots)
189
+ renderNode(root, '', true, true)
190
+
191
+ return 0
192
+ }
193
+
194
+ const TOP_USAGE = `proc top [options]: shows the heaviest processes by resident memory, open file descriptors, or age`
195
+ const TOP_EXITS: ExitRow[] = [[0, 'listed top processes'], [2, 'a usage error']]
196
+ const TOP_OPTIONS = {
197
+ by: { type: 'string', choices: ['rss', 'fds', 'age'] as const, description: 'rank by: rss (default), fds, or age' },
198
+ limit: { type: 'string', short: 'n', description: 'how many processes to show (15)' },
199
+ all: { type: 'boolean', short: 'a', description: 'include processes of other users' },
200
+ watch: watchOption('top processes'),
201
+ json: jsonOption('[{pid, comm, command, rss, fds, ageSeconds, cwd}]'),
202
+ } as const
203
+
204
+ export async function topCmd(args: string[]): Promise<number> {
205
+ const { values } = parse(args, TOP_USAGE, TOP_OPTIONS, {
206
+ exits: TOP_EXITS,
207
+ examples: ['proc top', 'proc top --by fds -n 10', 'proc top --watch 2s'],
208
+ })
209
+
210
+ if (values.watch !== undefined)
211
+ return watching(values.watch, async () => topCmd(withoutWatch(args)))
212
+
213
+ const uid = process.getuid?.() ?? -1
214
+ const by = values.by ?? 'rss'
215
+ const limit = wholeNumber(values.limit, 'limit', 15, 1)
216
+ const now = Date.now()
217
+ const procs = (await snapshot('/proc', owner => owner === uid)).filter(proc => values.all === true || proc.uid === uid)
218
+ const rows = await Promise.all(procs.map(async proc => ({
219
+ pid: proc.pid,
220
+ comm: proc.comm,
221
+ command: commandOf(proc),
222
+ rss: proc.rss,
223
+ fds: by === 'fds' ? (await fdCount(proc.pid) ?? 0) : undefined,
224
+ ageSeconds: Math.max(0, Math.round((now - proc.startMs) / 1000)),
225
+ cwd: proc.cwd,
226
+ })))
227
+
228
+ rows.sort((a, b) => {
229
+ if (by === 'fds')
230
+ return (b.fds ?? 0) - (a.fds ?? 0) || b.rss - a.rss
231
+
232
+ return by === 'age' ? b.ageSeconds - a.ageSeconds || b.rss - a.rss : b.rss - a.rss || a.pid - b.pid
233
+ })
234
+
235
+ const shown = rows.slice(0, limit)
236
+
237
+ if (values.json === true) {
238
+ printJson(shown)
239
+
240
+ return 0
241
+ }
242
+
243
+ const colors = paint(process.stdout)
244
+ const header = by === 'fds' ? ['PID', 'FDS', 'RSS', 'AGE', 'COMMAND'] : ['PID', 'RSS', 'AGE', 'COMMAND']
245
+
246
+ console.log(table([
247
+ header,
248
+ ...shown.map(row => by === 'fds'
249
+ ? [colors.cyan(String(row.pid)), String(row.fds ?? 0), formatFileSize(row.rss), formatSeconds(row.ageSeconds), truncate(row.command, 70)]
250
+ : [colors.cyan(String(row.pid)), formatFileSize(row.rss), formatSeconds(row.ageSeconds), truncate(row.command, 70)]),
251
+ ], { header: true, align: by === 'fds' ? ['right', 'right', 'right', 'right', 'left'] : ['right', 'right', 'right', 'left'] }))
252
+
253
+ return 0
254
+ }
255
+
256
+ const KILL_USAGE = `proc kill <pid>...: safely stops one or more processes owned by the calling user (SIGTERM, with --force escalating to SIGKILL)`
257
+ const KILL_EXITS: ExitRow[] = [[0, 'stopped every target process'], [1, 'a pid was missing, refused, or survived'], [2, 'a usage error']]
258
+ const KILL_OPTIONS = {
259
+ force: { type: 'boolean', short: 'f', description: 'escalate to SIGKILL if SIGTERM does not stop the process within --grace' },
260
+ yes: { type: 'boolean', short: 'y', description: 'do not ask for confirmation on a terminal' },
261
+ grace: { type: 'string', description: 'time SIGTERM gets before SIGKILL with --force (5s)' },
262
+ json: jsonOption('{terminated: number[], killed: number[], survived: number[]}'),
263
+ } as const
264
+
265
+ export async function killCmd(args: string[]): Promise<number> {
266
+ const { values, positionals } = parse(args, KILL_USAGE, KILL_OPTIONS, {
267
+ exits: KILL_EXITS,
268
+ positionals: ['<pid>...'],
269
+ examples: ['proc kill 4242 --yes', 'proc kill 4242 4243 --force --yes'],
270
+ })
271
+ const pids = positionals.map((given) => {
272
+ if (!DIGITS.test(given))
273
+ badUsage(`the pid takes a number, not ${given}`)
274
+
275
+ return Number(given)
276
+ })
277
+ const uid = process.getuid?.() ?? -1
278
+ const all = await snapshot('/proc', owner => owner === uid)
279
+ const byPid = new Map(all.map(proc => [proc.pid, proc]))
280
+ const guard = { uid, mine: new Set(ancestry(process.pid, byPid)) }
281
+ const allowed: ProcInfo[] = []
282
+ let refused = false
283
+
284
+ for (const pid of new Set(pids)) {
285
+ const proc = byPid.get(pid)
286
+
287
+ if (proc === undefined) {
288
+ problem(`no process with pid ${pid}`)
289
+ refused = true
290
+
291
+ continue
292
+ }
293
+
294
+ const reason = protectionOf(proc, guard)
295
+
296
+ if (reason !== undefined) {
297
+ problem(`pid ${pid} is ${reason}`)
298
+ refused = true
299
+
300
+ continue
301
+ }
302
+
303
+ allowed.push(proc)
304
+ }
305
+
306
+ if (allowed.length === 0)
307
+ return 1
308
+
309
+ const names = allowed.map(proc => `${proc.pid} (${truncate(commandOf(proc), 40)})`).join(', ')
310
+
311
+ if (values.yes !== true) {
312
+ if (!process.stdin.isTTY)
313
+ fail(`stopping ${names} needs a terminal to ask on: pass --yes`, 2)
314
+
315
+ if (await confirm(`Stop ${names}?`, { default: false, hint: 'pass --yes to stop without asking' }) !== true)
316
+ return 1
317
+ }
318
+
319
+ const outcome = await terminate(allowed.map(proc => proc.pid), { escalate: values.force === true, graceMs: duration(values.grace, 'grace', 5000) })
320
+
321
+ if (values.json === true) {
322
+ printJson(outcome)
323
+ }
324
+ else {
325
+ for (const pid of [...outcome.terminated, ...outcome.killed])
326
+ console.log(`stopped ${pid}${outcome.killed.includes(pid) ? ' (SIGKILL)' : ''}`)
327
+
328
+ for (const pid of outcome.survived)
329
+ problem(`${pid} is still running${values.force === true ? '' : ', pass --force to SIGKILL it'}`)
330
+ }
331
+
332
+ return refused || outcome.survived.length > 0 ? 1 : 0
333
+ }
package/src/pid.ts CHANGED
@@ -5,7 +5,7 @@ import process from 'node:process'
5
5
  import { fail, formatFileSize, formatSeconds, jsonOption, paint, parse, printJson } from '@kaynooo/cli-kit'
6
6
  import { maskArgs, maskEnviron } from './mask'
7
7
  import { parseCgroup, parseEnviron, parseLimits, parseStat, parseStatus, statusBytes } from './parse'
8
- import { bootMs, fdCount, readProc, readSockets, readText, socketsOf, userName } from './read'
8
+ import { bootMs, fdCount, readProc, readSockets, readText, snapshot, socketsOf, userName } from './read'
9
9
 
10
10
  const usage = `proc pid <pid>: shows what a process is, from its executable and command line to its parent chain, memory, open files, listening ports and cgroup
11
11
 
@@ -34,6 +34,7 @@ export interface Report {
34
34
  cwd: string | undefined
35
35
  command: string[]
36
36
  parents: Parent[]
37
+ children: Parent[]
37
38
  user: { uid: number, name: string | undefined }
38
39
  startedAt: string
39
40
  ageSeconds: number
@@ -101,6 +102,12 @@ async function report(pid: number, showEnv: boolean): Promise<Report | undefined
101
102
  if (showEnv && environText === undefined)
102
103
  unreadable.push('environment')
103
104
 
105
+ const [allProcs, parents] = await Promise.all([snapshot('/proc', () => false), parentsOf(proc, boot)])
106
+ const children: Parent[] = allProcs
107
+ .filter(child => child.ppid === pid)
108
+ .sort((a, b) => a.pid - b.pid)
109
+ .map(child => ({ pid: child.pid, comm: child.comm, command: maskArgs(child.args).join(' ') }))
110
+
104
111
  return {
105
112
  pid,
106
113
  comm: proc.comm,
@@ -108,7 +115,8 @@ async function report(pid: number, showEnv: boolean): Promise<Report | undefined
108
115
  exe: proc.exe,
109
116
  cwd: proc.cwd,
110
117
  command: maskArgs(proc.args),
111
- parents: await parentsOf(proc, boot),
118
+ parents,
119
+ children,
112
120
  user: { uid, name: await userName(uid) },
113
121
  startedAt: new Date(proc.startMs).toISOString(),
114
122
  ageSeconds: Math.max(0, (Date.now() - proc.startMs) / 1000),
@@ -139,6 +147,7 @@ function render(info: Report, showEnv: boolean): string {
139
147
  ['Directory', info.cwd ?? '-'],
140
148
  ['Command', info.command.join(' ') || `[${info.comm}]`],
141
149
  ['Parents', info.parents.length === 0 ? 'none (init)' : info.parents.map(parent => `${parent.pid} ${parent.comm}`).join(' < ')],
150
+ ...(info.children.length === 0 ? [] : [['Children', info.children.map(child => `${child.pid} ${child.comm}`).join(', ')] as [string, string]]),
142
151
  ['User', `${info.user.name ?? '?'} (${info.user.uid})`],
143
152
  ['State', info.state],
144
153
  ['Started', `${info.startedAt} (${formatSeconds(info.ageSeconds)} ago)`],
@@ -148,6 +157,9 @@ function render(info: Report, showEnv: boolean): string {
148
157
  ['Listening', info.listening.length === 0 ? 'nothing' : info.listening.map(({ protocol, address, port }) => `${protocol} ${address.includes(':') ? `[${address}]` : address}:${port}`).join(', ')],
149
158
  ]
150
159
 
160
+ if (info.container !== undefined)
161
+ rows.push(['Container', info.container])
162
+
151
163
  if (info.cgroup !== undefined)
152
164
  rows.push(['Cgroup', info.cgroup])
153
165
 
package/src/ports.ts CHANGED
@@ -3,7 +3,7 @@ import type { Container, Protocol, Socket } from './parse'
3
3
  import type { ProcInfo } from './read'
4
4
  import { basename } from 'node:path'
5
5
  import process from 'node:process'
6
- import { badUsage, duration, fail, jsonOption, paint, parse, printJson, problem, table, truncate, watching, watchOption, wholeNumber, withoutWatch } from '@kaynooo/cli-kit'
6
+ import { badUsage, duration, fail, jsonOption, paint, parse, printJson, problem, runCommand, table, truncate, watching, watchOption, wholeNumber, withoutWatch, writeErr } from '@kaynooo/cli-kit'
7
7
  import { confirm } from '@kaynooo/cli-kit/prompt'
8
8
  import { dockerContainers } from './docker'
9
9
  import { protectionOf, terminate } from './kill'
@@ -19,6 +19,7 @@ const EXITS: ExitRow[] = [[0, 'it listed or stopped'], [1, 'nothing listens on t
19
19
  const options = {
20
20
  json: jsonOption('[{ port, protocol, addresses, pid, command, cwd, container }]'),
21
21
  kill: { type: 'boolean', conflicts: ['watch'], description: 'stop the owner of the given port' },
22
+ docker: { type: 'boolean', description: 'with --kill, also stop Docker containers publishing the port' },
22
23
  watch: watchOption('the ports'),
23
24
  force: { type: 'boolean', description: 'with --kill, SIGKILL what SIGTERM did not stop within --grace' },
24
25
  yes: { type: 'boolean', short: 'y', description: 'with --kill, do not ask first' },
@@ -103,12 +104,21 @@ function render(rows: PortRow[]): string {
103
104
  return table([['PORT', 'PROTO', 'ADDRESS', 'PID', 'COMMAND', 'CWD'], ...cells], { header: true })
104
105
  }
105
106
 
106
- async function stop(port: number, rows: PortRow[], procs: Map<number, ProcInfo>, values: { force?: boolean | undefined, yes?: boolean | undefined, quiet?: boolean | undefined, grace?: string | undefined }): Promise<number> {
107
+ async function stop(port: number, rows: PortRow[], procs: Map<number, ProcInfo>, values: { docker?: boolean | undefined, force?: boolean | undefined, yes?: boolean | undefined, quiet?: boolean | undefined, grace?: string | undefined }): Promise<number> {
107
108
  const guard = { uid: process.getuid?.() ?? -1, mine: new Set(ancestry(process.pid, procs)) }
108
109
  const targets = new Map<number, PortRow>()
110
+ const containers = new Map<string, NonNullable<PortRow['container']>>()
109
111
 
110
112
  for (const row of rows) {
111
- const reason = refusal(row, row.pid === undefined ? undefined : procs.get(row.pid), guard)
113
+ const proc = row.pid === undefined ? undefined : procs.get(row.pid)
114
+
115
+ if (values.docker === true && row.container !== undefined && (proc === undefined || proc.comm === 'docker-proxy')) {
116
+ containers.set(row.container.name, row.container)
117
+
118
+ continue
119
+ }
120
+
121
+ const reason = refusal(row, proc, guard)
112
122
 
113
123
  if (reason !== undefined)
114
124
  problem(`port ${port}: ${reason}`)
@@ -116,28 +126,53 @@ async function stop(port: number, rows: PortRow[], procs: Map<number, ProcInfo>,
116
126
  targets.set(row.pid, row)
117
127
  }
118
128
 
119
- if (targets.size === 0)
129
+ if (targets.size === 0 && containers.size === 0)
120
130
  return 1
121
131
 
122
- const names = [...targets].map(([pid, row]) => `${pid} (${truncate(row.command ?? '', 40)})`).join(', ')
132
+ const names = [
133
+ ...[...targets].map(([pid, row]) => `${pid} (${truncate(row.command ?? '', 40)})`),
134
+ ...[...containers.values()].map(c => `docker ${containerLabel(c)}`),
135
+ ].join(', ')
123
136
 
124
137
  if (values.yes !== true) {
125
138
  if (!process.stdin.isTTY)
126
139
  fail(`stopping ${names} needs a terminal to ask on: pass --yes`, 2)
127
140
 
128
- if (await confirm(`Stop ${names}?`, { default: false }) !== true)
141
+ if (await confirm(`Stop ${names}?`, { default: false, hint: 'pass --yes to stop without asking' }) !== true)
129
142
  return 1
130
143
  }
131
144
 
132
- const outcome = await terminate([...targets.keys()], { escalate: values.force === true, graceMs: duration(values.grace, 'grace', 5000) })
145
+ let code = 0
146
+
147
+ if (containers.size > 0) {
148
+ for (const name of containers.keys()) {
149
+ const ran = await runCommand(['docker', 'stop', name])
150
+
151
+ if (ran.code === 0) {
152
+ if (values.quiet !== true)
153
+ console.log(`stopped container ${name}`)
154
+ }
155
+ else {
156
+ problem(`could not stop container ${name}: ${ran.text.trim() || `exit ${ran.code}`}`)
157
+ code = 1
158
+ }
159
+ }
160
+ }
161
+
162
+ if (targets.size > 0) {
163
+ const outcome = await terminate([...targets.keys()], { escalate: values.force === true, graceMs: duration(values.grace, 'grace', 5000) })
164
+
165
+ for (const pid of values.quiet === true ? [] : [...outcome.terminated, ...outcome.killed])
166
+ console.log(`stopped ${pid}${outcome.killed.includes(pid) ? ' (SIGKILL)' : ''}`)
133
167
 
134
- for (const pid of values.quiet === true ? [] : [...outcome.terminated, ...outcome.killed])
135
- console.log(`stopped ${pid}${outcome.killed.includes(pid) ? ' (SIGKILL)' : ''}`)
168
+ for (const pid of outcome.survived)
169
+ problem(`${pid} is still running${values.force === true ? '' : ', pass --force to SIGKILL it'}`)
136
170
 
137
- for (const pid of outcome.survived)
138
- problem(`${pid} is still running${values.force === true ? '' : ', pass --force to SIGKILL it'}`)
171
+ if (outcome.survived.length > 0)
172
+ code = 1
173
+ }
139
174
 
140
- return outcome.survived.length === 0 ? 0 : 1
175
+ return code
141
176
  }
142
177
 
143
178
  export async function ports(args: string[]): Promise<number> {
@@ -195,7 +230,7 @@ export async function ports(args: string[]): Promise<number> {
195
230
  const unknown = rows.filter(row => row.pid === undefined && row.container === undefined).length
196
231
 
197
232
  if (unknown > 0)
198
- console.error(paint(process.stderr).dim(`${unknown} ${unknown === 1 ? 'port has' : 'ports have'} an owner this user cannot read, shown as -`))
233
+ writeErr(paint(process.stderr).dim(`${unknown} ${unknown === 1 ? 'port has' : 'ports have'} an owner this user cannot read, shown as -`))
199
234
 
200
235
  return 0
201
236
  }
package/src/proc-cli.ts CHANGED
@@ -2,18 +2,24 @@
2
2
 
3
3
  import process from 'node:process'
4
4
  import { runCli } from '@kaynooo/cli-kit'
5
+ import { killCmd, lsCmd, topCmd, treeCmd } from './manage'
5
6
  import { pid } from './pid'
6
7
  import { ports } from './ports'
7
- import { procs } from './procs'
8
+ import { cleanup } from './procs'
8
9
 
9
10
  process.exitCode = await runCli({
10
11
  name: 'proc',
11
- about: 'what a process is, who listens on a port and which dev processes are worth cleaning, read from /proc',
12
- replaces: 'cat /proc/<pid>/..., ss -ltnp, lsof -i and pgrep -f one-liners',
13
- examples: ['proc pid 1234', 'proc ports', ['proc procs', 'the leftover or heavy processes, dry-run first']],
12
+ about: 'inspect, search, tree, rank and safely clean processes and listening ports from /proc',
13
+ replaces: 'cat /proc/<pid>/..., ps aux | grep, pstree, ss -ltnp, lsof -i and pkill -f one-liners',
14
+ examples: ['proc pid 1234', 'proc ports', 'proc ls vite', 'proc tree', 'proc top', ['proc cleanup', 'leftover or heavy dev processes, dry-run first']],
15
+ aliases: { find: 'ls', procs: 'cleanup' },
14
16
  commands: {
15
- pid: { summary: 'what a process is: executable, parents, memory, limits and listening ports', run: pid },
16
- ports: { summary: 'what listens on this machine, with its owner, and a safe --kill', run: ports },
17
- procs: { summary: 'the leftover or heavy processes of the calling user, grouped by origin', run: procs },
17
+ pid: { summary: 'inspect one process: executable, parents, children, container, memory, limits and ports', run: pid },
18
+ ports: { summary: 'listening ports with owner/container and safe --kill (--docker for containers)', run: ports },
19
+ cleanup: { summary: 'leftover or heavy dev processes grouped by origin (--origin/--tool filters)', run: cleanup },
20
+ ls: { summary: 'list or search processes by pattern (alias: find)', run: lsCmd },
21
+ tree: { summary: 'process hierarchy rooted at a pid or user roots', run: treeCmd },
22
+ top: { summary: 'top processes by memory, open files or age', run: topCmd },
23
+ kill: { summary: 'safely stop one or more processes with protection checks', run: killCmd },
18
24
  },
19
25
  })
package/src/procs.ts CHANGED
@@ -3,20 +3,22 @@ import type { Group } from './select'
3
3
  import { existsSync } from 'node:fs'
4
4
  import { homedir } from 'node:os'
5
5
  import process from 'node:process'
6
- import { duration, fail, formatFileSize, formatSeconds, jsonOption, paint, parse, parseSize, printJson, problem, table, truncate, watching, watchOption, withoutWatch } from '@kaynooo/cli-kit'
6
+ import { duration, fail, formatFileSize, formatSeconds, jsonOption, paint, parse, parseSize, printJson, problem, table, truncate, watching, watchOption, withoutWatch, writeErr } from '@kaynooo/cli-kit'
7
7
  import { terminate } from './kill'
8
8
  import { maskArgs } from './mask'
9
9
  import { ancestry, snapshot } from './read'
10
10
  import { selectGroups } from './select'
11
11
 
12
- const usage = `proc procs: lists the calling user's leftover or heavy dev processes, grouped by project folder, browser profile or command
12
+ const usage = `proc cleanup: lists the calling user's leftover or heavy dev processes, grouped by project folder, browser profile or command
13
13
 
14
14
  A process is listed when it is a dev tool (bun, node, vite, chromium, playwright, language servers, test runners) and either an orphan, reparented to init or to the user's systemd, or heavy (500M resident by default); the processes below it and those sharing its browser profile come with it.
15
- \`--kill\` is a dry run that names what it would stop unless --yes is given. It never signals pid 1, shells, terminals, this command and its ancestors, or processes of other users.`
15
+ Filter by --origin or --tool before running --kill --yes. \`--kill\` is a dry run that names what it would stop unless --yes is given.`
16
16
  const EXITS: ExitRow[] = [[0, 'it listed or stopped everything'], [1, 'a process survived SIGKILL'], [2, 'a usage error']]
17
17
 
18
18
  const options = {
19
19
  'json': jsonOption('{ groups: [{ origin, kind, count, rss, oldestSeconds, tools, orphans, pids, processes }], skipped }'),
20
+ 'origin': { type: 'string', description: 'keep only groups whose origin contains this substring (case-insensitive)' },
21
+ 'tool': { type: 'string', description: 'keep only processes matching this tool name (comma-separated, e.g. chromium,vite)' },
20
22
  'kill': { type: 'boolean', conflicts: ['watch'], description: 'stop the listed processes: a dry run without --yes' },
21
23
  'watch': watchOption('the processes'),
22
24
  'yes': { type: 'boolean', short: 'y', description: 'with --kill, really stop them, without asking' },
@@ -59,15 +61,14 @@ function render(groups: Group[]): string {
59
61
  return table([['ORIGIN', 'PROCS', 'RSS', 'OLDEST', 'WHAT', ''], ...rows], { header: true, align: ['left', 'right', 'right', 'right'] })
60
62
  }
61
63
 
62
- export async function procs(args: string[]): Promise<number> {
64
+ export async function cleanup(args: string[]): Promise<number> {
63
65
  const { values } = parse(args, usage, options, {
64
66
  exits: EXITS,
65
67
  replaces: 'pkill -f and pgrep -f one-liners (which match their own shell), ps aux | grep for leftover chromium, bun or vite processes',
66
68
  examples: [
67
- ['proc procs', 'leftover and heavy dev processes, by origin'],
68
- ['proc procs --min-mem 1G --older 1h', 'only the big ones that have run a while'],
69
- ['proc procs --kill', 'dry run: what would be stopped'],
70
- 'proc procs --kill --yes',
69
+ ['proc cleanup', 'leftover and heavy dev processes, by origin'],
70
+ ['proc cleanup --tool chromium --kill --yes', 'stop leftover Chromium processes'],
71
+ ['proc cleanup --origin workspace/app --min-mem 1G', 'filter by project origin and memory'],
71
72
  ],
72
73
  })
73
74
  const minMem = values['min-mem'] === undefined ? undefined : parseSize(values['min-mem'], 1024 ** 2)
@@ -76,13 +77,36 @@ export async function procs(args: string[]): Promise<number> {
76
77
  fail(`--min-mem takes a size such as 500M or 1.5G, not ${values['min-mem']}`, 2)
77
78
 
78
79
  if (values.watch !== undefined)
79
- return watching(values.watch, async () => procs(withoutWatch(args)))
80
+ return watching(values.watch, async () => cleanup(withoutWatch(args)))
80
81
 
81
82
  const olderMs = values.older === undefined ? undefined : duration(values.older, 'older', 0, 'm')
82
83
  const uid = process.getuid?.() ?? -1
83
84
  const all = await snapshot('/proc', owner => owner === uid)
84
85
  const mine = new Set(ancestry(process.pid, new Map(all.map(proc => [proc.pid, proc]))))
85
- const { groups, protectedCount } = selectGroups(all, { guard: { uid, mine }, now: Date.now(), home: homedir(), exists: existsSync, minMem, olderMs })
86
+ const selected = selectGroups(all, { guard: { uid, mine }, now: Date.now(), home: homedir(), exists: existsSync, minMem, olderMs })
87
+ const originFilter = values.origin?.toLowerCase()
88
+ const toolFilter = values.tool === undefined ? undefined : new Set(values.tool.split(',').map(item => item.trim().toLowerCase()).filter(Boolean))
89
+ const groups = selected.groups
90
+ .filter(group => originFilter === undefined || group.origin.toLowerCase().includes(originFilter))
91
+ .map((group): Group | undefined => {
92
+ if (toolFilter === undefined)
93
+ return group
94
+
95
+ const members = group.members.filter(member => toolFilter.has(member.tool.toLowerCase()))
96
+
97
+ if (members.length === 0)
98
+ return undefined
99
+
100
+ return {
101
+ ...group,
102
+ members,
103
+ rss: members.reduce((sum, member) => sum + member.proc.rss, 0),
104
+ oldestMs: Math.max(...members.map(member => member.ageMs)),
105
+ orphans: members.filter(member => member.orphan).length,
106
+ }
107
+ })
108
+ .filter((group): group is Group => group !== undefined)
109
+ const { protectedCount } = selected
86
110
  const pids = groups.flatMap(group => group.members.map(({ proc }) => proc.pid))
87
111
 
88
112
  const show = (extra: object = {}): void => {
@@ -98,10 +122,10 @@ export async function procs(args: string[]): Promise<number> {
98
122
  show()
99
123
 
100
124
  if (values.json !== true && protectedCount > 0)
101
- console.error(paint(process.stderr).dim(`${protectedCount} more left out: shells, terminals and this command's ancestors are never touched`))
125
+ writeErr(paint(process.stderr).dim(`${protectedCount} more left out: shells, terminals and this command's ancestors are never touched`))
102
126
 
103
127
  if (values.kill === true && pids.length > 0)
104
- console.error(`dry run: would stop ${pids.length} ${pids.length === 1 ? 'process' : 'processes'} (${pids.join(' ')}), pass --yes to do it`)
128
+ writeErr(`dry run: would stop ${pids.length} ${pids.length === 1 ? 'process' : 'processes'} (${pids.join(' ')}), pass --yes to do it`)
105
129
 
106
130
  return 0
107
131
  }