| 87 | * @param {{intervalMs?: number, pid?: number}} options |
| 88 | */ |
| 89 | export function startSocketSampler(options = {}) { |
| 90 | const intervalMs = options.intervalMs ?? 600; |
| 91 | const rootPid = options.pid ?? process.pid; |
| 92 | const state = { |
| 93 | samples: 0, |
| 94 | lsofErrors: 0, |
| 95 | maxProcessTreeSize: 0, |
| 96 | violations: [], |
| 97 | loopback: new Map(), |
| 98 | }; |
| 99 | let running = true; |
| 100 | const started = Date.now(); |
| 101 | |
| 102 | const once = async () => { |
| 103 | const pids = await processTree(rootPid); |
| 104 | state.maxProcessTreeSize = Math.max(state.maxProcessTreeSize, pids.length); |
| 105 | const { lines, error } = await sockets(pids); |
| 106 | if (error !== null) { |
| 107 | state.lsofErrors += 1; |
| 108 | } |
| 109 | state.samples += 1; |
| 110 | for (const line of lines) { |
| 111 | const socket = classifyLine(line); |
| 112 | if (socket === null) { |
| 113 | continue; |
| 114 | } |
| 115 | if (socket.loopback) { |
| 116 | const key = `${socket.protocol} ${socket.remote}`; |
| 117 | state.loopback.set(key, (state.loopback.get(key) ?? 0) + 1); |
| 118 | continue; |
| 119 | } |
| 120 | state.violations.push({ |
| 121 | atMs: Date.now() - started, |
| 122 | protocol: socket.protocol, |
| 123 | command: socket.command, |
| 124 | pid: socket.pid, |
| 125 | local: socket.local, |
| 126 | remote: socket.remote, |
| 127 | }); |
| 128 | } |
| 129 | }; |
| 130 | |
| 131 | const loop = (async () => { |
| 132 | while (running) { |
| 133 | await once(); |
| 134 | if (!running) { |
| 135 | break; |
| 136 | } |
| 137 | await new Promise((wake) => setTimeout(wake, intervalMs)); |
| 138 | } |
| 139 | })(); |
| 140 | |
| 141 | return { |
| 142 | async stop() { |
| 143 | running = false; |
| 144 | await loop; |
| 145 | await once(); |
| 146 | return { |