@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/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kaynooo/cli-proc",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.2.0",
|
|
5
|
+
"description": "pid, ports, procs: one process inspected, who listens on a port, and leftover or heavy dev processes cleaned, read straight from /proc (Linux).",
|
|
6
|
+
"author": "Kaynooo <contact@kaynooo.fr>",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"homepage": "https://git.kaynooo.fr/kaynooo/cli/src/branch/main/packages/proc#readme",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://git.kaynooo.fr/kaynooo/cli.git",
|
|
12
|
+
"directory": "packages/proc"
|
|
13
|
+
},
|
|
14
|
+
"bugs": "https://git.kaynooo.fr/kaynooo/cli/issues",
|
|
15
|
+
"keywords": ["process", "port", "proc", "kill", "cli", "bun"],
|
|
16
|
+
"os": ["linux"],
|
|
17
|
+
"bin": {
|
|
18
|
+
"pid": "./dist/pid-cli.js",
|
|
19
|
+
"ports": "./dist/ports-cli.js",
|
|
20
|
+
"procs": "./dist/procs-cli.js"
|
|
21
|
+
},
|
|
22
|
+
"files": ["dist", "src"],
|
|
23
|
+
"engines": {
|
|
24
|
+
"bun": ">=1.4.3"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"registry": "https://git.kaynooo.fr/api/packages/kaynooo/npm/"
|
|
28
|
+
},
|
|
29
|
+
"scripts": {
|
|
30
|
+
"build": "$npm_execpath build src/pid-cli.ts src/ports-cli.ts src/procs-cli.ts --target bun --outdir dist",
|
|
31
|
+
"pid": "$npm_execpath src/pid-cli.ts",
|
|
32
|
+
"ports": "$npm_execpath src/ports-cli.ts",
|
|
33
|
+
"procs": "$npm_execpath src/procs-cli.ts"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@kaynooo/cli-kit": "0.21.0"
|
|
37
|
+
}
|
|
38
|
+
}
|
package/src/docker.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Container } from './parse'
|
|
2
|
+
import { runCommand } from '@kaynooo/cli-kit'
|
|
3
|
+
import { parseDockerPs } from './parse'
|
|
4
|
+
|
|
5
|
+
const FORMAT = '{{.Names}}\t{{.Ports}}\t{{.Label "com.docker.compose.project"}}\t{{.Label "com.docker.compose.service"}}'
|
|
6
|
+
|
|
7
|
+
// The running containers with their published ports and compose labels; none, quietly, when docker is missing or its daemon unreachable.
|
|
8
|
+
export async function dockerContainers(): Promise<Container[]> {
|
|
9
|
+
if (Bun.which('docker') === null)
|
|
10
|
+
return []
|
|
11
|
+
|
|
12
|
+
try {
|
|
13
|
+
const ran = await runCommand(['docker', 'ps', '--format', FORMAT], { timeoutMs: 4000 })
|
|
14
|
+
|
|
15
|
+
return ran.code === 0 ? parseDockerPs(ran.text) : []
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return []
|
|
19
|
+
}
|
|
20
|
+
}
|
package/src/kill.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import type { ProcInfo } from './read'
|
|
2
|
+
import { readText } from './read'
|
|
3
|
+
|
|
4
|
+
const SHELLS = new Set(['sh', 'bash', 'zsh', 'fish', 'dash', 'ash', 'nu', 'tcsh', 'ksh', 'elvish', 'xonsh'])
|
|
5
|
+
const TERMINALS = new Set(['kitty', 'alacritty', 'konsole', 'wezterm-gui', 'foot', 'footclient', 'xterm', 'gnome-terminal-', 'ghostty', 'tmux: server', 'tmux', 'screen', 'terminator', 'tilix', 'urxvt', 'st', 'yakuake', 'ptyxis'])
|
|
6
|
+
|
|
7
|
+
export interface Guard {
|
|
8
|
+
uid: number
|
|
9
|
+
// The calling process and each of its ancestors.
|
|
10
|
+
mine: ReadonlySet<number>
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// Why a process must not be signalled, undefined when it may be.
|
|
14
|
+
export function protectionOf(proc: ProcInfo, { uid, mine }: Guard): string | undefined {
|
|
15
|
+
if (proc.pid === 1)
|
|
16
|
+
return 'pid 1'
|
|
17
|
+
|
|
18
|
+
if (proc.uid !== uid)
|
|
19
|
+
return 'another user\'s process'
|
|
20
|
+
|
|
21
|
+
if (mine.has(proc.pid))
|
|
22
|
+
return 'this command or one of its ancestors'
|
|
23
|
+
|
|
24
|
+
if (SHELLS.has(proc.comm))
|
|
25
|
+
return 'a shell'
|
|
26
|
+
|
|
27
|
+
return TERMINALS.has(proc.comm) ? 'a terminal' : undefined
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface Signaller {
|
|
31
|
+
send: (pid: number, signal: NodeJS.Signals) => boolean
|
|
32
|
+
alive: (pid: number) => Promise<boolean>
|
|
33
|
+
sleep: (ms: number) => Promise<void>
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const realSignaller: Signaller = {
|
|
37
|
+
send(pid, signal) {
|
|
38
|
+
try {
|
|
39
|
+
process.kill(pid, signal)
|
|
40
|
+
|
|
41
|
+
return true
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return false
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
// A zombie is dead for our purposes: its parent has yet to reap it.
|
|
48
|
+
async alive(pid) {
|
|
49
|
+
const stat = await readText(`/proc/${pid}/stat`)
|
|
50
|
+
|
|
51
|
+
return stat !== undefined && !stat.slice(stat.lastIndexOf(')') + 2).startsWith('Z')
|
|
52
|
+
},
|
|
53
|
+
sleep: async ms => Bun.sleep(ms),
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface Outcome {
|
|
57
|
+
// Gone after SIGTERM.
|
|
58
|
+
terminated: number[]
|
|
59
|
+
// Needed SIGKILL.
|
|
60
|
+
killed: number[]
|
|
61
|
+
// Still there at the end, or refused the signal.
|
|
62
|
+
survived: number[]
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const POLL_MS = 100
|
|
66
|
+
|
|
67
|
+
async function waitGone(pids: number[], graceMs: number, signaller: Signaller): Promise<number[]> {
|
|
68
|
+
let alive = pids
|
|
69
|
+
let waited = 0
|
|
70
|
+
|
|
71
|
+
while (alive.length > 0 && waited < graceMs) {
|
|
72
|
+
await signaller.sleep(POLL_MS)
|
|
73
|
+
waited += POLL_MS
|
|
74
|
+
alive = await filterAlive(alive, signaller)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return alive
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function filterAlive(pids: number[], signaller: Signaller): Promise<number[]> {
|
|
81
|
+
const alive: number[] = []
|
|
82
|
+
|
|
83
|
+
for (const pid of pids) {
|
|
84
|
+
if (await signaller.alive(pid))
|
|
85
|
+
alive.push(pid)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return alive
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// SIGTERM to each pid, then with `escalate` SIGKILL to those still there after `graceMs`.
|
|
92
|
+
export async function terminate(pids: number[], { escalate, graceMs, signaller = realSignaller }: { escalate: boolean, graceMs: number, signaller?: Signaller }): Promise<Outcome> {
|
|
93
|
+
const failed = pids.filter(pid => !signaller.send(pid, 'SIGTERM'))
|
|
94
|
+
// A pid that no longer exists (ESRCH) is gone, not a survivor; only one that exists yet refused the signal is.
|
|
95
|
+
const refused = await filterAlive(failed, signaller)
|
|
96
|
+
const sent = pids.filter(pid => !failed.includes(pid))
|
|
97
|
+
const remaining = await waitGone(sent, graceMs, signaller)
|
|
98
|
+
const terminated = pids.filter(pid => (failed.includes(pid) ? !refused.includes(pid) : !remaining.includes(pid)))
|
|
99
|
+
|
|
100
|
+
if (!escalate || remaining.length === 0)
|
|
101
|
+
return { terminated, killed: [], survived: [...refused, ...remaining] }
|
|
102
|
+
|
|
103
|
+
for (const pid of remaining)
|
|
104
|
+
signaller.send(pid, 'SIGKILL')
|
|
105
|
+
|
|
106
|
+
const stuck = await waitGone(remaining, 2000, signaller)
|
|
107
|
+
|
|
108
|
+
return { terminated, killed: remaining.filter(pid => !stuck.includes(pid)), survived: [...refused, ...stuck] }
|
|
109
|
+
}
|
package/src/mask.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { basename } from 'node:path'
|
|
2
|
+
import { isSecretName } from '@kaynooo/cli-kit'
|
|
3
|
+
|
|
4
|
+
export const MASK = '***'
|
|
5
|
+
|
|
6
|
+
// Shapes of a secret that give themselves away whatever the name holding them: a URL password, a well known token format, a long opaque token.
|
|
7
|
+
const URL_PASSWORD = /(?<![a-z0-9+.-])([a-z][a-z0-9+.-]{0,31}:\/\/[^\s:/@]*:)[^\s'"@]{1,1024}@/gi
|
|
8
|
+
const TOKEN = /\b(?:gh[pousr]_|github_pat_|glpat-|sk-|xox[abprs]-|npm_|[sr]k_(?:live|test)_)[\w-]{10,}|\beyJ[\w-]+\.[\w-]+\.[\w-]+|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bBearer\s+[\w.~+/=-]{16,}/g
|
|
9
|
+
const OPAQUE = /(?<![\w-])(?=[\w-]{32,}(?![\w-]))(?=[\w-]*[A-Z])(?=[\w-]*\d)[\w-]+/gi
|
|
10
|
+
const PEM = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]*/
|
|
11
|
+
|
|
12
|
+
// A value with whatever looks like a secret inside it replaced.
|
|
13
|
+
export function maskText(value: string): string {
|
|
14
|
+
return value.replace(PEM, MASK).replace(URL_PASSWORD, `$1${MASK}@`).replace(TOKEN, MASK).replace(OPAQUE, MASK)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// A value under its variable name: all of it when the name says secret, else the secrets inside it.
|
|
18
|
+
export function maskValue(name: string, value: string): string {
|
|
19
|
+
if (value === '')
|
|
20
|
+
return value
|
|
21
|
+
|
|
22
|
+
return isSecretName(name) ? MASK : maskText(value)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function maskEnviron(entries: [name: string, value: string][]): [name: string, value: string][] {
|
|
26
|
+
return entries.map(([name, value]) => [name, maskValue(name, value)])
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const FLAG = /^-{1,2}([\w.-]+)(=|$)/
|
|
30
|
+
const ASSIGNMENT_NAME = /^[\w.-]+$/
|
|
31
|
+
// Commands whose short -p flag carries a password; for the others (ssh, docker, psql) it is a port.
|
|
32
|
+
const PASSWORD_SPLIT = new Set(['sshpass'])
|
|
33
|
+
const PASSWORD_JOINED = new Set(['mysql', 'mysqldump', 'mysqladmin', 'mariadb', 'mariadb-dump'])
|
|
34
|
+
|
|
35
|
+
// A command line with secrets masked: `--password=x`, `--token x` and `API_KEY=x` words, and secret shapes in any other.
|
|
36
|
+
export function maskArgs(args: string[]): string[] {
|
|
37
|
+
const command = basename(args[0] ?? '')
|
|
38
|
+
let hidden = false
|
|
39
|
+
|
|
40
|
+
return args.map((arg, index) => {
|
|
41
|
+
if (hidden) {
|
|
42
|
+
hidden = false
|
|
43
|
+
|
|
44
|
+
return arg.startsWith('-') ? maskText(arg) : MASK
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (index > 0 && arg === '-p' && PASSWORD_SPLIT.has(command)) {
|
|
48
|
+
hidden = true
|
|
49
|
+
|
|
50
|
+
return arg
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (index > 0 && arg.length > 2 && arg.startsWith('-p') && PASSWORD_JOINED.has(command))
|
|
54
|
+
return `-p${MASK}`
|
|
55
|
+
|
|
56
|
+
const flag = FLAG.exec(arg)
|
|
57
|
+
|
|
58
|
+
if (flag !== null) {
|
|
59
|
+
if (flag[2] === '=')
|
|
60
|
+
return isSecretName(flag[1]!) ? `${arg.slice(0, flag[0].length)}${MASK}` : maskText(arg)
|
|
61
|
+
|
|
62
|
+
hidden = isSecretName(flag[1]!)
|
|
63
|
+
|
|
64
|
+
return arg
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const equals = arg.indexOf('=')
|
|
68
|
+
|
|
69
|
+
return equals > 0 && ASSIGNMENT_NAME.test(arg.slice(0, equals)) ? `${arg.slice(0, equals + 1)}${maskValue(arg.slice(0, equals), arg.slice(equals + 1))}` : maskText(arg)
|
|
70
|
+
})
|
|
71
|
+
}
|
package/src/parse.ts
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
export type Protocol = 'tcp' | 'udp'
|
|
2
|
+
|
|
3
|
+
export interface Socket {
|
|
4
|
+
protocol: Protocol
|
|
5
|
+
family: 4 | 6
|
|
6
|
+
address: string
|
|
7
|
+
port: number
|
|
8
|
+
inode: number
|
|
9
|
+
uid: number
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// A TCP socket in LISTEN, or a UDP one bound and not connected.
|
|
13
|
+
const LISTENING: Record<Protocol, string> = { tcp: '0A', udp: '07' }
|
|
14
|
+
const WHITESPACE = /\s+/
|
|
15
|
+
const HEX_PAIR = /../g
|
|
16
|
+
const SOCKET_LINK = /^socket:\[(\d+)\]$/
|
|
17
|
+
const UNIT_SCOPE = /\.(?:service|scope)$/
|
|
18
|
+
const CONTAINER_ID = /(?:docker-|libpod-|\/docker\/)([0-9a-f]{64})/
|
|
19
|
+
const DOCKER_PORT = /:(\d+)(?:-(\d+))?->[\d-]+\/(tcp|udp)/
|
|
20
|
+
|
|
21
|
+
// One 32-bit word of an address, which /proc prints in the host's byte order (little endian), as its two hextets.
|
|
22
|
+
function word(hex: string): [number, number] {
|
|
23
|
+
const bytes = (hex.match(HEX_PAIR) ?? []).reverse().map(byte => Number.parseInt(byte, 16))
|
|
24
|
+
|
|
25
|
+
return [(bytes[0]! << 8) | bytes[1]!, (bytes[2]! << 8) | bytes[3]!]
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// An address as /proc/net/tcp and /proc/net/tcp6 write it: eight hex digits for IPv4, thirty-two for IPv6.
|
|
29
|
+
export function parseAddress(hex: string): string {
|
|
30
|
+
if (hex.length === 8) {
|
|
31
|
+
const [high, low] = word(hex)
|
|
32
|
+
|
|
33
|
+
return `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const hextets = (hex.match(/.{8}/g) ?? []).flatMap(word)
|
|
37
|
+
|
|
38
|
+
if (hextets.length !== 8)
|
|
39
|
+
return hex
|
|
40
|
+
|
|
41
|
+
if (hextets.slice(0, 5).every(part => part === 0) && hextets[5] === 0xFFFF)
|
|
42
|
+
return `::ffff:${hextets[6]! >> 8}.${hextets[6]! & 255}.${hextets[7]! >> 8}.${hextets[7]! & 255}`
|
|
43
|
+
|
|
44
|
+
return compress(hextets)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// The textual form of eight hextets, the longest run of zeros (two or more) written `::`.
|
|
48
|
+
function compress(hextets: number[]): string {
|
|
49
|
+
let best = { start: -1, length: 0 }
|
|
50
|
+
let run = { start: 0, length: 0 }
|
|
51
|
+
|
|
52
|
+
for (const [at, part] of hextets.entries()) {
|
|
53
|
+
run = part === 0 ? { start: run.length === 0 ? at : run.start, length: run.length + 1 } : { start: 0, length: 0 }
|
|
54
|
+
|
|
55
|
+
if (run.length > best.length)
|
|
56
|
+
best = run
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const text = (parts: number[]) => parts.map(part => part.toString(16)).join(':')
|
|
60
|
+
|
|
61
|
+
if (best.length < 2)
|
|
62
|
+
return text(hextets)
|
|
63
|
+
|
|
64
|
+
return `${text(hextets.slice(0, best.start))}::${text(hextets.slice(best.start + best.length))}`
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// The listening sockets of one /proc/net table, `family` telling its address width.
|
|
68
|
+
export function parseNetTable(text: string, protocol: Protocol, family: 4 | 6): Socket[] {
|
|
69
|
+
const sockets: Socket[] = []
|
|
70
|
+
|
|
71
|
+
for (const line of text.split('\n').slice(1)) {
|
|
72
|
+
const columns = line.trim().split(WHITESPACE)
|
|
73
|
+
const [address = '', port = ''] = (columns[1] ?? '').split(':')
|
|
74
|
+
|
|
75
|
+
if (columns.length < 10 || columns[3] !== LISTENING[protocol])
|
|
76
|
+
continue
|
|
77
|
+
|
|
78
|
+
const number = Number.parseInt(port, 16)
|
|
79
|
+
|
|
80
|
+
if (number === 0 || Number.isNaN(number))
|
|
81
|
+
continue
|
|
82
|
+
|
|
83
|
+
sockets.push({ protocol, family, address: parseAddress(address), port: number, uid: Number(columns[7]), inode: Number(columns[9]) })
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return sockets
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// The inode of a `socket:[12345]` fd link, undefined for any other.
|
|
90
|
+
export function socketInode(link: string): number | undefined {
|
|
91
|
+
const match = SOCKET_LINK.exec(link)
|
|
92
|
+
|
|
93
|
+
return match === null ? undefined : Number(match[1])
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface Stat {
|
|
97
|
+
comm: string
|
|
98
|
+
state: string
|
|
99
|
+
ppid: number
|
|
100
|
+
pgrp: number
|
|
101
|
+
session: number
|
|
102
|
+
tty: number
|
|
103
|
+
// Clock ticks after boot at which the process started.
|
|
104
|
+
startTicks: number
|
|
105
|
+
threads: number
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// /proc/<pid>/stat. The command sits in parentheses and may hold spaces and parentheses itself, so the fields are counted from its last one.
|
|
109
|
+
export function parseStat(text: string): Stat | undefined {
|
|
110
|
+
const open = text.indexOf('(')
|
|
111
|
+
const close = text.lastIndexOf(')')
|
|
112
|
+
|
|
113
|
+
if (open === -1 || close < open)
|
|
114
|
+
return undefined
|
|
115
|
+
|
|
116
|
+
const rest = text.slice(close + 2).trim().split(WHITESPACE)
|
|
117
|
+
const field = (number: number) => Number(rest[number - 3])
|
|
118
|
+
|
|
119
|
+
if (rest.length < 20)
|
|
120
|
+
return undefined
|
|
121
|
+
|
|
122
|
+
return { comm: text.slice(open + 1, close), state: rest[0]!, ppid: field(4), pgrp: field(5), session: field(6), tty: field(7), threads: field(20), startTicks: field(22) }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// The `Key:\tvalue` lines of /proc/<pid>/status.
|
|
126
|
+
export function parseStatus(text: string): Map<string, string> {
|
|
127
|
+
const fields = new Map<string, string>()
|
|
128
|
+
|
|
129
|
+
for (const line of text.split('\n')) {
|
|
130
|
+
const colon = line.indexOf(':')
|
|
131
|
+
|
|
132
|
+
if (colon > 0)
|
|
133
|
+
fields.set(line.slice(0, colon), line.slice(colon + 1).trim())
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return fields
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// A status value in kB (`VmRSS: 1234 kB`) in bytes.
|
|
140
|
+
export function statusBytes(fields: Map<string, string>, key: string): number | undefined {
|
|
141
|
+
const value = Number.parseInt(fields.get(key) ?? '', 10)
|
|
142
|
+
|
|
143
|
+
return Number.isNaN(value) ? undefined : value * 1024
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// The real user id of `Uid:\t1000\t1000\t1000\t1000`.
|
|
147
|
+
export function statusUid(fields: Map<string, string>): number | undefined {
|
|
148
|
+
const value = Number.parseInt(fields.get('Uid') ?? '', 10)
|
|
149
|
+
|
|
150
|
+
return Number.isNaN(value) ? undefined : value
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export interface Limit {
|
|
154
|
+
name: string
|
|
155
|
+
soft: string
|
|
156
|
+
hard: string
|
|
157
|
+
units: string
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const LIMIT_LINE = /^(\S+(?: \S+)*)\s{2,}(\S+)\s+(\S+)(?:\s+(\S+))?\s*$/
|
|
161
|
+
|
|
162
|
+
// /proc/<pid>/limits, whose columns are padded with spaces and whose names hold single ones.
|
|
163
|
+
export function parseLimits(text: string): Limit[] {
|
|
164
|
+
const limits: Limit[] = []
|
|
165
|
+
|
|
166
|
+
for (const line of text.split('\n').slice(1)) {
|
|
167
|
+
const match = LIMIT_LINE.exec(line)
|
|
168
|
+
|
|
169
|
+
if (match !== null)
|
|
170
|
+
limits.push({ name: match[1]!, soft: match[2]!, hard: match[3]!, units: match[4] ?? '' })
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
return limits
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// /proc/<pid>/cmdline: arguments joined by NUL, empty for a kernel thread.
|
|
177
|
+
export function parseCmdline(text: string): string[] {
|
|
178
|
+
return text.split('\0').filter((_, at, parts) => at < parts.length - 1 || parts[at] !== '')
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export function parseEnviron(text: string): [name: string, value: string][] {
|
|
182
|
+
return parseCmdline(text).map((entry) => {
|
|
183
|
+
const equals = entry.indexOf('=')
|
|
184
|
+
|
|
185
|
+
return equals === -1 ? [entry, ''] : [entry.slice(0, equals), entry.slice(equals + 1)]
|
|
186
|
+
})
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export interface CgroupEntry {
|
|
190
|
+
hierarchy: string
|
|
191
|
+
controllers: string
|
|
192
|
+
path: string
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export function parseCgroup(text: string): CgroupEntry[] {
|
|
196
|
+
return text.split('\n').filter(line => line !== '').map((line) => {
|
|
197
|
+
const [hierarchy = '', controllers = '', ...path] = line.split(':')
|
|
198
|
+
|
|
199
|
+
return { hierarchy, controllers, path: path.join(':') }
|
|
200
|
+
})
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// The innermost systemd unit or scope of a cgroup v2 path: `app-kitty-123.scope`, `docker-<id>.scope`, `foo.service`.
|
|
204
|
+
export function cgroupUnit(entries: CgroupEntry[]): string | undefined {
|
|
205
|
+
const path = (entries.find(entry => entry.hierarchy === '0') ?? entries[0])?.path ?? ''
|
|
206
|
+
|
|
207
|
+
return path.split('/').reverse().find(part => UNIT_SCOPE.test(part))
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// The container id a cgroup path names, for Docker (`docker-<id>.scope` or `/docker/<id>`) and Podman (`libpod-<id>.scope`).
|
|
211
|
+
export function cgroupContainer(entries: CgroupEntry[]): string | undefined {
|
|
212
|
+
for (const { path } of entries) {
|
|
213
|
+
const match = CONTAINER_ID.exec(path)
|
|
214
|
+
|
|
215
|
+
if (match !== null)
|
|
216
|
+
return match[1]
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
return undefined
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// The name behind a uid in /etc/passwd text.
|
|
223
|
+
export function userNameOf(passwd: string, uid: number): string | undefined {
|
|
224
|
+
for (const line of passwd.split('\n')) {
|
|
225
|
+
const [name, , id] = line.split(':')
|
|
226
|
+
|
|
227
|
+
if (id === String(uid) && name !== undefined && name !== '')
|
|
228
|
+
return name
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
return undefined
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export interface Published {
|
|
235
|
+
host: number
|
|
236
|
+
protocol: Protocol
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export interface Container {
|
|
240
|
+
name: string
|
|
241
|
+
project: string | undefined
|
|
242
|
+
service: string | undefined
|
|
243
|
+
published: Published[]
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// The tab separated rows of `docker ps --format '{{.Names}}\t{{.Ports}}\t{{.Label "com.docker.compose.project"}}\t{{.Label "com.docker.compose.service"}}'`; a published range (`8000-8002->80-82/tcp`) counts each of its host ports.
|
|
247
|
+
export function parseDockerPs(text: string): Container[] {
|
|
248
|
+
const containers: Container[] = []
|
|
249
|
+
|
|
250
|
+
for (const line of text.split('\n')) {
|
|
251
|
+
const [name = '', ports = '', project = '', service = ''] = line.split('\t')
|
|
252
|
+
|
|
253
|
+
if (name === '')
|
|
254
|
+
continue
|
|
255
|
+
|
|
256
|
+
const published: Published[] = []
|
|
257
|
+
|
|
258
|
+
for (const entry of ports.split(',')) {
|
|
259
|
+
const match = DOCKER_PORT.exec(entry)
|
|
260
|
+
|
|
261
|
+
if (match === null)
|
|
262
|
+
continue
|
|
263
|
+
|
|
264
|
+
const first = Number(match[1])
|
|
265
|
+
|
|
266
|
+
for (let host = first; host <= Number(match[2] ?? first); host++)
|
|
267
|
+
published.push({ host, protocol: match[3] as Protocol })
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
containers.push({ name, project: project === '' ? undefined : project, service: service === '' ? undefined : service, published })
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
return containers
|
|
274
|
+
}
|