/* * plugin_nvtop - SCORPIOX BOT open-source local GPU telemetry plugin * * A single clean-room C99 binary that serves THREE modes: * 1. --meta / SX_PLUGIN_META=1 -> JSON metadata for discovery * 2. ?action=metrics | ?action=info | ?format=json * -> JSON node API * 3. GET (default) -> responsive HTML dashboard * * Strictly LOCAL. The plugin runs nvidia-smi / rocm-smi / ioreg on THIS node * (the one the plugin is installed on) and parses their CSV/text output. It * never opens a socket, never runs ssh, and never accepts a host, a command or * a path from the query string: every command below is a fixed constant. * * On a node with no local GPU it reports a clean empty state instead of an * error, so the dashboard is useful on every machine in the fleet. * * Offline determinism: set NVTOP_MOCK_CSV= to make the plugin read a * small CSV fixture instead of shelling out. That is how the test suite * exercises multi-GPU behaviour on CPU-only build hosts. * * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under * scorpiox-server on the node. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ #if defined(__APPLE__) /* sysctl / ioctl headers pull BSD types that strict c99 would hide */ # define _DARWIN_C_SOURCE 1 #elif !defined(_WIN32) # define _POSIX_C_SOURCE 200809L # define _DEFAULT_SOURCE 1 #endif #if defined(_WIN32) && !defined(_WIN32_WINNT) # define _WIN32_WINNT 0x0601 #endif #include #include #include #include #include #include #if defined(_WIN32) # define WIN32_LEAN_AND_MEAN # include #else # include # include # if defined(__APPLE__) # include # endif #endif #include "bot_theme_plugin.h" #define PLUGIN_SLUG "nvtop" #define PLUGIN_ID "plugin_nvtop" #define PLUGIN_VER "1.0.3" #define MAX_GPUS 32 #define MAX_PROCS 256 #define MAX_NAME 96 #define MAX_UUID 64 #define MAX_DRIVER 48 /* ioreg prints the whole PerformanceStatistics dictionary on one line, which is * routinely several kilobytes. A 1 KB read buffer silently truncated it and the * utilisation counter looked like it was missing. */ #define LINE_MAX_BUF 131072 /* popen is the only external-process mechanism used, and every command string * is a compile-time constant. stderr redirection differs per platform because * popen() goes through the shell. */ #if defined(_WIN32) # define DEV_NULL " 2>NUL" #else # define DEV_NULL " 2>/dev/null" #endif /* ------------------------------------------------------------------ */ /* Small utilities */ /* ------------------------------------------------------------------ */ /* Percent-decode in place ('+' becomes space). */ static void url_decode(char *s) { char *o = s; if (!s) return; while (*s) { if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); *o++ = (char)((hi << 4) | lo); s += 3; } else if (*s == '+') { *o++ = ' '; s++; } else { *o++ = *s++; } } *o = '\0'; } /* Read one parameter (decoded) out of a form/query string. */ static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) { size_t klen; const char *p; if (!out || outsz == 0) return 0; out[0] = '\0'; if (!qs || !key) return 0; klen = strlen(key); for (p = qs; *p; ) { if (strncmp(p, key, klen) == 0 && p[klen] == '=') { const char *v = p + klen + 1; size_t i = 0; while (*v && *v != '&' && i + 1 < outsz) out[i++] = *v++; out[i] = '\0'; url_decode(out); return 1; } p = strchr(p, '&'); if (!p) break; p++; } return 0; } static void json_str(const char *s) { putchar('"'); for (; s && *s; s++) { unsigned char c = (unsigned char)*s; switch (c) { case '"': fputs("\\\"", stdout); break; case '\\': fputs("\\\\", stdout); break; case '\n': fputs("\\n", stdout); break; case '\r': fputs("\\r", stdout); break; case '\t': fputs("\\t", stdout); break; default: if (c >= 0x20) putchar((int)c); break; } } putchar('"'); } static void utc_now(char *buf, size_t sz) { time_t t = time(NULL); struct tm tmv; memset(&tmv, 0, sizeof(tmv)); #if defined(_WIN32) { struct tm *p = gmtime(&t); if (p) tmv = *p; } #else gmtime_r(&t, &tmv); #endif strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); } static long node_pid(void) { #if defined(_WIN32) return (long)GetCurrentProcessId(); #else return (long)getpid(); #endif } static void copy_str(char *dst, size_t dstsz, const char *src) { size_t n; if (!dst || dstsz == 0) return; if (!src) { dst[0] = '\0'; return; } n = strlen(src); if (n >= dstsz) n = dstsz - 1; memcpy(dst, src, n); dst[n] = '\0'; } /* Trim leading/trailing whitespace in place, return the trimmed start. */ static char *trim(char *s) { char *e; if (!s) return s; while (*s && (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')) s++; e = s + strlen(s); while (e > s && (e[-1] == ' ' || e[-1] == '\t' || e[-1] == '\r' || e[-1] == '\n')) e--; *e = '\0'; return s; } /* nvidia-smi prints "[N/A]" / "N/A" when a counter is unsupported. */ static int parse_num(const char *s, double *out) { char *end = NULL; double v; if (!s || !*s) return 0; if (strstr(s, "N/A") || strstr(s, "n/a")) return 0; errno = 0; v = strtod(s, &end); if (end == s || errno != 0) return 0; *out = v; return 1; } /* Split one CSV line in place; returns the field count (max maxf). */ static int split_csv(char *line, char **fields, int maxf) { int n = 0; char *p = line; if (!line) return 0; while (n < maxf) { fields[n++] = p; p = strchr(p, ','); if (!p) break; *p++ = '\0'; } return n; } /* ------------------------------------------------------------------ */ /* Node authentication */ /* ------------------------------------------------------------------ */ /* * The node API on :8150 is reachable from the LAN. Every request except * --meta discovery must prove it knows the node password. Accepted forms * match the rest of the node API: X-Bot-Password (what bot-web proxies * with), Authorization: Bearer, and ?pwd= (what the plugin iframe appends). * When BOT_PASSWORD is unset the plugin is a deliberate no-op, which is how * a developer runs it locally from a shell. */ static void require_node_auth(void) { const char *np = getenv("BOT_PASSWORD"); const char *xp; const char *auth; char qpwd[256]; const char *qs; if (!np || !*np) return; xp = getenv("HTTP_X_BOT_PASSWORD"); if (xp && strcmp(xp, np) == 0) return; auth = getenv("HTTP_AUTHORIZATION"); if (auth) { while (*auth == ' ') auth++; if (strncmp(auth, "Bearer ", 7) == 0) { auth += 7; while (*auth == ' ') auth++; if (strcmp(auth, np) == 0) return; } } qs = getenv("QUERY_STRING"); if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) return; fputs("Status: 401 Unauthorized\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n" "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); exit(0); } /* ------------------------------------------------------------------ */ /* Snapshot */ /* ------------------------------------------------------------------ */ typedef struct { int index; char uuid[MAX_UUID]; char name[MAX_NAME]; double util_gpu; double mem_used_mb; double mem_total_mb; double temp_c; double power_w; double power_limit_w; int has_temp; int has_power; int has_plimit; } gpu_t; typedef struct { char gpu_uuid[MAX_UUID]; long pid; char name[MAX_NAME]; double used_mb; } proc_t; typedef struct { gpu_t gpus[MAX_GPUS]; int ngpu; proc_t procs[MAX_PROCS]; int nproc; char driver[MAX_DRIVER]; char source[16]; /* nvidia / amd / apple / mock / none */ int available; int mocked; char note[192]; } snap_t; static void snap_init(snap_t *s) { memset(s, 0, sizeof(*s)); copy_str(s->source, sizeof(s->source), "none"); copy_str(s->note, sizeof(s->note), "No local NVIDIA/AMD GPU detected"); } /* Run a fixed command and stream its stdout line by line. */ typedef void (*line_fn)(char *line, void *ctx); static int feed_file_lines(const char *path, line_fn fn, void *ctx); static int run_cmd_lines(const char *cmd, line_fn fn, void *ctx) { FILE *fp; char buf[LINE_MAX_BUF]; int any = 0; fp = popen(cmd, "r"); if (!fp) return 0; while (fgets(buf, (int)sizeof(buf), fp)) { size_t n = strlen(buf); while (n && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; if (!buf[0] || buf[0] == '#') continue; any = 1; fn(buf, ctx); } pclose(fp); return any; } /* ---- mock fixture ------------------------------------------------- */ /* * NVTOP_MOCK_CSV fixture format (one record per line, '#' comments allowed): * * GPU,,,,,,,,,, * APP,,,, * * A field of "-" or "N/A" means "this counter is unavailable". Only the default * test fixtures use this path; production runs never set the variable. */ static void mock_line(char *line, void *ctx) { snap_t *s = (snap_t *)ctx; char *f[12]; int n; if (line[0] == '#') return; n = split_csv(line, f, 12); if (n < 2) return; if (strcmp(trim(f[0]), "GPU") == 0 && n >= 11 && s->ngpu < MAX_GPUS) { gpu_t *g = &s->gpus[s->ngpu]; char *idx; memset(g, 0, sizeof(*g)); idx = trim(f[1]); g->index = atoi(idx); copy_str(g->uuid, sizeof(g->uuid), trim(f[2])); copy_str(g->name, sizeof(g->name), trim(f[3])); parse_num(trim(f[4]), &g->util_gpu); parse_num(trim(f[5]), &g->mem_used_mb); parse_num(trim(f[6]), &g->mem_total_mb); g->has_temp = parse_num(trim(f[7]), &g->temp_c); g->has_power = parse_num(trim(f[8]), &g->power_w); g->has_plimit = parse_num(trim(f[9]), &g->power_limit_w); if (!s->driver[0] && trim(f[10])[0] && strcmp(trim(f[10]), "-") != 0) copy_str(s->driver, sizeof(s->driver), trim(f[10])); s->ngpu++; } else if (strcmp(trim(f[0]), "APP") == 0 && n >= 5 && s->nproc < MAX_PROCS) { proc_t *p = &s->procs[s->nproc]; memset(p, 0, sizeof(*p)); copy_str(p->gpu_uuid, sizeof(p->gpu_uuid), trim(f[1])); p->pid = (long)atoi(trim(f[2])); copy_str(p->name, sizeof(p->name), trim(f[3])); parse_num(trim(f[4]), &p->used_mb); s->nproc++; } } static int load_mock(snap_t *s, const char *path) { FILE *fp; char buf[LINE_MAX_BUF]; int any = 0; fp = fopen(path, "r"); if (!fp) return 0; while (fgets(buf, (int)sizeof(buf), fp)) { size_t n = strlen(buf); while (n && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; if (!buf[0]) continue; any = 1; mock_line(buf, s); } fclose(fp); if (!any) return 0; s->mocked = 1; copy_str(s->source, sizeof(s->source), "mock"); s->available = s->ngpu > 0; if (s->available) s->note[0] = '\0'; return 1; } /* ---- NVIDIA ------------------------------------------------------- */ struct nv_ctx { snap_t *s; int stage; }; struct nv_mock_ctx { struct nv_ctx gpu; snap_t *s; }; /* * nvidia-smi --query-gpu=... --format=csv,noheader,nounits * index,uuid,name,utilization.gpu,memory.used,memory.total, * temperature.gpu,power.draw,power.limit,driver_version */ static void nv_gpu_line(char *line, void *ctx) { struct nv_ctx *c = (struct nv_ctx *)ctx; snap_t *s = c->s; char *f[12]; int n = split_csv(line, f, 12); gpu_t *g; if (n < 10 || s->ngpu >= MAX_GPUS) return; g = &s->gpus[s->ngpu]; memset(g, 0, sizeof(*g)); g->index = atoi(trim(f[0])); copy_str(g->uuid, sizeof(g->uuid), trim(f[1])); copy_str(g->name, sizeof(g->name), trim(f[2])); parse_num(trim(f[3]), &g->util_gpu); parse_num(trim(f[4]), &g->mem_used_mb); parse_num(trim(f[5]), &g->mem_total_mb); g->has_temp = parse_num(trim(f[6]), &g->temp_c); g->has_power = parse_num(trim(f[7]), &g->power_w); g->has_plimit = parse_num(trim(f[8]), &g->power_limit_w); if (!s->driver[0]) copy_str(s->driver, sizeof(s->driver), trim(f[9])); s->ngpu++; } static void nv_proc_line(char *line, void *ctx) { snap_t *s = (snap_t *)ctx; char *f[8]; int n = split_csv(line, f, 8); proc_t *p; if (n < 4 || s->nproc >= MAX_PROCS) return; p = &s->procs[s->nproc]; memset(p, 0, sizeof(*p)); copy_str(p->gpu_uuid, sizeof(p->gpu_uuid), trim(f[0])); p->pid = (long)atoi(trim(f[1])); copy_str(p->name, sizeof(p->name), trim(f[2])); parse_num(trim(f[3]), &p->used_mb); s->nproc++; } static int collect_nvidia(snap_t *s) { struct nv_ctx c; int got; const char *mocksmi = getenv("NVTOP_MOCK_NVIDIA"); c.s = s; if (mocksmi && *mocksmi) s->mocked = 1; c.stage = 0; if (mocksmi && *mocksmi) { /* Fixture may interleave raw nvidia-smi GPU csv lines and "APP,..." * process lines; dispatch each line to the parser it belongs to. */ FILE *fp = fopen(mocksmi, "r"); char buf[LINE_MAX_BUF]; got = 0; if (fp) { while (fgets(buf, (int)sizeof(buf), fp)) { size_t n = strlen(buf); char *ln; while (n && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; ln = trim(buf); if (!ln[0] || ln[0] == '#') continue; got = 1; /* Process lines are re-shaped into the csv,noheader layout that * nv_proc_line expects: uuid,pid,name,used_mb. */ if (strncmp(ln, "APP,", 4) == 0) nv_proc_line(ln + 4, (void *)s); else nv_gpu_line(ln, (void *)&c); } fclose(fp); } } else { got = run_cmd_lines( "nvidia-smi --query-gpu=index,uuid,name,utilization.gpu,memory.used," "memory.total,temperature.gpu,power.draw,power.limit,driver_version " "--format=csv,noheader,nounits" DEV_NULL, nv_gpu_line, &c); } if (!got || s->ngpu == 0) return 0; run_cmd_lines( "nvidia-smi --query-compute-apps=gpu_uuid,pid,process_name,used_memory " "--format=csv,noheader,nounits" DEV_NULL, nv_proc_line, s); copy_str(s->source, sizeof(s->source), "nvidia"); s->available = 1; s->note[0] = '\0'; return 1; } /* ---- AMD (rocm-smi) ----------------------------------------------- */ /* * rocm-smi prints one "GPU[n] : : " line per counter, which is * stable across the 5.x and 6.x releases. VRAM is reported in bytes. */ static void amd_line(char *line, void *ctx) { snap_t *s = (snap_t *)ctx; char *lb, *key, *val, *rbr, *sep; int idx; gpu_t *g; if (strncmp(line, "GPU[", 4) != 0) return; idx = atoi(line + 4); if (idx < 0 || idx >= MAX_GPUS) return; lb = strchr(line, '['); rbr = lb ? strchr(lb, ']') : NULL; if (!rbr) return; /* "GPU[0] : GPU use (%): 87" -> key "GPU use (%)", value "87" */ key = trim(rbr + 1); if (*key == ':') key++; sep = strrchr(key, ':'); if (!sep) return; *sep = '\0'; val = trim(sep + 1); key = trim(key); if (!key[0] || !val[0]) return; while (s->ngpu <= idx) { int i = s->ngpu; memset(&s->gpus[i], 0, sizeof(s->gpus[i])); s->gpus[i].index = i; copy_str(s->gpus[i].name, sizeof(s->gpus[i].name), "AMD GPU"); s->ngpu++; } g = &s->gpus[idx]; if (strstr(key, "Card series") || strstr(key, "Card SKU")) { copy_str(g->name, sizeof(g->name), val); } else if (strstr(key, "GPU use (%)")) { parse_num(val, &g->util_gpu); } else if (strstr(key, "VRAM Total Memory (B)")) { double b = 0; if (parse_num(val, &b)) g->mem_total_mb = b / (1024.0 * 1024.0); } else if (strstr(key, "VRAM Total Used Memory (B)")) { double b = 0; if (parse_num(val, &b)) g->mem_used_mb = b / (1024.0 * 1024.0); } else if (strstr(key, "Temperature (Sensor edge)") || strstr(key, "Temperature (Sensor junction)")) { double v = 0; if (parse_num(val, &v) && !g->has_temp) { g->temp_c = v; g->has_temp = 1; } } else if (strstr(key, "Average Graphics Package Power") || strstr(key, "Current Socket Graphics Package Power")) { double v = 0; if (parse_num(val, &v) && !g->has_power) { g->power_w = v; g->has_power = 1; } } else if (strstr(key, "Max Graphics Package Power")) { double v = 0; if (parse_num(val, &v) && !g->has_plimit) { g->power_limit_w = v; g->has_plimit = 1; } } } /* Feed a rocm-smi text fixture through the real parser (offline tests). */ static int feed_file_lines(const char *path, line_fn fn, void *ctx) { FILE *fp; char buf[LINE_MAX_BUF]; int any = 0; fp = fopen(path, "r"); if (!fp) return 0; while (fgets(buf, (int)sizeof(buf), fp)) { size_t n = strlen(buf); while (n && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; if (!buf[0] || buf[0] == '#') continue; any = 1; fn(buf, ctx); } fclose(fp); return any; } static int collect_amd(snap_t *s) { const char *mockrocm = getenv("NVTOP_MOCK_ROCM"); int got; if (mockrocm && *mockrocm) { s->mocked = 1; got = feed_file_lines(mockrocm, amd_line, s); } else got = run_cmd_lines( "rocm-smi --showproductname --showuse --showmeminfo vram " "--showtemp --showpower" DEV_NULL, amd_line, s); if (!got || s->ngpu == 0) return 0; copy_str(s->source, sizeof(s->source), "amd"); s->available = 1; s->note[0] = '\0'; return 1; } /* ---- Apple Silicon (ioreg IOAccelerator) -------------------------- */ /* * ioreg prints one big nested dictionary, and several counters live inside the * "PerformanceStatistics" sub-dictionary on the SAME physical line: * * "PerformanceStatistics" = {"In use system memory (driver)"=0, ..., * "Device Utilization %"=19, * "In use system memory"=51597524992} * * So the value of a counter is not "everything after the first '=' in the * line" - that would parse the sub-dictionary opener. Locate the key first, * then take the '=' that follows it. */ #if defined(__APPLE__) static const char *apple_value(const char *line, const char *key, int skip_paren) { const char *p = line; size_t klen = strlen(key); while ((p = strstr(p, key)) != NULL) { const char *v = p + klen; /* "In use system memory (driver)" also starts with the same text, so a * paren-suffixed hit must be skipped rather than ending the search. */ if (skip_paren && v[0] == ' ') { p = v; continue; } while (*v == '"' || *v == ' ') v++; if (*v != '=') { p = v; continue; } v++; while (*v == ' ') v++; return v; } return NULL; } static void apple_quoted(const char *v, char *out, size_t outsz) { const char *end; size_t n; if (!v || !*v) return; if (*v == '"') { v++; end = strchr(v, '"'); n = end ? (size_t)(end - v) : strlen(v); } else if (*v == '<') { v++; end = strchr(v, '>'); n = end ? (size_t)(end - v) : strlen(v); } else { end = v; while (*end && *end != ',' && *end != '}') end++; n = (size_t)(end - v); while (n && v[n - 1] == ' ') n--; } if (n >= outsz) n = outsz - 1; if (n) { memcpy(out, v, n); out[n] = '\0'; } } static void apple_line(char *line, void *ctx) { snap_t *s = (snap_t *)ctx; gpu_t *g; const char *v; double num = 0; if (s->ngpu == 0) { memset(&s->gpus[0], 0, sizeof(s->gpus[0])); copy_str(s->gpus[0].name, sizeof(s->gpus[0].name), "Apple GPU"); s->ngpu = 1; } g = &s->gpus[0]; if ((v = apple_value(line, "\"model\"", 0)) != NULL) apple_quoted(v, g->name, sizeof(g->name)); if ((v = apple_value(line, "Device Utilization %", 0)) != NULL && parse_num(v, &num)) g->util_gpu = num; /* Prefer the plain "In use system memory" over "(driver)". */ if ((v = apple_value(line, "In use system memory", 1)) != NULL && parse_num(v, &num)) g->mem_used_mb = num / (1024.0 * 1024.0); (void)v; } static int collect_apple(snap_t *s) { int got = run_cmd_lines("ioreg -rc IOAccelerator -d 1" DEV_NULL, apple_line, s); unsigned long long memsize = 0; size_t len = sizeof(memsize); if (!got || s->ngpu == 0) return 0; /* Apple GPUs share the unified memory pool, so the honest "VRAM total" on a * Mac is the machine's physical RAM, not an allocation counter. */ if (sysctlbyname("hw.memsize", &memsize, &len, NULL, 0) == 0 && memsize > 0) s->gpus[0].mem_total_mb = (double)memsize / (1024.0 * 1024.0); copy_str(s->source, sizeof(s->source), "apple"); s->available = 1; s->note[0] = '\0'; return 1; } #endif /* ---- orchestration ------------------------------------------------ */ static void snapshot(snap_t *s) { const char *mock = getenv("NVTOP_MOCK_CSV"); snap_init(s); if (mock && *mock && load_mock(s, mock)) return; if (collect_nvidia(s)) return; if (collect_amd(s)) return; #if defined(__APPLE__) if (collect_apple(s)) return; #endif /* Nothing found: keep the clean CPU-only empty state. */ copy_str(s->source, sizeof(s->source), "none"); s->available = 0; copy_str(s->note, sizeof(s->note), "No local NVIDIA/AMD GPU detected"); } /* Attach "gpu_index" to each process by matching its UUID. */ static int gpu_index_for(snap_t *s, const char *uuid) { int i; if (!uuid || !*uuid) return -1; for (i = 0; i < s->ngpu; i++) if (strcmp(s->gpus[i].uuid, uuid) == 0) return s->gpus[i].index; return -1; } /* ------------------------------------------------------------------ */ /* Modes */ /* ------------------------------------------------------------------ */ static int mode_meta(void) { puts("{\"name\":\"nvtop\",\"desc\":\"Local GPUs\"}"); return 0; } static void json_header(void) { /* Deliberately no Content-Length - the server owns framing. */ fputs("Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n", stdout); } static void emit_gpu(const gpu_t *g) { fputs("{\"index\":", stdout); printf("%d", g->index); fputs(",\"uuid\":", stdout); json_str(g->uuid); fputs(",\"name\":", stdout); json_str(g->name); printf(",\"util_gpu\":%.1f", g->util_gpu); printf(",\"mem_used_mb\":%.0f", g->mem_used_mb); printf(",\"mem_total_mb\":%.0f", g->mem_total_mb); fputs(",\"temp_c\":", stdout); if (g->has_temp) printf("%.0f", g->temp_c); else fputs("null", stdout); fputs(",\"power_w\":", stdout); if (g->has_power) printf("%.1f", g->power_w); else fputs("null", stdout); fputs(",\"power_limit_w\":", stdout); if (g->has_plimit) printf("%.1f", g->power_limit_w); else fputs("null", stdout); fputs("}", stdout); } static void emit_metrics(snap_t *s, const char *utc) { int i; double mem_used = 0, mem_total = 0, util_sum = 0, power = 0; int power_n = 0; json_header(); fputs("{\"ok\":true,\"action\":\"metrics\"", stdout); fputs(",\"available\":", stdout); fputs(s->available ? "true" : "false", stdout); fputs(",\"source\":", stdout); json_str(s->source); fputs(",\"mocked\":", stdout); fputs(s->mocked ? "true" : "false", stdout); fputs(",\"driver\":", stdout); json_str(s->driver); fputs(",\"utc\":", stdout); json_str(utc); fputs(",\"count\":", stdout); printf("%d", s->ngpu); fputs(",\"process_count\":", stdout); printf("%d", s->nproc); for (i = 0; i < s->ngpu; i++) { mem_used += s->gpus[i].mem_used_mb; mem_total += s->gpus[i].mem_total_mb; util_sum += s->gpus[i].util_gpu; if (s->gpus[i].has_power) { power += s->gpus[i].power_w; power_n++; } } printf(",\"util_gpu_avg\":%.1f", s->ngpu ? util_sum / (double)s->ngpu : 0.0); printf(",\"mem_used_mb\":%.0f,\"mem_total_mb\":%.0f", mem_used, mem_total); fputs(",\"power_w\":", stdout); if (power_n) printf("%.1f", power); else fputs("null", stdout); fputs(",\"gpus\":[", stdout); for (i = 0; i < s->ngpu; i++) { if (i) putchar(','); emit_gpu(&s->gpus[i]); } fputs("],\"processes\":[", stdout); for (i = 0; i < s->nproc; i++) { const proc_t *p = &s->procs[i]; if (i) putchar(','); fputs("{\"gpu_uuid\":", stdout); json_str(p->gpu_uuid); fputs(",\"gpu_index\":", stdout); printf("%d", gpu_index_for(s, p->gpu_uuid)); fputs(",\"pid\":", stdout); printf("%ld", p->pid); fputs(",\"name\":", stdout); json_str(p->name); printf(",\"used_mb\":%.0f}", p->used_mb); } fputs("],\"message\":", stdout); json_str(s->note); fputs("}\n", stdout); } static int mode_json(const char *qs) { char action[64]; char utc[40]; snap_t s; action[0] = '\0'; get_query_val(qs, "action", action, sizeof(action)); if (action[0] && strcmp(action, "metrics") != 0 && strcmp(action, "info") != 0) { json_header(); printf("{\"ok\":false,\"error\":\"unknown_action\"," "\"supported\":[\"metrics\",\"info\"],\"requested\":"); json_str(action); fputs("}\n", stdout); return 0; } if (!action[0]) copy_str(action, sizeof(action), "metrics"); utc_now(utc, sizeof(utc)); if (strcmp(action, "info") == 0) { char platform[64]; json_header(); fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\"," "\"version\":\"" PLUGIN_VER "\",\"platform\":", stdout); #if defined(_WIN32) copy_str(platform, sizeof(platform), "windows"); #elif defined(__APPLE__) copy_str(platform, sizeof(platform), "macos"); #else copy_str(platform, sizeof(platform), "linux"); #endif json_str(platform); fputs(",\"pid\":", stdout); printf("%ld", node_pid()); fputs(",\"utc\":", stdout); json_str(utc); fputs(",\"node_auth\":", stdout); { const char *np = getenv("BOT_PASSWORD"); fputs((np && *np) ? "true" : "false", stdout); } fputs(",\"supported\":[\"metrics\",\"info\"]," "\"probes\":[\"nvidia-smi\",\"rocm-smi\"]," "\"mock_hook\":\"NVTOP_MOCK_CSV\"," "\"max_gpus\":", stdout); printf("%d", MAX_GPUS); fputs(",\"zero_network\":true}\n", stdout); return 0; } snapshot(&s); emit_metrics(&s, utc); return 0; } static void mode_html(int embed) { fputs("Content-Type: text/html; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n", stdout); fputs("\n" "" "nvtop", stdout); fputs(SX_BOT_THEME_PREPAINT "" SX_BOT_THEME_HANDOFF "
", stdout); fputs("
" "

nvtop

" "local" "driver" "" "" "" "
", stdout); fputs("

Overview

" "
GPUs
—
" "
Avg compute
—
" "
VRAM used
—
" "
Power draw
—
" "
Compute procs
—
" "
", stdout); fputs("

GPUs

" "
" "
" "
No local NVIDIA/AMD GPU detected
" "
This node answers via nvidia-smi and " "rocm-smi; neither reported a GPU, so there is nothing to " "chart. Apple Silicon nodes are probed through ioreg.
" "
To monitor a remote GPU rig from this node, " "customize src/plugin_nvtop.c: replace the fixed " "nvidia-smi probe in collect_nvidia() with your " "own collection step, rebuild with make and the dashboard " "works unchanged.
" "
" "
compute %" "VRAM" "rolling 60 samples
" "
", stdout); fputs("

Compute processes

" "" "" "
GPUPIDProcessVRAM
" "
No compute processes reported.
" "
", stdout); fputs("

About this plugin

" "

Local node only. Probes " "nvidia-smi and rocm-smi on this machine and, on " "Apple Silicon, ioreg. Makes zero outbound network requests " "and opens no sockets.

" "

Every command is a compile-time " "constant; nothing from the query string is ever executed.

", stdout); if (!embed) fputs("
Opened directly from the " "node API.
", stdout); fputs("
\n", stdout); } int main(int argc, char **argv) { const char *qs; int embed; if (argc > 1) { if (strcmp(argv[1], "--meta") == 0) return mode_meta(); if (strcmp(argv[1], "--version") == 0) { puts(PLUGIN_VER); return 0; } if (strcmp(argv[1], "--help") == 0) { puts("usage: " PLUGIN_ID " [--meta|--version|--help]"); puts(""); puts("Runs as a CGI-style program under scorpiox-server."); puts(" --meta print discovery metadata JSON and exit"); puts(" --version print the plugin version and exit"); puts(""); puts("Query string actions:"); puts(" (none) or action=metrics local GPU telemetry + compute procs"); puts(" action=info plugin/platform capabilities"); puts(" format=json same as an action, JSON output"); puts(" (any other) HTML dashboard"); puts(""); puts("Environment:"); puts(" NVTOP_MOCK_CSV= read a CSV fixture instead of probing"); return 0; } } if (getenv("SX_PLUGIN_META")) return mode_meta(); require_node_auth(); qs = getenv("QUERY_STRING"); if (!qs) qs = ""; if (strstr(qs, "action=") || strstr(qs, "format=json")) return mode_json(qs); embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL); mode_html(embed); return 0; }