@kaynooo/cli-proc 0.0.0-stage → 0.2.0
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/LICENSE +21 -0
- package/README.md +39 -2
- package/dist/pid-cli.js +1422 -0
- package/dist/ports-cli.js +1571 -0
- package/dist/procs-cli.js +1558 -0
- package/package.json +36 -4
- package/src/docker.ts +20 -0
- package/src/kill.ts +109 -0
- package/src/mask.ts +71 -0
- package/src/parse.ts +274 -0
- package/src/pid-cli.ts +7 -0
- package/src/pid.ts +193 -0
- package/src/ports-cli.ts +7 -0
- package/src/ports.ts +195 -0
- package/src/procs-cli.ts +7 -0
- package/src/procs.ts +113 -0
- package/src/read.ts +175 -0
- package/src/select.ts +201 -0
package/src/pid.ts
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import type { Limit, Socket } from './parse'
|
|
2
|
+
import type { ProcInfo } from './read'
|
|
3
|
+
import process from 'node:process'
|
|
4
|
+
import { fail, formatFileSize, formatSeconds, jsonOption, paint, parse, printJson } from '@kaynooo/cli-kit'
|
|
5
|
+
import { maskArgs, maskEnviron } from './mask'
|
|
6
|
+
import { parseCgroup, parseEnviron, parseLimits, parseStat, parseStatus, statusBytes } from './parse'
|
|
7
|
+
import { bootMs, fdCount, readProc, readSockets, readText, socketsOf, userName } from './read'
|
|
8
|
+
|
|
9
|
+
const usage = `pid <pid>
|
|
10
|
+
|
|
11
|
+
Shows what a process is: its executable, working directory, command line, parent chain up to init, user, start time and age, memory, open files and limits, the TCP and UDP ports it listens on and its cgroup. Everything is read from /proc; what the calling user cannot read of another user's process is left out and named at the end.
|
|
12
|
+
The environment is not shown unless --env is given, with every value that looks like a secret masked.
|
|
13
|
+
|
|
14
|
+
Exits 0 when it showed the process, 1 when no process has this pid, 2 on a usage error.`
|
|
15
|
+
|
|
16
|
+
const DIGITS = /^\d+$/
|
|
17
|
+
|
|
18
|
+
const options = {
|
|
19
|
+
env: { type: 'boolean', description: 'show the environment, secrets masked' },
|
|
20
|
+
json: jsonOption('everything, with the environment under env when --env is given'),
|
|
21
|
+
} as const
|
|
22
|
+
|
|
23
|
+
export interface Parent {
|
|
24
|
+
pid: number
|
|
25
|
+
comm: string
|
|
26
|
+
command: string
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface Report {
|
|
30
|
+
pid: number
|
|
31
|
+
comm: string
|
|
32
|
+
state: string
|
|
33
|
+
exe: string | undefined
|
|
34
|
+
cwd: string | undefined
|
|
35
|
+
command: string[]
|
|
36
|
+
parents: Parent[]
|
|
37
|
+
user: { uid: number, name: string | undefined }
|
|
38
|
+
startedAt: string
|
|
39
|
+
ageSeconds: number
|
|
40
|
+
threads: number | undefined
|
|
41
|
+
memory: { rss: number | undefined, peak: number | undefined, virtual: number | undefined, swap: number | undefined }
|
|
42
|
+
openFiles: number | undefined
|
|
43
|
+
limits: Limit[]
|
|
44
|
+
listening: { protocol: string, address: string, port: number }[]
|
|
45
|
+
cgroup: string | undefined
|
|
46
|
+
container: string | undefined
|
|
47
|
+
env: { name: string, value: string }[] | undefined
|
|
48
|
+
unreadable: string[]
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function parentsOf(proc: ProcInfo, boot: number): Promise<Parent[]> {
|
|
52
|
+
const parents: Parent[] = []
|
|
53
|
+
const seen = new Set([proc.pid])
|
|
54
|
+
let at = proc.ppid
|
|
55
|
+
|
|
56
|
+
while (at > 0 && !seen.has(at)) {
|
|
57
|
+
seen.add(at)
|
|
58
|
+
|
|
59
|
+
const parent = await readProc(at, boot, { detail: false })
|
|
60
|
+
|
|
61
|
+
if (parent === undefined)
|
|
62
|
+
break
|
|
63
|
+
|
|
64
|
+
parents.push({ pid: parent.pid, comm: parent.comm, command: maskArgs(parent.args).join(' ') })
|
|
65
|
+
at = parent.ppid
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return parents
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function report(pid: number, showEnv: boolean): Promise<Report | undefined> {
|
|
72
|
+
const boot = await bootMs()
|
|
73
|
+
const proc = await readProc(pid, boot)
|
|
74
|
+
|
|
75
|
+
if (proc === undefined)
|
|
76
|
+
return undefined
|
|
77
|
+
|
|
78
|
+
const unreadable: string[] = []
|
|
79
|
+
const status = parseStatus(await readText(`/proc/${pid}/status`) ?? '')
|
|
80
|
+
const limitsText = await readText(`/proc/${pid}/limits`)
|
|
81
|
+
const sockets = await socketsOf(pid)
|
|
82
|
+
const listening: Socket[] = sockets.size === 0 ? [] : (await readSockets()).filter(socket => sockets.has(socket.inode))
|
|
83
|
+
const environText = showEnv ? await readText(`/proc/${pid}/environ`) : undefined
|
|
84
|
+
const cgroup = parseCgroup(await readText(`/proc/${pid}/cgroup`) ?? '')[0]?.path
|
|
85
|
+
const files = await fdCount(pid)
|
|
86
|
+
const stat = parseStat(await readText(`/proc/${pid}/stat`) ?? '')
|
|
87
|
+
const uid = proc.uid
|
|
88
|
+
|
|
89
|
+
if (proc.exe === undefined)
|
|
90
|
+
unreadable.push('executable')
|
|
91
|
+
|
|
92
|
+
if (proc.cwd === undefined)
|
|
93
|
+
unreadable.push('working directory')
|
|
94
|
+
|
|
95
|
+
if (files === undefined)
|
|
96
|
+
unreadable.push('open files')
|
|
97
|
+
|
|
98
|
+
if (limitsText === undefined)
|
|
99
|
+
unreadable.push('limits')
|
|
100
|
+
|
|
101
|
+
if (showEnv && environText === undefined)
|
|
102
|
+
unreadable.push('environment')
|
|
103
|
+
|
|
104
|
+
return {
|
|
105
|
+
pid,
|
|
106
|
+
comm: proc.comm,
|
|
107
|
+
state: proc.state,
|
|
108
|
+
exe: proc.exe,
|
|
109
|
+
cwd: proc.cwd,
|
|
110
|
+
command: maskArgs(proc.args),
|
|
111
|
+
parents: await parentsOf(proc, boot),
|
|
112
|
+
user: { uid, name: await userName(uid) },
|
|
113
|
+
startedAt: new Date(proc.startMs).toISOString(),
|
|
114
|
+
ageSeconds: Math.max(0, (Date.now() - proc.startMs) / 1000),
|
|
115
|
+
threads: stat?.threads,
|
|
116
|
+
memory: { rss: statusBytes(status, 'VmRSS'), peak: statusBytes(status, 'VmHWM'), virtual: statusBytes(status, 'VmSize'), swap: statusBytes(status, 'VmSwap') },
|
|
117
|
+
openFiles: files,
|
|
118
|
+
limits: parseLimits(limitsText ?? ''),
|
|
119
|
+
listening: listening.map(({ protocol, address, port }) => ({ protocol, address, port })),
|
|
120
|
+
cgroup: cgroup === '' ? undefined : cgroup,
|
|
121
|
+
container: proc.container,
|
|
122
|
+
env: environText === undefined ? undefined : maskEnviron(parseEnviron(environText)).map(([name, value]) => ({ name, value })),
|
|
123
|
+
unreadable,
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function limitLine(limits: Limit[], name: string): string {
|
|
128
|
+
const limit = limits.find(candidate => candidate.name === name)
|
|
129
|
+
|
|
130
|
+
return limit === undefined ? '-' : `soft ${limit.soft}, hard ${limit.hard}`
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function render(info: Report, showEnv: boolean): string {
|
|
134
|
+
const colors = paint(process.stdout)
|
|
135
|
+
const memory = info.memory
|
|
136
|
+
const size = (bytes: number | undefined) => bytes === undefined ? '-' : formatFileSize(bytes)
|
|
137
|
+
const rows: [string, string][] = [
|
|
138
|
+
['Executable', info.exe ?? '-'],
|
|
139
|
+
['Directory', info.cwd ?? '-'],
|
|
140
|
+
['Command', info.command.join(' ') || `[${info.comm}]`],
|
|
141
|
+
['Parents', info.parents.length === 0 ? 'none (init)' : info.parents.map(parent => `${parent.pid} ${parent.comm}`).join(' < ')],
|
|
142
|
+
['User', `${info.user.name ?? '?'} (${info.user.uid})`],
|
|
143
|
+
['State', info.state],
|
|
144
|
+
['Started', `${info.startedAt} (${formatSeconds(info.ageSeconds)} ago)`],
|
|
145
|
+
['Memory', `rss ${size(memory.rss)}, peak ${size(memory.peak)}, virtual ${size(memory.virtual)}, swap ${size(memory.swap)}`],
|
|
146
|
+
['Open files', `${info.openFiles ?? '-'} (limit ${limitLine(info.limits, 'Max open files')})`],
|
|
147
|
+
['Processes', `${info.threads ?? '-'} threads (limit ${limitLine(info.limits, 'Max processes')})`],
|
|
148
|
+
['Listening', info.listening.length === 0 ? 'nothing' : info.listening.map(({ protocol, address, port }) => `${protocol} ${address.includes(':') ? `[${address}]` : address}:${port}`).join(', ')],
|
|
149
|
+
]
|
|
150
|
+
|
|
151
|
+
if (info.cgroup !== undefined)
|
|
152
|
+
rows.push(['Cgroup', info.cgroup])
|
|
153
|
+
|
|
154
|
+
const lines = [colors.bold(`pid ${info.pid} ${info.comm}`), ...rows.map(([label, value]) => `${colors.dim(label.padEnd(11))} ${value}`)]
|
|
155
|
+
|
|
156
|
+
if (showEnv && info.env !== undefined)
|
|
157
|
+
lines.push('', colors.bold('Environment'), ...info.env.map(({ name, value }) => `${name}=${value}`))
|
|
158
|
+
else if (!showEnv)
|
|
159
|
+
lines.push('', colors.dim('Environment hidden, pass --env to show it with secrets masked'))
|
|
160
|
+
|
|
161
|
+
if (info.unreadable.length > 0)
|
|
162
|
+
lines.push('', colors.yellow(`Could not read: ${info.unreadable.join(', ')} (a process of another user: rerun as that user)`))
|
|
163
|
+
|
|
164
|
+
return lines.join('\n')
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export async function pid(args: string[]): Promise<number> {
|
|
168
|
+
const { values, positionals } = parse(args, usage, options, {
|
|
169
|
+
positionals: ['<pid>'],
|
|
170
|
+
replaces: 'cat /proc/<pid>/{cmdline,environ,limits}, readlink /proc/<pid>/{exe,cwd}, the fish pid function',
|
|
171
|
+
examples: [
|
|
172
|
+
['pid 4242', 'executable, directory, command, parents, memory, limits and ports'],
|
|
173
|
+
['pid 4242 --env', 'with the environment, secrets masked'],
|
|
174
|
+
'pid 4242 --json',
|
|
175
|
+
],
|
|
176
|
+
})
|
|
177
|
+
const [given] = positionals
|
|
178
|
+
|
|
179
|
+
if (!DIGITS.test(given))
|
|
180
|
+
fail(`the pid takes a number, not ${given}`, 2)
|
|
181
|
+
|
|
182
|
+
const info = await report(Number(given), values.env === true)
|
|
183
|
+
|
|
184
|
+
if (info === undefined)
|
|
185
|
+
return fail(`no process with pid ${given}`, 1)
|
|
186
|
+
|
|
187
|
+
if (values.json === true)
|
|
188
|
+
printJson(info)
|
|
189
|
+
else
|
|
190
|
+
console.log(render(info, values.env === true))
|
|
191
|
+
|
|
192
|
+
return 0
|
|
193
|
+
}
|
package/src/ports-cli.ts
ADDED
package/src/ports.ts
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import type { Container, Protocol, Socket } from './parse'
|
|
2
|
+
import type { ProcInfo } from './read'
|
|
3
|
+
import { basename } from 'node:path'
|
|
4
|
+
import process from 'node:process'
|
|
5
|
+
import { badUsage, duration, fail, jsonOption, paint, parse, printJson, table, truncate, wholeNumber } from '@kaynooo/cli-kit'
|
|
6
|
+
import { confirm } from '@kaynooo/cli-kit/prompt'
|
|
7
|
+
import { dockerContainers } from './docker'
|
|
8
|
+
import { protectionOf, terminate } from './kill'
|
|
9
|
+
import { maskArgs } from './mask'
|
|
10
|
+
import { ancestry, readSockets, snapshot, socketOwners } from './read'
|
|
11
|
+
|
|
12
|
+
const usage = `ports [port]
|
|
13
|
+
|
|
14
|
+
Lists what listens on this machine, TCP and UDP over IPv4 and IPv6, one row per port with its bound address, the owning process, its command and its working directory. A port Docker publishes is held by docker-proxy, and shows as its compose project and service when docker is installed; the owner of a socket of another user cannot be read and shows as -.
|
|
15
|
+
\`ports <port>\` keeps that port alone and exits 1 when nothing listens on it.
|
|
16
|
+
\`ports <port> --kill\` stops its owner with SIGTERM, and with --force SIGKILL once --grace has passed, after asking on a terminal unless --yes is given. It refuses processes of other users, pid 1, this command and its ancestors, and docker-proxy, for which it names the container to stop instead.
|
|
17
|
+
|
|
18
|
+
Exits 0 when it listed or stopped, 1 when nothing listens on the given port or the owner could not be stopped, 2 on a usage error.`
|
|
19
|
+
|
|
20
|
+
const options = {
|
|
21
|
+
json: jsonOption('[{ port, protocol, addresses, pid, command, cwd, container }]'),
|
|
22
|
+
kill: { type: 'boolean', description: 'stop the owner of the given port' },
|
|
23
|
+
force: { type: 'boolean', description: 'with --kill, SIGKILL what SIGTERM did not stop within --grace' },
|
|
24
|
+
yes: { type: 'boolean', short: 'y', description: 'with --kill, do not ask first' },
|
|
25
|
+
grace: { type: 'string', description: 'with --force, how long SIGTERM gets before SIGKILL (5s)' },
|
|
26
|
+
} as const
|
|
27
|
+
|
|
28
|
+
export interface PortRow {
|
|
29
|
+
port: number
|
|
30
|
+
protocol: Protocol
|
|
31
|
+
addresses: string[]
|
|
32
|
+
pid: number | undefined
|
|
33
|
+
command: string | undefined
|
|
34
|
+
cwd: string | undefined
|
|
35
|
+
uid: number | undefined
|
|
36
|
+
container: { name: string, project: string | undefined, service: string | undefined } | undefined
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// One row per protocol, port and owner; IPv4 and IPv6 sockets of the same process merge. A socket whose owner is not readable, or is docker-proxy, takes the container publishing its port.
|
|
40
|
+
export function buildRows(sockets: Socket[], owners: Map<number, number>, procs: Map<number, ProcInfo>, containers: Container[]): PortRow[] {
|
|
41
|
+
const rows = new Map<string, PortRow>()
|
|
42
|
+
|
|
43
|
+
for (const socket of sockets) {
|
|
44
|
+
const pid = owners.get(socket.inode)
|
|
45
|
+
const proc = pid === undefined ? undefined : procs.get(pid)
|
|
46
|
+
const key = `${socket.protocol}/${socket.port}/${pid ?? 'unknown'}`
|
|
47
|
+
const row = rows.get(key)
|
|
48
|
+
|
|
49
|
+
if (row !== undefined) {
|
|
50
|
+
if (!row.addresses.includes(socket.address))
|
|
51
|
+
row.addresses.push(socket.address)
|
|
52
|
+
|
|
53
|
+
continue
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const held = proc === undefined || proc.comm === 'docker-proxy'
|
|
57
|
+
const container = held ? containers.find(candidate => candidate.published.some(port => port.host === socket.port && port.protocol === socket.protocol)) : undefined
|
|
58
|
+
|
|
59
|
+
rows.set(key, {
|
|
60
|
+
port: socket.port,
|
|
61
|
+
protocol: socket.protocol,
|
|
62
|
+
addresses: [socket.address],
|
|
63
|
+
pid,
|
|
64
|
+
command: proc === undefined ? undefined : maskArgs([basename(proc.args[0] ?? proc.comm), ...proc.args.slice(1)]).join(' '),
|
|
65
|
+
cwd: proc?.cwd,
|
|
66
|
+
uid: proc?.uid ?? socket.uid,
|
|
67
|
+
container: container === undefined ? undefined : { name: container.name, project: container.project, service: container.service },
|
|
68
|
+
})
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return [...rows.values()].sort((a, b) => a.port - b.port || a.protocol.localeCompare(b.protocol) || (a.pid ?? 0) - (b.pid ?? 0))
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function containerLabel(container: NonNullable<PortRow['container']>): string {
|
|
75
|
+
return container.project === undefined ? container.name : `${container.project}/${container.service ?? container.name}`
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Why the owner of a row cannot be stopped, undefined when it can.
|
|
79
|
+
export function refusal(row: PortRow, proc: ProcInfo | undefined, guard: { uid: number, mine: ReadonlySet<number> }): string | undefined {
|
|
80
|
+
if (row.container !== undefined && (proc === undefined || proc.comm === 'docker-proxy'))
|
|
81
|
+
return `published by the container ${row.container.name} (${containerLabel(row.container)}): stop it with \`docker stop ${row.container.name}\``
|
|
82
|
+
|
|
83
|
+
if (proc === undefined || row.pid === undefined)
|
|
84
|
+
return 'its owner is not readable (another user\'s process): rerun as that user'
|
|
85
|
+
|
|
86
|
+
const reason = protectionOf(proc, guard)
|
|
87
|
+
|
|
88
|
+
return reason === undefined ? undefined : `pid ${row.pid} is ${reason}`
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function render(rows: PortRow[]): string {
|
|
92
|
+
const colors = paint(process.stdout)
|
|
93
|
+
const cells = rows.map(row => [
|
|
94
|
+
colors.cyan(String(row.port)),
|
|
95
|
+
row.protocol,
|
|
96
|
+
row.addresses.join(', '),
|
|
97
|
+
row.pid === undefined ? '-' : String(row.pid),
|
|
98
|
+
row.container === undefined ? truncate(row.command ?? '-', 60) : colors.yellow(`docker ${containerLabel(row.container)}`),
|
|
99
|
+
colors.dim(row.cwd ?? '-'),
|
|
100
|
+
])
|
|
101
|
+
|
|
102
|
+
return table([['PORT', 'PROTO', 'ADDRESS', 'PID', 'COMMAND', 'CWD'], ...cells], { header: true })
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function stop(port: number, rows: PortRow[], procs: Map<number, ProcInfo>, values: { force?: boolean | undefined, yes?: boolean | undefined, grace?: string | undefined }): Promise<number> {
|
|
106
|
+
const guard = { uid: process.getuid?.() ?? -1, mine: new Set(ancestry(process.pid, procs)) }
|
|
107
|
+
const targets = new Map<number, PortRow>()
|
|
108
|
+
|
|
109
|
+
for (const row of rows) {
|
|
110
|
+
const reason = refusal(row, row.pid === undefined ? undefined : procs.get(row.pid), guard)
|
|
111
|
+
|
|
112
|
+
if (reason !== undefined)
|
|
113
|
+
console.error(`port ${port}: ${reason}`)
|
|
114
|
+
else if (row.pid !== undefined)
|
|
115
|
+
targets.set(row.pid, row)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (targets.size === 0)
|
|
119
|
+
return 1
|
|
120
|
+
|
|
121
|
+
const names = [...targets].map(([pid, row]) => `${pid} (${truncate(row.command ?? '', 40)})`).join(', ')
|
|
122
|
+
|
|
123
|
+
if (values.yes !== true) {
|
|
124
|
+
if (!process.stdin.isTTY)
|
|
125
|
+
fail(`stopping ${names} needs a terminal to ask on: pass --yes`, 2)
|
|
126
|
+
|
|
127
|
+
if (await confirm(`Stop ${names}?`, { default: false }) !== true)
|
|
128
|
+
return 1
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const outcome = await terminate([...targets.keys()], { escalate: values.force === true, graceMs: duration(values.grace, 'grace', 5000) })
|
|
132
|
+
|
|
133
|
+
for (const pid of [...outcome.terminated, ...outcome.killed])
|
|
134
|
+
console.log(`stopped ${pid}${outcome.killed.includes(pid) ? ' (SIGKILL)' : ''}`)
|
|
135
|
+
|
|
136
|
+
for (const pid of outcome.survived)
|
|
137
|
+
console.error(`${pid} is still running${values.force === true ? '' : ', pass --force to SIGKILL it'}`)
|
|
138
|
+
|
|
139
|
+
return outcome.survived.length === 0 ? 0 : 1
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export async function ports(args: string[]): Promise<number> {
|
|
143
|
+
const { values, positionals } = parse(args, usage, options, {
|
|
144
|
+
positionals: ['[port]'],
|
|
145
|
+
replaces: 'ss -ltnp | grep, lsof -i, fuser -k and lookups of docker-proxy by hand',
|
|
146
|
+
examples: [
|
|
147
|
+
['ports', 'every listening port with its owner'],
|
|
148
|
+
['ports 3000', 'who holds 3000, exit 1 when nobody does'],
|
|
149
|
+
['ports 3000 --kill --yes', 'stop it'],
|
|
150
|
+
'ports --json',
|
|
151
|
+
],
|
|
152
|
+
})
|
|
153
|
+
const [given] = positionals
|
|
154
|
+
const port = given === undefined ? undefined : wholeNumber(given, '<port>', 0)
|
|
155
|
+
|
|
156
|
+
if (port !== undefined && port > 65_535)
|
|
157
|
+
badUsage(`<port> takes a whole number from 1 to 65535, not ${given}`)
|
|
158
|
+
|
|
159
|
+
if (values.kill === true && port === undefined)
|
|
160
|
+
badUsage('--kill takes the port to free: ports <port> --kill')
|
|
161
|
+
|
|
162
|
+
const [sockets, owners, procs] = await Promise.all([readSockets(), socketOwners(), snapshot('/proc', uid => uid === process.getuid?.())])
|
|
163
|
+
const byPid = new Map(procs.map(proc => [proc.pid, proc]))
|
|
164
|
+
const wanted = sockets.filter(socket => port === undefined || socket.port === port)
|
|
165
|
+
const needsDocker = wanted.some((socket) => {
|
|
166
|
+
const pid = owners.get(socket.inode)
|
|
167
|
+
|
|
168
|
+
return pid === undefined || byPid.get(pid)?.comm === 'docker-proxy'
|
|
169
|
+
})
|
|
170
|
+
const rows = buildRows(wanted, owners, byPid, needsDocker ? await dockerContainers() : [])
|
|
171
|
+
|
|
172
|
+
if (port !== undefined && rows.length === 0) {
|
|
173
|
+
console.error(`nothing listens on port ${port}`)
|
|
174
|
+
|
|
175
|
+
return 1
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (values.kill === true && port !== undefined)
|
|
179
|
+
return stop(port, rows, byPid, values)
|
|
180
|
+
|
|
181
|
+
if (values.json === true) {
|
|
182
|
+
printJson(rows)
|
|
183
|
+
|
|
184
|
+
return 0
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
console.log(render(rows))
|
|
188
|
+
|
|
189
|
+
const unknown = rows.filter(row => row.pid === undefined && row.container === undefined).length
|
|
190
|
+
|
|
191
|
+
if (unknown > 0)
|
|
192
|
+
console.error(paint(process.stderr).dim(`${unknown} ${unknown === 1 ? 'port has' : 'ports have'} an owner this user cannot read, shown as -`))
|
|
193
|
+
|
|
194
|
+
return 0
|
|
195
|
+
}
|
package/src/procs-cli.ts
ADDED
package/src/procs.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import type { Group } from './select'
|
|
2
|
+
import { existsSync } from 'node:fs'
|
|
3
|
+
import { homedir } from 'node:os'
|
|
4
|
+
import process from 'node:process'
|
|
5
|
+
import { duration, fail, formatFileSize, formatSeconds, jsonOption, paint, parse, parseSize, printJson, table, truncate } from '@kaynooo/cli-kit'
|
|
6
|
+
import { terminate } from './kill'
|
|
7
|
+
import { maskArgs } from './mask'
|
|
8
|
+
import { ancestry, snapshot } from './read'
|
|
9
|
+
import { selectGroups } from './select'
|
|
10
|
+
|
|
11
|
+
const usage = `procs
|
|
12
|
+
|
|
13
|
+
Lists the leftover or heavy processes of the calling user that are worth cleaning, grouped by origin: the project folder their working directory is in, a browser profile for a chromium and its helpers, else their command. Each group shows its process count, total resident memory and oldest age.
|
|
14
|
+
A process is listed when it is a dev tool (bun, node, vite, nuxt, next, chromium and chrome, playwright and webview browsers and their helpers, 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 a listed one, and those sharing a browser profile with it, are listed too, so a chromium whose main process was killed groups with its leftover helpers.
|
|
15
|
+
\`--kill\` is a dry run that names what it would stop unless --yes is given; it sends SIGTERM, then SIGKILL after --grace to what is still there. It never signals pid 1, shells, terminals, this command and its ancestors, or processes of other users.
|
|
16
|
+
|
|
17
|
+
Exits 0 when it listed or stopped everything, 1 when a process survived SIGKILL, 2 on a usage error.`
|
|
18
|
+
|
|
19
|
+
const options = {
|
|
20
|
+
'json': jsonOption('{ groups: [{ origin, kind, count, rss, oldestSeconds, tools, orphans, pids, processes }], skipped }'),
|
|
21
|
+
'kill': { type: 'boolean', description: 'stop the listed processes: a dry run without --yes' },
|
|
22
|
+
'yes': { type: 'boolean', short: 'y', description: 'with --kill, really stop them, without asking' },
|
|
23
|
+
'min-mem': { type: 'string', description: 'heavy from this resident size (500M), and the least a left over process must use to be listed; a bare number counts megabytes' },
|
|
24
|
+
'older': { type: 'string', description: 'only processes at least this old: 30m, 2h, 1d' },
|
|
25
|
+
'grace': { type: 'string', description: 'how long SIGTERM gets before SIGKILL (5s)' },
|
|
26
|
+
} as const
|
|
27
|
+
|
|
28
|
+
function summary(group: Group) {
|
|
29
|
+
const tools: Record<string, number> = {}
|
|
30
|
+
|
|
31
|
+
for (const { tool } of group.members)
|
|
32
|
+
tools[tool] = (tools[tool] ?? 0) + 1
|
|
33
|
+
|
|
34
|
+
return {
|
|
35
|
+
origin: group.origin,
|
|
36
|
+
kind: group.kind,
|
|
37
|
+
count: group.members.length,
|
|
38
|
+
rss: group.rss,
|
|
39
|
+
oldestSeconds: Math.round(group.oldestMs / 1000),
|
|
40
|
+
tools,
|
|
41
|
+
orphans: group.orphans,
|
|
42
|
+
pids: group.members.map(({ proc }) => proc.pid),
|
|
43
|
+
processes: group.members.map(({ proc, tool, orphan, heavy, ageMs }) => ({ pid: proc.pid, ppid: proc.ppid, tool, command: maskArgs(proc.args).join(' ') || proc.comm, cwd: proc.cwd, rss: proc.rss, ageSeconds: Math.round(ageMs / 1000), orphan, heavy })),
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function render(groups: Group[]): string {
|
|
48
|
+
const colors = paint(process.stdout)
|
|
49
|
+
const rows = groups.map(group => [
|
|
50
|
+
group.origin,
|
|
51
|
+
String(group.members.length),
|
|
52
|
+
formatFileSize(group.rss),
|
|
53
|
+
formatSeconds(group.oldestMs / 1000),
|
|
54
|
+
colors.dim(truncate(Object.entries(Object.groupBy(group.members, ({ tool }) => tool)).map(([tool, list]) => `${tool}${list!.length > 1 ? ` x${list!.length}` : ''}`).join(', '), 50)),
|
|
55
|
+
group.orphans === 0 ? '' : colors.yellow(`${group.orphans} orphaned`),
|
|
56
|
+
])
|
|
57
|
+
|
|
58
|
+
return table([['ORIGIN', 'PROCS', 'RSS', 'OLDEST', 'WHAT', ''], ...rows], { header: true, align: ['left', 'right', 'right', 'right'] })
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function procs(args: string[]): Promise<number> {
|
|
62
|
+
const { values } = parse(args, usage, options, {
|
|
63
|
+
replaces: 'pkill -f and pgrep -f one-liners (which match their own shell), ps aux | grep for leftover chromium, bun or vite processes',
|
|
64
|
+
examples: [
|
|
65
|
+
['procs', 'leftover and heavy dev processes, by origin'],
|
|
66
|
+
['procs --min-mem 1G --older 1h', 'only the big ones that have run a while'],
|
|
67
|
+
['procs --kill', 'dry run: what would be stopped'],
|
|
68
|
+
'procs --kill --yes',
|
|
69
|
+
],
|
|
70
|
+
})
|
|
71
|
+
const minMem = values['min-mem'] === undefined ? undefined : parseSize(values['min-mem'], 1024 ** 2)
|
|
72
|
+
|
|
73
|
+
if (values['min-mem'] !== undefined && minMem === undefined)
|
|
74
|
+
fail(`--min-mem takes a size such as 500M or 1.5G, not ${values['min-mem']}`, 2)
|
|
75
|
+
|
|
76
|
+
const olderMs = values.older === undefined ? undefined : duration(values.older, 'older', 0, 'm')
|
|
77
|
+
const uid = process.getuid?.() ?? -1
|
|
78
|
+
const all = await snapshot('/proc', owner => owner === uid)
|
|
79
|
+
const mine = new Set(ancestry(process.pid, new Map(all.map(proc => [proc.pid, proc]))))
|
|
80
|
+
const { groups, protectedCount } = selectGroups(all, { guard: { uid, mine }, now: Date.now(), home: homedir(), exists: existsSync, minMem, olderMs })
|
|
81
|
+
const pids = groups.flatMap(group => group.members.map(({ proc }) => proc.pid))
|
|
82
|
+
|
|
83
|
+
const show = (extra: object = {}): void => {
|
|
84
|
+
if (values.json === true)
|
|
85
|
+
printJson({ groups: groups.map(summary), skipped: protectedCount, ...extra })
|
|
86
|
+
else
|
|
87
|
+
console.log(groups.length === 0 ? 'nothing to clean' : render(groups))
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (values.kill !== true || pids.length === 0 || values.yes !== true) {
|
|
91
|
+
show()
|
|
92
|
+
|
|
93
|
+
if (values.json !== true && protectedCount > 0)
|
|
94
|
+
console.error(paint(process.stderr).dim(`${protectedCount} more left out: shells, terminals and this command's ancestors are never touched`))
|
|
95
|
+
|
|
96
|
+
if (values.kill === true && pids.length > 0)
|
|
97
|
+
console.error(`dry run: would stop ${pids.length} ${pids.length === 1 ? 'process' : 'processes'} (${pids.join(' ')}), pass --yes to do it`)
|
|
98
|
+
|
|
99
|
+
return 0
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const outcome = await terminate(pids, { escalate: true, graceMs: duration(values.grace, 'grace', 5000) })
|
|
103
|
+
|
|
104
|
+
show({ stopped: [...outcome.terminated, ...outcome.killed], killed: outcome.killed, survived: outcome.survived })
|
|
105
|
+
|
|
106
|
+
if (values.json !== true)
|
|
107
|
+
console.log(`stopped ${outcome.terminated.length + outcome.killed.length} of ${pids.length}${outcome.killed.length === 0 ? '' : `, ${outcome.killed.length} needed SIGKILL`}`)
|
|
108
|
+
|
|
109
|
+
if (outcome.survived.length > 0)
|
|
110
|
+
console.error(`still running: ${outcome.survived.join(' ')}`)
|
|
111
|
+
|
|
112
|
+
return outcome.survived.length === 0 ? 0 : 1
|
|
113
|
+
}
|