-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocal_tools.js
More file actions
218 lines (204 loc) · 6.76 KB
/
Copy pathlocal_tools.js
File metadata and controls
218 lines (204 loc) · 6.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import { execFileSync } from "node:child_process";
function powershell(script) {
return execFileSync(
"powershell.exe",
["-NoProfile", "-Command", script],
{ encoding: "utf8", timeout: 15_000, windowsHide: true }
).trim();
}
function wslExec(distro, args, user = "root") {
return execFileSync(
"wsl.exe",
["-d", distro, "-u", user, "--", ...args],
{ encoding: "utf8", timeout: 15_000, windowsHide: true }
).trim();
}
function asArray(value) {
if (value == null) return [];
return Array.isArray(value) ? value : [value];
}
export function getProcesses() {
const script = [
"Get-CimInstance Win32_Process |",
"Select-Object ProcessId,ParentProcessId,Name,CommandLine,WorkingSetSize |",
"ConvertTo-Json -Compress"
].join(" ");
const rows = asArray(JSON.parse(powershell(script) || "[]"));
return rows.map(row => ({
pid: Number(row.ProcessId),
parent_pid: Number(row.ParentProcessId),
name: row.Name,
command_line: redactCommandLine(row.CommandLine),
working_set_mb: Math.round(Number(row.WorkingSetSize || 0) / 1048576)
}));
}
function redactCommandLine(value) {
if (!value) return null;
return String(value)
.replace(/(api[-_]?key|token|secret)(\s+|=)([^\s"]+)/gi, "$1$2[REDACTED]")
.replace(/Bearer\s+[^\s"]+/gi, "Bearer [REDACTED]")
.slice(0, 500);
}
export function getListeningPid(port) {
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error("invalid endpoint port");
}
const script = [
"$row=$null;",
`try{$row=Get-NetTCPConnection -State Listen -LocalPort ${port}`,
"-ErrorAction Stop | Select-Object -First 1}catch{};",
"if($null -ne $row){$row.OwningProcess}; exit 0"
].join(" ");
const pid = Number(powershell(script));
if (!Number.isInteger(pid) || pid <= 0) {
throw new Error(`no listening process found on port ${port}`);
}
return pid;
}
export function getWslProcesses(distro = "Ubuntu") {
const text = wslExec(distro, [
"ps", "-eo", "pid=,ppid=,comm=,rss=,args=", "--sort=pid"
]);
return text.split(/\r?\n/).map(line => {
const match = line.match(/^\s*(\d+)\s+(\d+)\s+(\S+)\s+(\d+)\s+(.*)$/);
if (!match) return null;
return {
pid: Number(match[1]),
parent_pid: Number(match[2]),
name: match[3],
working_set_mb: Math.round(Number(match[4]) / 1024),
command_line: redactCommandLine(match[5])
};
}).filter(Boolean);
}
export function getWslListeningPid(port, distro = "Ubuntu") {
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error("invalid endpoint port");
}
const text = wslExec(distro, [
"bash", "-lc",
`ss -H -ltnp 'sport = :${port}' 2>/dev/null || true`
]);
const match = text.match(/pid=(\d+)/);
if (!match) throw new Error(`no WSL listener found on port ${port}`);
return Number(match[1]);
}
function csvRows(text) {
return text.split(/\r?\n/).filter(Boolean)
.map(line => line.split(",").map(value => value.trim()));
}
export function getGpuSnapshot() {
const gpuText = execFileSync("nvidia-smi", [
"--query-gpu=name,temperature.gpu,utilization.gpu,utilization.memory,memory.used,memory.total,power.draw",
"--format=csv,noheader,nounits"
], { encoding: "utf8", timeout: 10_000, windowsHide: true }).trim();
let appsText = "";
try {
appsText = execFileSync("nvidia-smi", [
"--query-compute-apps=pid,process_name,used_gpu_memory",
"--format=csv,noheader,nounits"
], { encoding: "utf8", timeout: 10_000, windowsHide: true }).trim();
} catch {
// WDDM may expose incomplete per-process memory data.
}
const gpu = csvRows(gpuText)[0];
return {
gpu: {
name: gpu[0],
temperature_c: Number(gpu[1]),
gpu_util_pct: Number(gpu[2]),
memory_controller_util_pct: Number(gpu[3]),
vram_used_mb: Number(gpu[4]),
vram_total_mb: Number(gpu[5]),
power_draw_w: Number(gpu[6])
},
compute_processes: csvRows(appsText).map(row => ({
pid: Number(row[0]),
process_name: row[1],
used_gpu_memory_mb: /^\d/.test(row[2] || "") ? Number(row[2]) : null
})).filter(row => Number.isInteger(row.pid))
};
}
export function getWslGpuSnapshot(distro = "Ubuntu") {
const gpuText = wslExec(distro, ["nvidia-smi",
"--query-gpu=name,temperature.gpu,utilization.gpu,utilization.memory,memory.used,memory.total,power.draw",
"--format=csv,noheader,nounits"
]);
let appsText = "";
try {
appsText = wslExec(distro, ["nvidia-smi",
"--query-compute-apps=pid,process_name,used_gpu_memory",
"--format=csv,noheader,nounits"
]);
} catch {
// WSL/WDDM may omit per-process memory.
}
const gpu = csvRows(gpuText)[0];
return {
gpu: {
name: gpu[0],
temperature_c: Number(gpu[1]),
gpu_util_pct: Number(gpu[2]),
memory_controller_util_pct: Number(gpu[3]),
vram_used_mb: Number(gpu[4]),
vram_total_mb: Number(gpu[5]),
power_draw_w: Number(gpu[6])
},
compute_processes: csvRows(appsText).map(row => ({
pid: Number(row[0]),
process_name: row[1],
used_gpu_memory_mb: /^\d/.test(row[2] || "") ? Number(row[2]) : null
})).filter(row => Number.isInteger(row.pid))
};
}
export function descendantPids(rootPid, processes) {
const found = new Set([rootPid]);
let changed = true;
while (changed) {
changed = false;
for (const process of processes) {
if (found.has(process.parent_pid) && !found.has(process.pid)) {
found.add(process.pid);
changed = true;
}
}
}
return found;
}
export function resolveRuntimePid(listenerPid, processes, gpuProcesses) {
const tree = descendantPids(listenerPid, processes);
const gpuWorkers = gpuProcesses.filter(row => tree.has(row.pid));
gpuWorkers.sort((a, b) =>
(b.used_gpu_memory_mb ?? -1) - (a.used_gpu_memory_mb ?? -1)
);
return gpuWorkers[0]?.pid ?? listenerPid;
}
export function buildInspectionSnapshot(
port,
runtimePidOverride,
{ environment = "windows", distro = "Ubuntu" } = {}
) {
const inWsl = environment === "wsl";
const processes = inWsl ? getWslProcesses(distro) : getProcesses();
const listener_pid = inWsl
? getWslListeningPid(port, distro)
: getListeningPid(port);
const gpu = inWsl ? getWslGpuSnapshot(distro) : getGpuSnapshot();
const runtime_pid = runtimePidOverride ??
resolveRuntimePid(listener_pid, processes, gpu.compute_processes);
const tree = descendantPids(listener_pid, processes);
const relevant = processes.filter(process =>
tree.has(process.pid) ||
gpu.compute_processes.some(item => item.pid === process.pid)
);
return {
captured_at: new Date().toISOString(),
endpoint: {
host: "127.0.0.1", port, listener_pid, environment,
distro: inWsl ? distro : null
},
gpu,
relevant_processes: relevant,
ground_truth: { runtime_pid }
};
}