-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
383 lines (331 loc) · 11.1 KB
/
index.ts
File metadata and controls
383 lines (331 loc) · 11.1 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import { cpus, totalmem, freemem, loadavg, hostname, uptime, platform, arch } from "os";
import { exec } from "child_process";
import { promisify } from "util";
import { initInfluxDB, writeMetrics, queryMetrics, isEnabled as isInfluxEnabled } from "./influxdb";
const execAsync = promisify(exec);
// Parse command-line flags
const args = process.argv.slice(2);
const DEBUG = args.includes("--debug");
function debug(...messages: unknown[]) {
if (DEBUG) {
console.log(`[DEBUG ${new Date().toISOString()}]`, ...messages);
}
}
if (DEBUG) {
console.log("🐛 Debug mode enabled");
}
// Initialize InfluxDB timeseries storage
initInfluxDB(debug);
interface ProcessInfo {
pid: number;
user: string;
cpu: number;
mem: number;
vsz: string;
rss: string;
tty: string;
stat: string;
start: string;
time: string;
command: string;
}
interface CpuUsage {
core: number;
usage: number;
user: number;
system: number;
idle: number;
}
interface SystemMetrics {
hostname: string;
platform: string;
arch: string;
uptime: number;
loadAvg: number[];
cpuCount: number;
cpuModel: string;
cpuUsage: CpuUsage[];
totalMem: number;
freeMem: number;
usedMem: number;
memPercent: number;
processes: ProcessInfo[];
processCount: number;
timestamp: number;
}
// Store previous CPU times for calculating usage
let prevCpuTimes: { user: number; nice: number; sys: number; idle: number; irq: number }[] = [];
function getCpuUsage(): CpuUsage[] {
debug("Collecting CPU usage");
const cpuInfo = cpus();
const usage: CpuUsage[] = [];
cpuInfo.forEach((cpu, index) => {
const total = cpu.times.user + cpu.times.nice + cpu.times.sys + cpu.times.idle + cpu.times.irq;
const prev = prevCpuTimes[index];
if (prev) {
const prevTotal = prev.user + prev.nice + prev.sys + prev.idle + prev.irq;
const totalDiff = total - prevTotal;
const idleDiff = cpu.times.idle - prev.idle;
const userDiff = cpu.times.user - prev.user;
const sysDiff = cpu.times.sys - prev.sys;
if (totalDiff > 0) {
usage.push({
core: index,
usage: Math.round(((totalDiff - idleDiff) / totalDiff) * 100),
user: Math.round((userDiff / totalDiff) * 100),
system: Math.round((sysDiff / totalDiff) * 100),
idle: Math.round((idleDiff / totalDiff) * 100),
});
} else {
usage.push({ core: index, usage: 0, user: 0, system: 0, idle: 100 });
}
} else {
// First run, estimate from current times
const usagePercent = Math.round(((total - cpu.times.idle) / total) * 100);
usage.push({
core: index,
usage: usagePercent,
user: Math.round((cpu.times.user / total) * 100),
system: Math.round((cpu.times.sys / total) * 100),
idle: Math.round((cpu.times.idle / total) * 100),
});
}
prevCpuTimes[index] = { ...cpu.times };
});
return usage;
}
async function getProcesses(): Promise<ProcessInfo[]> {
debug("Fetching process list");
const os = platform();
let command: string;
if (os === "darwin") {
// macOS - use ps with specific format
command = "ps aux -r | head -50";
} else {
// Linux
command = "ps aux --sort=-%cpu | head -50";
}
try {
const { stdout } = await execAsync(command);
const lines = stdout.trim().split("\n");
const processes: ProcessInfo[] = [];
// Skip header line
for (let i = 1; i < lines.length; i++) {
const parts = lines[i].trim().split(/\s+/);
if (parts.length >= 11) {
processes.push({
user: parts[0],
pid: parseInt(parts[1], 10),
cpu: parseFloat(parts[2]),
mem: parseFloat(parts[3]),
vsz: formatBytes(parseInt(parts[4], 10) * 1024),
rss: formatBytes(parseInt(parts[5], 10) * 1024),
tty: parts[6],
stat: parts[7],
start: parts[8],
time: parts[9],
command: parts.slice(10).join(" ").substring(0, 80),
});
}
}
debug(`Found ${processes.length} processes`);
return processes;
} catch (error) {
console.error("Error getting processes:", error);
return [];
}
}
function formatBytes(bytes: number): string {
if (bytes === 0) return "0 B";
const k = 1024;
const sizes = ["B", "K", "M", "G", "T"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + sizes[i];
}
async function getMemoryInfo(): Promise<{ total: number; free: number; used: number; percent: number }> {
const totalMemory = totalmem();
const os = platform();
if (os === "darwin") {
// macOS: use vm_stat to get accurate available memory
// freemem() only reports "free" pages, not inactive/purgeable which are also available
try {
const { stdout } = await execAsync("vm_stat");
const lines = stdout.split("\n");
// Parse page size
const pageSizeMatch = lines[0].match(/page size of (\d+) bytes/);
const pageSize = pageSizeMatch ? parseInt(pageSizeMatch[1], 10) : 16384;
// Parse memory pages
let freePages = 0;
let inactivePages = 0;
let purgeablePages = 0;
let speculativePages = 0;
for (const line of lines) {
if (line.includes("Pages free:")) {
freePages = parseInt(line.match(/(\d+)/)?.[1] || "0", 10);
} else if (line.includes("Pages inactive:")) {
inactivePages = parseInt(line.match(/(\d+)/)?.[1] || "0", 10);
} else if (line.includes("Pages purgeable:")) {
purgeablePages = parseInt(line.match(/(\d+)/)?.[1] || "0", 10);
} else if (line.includes("Pages speculative:")) {
speculativePages = parseInt(line.match(/(\d+)/)?.[1] || "0", 10);
}
}
// Available memory = free + inactive + purgeable + speculative
const availableMemory = (freePages + inactivePages + purgeablePages + speculativePages) * pageSize;
const usedMemory = totalMemory - availableMemory;
return {
total: totalMemory,
free: availableMemory,
used: usedMemory,
percent: Math.round((usedMemory / totalMemory) * 100),
};
} catch {
// Fallback to freemem if vm_stat fails
}
} else if (os === "linux") {
// Linux: read /proc/meminfo for MemAvailable
try {
const { stdout } = await execAsync("cat /proc/meminfo");
const lines = stdout.split("\n");
let memAvailable = 0;
for (const line of lines) {
if (line.startsWith("MemAvailable:")) {
memAvailable = parseInt(line.match(/(\d+)/)?.[1] || "0", 10) * 1024; // Convert KB to bytes
break;
}
}
if (memAvailable > 0) {
const usedMemory = totalMemory - memAvailable;
return {
total: totalMemory,
free: memAvailable,
used: usedMemory,
percent: Math.round((usedMemory / totalMemory) * 100),
};
}
} catch {
// Fallback to freemem if /proc/meminfo fails
}
}
// Fallback for other platforms
const freeMemory = freemem();
const usedMemory = totalMemory - freeMemory;
return {
total: totalMemory,
free: freeMemory,
used: usedMemory,
percent: Math.round((usedMemory / totalMemory) * 100),
};
}
async function getSystemMetrics(): Promise<SystemMetrics> {
debug("Collecting system metrics");
const cpuInfo = cpus();
const memInfo = await getMemoryInfo();
const processes = await getProcesses();
return {
hostname: hostname(),
platform: platform(),
arch: arch(),
uptime: uptime(),
loadAvg: loadavg(),
cpuCount: cpuInfo.length,
cpuModel: cpuInfo[0]?.model || "Unknown",
cpuUsage: getCpuUsage(),
totalMem: memInfo.total,
freeMem: memInfo.free,
usedMem: memInfo.used,
memPercent: memInfo.percent,
processes,
processCount: processes.length,
timestamp: Date.now(),
};
}
const server = Bun.serve({
port: 3001,
async fetch(req) {
const url = new URL(req.url);
// CORS headers
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
};
debug(`${req.method} ${url.pathname}`);
if (req.method === "OPTIONS") {
return new Response(null, { headers: corsHeaders });
}
if (url.pathname === "/api/metrics") {
const metrics = await getSystemMetrics();
// Write to InfluxDB timeseries database
writeMetrics(metrics);
return new Response(JSON.stringify(metrics), {
headers: {
"Content-Type": "application/json",
...corsHeaders,
},
});
}
if (url.pathname === "/api/history") {
if (!isInfluxEnabled()) {
return new Response(JSON.stringify({ error: "Timeseries database not configured" }), {
status: 503,
headers: { "Content-Type": "application/json", ...corsHeaders },
});
}
const measurement = url.searchParams.get("measurement") || "cpu";
const range = url.searchParams.get("range") || "-1h";
const field = url.searchParams.get("field") || "usage_percent";
try {
const data = await queryMetrics(measurement, range, field);
return new Response(JSON.stringify({ measurement, range, field, data }), {
headers: { "Content-Type": "application/json", ...corsHeaders },
});
} catch (error) {
debug("History query error:", error);
return new Response(JSON.stringify({ error: "Query failed" }), {
status: 500,
headers: { "Content-Type": "application/json", ...corsHeaders },
});
}
}
if (url.pathname === "/api/health") {
return new Response(JSON.stringify({ status: "ok" }), {
headers: {
"Content-Type": "application/json",
...corsHeaders,
},
});
}
if (url.pathname === "/api/environment") {
// Return filtered environment variables for system diagnostics
// Only expose safe, non-sensitive variables
const safeVariables = [
"PATH", "HOME", "USER", "SHELL", "TERM", "LANG", "LC_ALL",
"EDITOR", "VISUAL", "PAGER", "TZ", "PWD", "OLDPWD",
"HOSTNAME", "LOGNAME", "XDG_CONFIG_HOME", "XDG_DATA_HOME",
"NODE_ENV", "RUST_BACKTRACE", "PYTHONDONTWRITEBYTECODE",
];
const sensitivePatterns = [
"KEY", "SECRET", "TOKEN", "PASSWORD", "CREDENTIAL",
"AUTH", "PRIVATE", "API_KEY", "ACCESS_KEY",
];
const isSensitive = (name: string): boolean => {
return sensitivePatterns.some(pattern => name.includes(pattern));
};
const envVars = Object.entries(process.env)
.filter(([key]) => safeVariables.includes(key) || key.startsWith("LC_") || key.startsWith("XDG_"))
.map(([key, value]) => ({
name: key,
value: isSensitive(key) ? "[REDACTED]" : (value || ""),
}));
return new Response(JSON.stringify({ variables: envVars }), {
headers: {
"Content-Type": "application/json",
...corsHeaders,
},
});
}
return new Response("Not Found", { status: 404, headers: corsHeaders });
},
});
console.log(`🖥️ btop server running at http://localhost:${server.port}`);