| 1 | /* |
| 2 | * plugin_nvtop - SCORPIOX BOT open-source local GPU telemetry plugin |
| 3 | * |
| 4 | * A single clean-room C99 binary that serves THREE modes: |
| 5 | * 1. --meta / SX_PLUGIN_META=1 -> JSON metadata for discovery |
| 6 | * 2. ?action=metrics | ?action=info | ?format=json |
| 7 | * -> JSON node API |
| 8 | * 3. GET (default) -> responsive HTML dashboard |
| 9 | * |
| 10 | * Strictly LOCAL. The plugin runs nvidia-smi / rocm-smi / ioreg on THIS node |
| 11 | * (the one the plugin is installed on) and parses their CSV/text output. It |
| 12 | * never opens a socket, never runs ssh, and never accepts a host, a command or |
| 13 | * a path from the query string: every command below is a fixed constant. |
| 14 | * |
| 15 | * On a node with no local GPU it reports a clean empty state instead of an |
| 16 | * error, so the dashboard is useful on every machine in the fleet. |
| 17 | * |
| 18 | * Offline determinism: set NVTOP_MOCK_CSV=<path> to make the plugin read a |
| 19 | * small CSV fixture instead of shelling out. That is how the test suite |
| 20 | * exercises multi-GPU behaviour on CPU-only build hosts. |
| 21 | * |
| 22 | * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and |
| 23 | * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under |
| 24 | * scorpiox-server on the node. |
| 25 | * |
| 26 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 27 | */ |
| 28 | |
| 29 | #if defined(__APPLE__) |
| 30 | /* sysctl / ioctl headers pull BSD types that strict c99 would hide */ |
| 31 | # define _DARWIN_C_SOURCE 1 |
| 32 | #elif !defined(_WIN32) |
| 33 | # define _POSIX_C_SOURCE 200809L |
| 34 | # define _DEFAULT_SOURCE 1 |
| 35 | #endif |
| 36 | |
| 37 | #if defined(_WIN32) && !defined(_WIN32_WINNT) |
| 38 | # define _WIN32_WINNT 0x0601 |
| 39 | #endif |
| 40 | |
| 41 | #include <stdio.h> |
| 42 | #include <stdlib.h> |
| 43 | #include <string.h> |
| 44 | #include <time.h> |
| 45 | #include <ctype.h> |
| 46 | #include <errno.h> |
| 47 | |
| 48 | #if defined(_WIN32) |
| 49 | # define WIN32_LEAN_AND_MEAN |
| 50 | # include <windows.h> |
| 51 | #else |
| 52 | # include <unistd.h> |
| 53 | # include <sys/types.h> |
| 54 | # if defined(__APPLE__) |
| 55 | # include <sys/sysctl.h> |
| 56 | # endif |
| 57 | #endif |
| 58 | |
| 59 | #include "bot_theme_plugin.h" |
| 60 | |
| 61 | #define PLUGIN_SLUG "nvtop" |
| 62 | #define PLUGIN_ID "plugin_nvtop" |
| 63 | #define PLUGIN_VER "1.0.3" |
| 64 | |
| 65 | #define MAX_GPUS 32 |
| 66 | #define MAX_PROCS 256 |
| 67 | #define MAX_NAME 96 |
| 68 | #define MAX_UUID 64 |
| 69 | #define MAX_DRIVER 48 |
| 70 | /* ioreg prints the whole PerformanceStatistics dictionary on one line, which is |
| 71 | * routinely several kilobytes. A 1 KB read buffer silently truncated it and the |
| 72 | * utilisation counter looked like it was missing. */ |
| 73 | #define LINE_MAX_BUF 131072 |
| 74 | |
| 75 | /* popen is the only external-process mechanism used, and every command string |
| 76 | * is a compile-time constant. stderr redirection differs per platform because |
| 77 | * popen() goes through the shell. */ |
| 78 | #if defined(_WIN32) |
| 79 | # define DEV_NULL " 2>NUL" |
| 80 | #else |
| 81 | # define DEV_NULL " 2>/dev/null" |
| 82 | #endif |
| 83 | |
| 84 | /* ------------------------------------------------------------------ */ |
| 85 | /* Small utilities */ |
| 86 | /* ------------------------------------------------------------------ */ |
| 87 | |
| 88 | /* Percent-decode in place ('+' becomes space). */ |
| 89 | static void url_decode(char *s) |
| 90 | { |
| 91 | char *o = s; |
| 92 | if (!s) return; |
| 93 | while (*s) { |
| 94 | if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { |
| 95 | int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); |
| 96 | int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); |
| 97 | *o++ = (char)((hi << 4) | lo); |
| 98 | s += 3; |
| 99 | } else if (*s == '+') { |
| 100 | *o++ = ' '; |
| 101 | s++; |
| 102 | } else { |
| 103 | *o++ = *s++; |
| 104 | } |
| 105 | } |
| 106 | *o = '\0'; |
| 107 | } |
| 108 | |
| 109 | /* Read one parameter (decoded) out of a form/query string. */ |
| 110 | static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) |
| 111 | { |
| 112 | size_t klen; |
| 113 | const char *p; |
| 114 | |
| 115 | if (!out || outsz == 0) return 0; |
| 116 | out[0] = '\0'; |
| 117 | if (!qs || !key) return 0; |
| 118 | klen = strlen(key); |
| 119 | |
| 120 | for (p = qs; *p; ) { |
| 121 | if (strncmp(p, key, klen) == 0 && p[klen] == '=') { |
| 122 | const char *v = p + klen + 1; |
| 123 | size_t i = 0; |
| 124 | while (*v && *v != '&' && i + 1 < outsz) |
| 125 | out[i++] = *v++; |
| 126 | out[i] = '\0'; |
| 127 | url_decode(out); |
| 128 | return 1; |
| 129 | } |
| 130 | p = strchr(p, '&'); |
| 131 | if (!p) break; |
| 132 | p++; |
| 133 | } |
| 134 | return 0; |
| 135 | } |
| 136 | |
| 137 | static void json_str(const char *s) |
| 138 | { |
| 139 | putchar('"'); |
| 140 | for (; s && *s; s++) { |
| 141 | unsigned char c = (unsigned char)*s; |
| 142 | switch (c) { |
| 143 | case '"': fputs("\\\"", stdout); break; |
| 144 | case '\\': fputs("\\\\", stdout); break; |
| 145 | case '\n': fputs("\\n", stdout); break; |
| 146 | case '\r': fputs("\\r", stdout); break; |
| 147 | case '\t': fputs("\\t", stdout); break; |
| 148 | default: |
| 149 | if (c >= 0x20) putchar((int)c); |
| 150 | break; |
| 151 | } |
| 152 | } |
| 153 | putchar('"'); |
| 154 | } |
| 155 | |
| 156 | static void utc_now(char *buf, size_t sz) |
| 157 | { |
| 158 | time_t t = time(NULL); |
| 159 | struct tm tmv; |
| 160 | memset(&tmv, 0, sizeof(tmv)); |
| 161 | #if defined(_WIN32) |
| 162 | { |
| 163 | struct tm *p = gmtime(&t); |
| 164 | if (p) tmv = *p; |
| 165 | } |
| 166 | #else |
| 167 | gmtime_r(&t, &tmv); |
| 168 | #endif |
| 169 | strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); |
| 170 | } |
| 171 | |
| 172 | static long node_pid(void) |
| 173 | { |
| 174 | #if defined(_WIN32) |
| 175 | return (long)GetCurrentProcessId(); |
| 176 | #else |
| 177 | return (long)getpid(); |
| 178 | #endif |
| 179 | } |
| 180 | |
| 181 | static void copy_str(char *dst, size_t dstsz, const char *src) |
| 182 | { |
| 183 | size_t n; |
| 184 | if (!dst || dstsz == 0) return; |
| 185 | if (!src) { dst[0] = '\0'; return; } |
| 186 | n = strlen(src); |
| 187 | if (n >= dstsz) n = dstsz - 1; |
| 188 | memcpy(dst, src, n); |
| 189 | dst[n] = '\0'; |
| 190 | } |
| 191 | |
| 192 | /* Trim leading/trailing whitespace in place, return the trimmed start. */ |
| 193 | static char *trim(char *s) |
| 194 | { |
| 195 | char *e; |
| 196 | if (!s) return s; |
| 197 | while (*s && (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')) s++; |
| 198 | e = s + strlen(s); |
| 199 | while (e > s && (e[-1] == ' ' || e[-1] == '\t' || e[-1] == '\r' || e[-1] == '\n')) e--; |
| 200 | *e = '\0'; |
| 201 | return s; |
| 202 | } |
| 203 | |
| 204 | /* nvidia-smi prints "[N/A]" / "N/A" when a counter is unsupported. */ |
| 205 | static int parse_num(const char *s, double *out) |
| 206 | { |
| 207 | char *end = NULL; |
| 208 | double v; |
| 209 | if (!s || !*s) return 0; |
| 210 | if (strstr(s, "N/A") || strstr(s, "n/a")) return 0; |
| 211 | errno = 0; |
| 212 | v = strtod(s, &end); |
| 213 | if (end == s || errno != 0) return 0; |
| 214 | *out = v; |
| 215 | return 1; |
| 216 | } |
| 217 | |
| 218 | /* Split one CSV line in place; returns the field count (max maxf). */ |
| 219 | static int split_csv(char *line, char **fields, int maxf) |
| 220 | { |
| 221 | int n = 0; |
| 222 | char *p = line; |
| 223 | if (!line) return 0; |
| 224 | while (n < maxf) { |
| 225 | fields[n++] = p; |
| 226 | p = strchr(p, ','); |
| 227 | if (!p) break; |
| 228 | *p++ = '\0'; |
| 229 | } |
| 230 | return n; |
| 231 | } |
| 232 | |
| 233 | /* ------------------------------------------------------------------ */ |
| 234 | /* Node authentication */ |
| 235 | /* ------------------------------------------------------------------ */ |
| 236 | |
| 237 | /* |
| 238 | * The node API on :8150 is reachable from the LAN. Every request except |
| 239 | * --meta discovery must prove it knows the node password. Accepted forms |
| 240 | * match the rest of the node API: X-Bot-Password (what bot-web proxies |
| 241 | * with), Authorization: Bearer, and ?pwd= (what the plugin iframe appends). |
| 242 | * When BOT_PASSWORD is unset the plugin is a deliberate no-op, which is how |
| 243 | * a developer runs it locally from a shell. |
| 244 | */ |
| 245 | static void require_node_auth(void) |
| 246 | { |
| 247 | const char *np = getenv("BOT_PASSWORD"); |
| 248 | const char *xp; |
| 249 | const char *auth; |
| 250 | char qpwd[256]; |
| 251 | const char *qs; |
| 252 | |
| 253 | if (!np || !*np) return; |
| 254 | |
| 255 | xp = getenv("HTTP_X_BOT_PASSWORD"); |
| 256 | if (xp && strcmp(xp, np) == 0) return; |
| 257 | |
| 258 | auth = getenv("HTTP_AUTHORIZATION"); |
| 259 | if (auth) { |
| 260 | while (*auth == ' ') auth++; |
| 261 | if (strncmp(auth, "Bearer ", 7) == 0) { |
| 262 | auth += 7; |
| 263 | while (*auth == ' ') auth++; |
| 264 | if (strcmp(auth, np) == 0) return; |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | qs = getenv("QUERY_STRING"); |
| 269 | if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) |
| 270 | return; |
| 271 | |
| 272 | fputs("Status: 401 Unauthorized\r\n" |
| 273 | "Content-Type: application/json; charset=utf-8\r\n" |
| 274 | "Cache-Control: no-store\r\n" |
| 275 | "X-Content-Type-Options: nosniff\r\n\r\n" |
| 276 | "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); |
| 277 | exit(0); |
| 278 | } |
| 279 | |
| 280 | /* ------------------------------------------------------------------ */ |
| 281 | /* Snapshot */ |
| 282 | /* ------------------------------------------------------------------ */ |
| 283 | |
| 284 | typedef struct { |
| 285 | int index; |
| 286 | char uuid[MAX_UUID]; |
| 287 | char name[MAX_NAME]; |
| 288 | double util_gpu; |
| 289 | double mem_used_mb; |
| 290 | double mem_total_mb; |
| 291 | double temp_c; |
| 292 | double power_w; |
| 293 | double power_limit_w; |
| 294 | int has_temp; |
| 295 | int has_power; |
| 296 | int has_plimit; |
| 297 | } gpu_t; |
| 298 | |
| 299 | typedef struct { |
| 300 | char gpu_uuid[MAX_UUID]; |
| 301 | long pid; |
| 302 | char name[MAX_NAME]; |
| 303 | double used_mb; |
| 304 | } proc_t; |
| 305 | |
| 306 | typedef struct { |
| 307 | gpu_t gpus[MAX_GPUS]; |
| 308 | int ngpu; |
| 309 | proc_t procs[MAX_PROCS]; |
| 310 | int nproc; |
| 311 | char driver[MAX_DRIVER]; |
| 312 | char source[16]; /* nvidia / amd / apple / mock / none */ |
| 313 | int available; |
| 314 | int mocked; |
| 315 | char note[192]; |
| 316 | } snap_t; |
| 317 | |
| 318 | static void snap_init(snap_t *s) |
| 319 | { |
| 320 | memset(s, 0, sizeof(*s)); |
| 321 | copy_str(s->source, sizeof(s->source), "none"); |
| 322 | copy_str(s->note, sizeof(s->note), "No local NVIDIA/AMD GPU detected"); |
| 323 | } |
| 324 | |
| 325 | /* Run a fixed command and stream its stdout line by line. */ |
| 326 | typedef void (*line_fn)(char *line, void *ctx); |
| 327 | |
| 328 | static int feed_file_lines(const char *path, line_fn fn, void *ctx); |
| 329 | |
| 330 | static int run_cmd_lines(const char *cmd, line_fn fn, void *ctx) |
| 331 | { |
| 332 | FILE *fp; |
| 333 | char buf[LINE_MAX_BUF]; |
| 334 | int any = 0; |
| 335 | |
| 336 | fp = popen(cmd, "r"); |
| 337 | if (!fp) return 0; |
| 338 | while (fgets(buf, (int)sizeof(buf), fp)) { |
| 339 | size_t n = strlen(buf); |
| 340 | while (n && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; |
| 341 | if (!buf[0] || buf[0] == '#') continue; |
| 342 | any = 1; |
| 343 | fn(buf, ctx); |
| 344 | } |
| 345 | pclose(fp); |
| 346 | return any; |
| 347 | } |
| 348 | |
| 349 | /* ---- mock fixture ------------------------------------------------- */ |
| 350 | |
| 351 | /* |
| 352 | * NVTOP_MOCK_CSV fixture format (one record per line, '#' comments allowed): |
| 353 | * |
| 354 | * GPU,<index>,<uuid>,<name>,<util%>,<mem_used_mb>,<mem_total_mb>,<temp_c>,<power_w>,<power_limit_w>,<driver> |
| 355 | * APP,<gpu_uuid>,<pid>,<process name>,<used_mb> |
| 356 | * |
| 357 | * A field of "-" or "N/A" means "this counter is unavailable". Only the default |
| 358 | * test fixtures use this path; production runs never set the variable. |
| 359 | */ |
| 360 | static void mock_line(char *line, void *ctx) |
| 361 | { |
| 362 | snap_t *s = (snap_t *)ctx; |
| 363 | char *f[12]; |
| 364 | int n; |
| 365 | |
| 366 | if (line[0] == '#') return; |
| 367 | n = split_csv(line, f, 12); |
| 368 | if (n < 2) return; |
| 369 | |
| 370 | if (strcmp(trim(f[0]), "GPU") == 0 && n >= 11 && s->ngpu < MAX_GPUS) { |
| 371 | gpu_t *g = &s->gpus[s->ngpu]; |
| 372 | char *idx; |
| 373 | memset(g, 0, sizeof(*g)); |
| 374 | idx = trim(f[1]); |
| 375 | g->index = atoi(idx); |
| 376 | copy_str(g->uuid, sizeof(g->uuid), trim(f[2])); |
| 377 | copy_str(g->name, sizeof(g->name), trim(f[3])); |
| 378 | parse_num(trim(f[4]), &g->util_gpu); |
| 379 | parse_num(trim(f[5]), &g->mem_used_mb); |
| 380 | parse_num(trim(f[6]), &g->mem_total_mb); |
| 381 | g->has_temp = parse_num(trim(f[7]), &g->temp_c); |
| 382 | g->has_power = parse_num(trim(f[8]), &g->power_w); |
| 383 | g->has_plimit = parse_num(trim(f[9]), &g->power_limit_w); |
| 384 | if (!s->driver[0] && trim(f[10])[0] && strcmp(trim(f[10]), "-") != 0) |
| 385 | copy_str(s->driver, sizeof(s->driver), trim(f[10])); |
| 386 | s->ngpu++; |
| 387 | } else if (strcmp(trim(f[0]), "APP") == 0 && n >= 5 && s->nproc < MAX_PROCS) { |
| 388 | proc_t *p = &s->procs[s->nproc]; |
| 389 | memset(p, 0, sizeof(*p)); |
| 390 | copy_str(p->gpu_uuid, sizeof(p->gpu_uuid), trim(f[1])); |
| 391 | p->pid = (long)atoi(trim(f[2])); |
| 392 | copy_str(p->name, sizeof(p->name), trim(f[3])); |
| 393 | parse_num(trim(f[4]), &p->used_mb); |
| 394 | s->nproc++; |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | static int load_mock(snap_t *s, const char *path) |
| 399 | { |
| 400 | FILE *fp; |
| 401 | char buf[LINE_MAX_BUF]; |
| 402 | int any = 0; |
| 403 | |
| 404 | fp = fopen(path, "r"); |
| 405 | if (!fp) return 0; |
| 406 | while (fgets(buf, (int)sizeof(buf), fp)) { |
| 407 | size_t n = strlen(buf); |
| 408 | while (n && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; |
| 409 | if (!buf[0]) continue; |
| 410 | any = 1; |
| 411 | mock_line(buf, s); |
| 412 | } |
| 413 | fclose(fp); |
| 414 | if (!any) return 0; |
| 415 | s->mocked = 1; |
| 416 | copy_str(s->source, sizeof(s->source), "mock"); |
| 417 | s->available = s->ngpu > 0; |
| 418 | if (s->available) s->note[0] = '\0'; |
| 419 | return 1; |
| 420 | } |
| 421 | |
| 422 | /* ---- NVIDIA ------------------------------------------------------- */ |
| 423 | |
| 424 | struct nv_ctx { snap_t *s; int stage; }; |
| 425 | struct nv_mock_ctx { struct nv_ctx gpu; snap_t *s; }; |
| 426 | |
| 427 | /* |
| 428 | * nvidia-smi --query-gpu=... --format=csv,noheader,nounits |
| 429 | * index,uuid,name,utilization.gpu,memory.used,memory.total, |
| 430 | * temperature.gpu,power.draw,power.limit,driver_version |
| 431 | */ |
| 432 | static void nv_gpu_line(char *line, void *ctx) |
| 433 | { |
| 434 | struct nv_ctx *c = (struct nv_ctx *)ctx; |
| 435 | snap_t *s = c->s; |
| 436 | char *f[12]; |
| 437 | int n = split_csv(line, f, 12); |
| 438 | gpu_t *g; |
| 439 | |
| 440 | if (n < 10 || s->ngpu >= MAX_GPUS) return; |
| 441 | g = &s->gpus[s->ngpu]; |
| 442 | memset(g, 0, sizeof(*g)); |
| 443 | g->index = atoi(trim(f[0])); |
| 444 | copy_str(g->uuid, sizeof(g->uuid), trim(f[1])); |
| 445 | copy_str(g->name, sizeof(g->name), trim(f[2])); |
| 446 | parse_num(trim(f[3]), &g->util_gpu); |
| 447 | parse_num(trim(f[4]), &g->mem_used_mb); |
| 448 | parse_num(trim(f[5]), &g->mem_total_mb); |
| 449 | g->has_temp = parse_num(trim(f[6]), &g->temp_c); |
| 450 | g->has_power = parse_num(trim(f[7]), &g->power_w); |
| 451 | g->has_plimit = parse_num(trim(f[8]), &g->power_limit_w); |
| 452 | if (!s->driver[0]) copy_str(s->driver, sizeof(s->driver), trim(f[9])); |
| 453 | s->ngpu++; |
| 454 | } |
| 455 | |
| 456 | static void nv_proc_line(char *line, void *ctx) |
| 457 | { |
| 458 | snap_t *s = (snap_t *)ctx; |
| 459 | char *f[8]; |
| 460 | int n = split_csv(line, f, 8); |
| 461 | proc_t *p; |
| 462 | |
| 463 | if (n < 4 || s->nproc >= MAX_PROCS) return; |
| 464 | p = &s->procs[s->nproc]; |
| 465 | memset(p, 0, sizeof(*p)); |
| 466 | copy_str(p->gpu_uuid, sizeof(p->gpu_uuid), trim(f[0])); |
| 467 | p->pid = (long)atoi(trim(f[1])); |
| 468 | copy_str(p->name, sizeof(p->name), trim(f[2])); |
| 469 | parse_num(trim(f[3]), &p->used_mb); |
| 470 | s->nproc++; |
| 471 | } |
| 472 | |
| 473 | static int collect_nvidia(snap_t *s) |
| 474 | { |
| 475 | struct nv_ctx c; |
| 476 | int got; |
| 477 | |
| 478 | const char *mocksmi = getenv("NVTOP_MOCK_NVIDIA"); |
| 479 | |
| 480 | c.s = s; |
| 481 | if (mocksmi && *mocksmi) s->mocked = 1; |
| 482 | c.stage = 0; |
| 483 | if (mocksmi && *mocksmi) { |
| 484 | /* Fixture may interleave raw nvidia-smi GPU csv lines and "APP,..." |
| 485 | * process lines; dispatch each line to the parser it belongs to. */ |
| 486 | FILE *fp = fopen(mocksmi, "r"); |
| 487 | char buf[LINE_MAX_BUF]; |
| 488 | got = 0; |
| 489 | if (fp) { |
| 490 | while (fgets(buf, (int)sizeof(buf), fp)) { |
| 491 | size_t n = strlen(buf); |
| 492 | char *ln; |
| 493 | while (n && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; |
| 494 | ln = trim(buf); |
| 495 | if (!ln[0] || ln[0] == '#') continue; |
| 496 | got = 1; |
| 497 | /* Process lines are re-shaped into the csv,noheader layout that |
| 498 | * nv_proc_line expects: uuid,pid,name,used_mb. */ |
| 499 | if (strncmp(ln, "APP,", 4) == 0) |
| 500 | nv_proc_line(ln + 4, (void *)s); |
| 501 | else |
| 502 | nv_gpu_line(ln, (void *)&c); |
| 503 | } |
| 504 | fclose(fp); |
| 505 | } |
| 506 | } else { |
| 507 | got = run_cmd_lines( |
| 508 | "nvidia-smi --query-gpu=index,uuid,name,utilization.gpu,memory.used," |
| 509 | "memory.total,temperature.gpu,power.draw,power.limit,driver_version " |
| 510 | "--format=csv,noheader,nounits" DEV_NULL, nv_gpu_line, &c); |
| 511 | } |
| 512 | if (!got || s->ngpu == 0) return 0; |
| 513 | |
| 514 | run_cmd_lines( |
| 515 | "nvidia-smi --query-compute-apps=gpu_uuid,pid,process_name,used_memory " |
| 516 | "--format=csv,noheader,nounits" DEV_NULL, nv_proc_line, s); |
| 517 | |
| 518 | copy_str(s->source, sizeof(s->source), "nvidia"); |
| 519 | s->available = 1; |
| 520 | s->note[0] = '\0'; |
| 521 | return 1; |
| 522 | } |
| 523 | |
| 524 | /* ---- AMD (rocm-smi) ----------------------------------------------- */ |
| 525 | |
| 526 | /* |
| 527 | * rocm-smi prints one "GPU[n] : <key>: <value>" line per counter, which is |
| 528 | * stable across the 5.x and 6.x releases. VRAM is reported in bytes. |
| 529 | */ |
| 530 | static void amd_line(char *line, void *ctx) |
| 531 | { |
| 532 | snap_t *s = (snap_t *)ctx; |
| 533 | char *lb, *key, *val, *rbr, *sep; |
| 534 | int idx; |
| 535 | gpu_t *g; |
| 536 | |
| 537 | if (strncmp(line, "GPU[", 4) != 0) return; |
| 538 | idx = atoi(line + 4); |
| 539 | if (idx < 0 || idx >= MAX_GPUS) return; |
| 540 | lb = strchr(line, '['); |
| 541 | rbr = lb ? strchr(lb, ']') : NULL; |
| 542 | if (!rbr) return; |
| 543 | /* "GPU[0] : GPU use (%): 87" -> key "GPU use (%)", value "87" */ |
| 544 | key = trim(rbr + 1); |
| 545 | if (*key == ':') key++; |
| 546 | sep = strrchr(key, ':'); |
| 547 | if (!sep) return; |
| 548 | *sep = '\0'; |
| 549 | val = trim(sep + 1); |
| 550 | key = trim(key); |
| 551 | if (!key[0] || !val[0]) return; |
| 552 | |
| 553 | while (s->ngpu <= idx) { |
| 554 | int i = s->ngpu; |
| 555 | memset(&s->gpus[i], 0, sizeof(s->gpus[i])); |
| 556 | s->gpus[i].index = i; |
| 557 | copy_str(s->gpus[i].name, sizeof(s->gpus[i].name), "AMD GPU"); |
| 558 | s->ngpu++; |
| 559 | } |
| 560 | g = &s->gpus[idx]; |
| 561 | |
| 562 | if (strstr(key, "Card series") || strstr(key, "Card SKU")) { |
| 563 | copy_str(g->name, sizeof(g->name), val); |
| 564 | } else if (strstr(key, "GPU use (%)")) { |
| 565 | parse_num(val, &g->util_gpu); |
| 566 | } else if (strstr(key, "VRAM Total Memory (B)")) { |
| 567 | double b = 0; |
| 568 | if (parse_num(val, &b)) g->mem_total_mb = b / (1024.0 * 1024.0); |
| 569 | } else if (strstr(key, "VRAM Total Used Memory (B)")) { |
| 570 | double b = 0; |
| 571 | if (parse_num(val, &b)) g->mem_used_mb = b / (1024.0 * 1024.0); |
| 572 | } else if (strstr(key, "Temperature (Sensor edge)") || strstr(key, "Temperature (Sensor junction)")) { |
| 573 | double v = 0; |
| 574 | if (parse_num(val, &v) && !g->has_temp) { g->temp_c = v; g->has_temp = 1; } |
| 575 | } else if (strstr(key, "Average Graphics Package Power") || strstr(key, "Current Socket Graphics Package Power")) { |
| 576 | double v = 0; |
| 577 | if (parse_num(val, &v) && !g->has_power) { g->power_w = v; g->has_power = 1; } |
| 578 | } else if (strstr(key, "Max Graphics Package Power")) { |
| 579 | double v = 0; |
| 580 | if (parse_num(val, &v) && !g->has_plimit) { g->power_limit_w = v; g->has_plimit = 1; } |
| 581 | } |
| 582 | } |
| 583 | |
| 584 | /* Feed a rocm-smi text fixture through the real parser (offline tests). */ |
| 585 | static int feed_file_lines(const char *path, line_fn fn, void *ctx) |
| 586 | { |
| 587 | FILE *fp; |
| 588 | char buf[LINE_MAX_BUF]; |
| 589 | int any = 0; |
| 590 | |
| 591 | fp = fopen(path, "r"); |
| 592 | if (!fp) return 0; |
| 593 | while (fgets(buf, (int)sizeof(buf), fp)) { |
| 594 | size_t n = strlen(buf); |
| 595 | while (n && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; |
| 596 | if (!buf[0] || buf[0] == '#') continue; |
| 597 | any = 1; |
| 598 | fn(buf, ctx); |
| 599 | } |
| 600 | fclose(fp); |
| 601 | return any; |
| 602 | } |
| 603 | |
| 604 | static int collect_amd(snap_t *s) |
| 605 | { |
| 606 | const char *mockrocm = getenv("NVTOP_MOCK_ROCM"); |
| 607 | int got; |
| 608 | |
| 609 | if (mockrocm && *mockrocm) { |
| 610 | s->mocked = 1; |
| 611 | got = feed_file_lines(mockrocm, amd_line, s); |
| 612 | } |
| 613 | else |
| 614 | got = run_cmd_lines( |
| 615 | "rocm-smi --showproductname --showuse --showmeminfo vram " |
| 616 | "--showtemp --showpower" DEV_NULL, amd_line, s); |
| 617 | |
| 618 | if (!got || s->ngpu == 0) return 0; |
| 619 | copy_str(s->source, sizeof(s->source), "amd"); |
| 620 | s->available = 1; |
| 621 | s->note[0] = '\0'; |
| 622 | return 1; |
| 623 | } |
| 624 | |
| 625 | /* ---- Apple Silicon (ioreg IOAccelerator) -------------------------- */ |
| 626 | |
| 627 | /* |
| 628 | * ioreg prints one big nested dictionary, and several counters live inside the |
| 629 | * "PerformanceStatistics" sub-dictionary on the SAME physical line: |
| 630 | * |
| 631 | * "PerformanceStatistics" = {"In use system memory (driver)"=0, ..., |
| 632 | * "Device Utilization %"=19, |
| 633 | * "In use system memory"=51597524992} |
| 634 | * |
| 635 | * So the value of a counter is not "everything after the first '=' in the |
| 636 | * line" - that would parse the sub-dictionary opener. Locate the key first, |
| 637 | * then take the '=' that follows it. |
| 638 | */ |
| 639 | #if defined(__APPLE__) |
| 640 | static const char *apple_value(const char *line, const char *key, int skip_paren) |
| 641 | { |
| 642 | const char *p = line; |
| 643 | size_t klen = strlen(key); |
| 644 | |
| 645 | while ((p = strstr(p, key)) != NULL) { |
| 646 | const char *v = p + klen; |
| 647 | /* "In use system memory (driver)" also starts with the same text, so a |
| 648 | * paren-suffixed hit must be skipped rather than ending the search. */ |
| 649 | if (skip_paren && v[0] == ' ') { p = v; continue; } |
| 650 | while (*v == '"' || *v == ' ') v++; |
| 651 | if (*v != '=') { p = v; continue; } |
| 652 | v++; |
| 653 | while (*v == ' ') v++; |
| 654 | return v; |
| 655 | } |
| 656 | return NULL; |
| 657 | } |
| 658 | |
| 659 | static void apple_quoted(const char *v, char *out, size_t outsz) |
| 660 | { |
| 661 | const char *end; |
| 662 | size_t n; |
| 663 | if (!v || !*v) return; |
| 664 | if (*v == '"') { |
| 665 | v++; |
| 666 | end = strchr(v, '"'); |
| 667 | n = end ? (size_t)(end - v) : strlen(v); |
| 668 | } else if (*v == '<') { |
| 669 | v++; |
| 670 | end = strchr(v, '>'); |
| 671 | n = end ? (size_t)(end - v) : strlen(v); |
| 672 | } else { |
| 673 | end = v; |
| 674 | while (*end && *end != ',' && *end != '}') end++; |
| 675 | n = (size_t)(end - v); |
| 676 | while (n && v[n - 1] == ' ') n--; |
| 677 | } |
| 678 | if (n >= outsz) n = outsz - 1; |
| 679 | if (n) { memcpy(out, v, n); out[n] = '\0'; } |
| 680 | } |
| 681 | |
| 682 | static void apple_line(char *line, void *ctx) |
| 683 | { |
| 684 | snap_t *s = (snap_t *)ctx; |
| 685 | gpu_t *g; |
| 686 | const char *v; |
| 687 | double num = 0; |
| 688 | |
| 689 | if (s->ngpu == 0) { |
| 690 | memset(&s->gpus[0], 0, sizeof(s->gpus[0])); |
| 691 | copy_str(s->gpus[0].name, sizeof(s->gpus[0].name), "Apple GPU"); |
| 692 | s->ngpu = 1; |
| 693 | } |
| 694 | g = &s->gpus[0]; |
| 695 | |
| 696 | if ((v = apple_value(line, "\"model\"", 0)) != NULL) |
| 697 | apple_quoted(v, g->name, sizeof(g->name)); |
| 698 | |
| 699 | if ((v = apple_value(line, "Device Utilization %", 0)) != NULL && |
| 700 | parse_num(v, &num)) |
| 701 | g->util_gpu = num; |
| 702 | |
| 703 | /* Prefer the plain "In use system memory" over "(driver)". */ |
| 704 | if ((v = apple_value(line, "In use system memory", 1)) != NULL && |
| 705 | parse_num(v, &num)) |
| 706 | g->mem_used_mb = num / (1024.0 * 1024.0); |
| 707 | |
| 708 | (void)v; |
| 709 | } |
| 710 | |
| 711 | static int collect_apple(snap_t *s) |
| 712 | { |
| 713 | int got = run_cmd_lines("ioreg -rc IOAccelerator -d 1" DEV_NULL, apple_line, s); |
| 714 | unsigned long long memsize = 0; |
| 715 | size_t len = sizeof(memsize); |
| 716 | |
| 717 | if (!got || s->ngpu == 0) return 0; |
| 718 | |
| 719 | /* Apple GPUs share the unified memory pool, so the honest "VRAM total" on a |
| 720 | * Mac is the machine's physical RAM, not an allocation counter. */ |
| 721 | if (sysctlbyname("hw.memsize", &memsize, &len, NULL, 0) == 0 && memsize > 0) |
| 722 | s->gpus[0].mem_total_mb = (double)memsize / (1024.0 * 1024.0); |
| 723 | |
| 724 | copy_str(s->source, sizeof(s->source), "apple"); |
| 725 | s->available = 1; |
| 726 | s->note[0] = '\0'; |
| 727 | return 1; |
| 728 | } |
| 729 | #endif |
| 730 | |
| 731 | /* ---- orchestration ------------------------------------------------ */ |
| 732 | |
| 733 | static void snapshot(snap_t *s) |
| 734 | { |
| 735 | const char *mock = getenv("NVTOP_MOCK_CSV"); |
| 736 | |
| 737 | snap_init(s); |
| 738 | if (mock && *mock && load_mock(s, mock)) return; |
| 739 | |
| 740 | if (collect_nvidia(s)) return; |
| 741 | if (collect_amd(s)) return; |
| 742 | #if defined(__APPLE__) |
| 743 | if (collect_apple(s)) return; |
| 744 | #endif |
| 745 | /* Nothing found: keep the clean CPU-only empty state. */ |
| 746 | copy_str(s->source, sizeof(s->source), "none"); |
| 747 | s->available = 0; |
| 748 | copy_str(s->note, sizeof(s->note), "No local NVIDIA/AMD GPU detected"); |
| 749 | } |
| 750 | |
| 751 | /* Attach "gpu_index" to each process by matching its UUID. */ |
| 752 | static int gpu_index_for(snap_t *s, const char *uuid) |
| 753 | { |
| 754 | int i; |
| 755 | if (!uuid || !*uuid) return -1; |
| 756 | for (i = 0; i < s->ngpu; i++) |
| 757 | if (strcmp(s->gpus[i].uuid, uuid) == 0) return s->gpus[i].index; |
| 758 | return -1; |
| 759 | } |
| 760 | |
| 761 | /* ------------------------------------------------------------------ */ |
| 762 | /* Modes */ |
| 763 | /* ------------------------------------------------------------------ */ |
| 764 | |
| 765 | static int mode_meta(void) |
| 766 | { |
| 767 | puts("{\"name\":\"nvtop\",\"desc\":\"Local GPUs\"}"); |
| 768 | return 0; |
| 769 | } |
| 770 | |
| 771 | static void json_header(void) |
| 772 | { |
| 773 | /* Deliberately no Content-Length - the server owns framing. */ |
| 774 | fputs("Content-Type: application/json; charset=utf-8\r\n" |
| 775 | "Cache-Control: no-store\r\n" |
| 776 | "X-Content-Type-Options: nosniff\r\n\r\n", stdout); |
| 777 | } |
| 778 | |
| 779 | static void emit_gpu(const gpu_t *g) |
| 780 | { |
| 781 | fputs("{\"index\":", stdout); |
| 782 | printf("%d", g->index); |
| 783 | fputs(",\"uuid\":", stdout); |
| 784 | json_str(g->uuid); |
| 785 | fputs(",\"name\":", stdout); |
| 786 | json_str(g->name); |
| 787 | printf(",\"util_gpu\":%.1f", g->util_gpu); |
| 788 | printf(",\"mem_used_mb\":%.0f", g->mem_used_mb); |
| 789 | printf(",\"mem_total_mb\":%.0f", g->mem_total_mb); |
| 790 | fputs(",\"temp_c\":", stdout); |
| 791 | if (g->has_temp) printf("%.0f", g->temp_c); else fputs("null", stdout); |
| 792 | fputs(",\"power_w\":", stdout); |
| 793 | if (g->has_power) printf("%.1f", g->power_w); else fputs("null", stdout); |
| 794 | fputs(",\"power_limit_w\":", stdout); |
| 795 | if (g->has_plimit) printf("%.1f", g->power_limit_w); else fputs("null", stdout); |
| 796 | fputs("}", stdout); |
| 797 | } |
| 798 | |
| 799 | static void emit_metrics(snap_t *s, const char *utc) |
| 800 | { |
| 801 | int i; |
| 802 | double mem_used = 0, mem_total = 0, util_sum = 0, power = 0; |
| 803 | int power_n = 0; |
| 804 | |
| 805 | json_header(); |
| 806 | fputs("{\"ok\":true,\"action\":\"metrics\"", stdout); |
| 807 | fputs(",\"available\":", stdout); |
| 808 | fputs(s->available ? "true" : "false", stdout); |
| 809 | fputs(",\"source\":", stdout); |
| 810 | json_str(s->source); |
| 811 | fputs(",\"mocked\":", stdout); |
| 812 | fputs(s->mocked ? "true" : "false", stdout); |
| 813 | fputs(",\"driver\":", stdout); |
| 814 | json_str(s->driver); |
| 815 | fputs(",\"utc\":", stdout); |
| 816 | json_str(utc); |
| 817 | fputs(",\"count\":", stdout); |
| 818 | printf("%d", s->ngpu); |
| 819 | fputs(",\"process_count\":", stdout); |
| 820 | printf("%d", s->nproc); |
| 821 | |
| 822 | for (i = 0; i < s->ngpu; i++) { |
| 823 | mem_used += s->gpus[i].mem_used_mb; |
| 824 | mem_total += s->gpus[i].mem_total_mb; |
| 825 | util_sum += s->gpus[i].util_gpu; |
| 826 | if (s->gpus[i].has_power) { power += s->gpus[i].power_w; power_n++; } |
| 827 | } |
| 828 | printf(",\"util_gpu_avg\":%.1f", s->ngpu ? util_sum / (double)s->ngpu : 0.0); |
| 829 | printf(",\"mem_used_mb\":%.0f,\"mem_total_mb\":%.0f", mem_used, mem_total); |
| 830 | fputs(",\"power_w\":", stdout); |
| 831 | if (power_n) printf("%.1f", power); else fputs("null", stdout); |
| 832 | |
| 833 | fputs(",\"gpus\":[", stdout); |
| 834 | for (i = 0; i < s->ngpu; i++) { |
| 835 | if (i) putchar(','); |
| 836 | emit_gpu(&s->gpus[i]); |
| 837 | } |
| 838 | fputs("],\"processes\":[", stdout); |
| 839 | for (i = 0; i < s->nproc; i++) { |
| 840 | const proc_t *p = &s->procs[i]; |
| 841 | if (i) putchar(','); |
| 842 | fputs("{\"gpu_uuid\":", stdout); |
| 843 | json_str(p->gpu_uuid); |
| 844 | fputs(",\"gpu_index\":", stdout); |
| 845 | printf("%d", gpu_index_for(s, p->gpu_uuid)); |
| 846 | fputs(",\"pid\":", stdout); |
| 847 | printf("%ld", p->pid); |
| 848 | fputs(",\"name\":", stdout); |
| 849 | json_str(p->name); |
| 850 | printf(",\"used_mb\":%.0f}", p->used_mb); |
| 851 | } |
| 852 | fputs("],\"message\":", stdout); |
| 853 | json_str(s->note); |
| 854 | fputs("}\n", stdout); |
| 855 | } |
| 856 | |
| 857 | static int mode_json(const char *qs) |
| 858 | { |
| 859 | char action[64]; |
| 860 | char utc[40]; |
| 861 | snap_t s; |
| 862 | |
| 863 | action[0] = '\0'; |
| 864 | get_query_val(qs, "action", action, sizeof(action)); |
| 865 | |
| 866 | if (action[0] && strcmp(action, "metrics") != 0 && strcmp(action, "info") != 0) { |
| 867 | json_header(); |
| 868 | printf("{\"ok\":false,\"error\":\"unknown_action\"," |
| 869 | "\"supported\":[\"metrics\",\"info\"],\"requested\":"); |
| 870 | json_str(action); |
| 871 | fputs("}\n", stdout); |
| 872 | return 0; |
| 873 | } |
| 874 | if (!action[0]) copy_str(action, sizeof(action), "metrics"); |
| 875 | |
| 876 | utc_now(utc, sizeof(utc)); |
| 877 | |
| 878 | if (strcmp(action, "info") == 0) { |
| 879 | char platform[64]; |
| 880 | json_header(); |
| 881 | fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\"," |
| 882 | "\"version\":\"" PLUGIN_VER "\",\"platform\":", stdout); |
| 883 | #if defined(_WIN32) |
| 884 | copy_str(platform, sizeof(platform), "windows"); |
| 885 | #elif defined(__APPLE__) |
| 886 | copy_str(platform, sizeof(platform), "macos"); |
| 887 | #else |
| 888 | copy_str(platform, sizeof(platform), "linux"); |
| 889 | #endif |
| 890 | json_str(platform); |
| 891 | fputs(",\"pid\":", stdout); |
| 892 | printf("%ld", node_pid()); |
| 893 | fputs(",\"utc\":", stdout); |
| 894 | json_str(utc); |
| 895 | fputs(",\"node_auth\":", stdout); |
| 896 | { |
| 897 | const char *np = getenv("BOT_PASSWORD"); |
| 898 | fputs((np && *np) ? "true" : "false", stdout); |
| 899 | } |
| 900 | fputs(",\"supported\":[\"metrics\",\"info\"]," |
| 901 | "\"probes\":[\"nvidia-smi\",\"rocm-smi\"]," |
| 902 | "\"mock_hook\":\"NVTOP_MOCK_CSV\"," |
| 903 | "\"max_gpus\":", stdout); |
| 904 | printf("%d", MAX_GPUS); |
| 905 | fputs(",\"zero_network\":true}\n", stdout); |
| 906 | return 0; |
| 907 | } |
| 908 | |
| 909 | snapshot(&s); |
| 910 | emit_metrics(&s, utc); |
| 911 | return 0; |
| 912 | } |
| 913 | |
| 914 | static void mode_html(int embed) |
| 915 | { |
| 916 | fputs("Content-Type: text/html; charset=utf-8\r\n" |
| 917 | "Cache-Control: no-store\r\n" |
| 918 | "X-Content-Type-Options: nosniff\r\n\r\n", stdout); |
| 919 | |
| 920 | fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>" |
| 921 | "<meta name='viewport' content='width=device-width,initial-scale=1'>" |
| 922 | "<title>nvtop</title>", stdout); |
| 923 | |
| 924 | fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS |
| 925 | /* chart series come from the bot accent set */ |
| 926 | ":root{--compute:var(--orange);--vram:var(--blue)}", stdout); |
| 927 | fputs( |
| 928 | "*{box-sizing:border-box}" |
| 929 | "body{margin:0;padding:16px;background:var(--bg);color:var(--text);" |
| 930 | "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;" |
| 931 | "font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}" |
| 932 | ".wrap{max-width:1180px;margin:0 auto;min-width:0}" |
| 933 | ".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}" |
| 934 | ".title{font-size:20px;font-weight:700;margin:0}" |
| 935 | ".sub{color:var(--muted);font-size:12px;font-family:var(--mono);overflow-wrap:anywhere}" |
| 936 | ".spacer{flex:1}" |
| 937 | ".pill{font-size:11px;font-weight:600;padding:2px 9px;border-radius:999px;" |
| 938 | "background:var(--surface2);color:var(--muted);border:1px solid var(--line);" |
| 939 | "white-space:nowrap}" |
| 940 | ".pill.live{color:var(--ok);border-color:rgba(48,209,88,.4)}" |
| 941 | ".pill.warn{color:var(--warn);border-color:rgba(255,214,10,.4)}" |
| 942 | ".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;" |
| 943 | "padding:16px;margin-bottom:14px;min-width:0}" |
| 944 | ".card h2{margin:0 0 12px;font-size:12px;letter-spacing:.06em;" |
| 945 | "text-transform:uppercase;color:var(--muted);font-weight:600}" |
| 946 | ".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:10px}" |
| 947 | ".kpi{background:var(--surface2);border:1px solid var(--line);border-radius:10px;" |
| 948 | "padding:10px 12px;min-width:0}" |
| 949 | ".kpi .k{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}" |
| 950 | ".kpi .v{font-size:19px;font-weight:700;font-family:var(--mono);margin-top:2px;" |
| 951 | "overflow:hidden;text-overflow:ellipsis;white-space:nowrap}" |
| 952 | "button{background:var(--accent);color:#fff;border:0;border-radius:999px;" |
| 953 | "padding:6px 13px;font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}" |
| 954 | "button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}" |
| 955 | "button:active{transform:scale(.98)}" |
| 956 | ".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}" |
| 957 | ".gpus{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:12px}" |
| 958 | ".gpu{background:var(--surface2);border:1px solid var(--line);border-radius:12px;" |
| 959 | "padding:12px;min-width:0}" |
| 960 | ".gpu .h{display:flex;gap:8px;align-items:baseline;flex-wrap:wrap;margin-bottom:4px}" |
| 961 | ".gpu .idx{font-family:var(--mono);font-size:12px;font-weight:700;color:var(--compute)}" |
| 962 | ".gpu .nm{font-weight:700;font-size:13px;overflow-wrap:anywhere;min-width:0}" |
| 963 | ".gpu .uuid{color:var(--muted);font-size:10px;font-family:var(--mono);overflow-wrap:anywhere}" |
| 964 | ".chips{display:flex;gap:6px;flex-wrap:wrap;margin:8px 0 4px}" |
| 965 | ".chip{font-size:11px;font-family:var(--mono);padding:2px 8px;border-radius:999px;" |
| 966 | "background:rgba(255,255,255,.06);border:1px solid var(--line);color:var(--muted);" |
| 967 | "white-space:nowrap}" |
| 968 | ".chip.hot{color:var(--danger);border-color:rgba(255,69,58,.45)}" |
| 969 | ".chip.warm{color:var(--warn);border-color:rgba(255,214,10,.45)}" |
| 970 | ".legend{display:flex;gap:14px;flex-wrap:wrap;font-size:11px;color:var(--muted);" |
| 971 | "font-family:var(--mono);margin-top:8px}" |
| 972 | ".dotc,.dotv{display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:5px}" |
| 973 | ".dotc{background:var(--compute)}.dotv{background:var(--vram)}" |
| 974 | ".spark{display:block;width:100%;height:52px;margin-top:6px}" |
| 975 | ".tblwrap{overflow-x:auto;-webkit-overflow-scrolling:touch}" |
| 976 | "table{width:100%;border-collapse:collapse;font-size:13px}" |
| 977 | "th,td{text-align:left;padding:7px 8px;border-bottom:1px solid var(--line)}" |
| 978 | "th{color:var(--muted);font-size:11px;text-transform:uppercase;letter-spacing:.05em;" |
| 979 | "font-weight:600}" |
| 980 | "td.num,th.num{text-align:right;font-family:var(--mono)}" |
| 981 | ".muted{color:var(--muted)}" |
| 982 | ".hide{display:none}" |
| 983 | ".empty{text-align:center;padding:30px 12px}" |
| 984 | ".empty .big{font-size:16px;font-weight:700;margin-bottom:6px}" |
| 985 | ".empty .msg{color:var(--muted);font-size:13px;max-width:620px;margin:0 auto 10px}" |
| 986 | "code{font-family:var(--mono);font-size:12px;background:rgba(255,255,255,.07);" |
| 987 | "padding:1px 5px;border-radius:4px;overflow-wrap:anywhere}" |
| 988 | "@media(max-width:640px){body{padding:12px}.hide-sm{display:none}}" |
| 989 | "</style></head>" SX_BOT_THEME_HANDOFF "<body><div class='wrap'>", stdout); |
| 990 | |
| 991 | fputs("<div class='top'>" |
| 992 | "<h1 class='title'>nvtop</h1>" |
| 993 | "<span id='srcBadge' class='pill'>local</span>" |
| 994 | "<span id='drvBadge' class='pill'>driver</span>" |
| 995 | "<span class='spacer'></span>" |
| 996 | "<span id='stamp' class='sub'></span>" |
| 997 | "<button class='ghost' id='btnRefresh'>Refresh</button>" |
| 998 | "</div>", stdout); |
| 999 | |
| 1000 | fputs("<div class='card'><h2>Overview</h2><div class='grid'>" |
| 1001 | "<div class='kpi'><div class='k'>GPUs</div><div class='v' id='kGpus'>—</div></div>" |
| 1002 | "<div class='kpi'><div class='k'>Avg compute</div><div class='v' id='kUtil'>—</div></div>" |
| 1003 | "<div class='kpi'><div class='k'>VRAM used</div><div class='v' id='kMem'>—</div></div>" |
| 1004 | "<div class='kpi'><div class='k'>Power draw</div><div class='v' id='kPower'>—</div></div>" |
| 1005 | "<div class='kpi'><div class='k'>Compute procs</div><div class='v' id='kProcs'>—</div></div>" |
| 1006 | "</div></div>", stdout); |
| 1007 | |
| 1008 | fputs("<div class='card'><h2>GPUs</h2>" |
| 1009 | "<div id='gpuGrid' class='gpus'></div>" |
| 1010 | "<div id='emptyState' class='empty hide'>" |
| 1011 | "<div class='big'>No local NVIDIA/AMD GPU detected</div>" |
| 1012 | "<div class='msg'>This node answers via <code>nvidia-smi</code> and " |
| 1013 | "<code>rocm-smi</code>; neither reported a GPU, so there is nothing to " |
| 1014 | "chart. Apple Silicon nodes are probed through <code>ioreg</code>.</div>" |
| 1015 | "<div class='msg'>To monitor a <em>remote</em> GPU rig from this node, " |
| 1016 | "customize <code>src/plugin_nvtop.c</code>: replace the fixed " |
| 1017 | "<code>nvidia-smi</code> probe in <code>collect_nvidia()</code> with your " |
| 1018 | "own collection step, rebuild with <code>make</code> and the dashboard " |
| 1019 | "works unchanged.</div>" |
| 1020 | "</div>" |
| 1021 | "<div class='legend' id='legend'><span><i class='dotc'></i>compute %</span>" |
| 1022 | "<span><i class='dotv'></i>VRAM</span>" |
| 1023 | "<span>rolling 60 samples</span></div>" |
| 1024 | "</div>", stdout); |
| 1025 | |
| 1026 | fputs("<div class='card'><h2>Compute processes</h2><div class='tblwrap'>" |
| 1027 | "<table><thead><tr><th class='num'>GPU</th><th class='num'>PID</th>" |
| 1028 | "<th>Process</th><th class='num'>VRAM</th></tr></thead>" |
| 1029 | "<tbody id='procRows'></tbody></table></div>" |
| 1030 | "<div id='procEmpty' class='muted hide'>No compute processes reported.</div>" |
| 1031 | "</div>", stdout); |
| 1032 | |
| 1033 | fputs("<div class='card'><h2>About this plugin</h2>" |
| 1034 | "<p class='muted' style='margin:0 0 8px'>Local node only. Probes " |
| 1035 | "<code>nvidia-smi</code> and <code>rocm-smi</code> on this machine and, on " |
| 1036 | "Apple Silicon, <code>ioreg</code>. Makes zero outbound network requests " |
| 1037 | "and opens no sockets.</p>" |
| 1038 | "<p class='muted' style='margin:0'>Every command is a compile-time " |
| 1039 | "constant; nothing from the query string is ever executed.</p></div>", |
| 1040 | stdout); |
| 1041 | |
| 1042 | if (!embed) |
| 1043 | fputs("<div class='sub' style='margin-bottom:14px'>Opened directly from the " |
| 1044 | "node API.</div>", stdout); |
| 1045 | |
| 1046 | fputs("<script>\n(function(){\n", stdout); |
| 1047 | |
| 1048 | fputs( |
| 1049 | " var q = new URLSearchParams(location.search);\n" |
| 1050 | " var HUB = q.get('plugin') || '';\n" |
| 1051 | " var node = q.get('node') || '';\n" |
| 1052 | " var sid = q.get('id') || '';\n" |
| 1053 | " var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n" |
| 1054 | " localStorage.getItem('bot_active_pwd') || '';\n" |
| 1055 | " var TIMER = null, BUSY = false, HIST = {}, N = 60;\n" |
| 1056 | "\n" |
| 1057 | " /* Two routes, and getting this wrong is the classic plugin bug:\n" |
| 1058 | " page served through the hub -> call the hub proxy back\n" |
| 1059 | " page opened directly on node -> the plugin IS the route */\n" |
| 1060 | " function base(action){\n" |
| 1061 | " if (HUB) return '/plugins?plugin=' + encodeURIComponent(HUB) +\n" |
| 1062 | " '&action=' + encodeURIComponent(action);\n" |
| 1063 | " return '/" PLUGIN_ID "?action=' + encodeURIComponent(action);\n" |
| 1064 | " }\n" |
| 1065 | " function withCtx(u){\n" |
| 1066 | " if (node) u += '&node=' + encodeURIComponent(node);\n" |
| 1067 | " if (sid) u += '&id=' + encodeURIComponent(sid);\n" |
| 1068 | " if (pwd) u += '&pwd=' + encodeURIComponent(pwd);\n" |
| 1069 | " return u;\n" |
| 1070 | " }\n" |
| 1071 | " function hdr(){ return pwd ? {'X-Bot-Password': pwd} : {}; }\n" |
| 1072 | " function $(id){ return document.getElementById(id); }\n" |
| 1073 | " function txt(id, v){ var e = $(id); if (e) e.textContent =\n" |
| 1074 | " (v === undefined || v === null) ? '' : v; }\n" |
| 1075 | " function mb(n){\n" |
| 1076 | " if (n === null || n === undefined) return '\\u2014';\n" |
| 1077 | " return n >= 1024 ? (n / 1024).toFixed(1) + ' GB' : Math.round(n) + ' MB';\n" |
| 1078 | " }\n" |
| 1079 | " function el(tag, c, t){\n" |
| 1080 | " var e = document.createElement(tag);\n" |
| 1081 | " if (c) e.className = c;\n" |
| 1082 | " if (t !== undefined) e.textContent = t;\n" |
| 1083 | " return e;\n" |
| 1084 | " }\n" |
| 1085 | "\n" |
| 1086 | " /* Rolling sparkline: orange = compute %, blue = VRAM share. A polyline in\n" |
| 1087 | " an SVG keeps it crisp at any width and needs no canvas resize logic. */\n" |
| 1088 | " function spark(hist, colour){\n" |
| 1089 | " var W = 100, H = 40, n = hist.length;\n" |
| 1090 | " var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n" |
| 1091 | " svg.setAttribute('class', 'spark');\n" |
| 1092 | " svg.setAttribute('viewBox', '0 0 ' + W + ' ' + H);\n" |
| 1093 | " svg.setAttribute('preserveAspectRatio', 'none');\n" |
| 1094 | " var base = document.createElementNS('http://www.w3.org/2000/svg', 'line');\n" |
| 1095 | " base.setAttribute('x1','0'); base.setAttribute('x2', String(W));\n" |
| 1096 | " base.setAttribute('y1', String(H - 1)); base.setAttribute('y2', String(H - 1));\n" |
| 1097 | " base.setAttribute('stroke', 'rgba(255,255,255,.14)');\n" |
| 1098 | " base.setAttribute('stroke-width', '0.6');\n" |
| 1099 | " svg.appendChild(base);\n" |
| 1100 | " if (!n) return svg;\n" |
| 1101 | " var pts = [];\n" |
| 1102 | " for (var i = 0; i < n; i++){\n" |
| 1103 | " var x = n === 1 ? W : (i * W) / (n - 1);\n" |
| 1104 | " var v = Math.max(0, Math.min(100, hist[i]));\n" |
| 1105 | " var y = H - 1 - (v / 100) * (H - 3);\n" |
| 1106 | " pts.push(x.toFixed(2) + ',' + y.toFixed(2));\n" |
| 1107 | " }\n" |
| 1108 | " if (n === 1){\n" |
| 1109 | " var dot = document.createElementNS('http://www.w3.org/2000/svg', 'circle');\n" |
| 1110 | " var v1 = Math.max(0, Math.min(100, hist[0]));\n" |
| 1111 | " dot.setAttribute('cx', String(W));\n" |
| 1112 | " dot.setAttribute('cy', String(H - 1 - (v1 / 100) * (H - 3)));\n" |
| 1113 | " dot.setAttribute('r', '1.6');\n" |
| 1114 | " dot.setAttribute('fill', colour);\n" |
| 1115 | " svg.appendChild(dot);\n" |
| 1116 | " return svg;\n" |
| 1117 | " }\n" |
| 1118 | " var poly = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');\n" |
| 1119 | " poly.setAttribute('points', pts.join(' '));\n" |
| 1120 | " poly.setAttribute('fill', 'none');\n" |
| 1121 | " poly.setAttribute('stroke', colour);\n" |
| 1122 | " poly.setAttribute('stroke-width', '1.4');\n" |
| 1123 | " poly.setAttribute('stroke-linejoin', 'round');\n" |
| 1124 | " poly.setAttribute('vector-effect', 'non-scaling-stroke');\n" |
| 1125 | " svg.appendChild(poly);\n" |
| 1126 | " return svg;\n" |
| 1127 | " }\n" |
| 1128 | "\n" |
| 1129 | " function pushHist(key, util, memPct){\n" |
| 1130 | " var h = HIST[key];\n" |
| 1131 | " if (!h) h = HIST[key] = { u: [], m: [] };\n" |
| 1132 | " h.u.push(util); h.m.push(memPct);\n" |
| 1133 | " if (h.u.length > N) h.u.shift();\n" |
| 1134 | " if (h.m.length > N) h.m.shift();\n" |
| 1135 | " return h;\n" |
| 1136 | " }\n" |
| 1137 | "\n" |
| 1138 | " function chip(text, cls){ return el('span', 'chip' + (cls ? ' ' + cls : ''), text); }\n" |
| 1139 | "\n" |
| 1140 | " function renderGpus(d){\n" |
| 1141 | " var box = $('gpuGrid');\n" |
| 1142 | " box.textContent = '';\n" |
| 1143 | " var gpus = d.gpus || [];\n" |
| 1144 | " gpus.forEach(function(g){\n" |
| 1145 | " var memPct = g.mem_total_mb > 0 ? (g.mem_used_mb / g.mem_total_mb) * 100 : 0;\n" |
| 1146 | " var h = pushHist(String(g.index), g.util_gpu, memPct);\n" |
| 1147 | " var card = el('div', 'gpu');\n" |
| 1148 | " var head = el('div', 'h');\n" |
| 1149 | " head.appendChild(el('span', 'idx', 'GPU ' + g.index));\n" |
| 1150 | " head.appendChild(el('span', 'nm', g.name));\n" |
| 1151 | " card.appendChild(head);\n" |
| 1152 | " card.appendChild(el('div', 'uuid', g.uuid || 'no uuid'));\n" |
| 1153 | " var chips = el('div', 'chips');\n" |
| 1154 | " chips.appendChild(chip(g.util_gpu.toFixed(0) + '% compute'));\n" |
| 1155 | " chips.appendChild(chip(mb(g.mem_used_mb) + ' / ' + mb(g.mem_total_mb) + ' VRAM'));\n" |
| 1156 | " if (g.temp_c !== null && g.temp_c !== undefined)\n" |
| 1157 | " chips.appendChild(chip(Math.round(g.temp_c) + '\\u00b0C',\n" |
| 1158 | " g.temp_c >= 85 ? 'hot' : (g.temp_c >= 70 ? 'warm' : '')));\n" |
| 1159 | " if (g.power_w !== null && g.power_w !== undefined)\n" |
| 1160 | " chips.appendChild(chip(Math.round(g.power_w) + ' W' +\n" |
| 1161 | " (g.power_limit_w ? ' / ' + Math.round(g.power_limit_w) : '')));\n" |
| 1162 | " card.appendChild(chips);\n" |
| 1163 | " card.appendChild(spark(h.u, 'var(--compute)'));\n" |
| 1164 | " card.appendChild(spark(h.m, 'var(--vram)'));\n" |
| 1165 | " box.appendChild(card);\n" |
| 1166 | " });\n" |
| 1167 | " if (gpus.length) { $('emptyState').classList.add('hide');\n" |
| 1168 | " $('legend').classList.remove('hide'); }\n" |
| 1169 | " else { $('emptyState').classList.remove('hide');\n" |
| 1170 | " $('legend').classList.add('hide'); }\n" |
| 1171 | " txt('kGpus', String(gpus.length));\n" |
| 1172 | " txt('kUtil', gpus.length ? Number(d.util_gpu_avg).toFixed(0) + '%' : '\\u2014');\n" |
| 1173 | " txt('kMem', gpus.length\n" |
| 1174 | " ? (mb(d.mem_used_mb) + ' / ' + mb(d.mem_total_mb)).replace(' GB / ', '/').replace(' MB / ', '/')\n" |
| 1175 | " : '\\u2014');\n" |
| 1176 | " txt('kPower', (d.power_w === null || d.power_w === undefined)\n" |
| 1177 | " ? '\\u2014' : Math.round(d.power_w) + ' W');\n" |
| 1178 | " txt('kProcs', String((d.processes || []).length));\n" |
| 1179 | " }\n" |
| 1180 | "\n" |
| 1181 | " function renderProcs(d){\n" |
| 1182 | " var body = $('procRows');\n" |
| 1183 | " body.textContent = '';\n" |
| 1184 | " var procs = d.processes || [];\n" |
| 1185 | " procs.forEach(function(p){\n" |
| 1186 | " var tr = el('tr');\n" |
| 1187 | " tr.appendChild(el('td', 'num', p.gpu_index >= 0 ? String(p.gpu_index) : '-'));\n" |
| 1188 | " tr.appendChild(el('td', 'num', String(p.pid)));\n" |
| 1189 | " tr.appendChild(el('td', 'nm', p.name));\n" |
| 1190 | " tr.appendChild(el('td', 'num', mb(p.used_mb)));\n" |
| 1191 | " body.appendChild(tr);\n" |
| 1192 | " });\n" |
| 1193 | " if (procs.length) $('procEmpty').classList.add('hide');\n" |
| 1194 | " else $('procEmpty').classList.remove('hide');\n" |
| 1195 | " }\n" |
| 1196 | "\n" |
| 1197 | " function paint(d){\n" |
| 1198 | " txt('srcBadge', d.source || 'none');\n" |
| 1199 | " var sb = $('srcBadge');\n" |
| 1200 | " sb.className = 'pill' + (d.available ? ' live' : ' warn');\n" |
| 1201 | " txt('drvBadge', d.driver ? ('driver ' + d.driver) : 'no driver');\n" |
| 1202 | " txt('stamp', d.utc || '');\n" |
| 1203 | " renderGpus(d);\n" |
| 1204 | " renderProcs(d);\n" |
| 1205 | " }\n" |
| 1206 | "\n" |
| 1207 | " function refresh(){\n" |
| 1208 | " if (BUSY) return Promise.resolve();\n" |
| 1209 | " BUSY = true;\n" |
| 1210 | " return fetch(withCtx(base('metrics')), { headers: hdr(), cache: 'no-store' })\n" |
| 1211 | " .then(function(r){ return r.json(); })\n" |
| 1212 | " .then(function(d){ paint(d); })\n" |
| 1213 | " .catch(function(){ txt('stamp', 'refresh failed'); })\n" |
| 1214 | " .then(function(){ BUSY = false; });\n" |
| 1215 | " }\n" |
| 1216 | "\n" |
| 1217 | " function tick(){ refresh().then(function(){\n" |
| 1218 | " TIMER = setTimeout(tick, 2000);\n" |
| 1219 | " }); }\n" |
| 1220 | "\n" |
| 1221 | " if (!HUB && !pwd && node && localStorage.getItem('bot_pwd_' + node))\n" |
| 1222 | " pwd = localStorage.getItem('bot_pwd_' + node);\n" |
| 1223 | " $('btnRefresh').addEventListener('click', function(){ refresh(); });\n" |
| 1224 | " document.addEventListener('visibilitychange', function(){\n" |
| 1225 | " if (document.hidden){ if (TIMER) { clearTimeout(TIMER); TIMER = null; } }\n" |
| 1226 | " else if (!TIMER) tick();\n" |
| 1227 | " });\n" |
| 1228 | " tick();\n" |
| 1229 | "})();\n" |
| 1230 | "</script></div></body></html>\n", stdout); |
| 1231 | } |
| 1232 | |
| 1233 | int main(int argc, char **argv) |
| 1234 | { |
| 1235 | const char *qs; |
| 1236 | int embed; |
| 1237 | |
| 1238 | if (argc > 1) { |
| 1239 | if (strcmp(argv[1], "--meta") == 0) return mode_meta(); |
| 1240 | if (strcmp(argv[1], "--version") == 0) { |
| 1241 | puts(PLUGIN_VER); |
| 1242 | return 0; |
| 1243 | } |
| 1244 | if (strcmp(argv[1], "--help") == 0) { |
| 1245 | puts("usage: " PLUGIN_ID " [--meta|--version|--help]"); |
| 1246 | puts(""); |
| 1247 | puts("Runs as a CGI-style program under scorpiox-server."); |
| 1248 | puts(" --meta print discovery metadata JSON and exit"); |
| 1249 | puts(" --version print the plugin version and exit"); |
| 1250 | puts(""); |
| 1251 | puts("Query string actions:"); |
| 1252 | puts(" (none) or action=metrics local GPU telemetry + compute procs"); |
| 1253 | puts(" action=info plugin/platform capabilities"); |
| 1254 | puts(" format=json same as an action, JSON output"); |
| 1255 | puts(" (any other) HTML dashboard"); |
| 1256 | puts(""); |
| 1257 | puts("Environment:"); |
| 1258 | puts(" NVTOP_MOCK_CSV=<path> read a CSV fixture instead of probing"); |
| 1259 | return 0; |
| 1260 | } |
| 1261 | } |
| 1262 | |
| 1263 | if (getenv("SX_PLUGIN_META")) return mode_meta(); |
| 1264 | |
| 1265 | require_node_auth(); |
| 1266 | |
| 1267 | qs = getenv("QUERY_STRING"); |
| 1268 | if (!qs) qs = ""; |
| 1269 | |
| 1270 | if (strstr(qs, "action=") || strstr(qs, "format=json")) |
| 1271 | return mode_json(qs); |
| 1272 | |
| 1273 | embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL); |
| 1274 | mode_html(embed); |
| 1275 | return 0; |
| 1276 | } |