| 1 | /* |
| 2 | * plugin_sysmon - SCORPIOX BOT open-source local system monitor 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 | ?format=json -> JSON node API (local CPU, memory, swap, |
| 7 | * uptime, load average and top processes) |
| 8 | * 3. GET (default) -> responsive HTML dashboard |
| 9 | * |
| 10 | * Local node only. Reads the local kernel interfaces (/proc on Linux, mach and |
| 11 | * sysctl on macOS, Win32 APIs on Windows). Makes ZERO outbound network |
| 12 | * requests, opens no sockets, runs no remote commands, reads no credentials. |
| 13 | * |
| 14 | * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and |
| 15 | * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under |
| 16 | * scorpiox-server on the node. |
| 17 | * |
| 18 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 19 | */ |
| 20 | |
| 21 | #if defined(__APPLE__) |
| 22 | /* sysctl.h pulls in BSD types (u_int) that strict c99 would hide */ |
| 23 | # define _DARWIN_C_SOURCE 1 |
| 24 | #elif !defined(_WIN32) |
| 25 | # define _POSIX_C_SOURCE 200809L |
| 26 | # define _DEFAULT_SOURCE 1 |
| 27 | #endif |
| 28 | |
| 29 | #if defined(_WIN32) && !defined(_WIN32_WINNT) |
| 30 | # define _WIN32_WINNT 0x0601 /* GetTickCount64 needs Vista or later; must precede windows.h */ |
| 31 | #endif |
| 32 | |
| 33 | #include <stdio.h> |
| 34 | #include <stdlib.h> |
| 35 | #include <string.h> |
| 36 | #include <time.h> |
| 37 | #include <ctype.h> |
| 38 | #include <errno.h> |
| 39 | |
| 40 | #if defined(_WIN32) |
| 41 | |
| 42 | # define WIN32_LEAN_AND_MEAN |
| 43 | # include <windows.h> |
| 44 | # include <psapi.h> |
| 45 | # include <tlhelp32.h> |
| 46 | # include <io.h> |
| 47 | |
| 48 | #else |
| 49 | |
| 50 | # include <unistd.h> |
| 51 | # include <dirent.h> |
| 52 | # include <sys/types.h> |
| 53 | |
| 54 | #endif |
| 55 | |
| 56 | #if defined(__APPLE__) |
| 57 | # include <mach/mach.h> |
| 58 | # include <mach/mach_host.h> |
| 59 | # include <sys/sysctl.h> |
| 60 | # include <sys/time.h> |
| 61 | #endif |
| 62 | |
| 63 | #include "bot_theme_plugin.h" |
| 64 | |
| 65 | #define PLUGIN_SLUG "sysmon" |
| 66 | #define PLUGIN_ID "plugin_sysmon" |
| 67 | #define PLUGIN_VER "1.0.2" |
| 68 | |
| 69 | #define MAX_CORES 256 |
| 70 | #define MAX_PROCS 4096 |
| 71 | #define TOP_DEFAULT 25 |
| 72 | #define SAMPLE_MS 80 |
| 73 | |
| 74 | /* ------------------------------------------------------------------ */ |
| 75 | /* Small utilities */ |
| 76 | /* ------------------------------------------------------------------ */ |
| 77 | |
| 78 | /* Percent-decode in place ('+' becomes space). */ |
| 79 | static void url_decode(char *s) |
| 80 | { |
| 81 | char *o = s; |
| 82 | if (!s) return; |
| 83 | while (*s) { |
| 84 | if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { |
| 85 | int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); |
| 86 | int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); |
| 87 | *o++ = (char)((hi << 4) | lo); |
| 88 | s += 3; |
| 89 | } else if (*s == '+') { |
| 90 | *o++ = ' '; |
| 91 | s++; |
| 92 | } else { |
| 93 | *o++ = *s++; |
| 94 | } |
| 95 | } |
| 96 | *o = '\0'; |
| 97 | } |
| 98 | |
| 99 | /* Read one parameter (decoded) out of a form/query string. */ |
| 100 | static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) |
| 101 | { |
| 102 | size_t klen; |
| 103 | const char *p; |
| 104 | |
| 105 | if (!out || outsz == 0) return 0; |
| 106 | out[0] = '\0'; |
| 107 | if (!qs || !key) return 0; |
| 108 | klen = strlen(key); |
| 109 | |
| 110 | for (p = qs; *p; ) { |
| 111 | if (strncmp(p, key, klen) == 0 && p[klen] == '=') { |
| 112 | const char *v = p + klen + 1; |
| 113 | size_t i = 0; |
| 114 | while (*v && *v != '&' && i + 1 < outsz) |
| 115 | out[i++] = *v++; |
| 116 | out[i] = '\0'; |
| 117 | url_decode(out); |
| 118 | return 1; |
| 119 | } |
| 120 | p = strchr(p, '&'); |
| 121 | if (!p) break; |
| 122 | p++; |
| 123 | } |
| 124 | return 0; |
| 125 | } |
| 126 | |
| 127 | static void json_str(const char *s) |
| 128 | { |
| 129 | putchar('"'); |
| 130 | for (; s && *s; s++) { |
| 131 | unsigned char c = (unsigned char)*s; |
| 132 | switch (c) { |
| 133 | case '"': fputs("\\\"", stdout); break; |
| 134 | case '\\': fputs("\\\\", stdout); break; |
| 135 | case '\n': fputs("\\n", stdout); break; |
| 136 | case '\r': fputs("\\r", stdout); break; |
| 137 | case '\t': fputs("\\t", stdout); break; |
| 138 | default: |
| 139 | if (c < 0x20) printf("\\u%04x", (unsigned)c); |
| 140 | else putchar((int)c); |
| 141 | } |
| 142 | } |
| 143 | putchar('"'); |
| 144 | } |
| 145 | |
| 146 | static void utc_now(char *buf, size_t sz) |
| 147 | { |
| 148 | time_t t = time(NULL); |
| 149 | struct tm tmv; |
| 150 | #if defined(_WIN32) |
| 151 | gmtime_s(&tmv, &t); |
| 152 | #else |
| 153 | gmtime_r(&t, &tmv); |
| 154 | #endif |
| 155 | if (strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv) == 0) { |
| 156 | strncpy(buf, "1970-01-01T00:00:00Z", sz - 1); |
| 157 | buf[sz - 1] = '\0'; |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | static long node_pid(void) |
| 162 | { |
| 163 | #if defined(_WIN32) |
| 164 | return (long)GetCurrentProcessId(); |
| 165 | #else |
| 166 | return (long)getpid(); |
| 167 | #endif |
| 168 | } |
| 169 | |
| 170 | static void sx_sleep_ms(int ms) |
| 171 | { |
| 172 | #if defined(_WIN32) |
| 173 | Sleep((DWORD)ms); |
| 174 | #else |
| 175 | struct timespec ts; |
| 176 | ts.tv_sec = ms / 1000; |
| 177 | ts.tv_nsec = (long)(ms % 1000) * 1000000L; |
| 178 | nanosleep(&ts, NULL); |
| 179 | #endif |
| 180 | } |
| 181 | |
| 182 | static double clamp_pct(double v) |
| 183 | { |
| 184 | if (v < 0.0) return 0.0; |
| 185 | if (v > 100.0) return 100.0; |
| 186 | return v; |
| 187 | } |
| 188 | |
| 189 | /* ------------------------------------------------------------------ */ |
| 190 | /* Node authentication */ |
| 191 | /* ------------------------------------------------------------------ */ |
| 192 | |
| 193 | /* |
| 194 | * The node API on :8150 is reachable from the LAN. Every request except |
| 195 | * --meta discovery must prove it knows the node password. Accepted forms |
| 196 | * match the rest of the node API: X-Bot-Password (what bot-web proxies |
| 197 | * with), Authorization: Bearer, and ?pwd= (what the plugin iframe appends). |
| 198 | * When BOT_PASSWORD is unset the plugin is a deliberate no-op, which is how |
| 199 | * a developer runs it locally from a shell. |
| 200 | */ |
| 201 | static void require_node_auth(void) |
| 202 | { |
| 203 | const char *np = getenv("BOT_PASSWORD"); |
| 204 | const char *xp; |
| 205 | const char *auth; |
| 206 | char qpwd[256]; |
| 207 | const char *qs; |
| 208 | |
| 209 | if (!np || !*np) return; |
| 210 | |
| 211 | xp = getenv("HTTP_X_BOT_PASSWORD"); |
| 212 | if (xp && strcmp(xp, np) == 0) return; |
| 213 | |
| 214 | auth = getenv("HTTP_AUTHORIZATION"); |
| 215 | if (auth) { |
| 216 | while (*auth == ' ') auth++; |
| 217 | if (strncmp(auth, "Bearer ", 7) == 0) { |
| 218 | auth += 7; |
| 219 | while (*auth == ' ') auth++; |
| 220 | if (strcmp(auth, np) == 0) return; |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | qs = getenv("QUERY_STRING"); |
| 225 | if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) |
| 226 | return; |
| 227 | |
| 228 | fputs("Status: 401 Unauthorized\r\n" |
| 229 | "Content-Type: application/json; charset=utf-8\r\n" |
| 230 | "Cache-Control: no-store\r\n" |
| 231 | "X-Content-Type-Options: nosniff\r\n\r\n" |
| 232 | "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); |
| 233 | exit(0); |
| 234 | } |
| 235 | |
| 236 | /* ------------------------------------------------------------------ */ |
| 237 | /* Collected snapshot */ |
| 238 | /* ------------------------------------------------------------------ */ |
| 239 | |
| 240 | typedef struct { |
| 241 | int core; |
| 242 | double pct; |
| 243 | } core_t; |
| 244 | |
| 245 | typedef struct { |
| 246 | long pid; |
| 247 | char name[64]; |
| 248 | double cpu; /* percent of one core */ |
| 249 | long rss_kb; |
| 250 | char state; |
| 251 | } proc_t; |
| 252 | |
| 253 | typedef struct { |
| 254 | int ok; |
| 255 | char platform[16]; /* linux | macos | windows */ |
| 256 | char host[128]; |
| 257 | |
| 258 | double cpu_pct; |
| 259 | core_t cores[MAX_CORES]; |
| 260 | int ncores; |
| 261 | char cpu_model[128]; |
| 262 | |
| 263 | double mem_total_kb; |
| 264 | double mem_used_kb; |
| 265 | double mem_free_kb; |
| 266 | double mem_cached_kb; |
| 267 | |
| 268 | double swap_total_kb; |
| 269 | double swap_used_kb; |
| 270 | |
| 271 | double uptime_sec; |
| 272 | double load1, load5, load15; |
| 273 | int load_available; |
| 274 | |
| 275 | proc_t procs[MAX_PROCS]; |
| 276 | int nprocs; |
| 277 | } sys_t; |
| 278 | |
| 279 | /* ------------------------------------------------------------------ */ |
| 280 | /* Linux sampling */ |
| 281 | /* ------------------------------------------------------------------ */ |
| 282 | |
| 283 | #if !defined(_WIN32) && !defined(__APPLE__) |
| 284 | |
| 285 | typedef struct { |
| 286 | unsigned long long user, nice, system, idle, iowait, irq, softirq, steal; |
| 287 | } cpu_raw_t; |
| 288 | |
| 289 | /* |
| 290 | * /proc/stat reports st_size == 0, so seeking to the end and measuring is |
| 291 | * meaningless. Always stream with fgets until EOF. |
| 292 | */ |
| 293 | static int read_proc_stat(cpu_raw_t *agg, cpu_raw_t *cores, int maxcores) |
| 294 | { |
| 295 | FILE *fp; |
| 296 | char line[512]; |
| 297 | int n = 0; |
| 298 | |
| 299 | fp = fopen("/proc/stat", "r"); |
| 300 | if (!fp) return -1; |
| 301 | |
| 302 | memset(agg, 0, sizeof(*agg)); |
| 303 | while (fgets(line, sizeof(line), fp)) { |
| 304 | if (strncmp(line, "cpu", 3) != 0) break; |
| 305 | if (line[3] == ' ') { |
| 306 | (void)sscanf(line + 4, "%llu %llu %llu %llu %llu %llu %llu %llu", |
| 307 | &agg->user, &agg->nice, &agg->system, &agg->idle, |
| 308 | &agg->iowait, &agg->irq, &agg->softirq, &agg->steal); |
| 309 | continue; |
| 310 | } |
| 311 | if (isdigit((unsigned char)line[3])) { |
| 312 | cpu_raw_t r; |
| 313 | int idx = 0; |
| 314 | memset(&r, 0, sizeof(r)); |
| 315 | if (sscanf(line + 3, "%d %llu %llu %llu %llu %llu %llu %llu %llu", |
| 316 | &idx, &r.user, &r.nice, &r.system, &r.idle, |
| 317 | &r.iowait, &r.irq, &r.softirq, &r.steal) >= 5) { |
| 318 | if (n < maxcores) cores[n] = r; |
| 319 | n++; |
| 320 | } |
| 321 | } |
| 322 | } |
| 323 | fclose(fp); |
| 324 | return n; |
| 325 | } |
| 326 | |
| 327 | static double cpu_busy_pct(const cpu_raw_t *a, const cpu_raw_t *b) |
| 328 | { |
| 329 | unsigned long long ta = a->user + a->nice + a->system + a->idle + a->iowait |
| 330 | + a->irq + a->softirq + a->steal; |
| 331 | unsigned long long tb = b->user + b->nice + b->system + b->idle + b->iowait |
| 332 | + b->irq + b->softirq + b->steal; |
| 333 | unsigned long long ba = a->user + a->nice + a->system + a->irq + a->softirq + a->steal; |
| 334 | unsigned long long bb = b->user + b->nice + b->system + b->irq + b->softirq + b->steal; |
| 335 | unsigned long long dt, db; |
| 336 | |
| 337 | if (tb <= ta) return 0.0; |
| 338 | dt = tb - ta; |
| 339 | db = bb >= ba ? bb - ba : 0; |
| 340 | return clamp_pct(100.0 * (double)db / (double)dt); |
| 341 | } |
| 342 | |
| 343 | static void read_meminfo(sys_t *s) |
| 344 | { |
| 345 | FILE *fp; |
| 346 | char line[256]; |
| 347 | |
| 348 | s->mem_total_kb = s->mem_free_kb = s->mem_cached_kb = 0.0; |
| 349 | s->swap_total_kb = s->swap_used_kb = 0.0; |
| 350 | |
| 351 | fp = fopen("/proc/meminfo", "r"); |
| 352 | if (!fp) return; |
| 353 | |
| 354 | { |
| 355 | unsigned long long total = 0, free_kb = 0, avail = 0, cached = 0, sreclaim = 0; |
| 356 | unsigned long long swap_total = 0, swap_free = 0; |
| 357 | |
| 358 | while (fgets(line, sizeof(line), fp)) { |
| 359 | unsigned long long v = 0; |
| 360 | if (sscanf(line, "MemTotal: %llu kB", &v) == 1) total = v; |
| 361 | else if (sscanf(line, "MemFree: %llu kB", &v) == 1) free_kb = v; |
| 362 | else if (sscanf(line, "MemAvailable: %llu kB", &v) == 1) avail = v; |
| 363 | else if (sscanf(line, "Cached: %llu kB", &v) == 1) cached = v; |
| 364 | else if (sscanf(line, "SReclaimable: %llu kB", &v) == 1) sreclaim = v; |
| 365 | else if (sscanf(line, "SwapTotal: %llu kB", &v) == 1) swap_total = v; |
| 366 | else if (sscanf(line, "SwapFree: %llu kB", &v) == 1) swap_free = v; |
| 367 | } |
| 368 | fclose(fp); |
| 369 | |
| 370 | s->mem_total_kb = (double)total; |
| 371 | s->mem_free_kb = (double)(avail ? avail : free_kb); |
| 372 | s->mem_cached_kb = (double)(cached + sreclaim); |
| 373 | s->mem_used_kb = (double)total - s->mem_free_kb; |
| 374 | if (s->mem_used_kb < 0.0) s->mem_used_kb = 0.0; |
| 375 | s->swap_total_kb = (double)swap_total; |
| 376 | s->swap_used_kb = (double)(swap_total > swap_free ? swap_total - swap_free : 0); |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | static void read_uptime(sys_t *s) |
| 381 | { |
| 382 | FILE *fp = fopen("/proc/uptime", "r"); |
| 383 | double up = 0.0; |
| 384 | if (fp) { |
| 385 | if (fscanf(fp, "%lf", &up) != 1) up = 0.0; |
| 386 | fclose(fp); |
| 387 | } |
| 388 | s->uptime_sec = up; |
| 389 | } |
| 390 | |
| 391 | static void read_load(sys_t *s) |
| 392 | { |
| 393 | FILE *fp = fopen("/proc/loadavg", "r"); |
| 394 | if (fp) { |
| 395 | if (fscanf(fp, "%lf %lf %lf", &s->load1, &s->load5, &s->load15) == 3) |
| 396 | s->load_available = 1; |
| 397 | fclose(fp); |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | static void read_cpu_model(sys_t *s) |
| 402 | { |
| 403 | FILE *fp = fopen("/proc/cpuinfo", "r"); |
| 404 | char line[512]; |
| 405 | s->cpu_model[0] = '\0'; |
| 406 | if (!fp) return; |
| 407 | while (fgets(line, sizeof(line), fp)) { |
| 408 | char *colon; |
| 409 | if (!(strncmp(line, "model name", 10) == 0 || strncmp(line, "Model", 5) == 0)) |
| 410 | continue; |
| 411 | colon = strchr(line, ':'); |
| 412 | if (!colon) continue; |
| 413 | colon++; |
| 414 | while (*colon == ' ' || *colon == '\t') colon++; |
| 415 | { |
| 416 | size_t i = 0; |
| 417 | while (*colon && *colon != '\n' && i + 1 < sizeof(s->cpu_model)) |
| 418 | s->cpu_model[i++] = *colon++; |
| 419 | s->cpu_model[i] = '\0'; |
| 420 | while (i > 0 && (s->cpu_model[i - 1] == ' ' || s->cpu_model[i - 1] == '\t')) |
| 421 | s->cpu_model[--i] = '\0'; |
| 422 | } |
| 423 | break; |
| 424 | } |
| 425 | fclose(fp); |
| 426 | } |
| 427 | |
| 428 | static void read_hostname(sys_t *s) |
| 429 | { |
| 430 | if (gethostname(s->host, sizeof(s->host)) != 0) |
| 431 | s->host[0] = '\0'; |
| 432 | s->host[sizeof(s->host) - 1] = '\0'; |
| 433 | } |
| 434 | |
| 435 | /* One process: utime+stime ticks, rss pages, state char. */ |
| 436 | static int read_pid_stat(const char *pid, unsigned long long *ticks, long *rss_pages, char *state) |
| 437 | { |
| 438 | char path[64]; |
| 439 | char buf[4096]; |
| 440 | FILE *fp; |
| 441 | size_t got; |
| 442 | char *p; |
| 443 | int field; |
| 444 | unsigned long long utime = 0, stime = 0; |
| 445 | long rss = 0; |
| 446 | |
| 447 | snprintf(path, sizeof(path), "/proc/%s/stat", pid); |
| 448 | fp = fopen(path, "r"); |
| 449 | if (!fp) return 0; |
| 450 | got = fread(buf, 1, sizeof(buf) - 1, fp); |
| 451 | fclose(fp); |
| 452 | buf[got] = '\0'; |
| 453 | |
| 454 | p = strrchr(buf, ')'); |
| 455 | if (!p || !p[1]) return 0; |
| 456 | p++; |
| 457 | while (*p == ' ') p++; |
| 458 | if (state) *state = *p; |
| 459 | |
| 460 | /* fields after comm: state is 3, utime 14, stime 15, rss 24 */ |
| 461 | field = 3; |
| 462 | while (*p) { |
| 463 | char *end; |
| 464 | long long v; |
| 465 | while (*p == ' ') p++; |
| 466 | if (!*p) break; |
| 467 | if (field == 3) { |
| 468 | /* skip the single-letter state token */ |
| 469 | while (*p && *p != ' ') p++; |
| 470 | field++; |
| 471 | continue; |
| 472 | } |
| 473 | v = strtoll(p, &end, 10); |
| 474 | if (end == p) break; |
| 475 | if (field == 14) utime = (unsigned long long)v; |
| 476 | else if (field == 15) stime = (unsigned long long)v; |
| 477 | else if (field == 24) rss = (long)v; |
| 478 | if (field >= 24) break; |
| 479 | p = end; |
| 480 | field++; |
| 481 | } |
| 482 | |
| 483 | *ticks = utime + stime; |
| 484 | *rss_pages = rss; |
| 485 | return 1; |
| 486 | } |
| 487 | |
| 488 | static void read_pid_name(const char *pid, char *out, size_t outsz) |
| 489 | { |
| 490 | char path[64]; |
| 491 | FILE *fp; |
| 492 | size_t n; |
| 493 | |
| 494 | out[0] = '\0'; |
| 495 | snprintf(path, sizeof(path), "/proc/%s/comm", pid); |
| 496 | fp = fopen(path, "r"); |
| 497 | if (!fp) return; |
| 498 | n = fread(out, 1, outsz - 1, fp); |
| 499 | fclose(fp); |
| 500 | out[n] = '\0'; |
| 501 | while (n > 0 && (out[n - 1] == '\n' || out[n - 1] == '\r')) |
| 502 | out[--n] = '\0'; |
| 503 | } |
| 504 | |
| 505 | /* |
| 506 | * Two-pass scan of /proc. The second pass is what produces a live CPU |
| 507 | * percentage, because /proc/<pid>/stat only exposes cumulative ticks. |
| 508 | */ |
| 509 | typedef struct { |
| 510 | long pid; |
| 511 | unsigned long long ticks; |
| 512 | long rss_pages; |
| 513 | char state; |
| 514 | } psnap_t; |
| 515 | |
| 516 | static int scan_procs_linux(psnap_t *out, int max) |
| 517 | { |
| 518 | DIR *d; |
| 519 | struct dirent *e; |
| 520 | int n = 0; |
| 521 | |
| 522 | d = opendir("/proc"); |
| 523 | if (!d) return 0; |
| 524 | |
| 525 | while ((e = readdir(d)) != NULL) { |
| 526 | if (!isdigit((unsigned char)e->d_name[0])) continue; |
| 527 | if (n >= max) break; |
| 528 | if (!read_pid_stat(e->d_name, &out[n].ticks, &out[n].rss_pages, &out[n].state)) |
| 529 | continue; |
| 530 | out[n].pid = (long)strtol(e->d_name, NULL, 10); |
| 531 | n++; |
| 532 | } |
| 533 | closedir(d); |
| 534 | return n; |
| 535 | } |
| 536 | |
| 537 | static void sample_linux(sys_t *s) |
| 538 | { |
| 539 | static psnap_t snap0[MAX_PROCS], snap1[MAX_PROCS]; |
| 540 | cpu_raw_t agg0, agg1; |
| 541 | cpu_raw_t c0[MAX_CORES], c1[MAX_CORES]; |
| 542 | int n0, n1, p0, p1, i, j, k; |
| 543 | long hz = sysconf(_SC_CLK_TCK); |
| 544 | long page_kb = (long)(sysconf(_SC_PAGESIZE) / 1024); |
| 545 | double window = (double)SAMPLE_MS / 1000.0; |
| 546 | |
| 547 | strcpy(s->platform, "linux"); |
| 548 | read_hostname(s); |
| 549 | read_cpu_model(s); |
| 550 | |
| 551 | memset(c0, 0, sizeof(c0)); |
| 552 | memset(c1, 0, sizeof(c1)); |
| 553 | |
| 554 | n0 = read_proc_stat(&agg0, c0, MAX_CORES); |
| 555 | p0 = scan_procs_linux(snap0, MAX_PROCS); |
| 556 | |
| 557 | sx_sleep_ms(SAMPLE_MS); |
| 558 | |
| 559 | n1 = read_proc_stat(&agg1, c1, MAX_CORES); |
| 560 | p1 = scan_procs_linux(snap1, MAX_PROCS); |
| 561 | |
| 562 | if (hz <= 0) hz = 100; |
| 563 | |
| 564 | if (n0 > 0 && n1 > 0) { |
| 565 | s->cpu_pct = cpu_busy_pct(&agg0, &agg1); |
| 566 | s->ncores = n1 < MAX_CORES ? n1 : MAX_CORES; |
| 567 | for (i = 0; i < s->ncores; i++) { |
| 568 | s->cores[i].core = i; |
| 569 | s->cores[i].pct = cpu_busy_pct(&c0[i], &c1[i]); |
| 570 | } |
| 571 | } |
| 572 | |
| 573 | /* Processes: RSS is instantaneous, CPU needs a delta over the window. */ |
| 574 | s->nprocs = 0; |
| 575 | for (j = 0; j < p1 && s->nprocs < MAX_PROCS; j++) { |
| 576 | char name[64]; |
| 577 | unsigned long long dt = 0; |
| 578 | char pidbuf[24]; |
| 579 | |
| 580 | for (k = 0; k < p0; k++) { |
| 581 | if (snap0[k].pid == snap1[j].pid) { |
| 582 | dt = snap1[j].ticks > snap0[k].ticks |
| 583 | ? snap1[j].ticks - snap0[k].ticks : 0; |
| 584 | break; |
| 585 | } |
| 586 | } |
| 587 | |
| 588 | snprintf(pidbuf, sizeof(pidbuf), "%ld", snap1[j].pid); |
| 589 | read_pid_name(pidbuf, name, sizeof(name)); |
| 590 | |
| 591 | s->procs[s->nprocs].pid = snap1[j].pid; |
| 592 | s->procs[s->nprocs].cpu = clamp_pct(100.0 * (double)dt / ((double)hz * window)); |
| 593 | s->procs[s->nprocs].rss_kb = snap1[j].rss_pages * page_kb; |
| 594 | s->procs[s->nprocs].state = snap1[j].state; |
| 595 | memcpy(s->procs[s->nprocs].name, name, sizeof(name)); |
| 596 | s->nprocs++; |
| 597 | } |
| 598 | |
| 599 | read_meminfo(s); |
| 600 | read_uptime(s); |
| 601 | read_load(s); |
| 602 | |
| 603 | s->ok = (s->ncores > 0); |
| 604 | } |
| 605 | |
| 606 | #endif /* linux */ |
| 607 | |
| 608 | /* ------------------------------------------------------------------ */ |
| 609 | /* macOS sampling */ |
| 610 | /* ------------------------------------------------------------------ */ |
| 611 | |
| 612 | #if defined(__APPLE__) |
| 613 | |
| 614 | static void sample_macos(sys_t *s) |
| 615 | { |
| 616 | size_t sz; |
| 617 | char bbuf[256]; |
| 618 | unsigned int ncpu = 0; |
| 619 | uint64_t total_mem = 0; |
| 620 | struct timeval boot; |
| 621 | vm_statistics64_data_t vm; |
| 622 | mach_msg_type_number_t vmcount = HOST_VM_INFO64_COUNT; |
| 623 | integer_t *cpu0 = NULL, *cpu1 = NULL; |
| 624 | natural_t ncpu0 = 0, ncpu1 = 0; |
| 625 | unsigned long long page_kb; |
| 626 | |
| 627 | strcpy(s->platform, "macos"); |
| 628 | |
| 629 | sz = sizeof(bbuf); |
| 630 | if (sysctlbyname("kern.hostname", bbuf, &sz, NULL, 0) == 0) |
| 631 | snprintf(s->host, sizeof(s->host), "%s", bbuf); |
| 632 | else |
| 633 | s->host[0] = '\0'; |
| 634 | |
| 635 | s->cpu_model[0] = '\0'; |
| 636 | sz = sizeof(bbuf); |
| 637 | if (sysctlbyname("machdep.cpu.brand_string", bbuf, &sz, NULL, 0) == 0) |
| 638 | snprintf(s->cpu_model, sizeof(s->cpu_model), "%s", bbuf); |
| 639 | |
| 640 | sz = sizeof(ncpu); |
| 641 | if (sysctlbyname("hw.logicalcpu", &ncpu, &sz, NULL, 0) != 0 || |
| 642 | sysctlbyname("hw.ncpu", &ncpu, &sz, NULL, 0) != 0) |
| 643 | ncpu = 1; |
| 644 | |
| 645 | /* aggregate + per-core tick capture, twice */ |
| 646 | { |
| 647 | natural_t c0 = 0, c1 = 0; |
| 648 | if (host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, |
| 649 | &ncpu0, &cpu0, &c0) != KERN_SUCCESS) |
| 650 | cpu0 = NULL; |
| 651 | |
| 652 | sx_sleep_ms(SAMPLE_MS); |
| 653 | |
| 654 | if (host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, |
| 655 | &ncpu1, &cpu1, &c1) != KERN_SUCCESS) |
| 656 | cpu1 = NULL; |
| 657 | } |
| 658 | |
| 659 | if (cpu0 && cpu1) { |
| 660 | natural_t i; |
| 661 | natural_t n = ncpu1 < ncpu0 ? ncpu1 : ncpu0; |
| 662 | unsigned long long t_idle = 0, t_total = 0; |
| 663 | |
| 664 | s->ncores = 0; |
| 665 | for (i = 0; i < n && s->ncores < MAX_CORES; i++) { |
| 666 | unsigned long long a_idle = (unsigned long long)cpu0[i * CPU_STATE_MAX + CPU_STATE_IDLE]; |
| 667 | unsigned long long a_usr = (unsigned long long)cpu0[i * CPU_STATE_MAX + CPU_STATE_USER]; |
| 668 | unsigned long long a_sys = (unsigned long long)cpu0[i * CPU_STATE_MAX + CPU_STATE_SYSTEM]; |
| 669 | unsigned long long a_nice = (unsigned long long)cpu0[i * CPU_STATE_MAX + CPU_STATE_NICE]; |
| 670 | unsigned long long b_idle = (unsigned long long)cpu1[i * CPU_STATE_MAX + CPU_STATE_IDLE]; |
| 671 | unsigned long long b_usr = (unsigned long long)cpu1[i * CPU_STATE_MAX + CPU_STATE_USER]; |
| 672 | unsigned long long b_sys = (unsigned long long)cpu1[i * CPU_STATE_MAX + CPU_STATE_SYSTEM]; |
| 673 | unsigned long long b_nice = (unsigned long long)cpu1[i * CPU_STATE_MAX + CPU_STATE_NICE]; |
| 674 | unsigned long long ta = a_idle + a_usr + a_sys + a_nice; |
| 675 | unsigned long long tb = b_idle + b_usr + b_sys + b_nice; |
| 676 | unsigned long long di = b_idle > a_idle ? b_idle - a_idle : 0; |
| 677 | unsigned long long dt = tb > ta ? tb - ta : 0; |
| 678 | |
| 679 | s->cores[s->ncores].core = (int)i; |
| 680 | s->cores[s->ncores].pct = dt ? clamp_pct(100.0 - 100.0 * (double)di / (double)dt) : 0.0; |
| 681 | s->ncores++; |
| 682 | |
| 683 | t_idle += di; |
| 684 | t_total += dt; |
| 685 | } |
| 686 | s->cpu_pct = t_total ? clamp_pct(100.0 - 100.0 * (double)t_idle / (double)t_total) : 0.0; |
| 687 | } |
| 688 | |
| 689 | if (cpu0) |
| 690 | (void)vm_deallocate(mach_task_self(), (vm_address_t)cpu0, |
| 691 | (vm_size_t)(ncpu0 * CPU_STATE_MAX * sizeof(integer_t))); |
| 692 | if (cpu1) |
| 693 | (void)vm_deallocate(mach_task_self(), (vm_address_t)cpu1, |
| 694 | (vm_size_t)(ncpu1 * CPU_STATE_MAX * sizeof(integer_t))); |
| 695 | |
| 696 | sz = sizeof(total_mem); |
| 697 | if (sysctlbyname("hw.memsize", &total_mem, &sz, NULL, 0) != 0) |
| 698 | total_mem = 0; |
| 699 | |
| 700 | if (host_statistics64(mach_host_self(), HOST_VM_INFO64, |
| 701 | (host_info64_t)&vm, &vmcount) == KERN_SUCCESS) { |
| 702 | vm_size_t pagesz = 0; |
| 703 | host_page_size(mach_host_self(), &pagesz); |
| 704 | page_kb = (unsigned long long)(pagesz / 1024ULL); |
| 705 | s->mem_total_kb = (double)(total_mem / 1024ULL); |
| 706 | s->mem_free_kb = (double)(((unsigned long long)vm.free_count |
| 707 | + (unsigned long long)vm.inactive_count |
| 708 | + (unsigned long long)vm.speculative_count) * page_kb); |
| 709 | s->mem_cached_kb = (double)((unsigned long long)vm.purgeable_count * page_kb); |
| 710 | s->mem_used_kb = (double)(((unsigned long long)(vm.active_count |
| 711 | + vm.wire_count) * page_kb)); |
| 712 | } |
| 713 | |
| 714 | { |
| 715 | struct xsw_usage xs; |
| 716 | sz = sizeof(xs); |
| 717 | if (sysctlbyname("vm.swapusage", &xs, &sz, NULL, 0) == 0) { |
| 718 | s->swap_total_kb = (double)(xs.xsu_total / 1024ULL); |
| 719 | s->swap_used_kb = (double)(xs.xsu_used / 1024ULL); |
| 720 | } |
| 721 | } |
| 722 | |
| 723 | sz = sizeof(boot); |
| 724 | if (sysctlbyname("kern.boottime", &boot, &sz, NULL, 0) == 0) { |
| 725 | time_t now = time(NULL); |
| 726 | s->uptime_sec = (double)now - (double)boot.tv_sec; |
| 727 | if (s->uptime_sec < 0.0) s->uptime_sec = 0.0; |
| 728 | } |
| 729 | |
| 730 | { |
| 731 | double loads[3]; |
| 732 | if (getloadavg(loads, 3) == 3) { |
| 733 | s->load1 = loads[0]; |
| 734 | s->load5 = loads[1]; |
| 735 | s->load15 = loads[2]; |
| 736 | s->load_available = 1; |
| 737 | } |
| 738 | } |
| 739 | |
| 740 | /* Process list: the kernel exposes it most simply through ps. */ |
| 741 | { |
| 742 | FILE *fp = popen("ps -Ao pid=,pcpu=,rss=,comm=", "r"); |
| 743 | if (fp) { |
| 744 | char line[600]; |
| 745 | s->nprocs = 0; |
| 746 | while (fgets(line, sizeof(line), fp) && s->nprocs < MAX_PROCS) { |
| 747 | long pid = 0; |
| 748 | double pcpu = 0.0; |
| 749 | long rss = 0; |
| 750 | char comm[256]; |
| 751 | if (sscanf(line, "%ld %lf %ld %255[^\n]", &pid, &pcpu, &rss, comm) != 4) |
| 752 | continue; |
| 753 | s->procs[s->nprocs].pid = pid; |
| 754 | s->procs[s->nprocs].cpu = clamp_pct(pcpu); |
| 755 | s->procs[s->nprocs].rss_kb = rss; |
| 756 | s->procs[s->nprocs].state = 'R'; |
| 757 | { |
| 758 | const char *base = strrchr(comm, '/'); |
| 759 | base = base ? base + 1 : comm; |
| 760 | snprintf(s->procs[s->nprocs].name, sizeof(s->procs[s->nprocs].name), |
| 761 | "%s", base); |
| 762 | } |
| 763 | s->nprocs++; |
| 764 | } |
| 765 | pclose(fp); |
| 766 | } |
| 767 | } |
| 768 | |
| 769 | s->ok = (s->ncores > 0 && s->mem_total_kb > 0.0); |
| 770 | } |
| 771 | |
| 772 | #endif /* __APPLE__ */ |
| 773 | |
| 774 | /* ------------------------------------------------------------------ */ |
| 775 | /* Windows sampling */ |
| 776 | /* ------------------------------------------------------------------ */ |
| 777 | |
| 778 | #if defined(_WIN32) |
| 779 | |
| 780 | static unsigned long long filetime_to_100ns(const FILETIME *ft) |
| 781 | { |
| 782 | ULARGE_INTEGER u; |
| 783 | u.LowPart = ft->dwLowDateTime; |
| 784 | u.HighPart = ft->dwHighDateTime; |
| 785 | return (unsigned long long)u.QuadPart; |
| 786 | } |
| 787 | |
| 788 | static void sample_windows(sys_t *s) |
| 789 | { |
| 790 | MEMORYSTATUSEX ms; |
| 791 | FILETIME idle0, kern0, user0, idle1, kern1, user1; |
| 792 | ULARGE_INTEGER li; |
| 793 | double total0, total1, idle_d, kern_d, user_d, dt; |
| 794 | DWORD ncpu = 0; |
| 795 | HANDLE snap; |
| 796 | PROCESSENTRY32W pe; |
| 797 | |
| 798 | strcpy(s->platform, "windows"); |
| 799 | s->host[0] = '\0'; |
| 800 | s->cpu_model[0] = '\0'; |
| 801 | |
| 802 | { |
| 803 | char name[256]; |
| 804 | DWORD n = (DWORD)sizeof(name); |
| 805 | if (GetComputerNameA(name, &n)) |
| 806 | snprintf(s->host, sizeof(s->host), "%s", name); |
| 807 | } |
| 808 | |
| 809 | { |
| 810 | SYSTEM_INFO si; |
| 811 | GetSystemInfo(&si); |
| 812 | ncpu = si.dwNumberOfProcessors; |
| 813 | } |
| 814 | |
| 815 | if (!GetSystemTimes(&idle0, &kern0, &user0)) { |
| 816 | s->ok = 0; |
| 817 | return; |
| 818 | } |
| 819 | |
| 820 | sx_sleep_ms(SAMPLE_MS); |
| 821 | |
| 822 | if (!GetSystemTimes(&idle1, &kern1, &user1)) { |
| 823 | s->ok = 0; |
| 824 | return; |
| 825 | } |
| 826 | |
| 827 | total0 = (double)filetime_to_100ns(&kern0) + (double)filetime_to_100ns(&user0); |
| 828 | total1 = (double)filetime_to_100ns(&kern1) + (double)filetime_to_100ns(&user1); |
| 829 | idle_d = (double)filetime_to_100ns(&idle1) - (double)filetime_to_100ns(&idle0); |
| 830 | kern_d = (double)filetime_to_100ns(&kern1) - (double)filetime_to_100ns(&kern0); |
| 831 | user_d = (double)filetime_to_100ns(&user1) - (double)filetime_to_100ns(&user0); |
| 832 | dt = total1 - total0; |
| 833 | |
| 834 | if (dt > 0.0) { |
| 835 | /* kernel time already includes idle time */ |
| 836 | double busy = (kern_d - idle_d) + user_d; |
| 837 | s->cpu_pct = clamp_pct(100.0 * busy / dt); |
| 838 | } |
| 839 | |
| 840 | s->ncores = 0; |
| 841 | |
| 842 | /* Windows has no cheap per-core delta, so the UI shows an aggregate bar. */ |
| 843 | if (ncpu == 0) ncpu = 1; |
| 844 | s->ncores = 0; |
| 845 | |
| 846 | memset(&ms, 0, sizeof(ms)); |
| 847 | ms.dwLength = sizeof(ms); |
| 848 | if (GlobalMemoryStatusEx(&ms)) { |
| 849 | s->mem_total_kb = (double)(ms.ullTotalPhys / 1024ULL); |
| 850 | s->mem_free_kb = (double)(ms.ullAvailPhys / 1024ULL); |
| 851 | s->mem_used_kb = s->mem_total_kb - s->mem_free_kb; |
| 852 | if (s->mem_used_kb < 0.0) s->mem_used_kb = 0.0; |
| 853 | s->mem_cached_kb = 0.0; |
| 854 | s->swap_total_kb = (double)(ms.ullTotalPageFile / 1024ULL); |
| 855 | s->swap_used_kb = s->swap_total_kb > (double)(ms.ullAvailPageFile / 1024ULL) |
| 856 | ? s->swap_total_kb - (double)(ms.ullAvailPageFile / 1024ULL) : 0.0; |
| 857 | } |
| 858 | |
| 859 | (void)li; |
| 860 | s->uptime_sec = (double)GetTickCount64() / 1000.0; |
| 861 | s->load_available = 0; |
| 862 | |
| 863 | /* Process list via Toolhelp32, matching the POSIX fields. */ |
| 864 | snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); |
| 865 | if (snap != INVALID_HANDLE_VALUE) { |
| 866 | memset(&pe, 0, sizeof(pe)); |
| 867 | pe.dwSize = sizeof(pe); |
| 868 | s->nprocs = 0; |
| 869 | if (Process32FirstW(snap, &pe)) { |
| 870 | do { |
| 871 | HANDLE ph; |
| 872 | long rss_kb = 0; |
| 873 | |
| 874 | if (s->nprocs >= MAX_PROCS) break; |
| 875 | |
| 876 | ph = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ, |
| 877 | FALSE, pe.th32ProcessID); |
| 878 | if (ph) { |
| 879 | PROCESS_MEMORY_COUNTERS pmc; |
| 880 | memset(&pmc, 0, sizeof(pmc)); |
| 881 | if (GetProcessMemoryInfo(ph, &pmc, sizeof(pmc))) |
| 882 | rss_kb = (long)(pmc.WorkingSetSize / 1024); |
| 883 | CloseHandle(ph); |
| 884 | } |
| 885 | |
| 886 | s->procs[s->nprocs].pid = (long)pe.th32ProcessID; |
| 887 | s->procs[s->nprocs].cpu = 0.0; |
| 888 | s->procs[s->nprocs].rss_kb = rss_kb; |
| 889 | s->procs[s->nprocs].state = 'R'; |
| 890 | { |
| 891 | int i = 0; |
| 892 | while (pe.szExeFile[i] && i + 1 < (int)sizeof(s->procs[s->nprocs].name)) { |
| 893 | s->procs[s->nprocs].name[i] = (char)pe.szExeFile[i]; |
| 894 | i++; |
| 895 | } |
| 896 | s->procs[s->nprocs].name[i] = '\0'; |
| 897 | } |
| 898 | s->nprocs++; |
| 899 | } while (Process32NextW(snap, &pe)); |
| 900 | } |
| 901 | CloseHandle(snap); |
| 902 | } |
| 903 | |
| 904 | s->ok = (s->mem_total_kb > 0.0); |
| 905 | } |
| 906 | |
| 907 | #endif /* _WIN32 */ |
| 908 | |
| 909 | /* ------------------------------------------------------------------ */ |
| 910 | /* Sampling dispatch */ |
| 911 | /* ------------------------------------------------------------------ */ |
| 912 | |
| 913 | static void sample(sys_t *s) |
| 914 | { |
| 915 | memset(s, 0, sizeof(*s)); |
| 916 | |
| 917 | #if defined(_WIN32) |
| 918 | sample_windows(s); |
| 919 | #elif defined(__APPLE__) |
| 920 | sample_macos(s); |
| 921 | #else |
| 922 | sample_linux(s); |
| 923 | #endif |
| 924 | } |
| 925 | |
| 926 | static int proc_cmp_cpu(const void *a, const void *b) |
| 927 | { |
| 928 | const proc_t *pa = (const proc_t *)a; |
| 929 | const proc_t *pb = (const proc_t *)b; |
| 930 | if (pa->cpu < pb->cpu) return 1; |
| 931 | if (pa->cpu > pb->cpu) return -1; |
| 932 | if (pa->rss_kb < pb->rss_kb) return 1; |
| 933 | if (pa->rss_kb > pb->rss_kb) return -1; |
| 934 | return 0; |
| 935 | } |
| 936 | |
| 937 | static int proc_cmp_mem(const void *a, const void *b) |
| 938 | { |
| 939 | const proc_t *pa = (const proc_t *)a; |
| 940 | const proc_t *pb = (const proc_t *)b; |
| 941 | if (pa->rss_kb < pb->rss_kb) return 1; |
| 942 | if (pa->rss_kb > pb->rss_kb) return -1; |
| 943 | return proc_cmp_cpu(a, b); |
| 944 | } |
| 945 | |
| 946 | /* ------------------------------------------------------------------ */ |
| 947 | /* Modes */ |
| 948 | /* ------------------------------------------------------------------ */ |
| 949 | |
| 950 | static int mode_meta(void) |
| 951 | { |
| 952 | puts("{\"name\":\"sysmon\",\"desc\":\"CPU & memory\"}"); |
| 953 | return 0; |
| 954 | } |
| 955 | |
| 956 | static void json_header(void) |
| 957 | { |
| 958 | /* Deliberately no Content-Length - the server owns framing. */ |
| 959 | fputs("Content-Type: application/json; charset=utf-8\r\n" |
| 960 | "Cache-Control: no-store\r\n" |
| 961 | "X-Content-Type-Options: nosniff\r\n\r\n", stdout); |
| 962 | } |
| 963 | |
| 964 | static void emit_cores(const sys_t *s) |
| 965 | { |
| 966 | int i; |
| 967 | fputs("[", stdout); |
| 968 | for (i = 0; i < s->ncores && i < MAX_CORES; i++) { |
| 969 | if (i) fputs(",", stdout); |
| 970 | printf("{\"core\":%d,\"pct\":%.1f}", s->cores[i].core, s->cores[i].pct); |
| 971 | } |
| 972 | fputs("]", stdout); |
| 973 | } |
| 974 | |
| 975 | static void emit_procs(const sys_t *s, int limit) |
| 976 | { |
| 977 | int i; |
| 978 | fputs("[", stdout); |
| 979 | for (i = 0; i < limit; i++) { |
| 980 | if (i) fputs(",", stdout); |
| 981 | printf("{\"pid\":%ld,\"name\":", s->procs[i].pid); |
| 982 | json_str(s->procs[i].name); |
| 983 | printf(",\"cpu\":%.1f,\"rss_kb\":%ld,\"state\":\"%c\"}", |
| 984 | s->procs[i].cpu, s->procs[i].rss_kb, |
| 985 | (s->procs[i].state ? s->procs[i].state : '?')); |
| 986 | } |
| 987 | fputs("]", stdout); |
| 988 | } |
| 989 | |
| 990 | static int mode_json(const char *qs) |
| 991 | { |
| 992 | char action[64]; |
| 993 | char sortby[16]; |
| 994 | char topn[16]; |
| 995 | char utc[40]; |
| 996 | sys_t s; |
| 997 | int limit = TOP_DEFAULT; |
| 998 | int ntop; |
| 999 | |
| 1000 | action[0] = sortby[0] = topn[0] = '\0'; |
| 1001 | get_query_val(qs, "action", action, sizeof(action)); |
| 1002 | get_query_val(qs, "sort", sortby, sizeof(sortby)); |
| 1003 | get_query_val(qs, "top", topn, sizeof(topn)); |
| 1004 | |
| 1005 | if (topn[0]) { |
| 1006 | int v = atoi(topn); |
| 1007 | if (v > 0 && v <= MAX_PROCS) limit = v; |
| 1008 | } |
| 1009 | |
| 1010 | if (action[0] && strcmp(action, "metrics") != 0 && strcmp(action, "info") != 0) { |
| 1011 | json_header(); |
| 1012 | printf("{\"ok\":false,\"error\":\"unknown_action\"," |
| 1013 | "\"supported\":[\"metrics\",\"info\"],\"requested\":"); |
| 1014 | json_str(action); |
| 1015 | fputs("}\n", stdout); |
| 1016 | return 0; |
| 1017 | } |
| 1018 | |
| 1019 | sample(&s); |
| 1020 | utc_now(utc, sizeof(utc)); |
| 1021 | |
| 1022 | if (strcmp(action, "info") == 0) { |
| 1023 | json_header(); |
| 1024 | fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\"," |
| 1025 | "\"version\":\"" PLUGIN_VER "\",\"platform\":", stdout); |
| 1026 | json_str(s.platform); |
| 1027 | fputs(",\"pid\":", stdout); |
| 1028 | printf("%ld", node_pid()); |
| 1029 | fputs(",\"utc\":", stdout); |
| 1030 | json_str(utc); |
| 1031 | fputs(",\"node_auth\":", stdout); |
| 1032 | { |
| 1033 | const char *np = getenv("BOT_PASSWORD"); |
| 1034 | fputs((np && *np) ? "true" : "false", stdout); |
| 1035 | } |
| 1036 | fputs(",\"supported\":[\"metrics\",\"info\"],\"zero_network\":true," |
| 1037 | "\"samples_cpu_delta_ms\":", stdout); |
| 1038 | printf("%d", SAMPLE_MS); |
| 1039 | fputs("}\n", stdout); |
| 1040 | return 0; |
| 1041 | } |
| 1042 | |
| 1043 | /* sort the process table before taking the top slice */ |
| 1044 | ntop = s.nprocs < MAX_PROCS ? s.nprocs : MAX_PROCS; |
| 1045 | if (ntop > 0) { |
| 1046 | qsort(s.procs, (size_t)ntop, sizeof(s.procs[0]), |
| 1047 | strcmp(sortby, "mem") == 0 ? proc_cmp_mem : proc_cmp_cpu); |
| 1048 | } |
| 1049 | if (ntop > limit) ntop = limit; |
| 1050 | |
| 1051 | json_header(); |
| 1052 | if (!s.ok) { |
| 1053 | fputs("{\"ok\":false,\"error\":\"sample_failed\"," |
| 1054 | "\"message\":\"could not read local system counters on this node\"}\n", stdout); |
| 1055 | return 0; |
| 1056 | } |
| 1057 | |
| 1058 | fputs("{\"ok\":true,\"action\":\"metrics\",\"plugin\":\"" PLUGIN_ID "\"," |
| 1059 | "\"version\":\"" PLUGIN_VER "\"", stdout); |
| 1060 | |
| 1061 | fputs(",\"platform\":", stdout); json_str(s.platform); |
| 1062 | fputs(",\"host\":", stdout); json_str(s.host); |
| 1063 | fputs(",\"cpu_model\":", stdout); json_str(s.cpu_model); |
| 1064 | fputs(",\"utc\":", stdout); json_str(utc); |
| 1065 | |
| 1066 | printf(",\"cpu_pct\":%.1f,\"ncores\":%d,\"cores\":", s.cpu_pct, s.ncores); |
| 1067 | emit_cores(&s); |
| 1068 | |
| 1069 | printf(",\"mem\":{\"total_kb\":%.0f,\"used_kb\":%.0f,\"free_kb\":%.0f," |
| 1070 | "\"cached_kb\":%.0f,\"pct\":%.1f}", |
| 1071 | s.mem_total_kb, s.mem_used_kb, s.mem_free_kb, s.mem_cached_kb, |
| 1072 | s.mem_total_kb > 0.0 ? clamp_pct(100.0 * s.mem_used_kb / s.mem_total_kb) : 0.0); |
| 1073 | |
| 1074 | printf(",\"swap\":{\"total_kb\":%.0f,\"used_kb\":%.0f,\"pct\":%.1f}", |
| 1075 | s.swap_total_kb, s.swap_used_kb, |
| 1076 | s.swap_total_kb > 0.0 ? clamp_pct(100.0 * s.swap_used_kb / s.swap_total_kb) : 0.0); |
| 1077 | |
| 1078 | printf(",\"uptime_sec\":%.0f,\"load\":{\"available\":%s," |
| 1079 | "\"load1\":%.2f,\"load5\":%.2f,\"load15\":%.2f}", |
| 1080 | s.uptime_sec, s.load_available ? "true" : "false", |
| 1081 | s.load1, s.load5, s.load15); |
| 1082 | |
| 1083 | printf(",\"proc_count\":%d,\"top\":%d,\"sort\":", s.nprocs, ntop); |
| 1084 | json_str(strcmp(sortby, "mem") == 0 ? "mem" : "cpu"); |
| 1085 | fputs(",\"processes\":", stdout); |
| 1086 | emit_procs(&s, ntop); |
| 1087 | fputs("}\n", stdout); |
| 1088 | return 0; |
| 1089 | } |
| 1090 | |
| 1091 | /* ------------------------------------------------------------------ */ |
| 1092 | /* HTML */ |
| 1093 | /* ------------------------------------------------------------------ */ |
| 1094 | |
| 1095 | static int mode_html(int embed) |
| 1096 | { |
| 1097 | fputs("Content-Type: text/html; charset=utf-8\r\n" |
| 1098 | "Cache-Control: no-store\r\n" |
| 1099 | "X-Content-Type-Options: nosniff\r\n\r\n", stdout); |
| 1100 | |
| 1101 | fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>" |
| 1102 | "<meta name='viewport' content='width=device-width,initial-scale=1'>" |
| 1103 | "<title>sysmon</title>", stdout); |
| 1104 | |
| 1105 | fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS, stdout); |
| 1106 | fputs( |
| 1107 | "*{box-sizing:border-box}" |
| 1108 | "body{margin:0;padding:16px;background:var(--bg);color:var(--text);" |
| 1109 | "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;" |
| 1110 | "font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}" |
| 1111 | ".wrap{max-width:1120px;margin:0 auto}" |
| 1112 | ".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}" |
| 1113 | ".title{font-size:20px;font-weight:700;margin:0}" |
| 1114 | ".sub{color:var(--muted);font-size:12px;font-family:var(--mono)}" |
| 1115 | ".spacer{flex:1}" |
| 1116 | ".pill{font-size:11px;font-weight:600;padding:2px 9px;border-radius:999px;" |
| 1117 | "background:var(--surface2);color:var(--muted);border:1px solid var(--line);white-space:nowrap}" |
| 1118 | ".pill.live{color:var(--ok);border-color:rgba(48,209,88,.4)}" |
| 1119 | ".pill.paused{color:var(--warn);border-color:rgba(255,214,10,.4)}" |
| 1120 | ".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;" |
| 1121 | "padding:16px;margin-bottom:14px}" |
| 1122 | ".card h2{margin:0 0 12px;font-size:12px;letter-spacing:.06em;text-transform:uppercase;" |
| 1123 | "color:var(--muted);font-weight:600}" |
| 1124 | ".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(132px,1fr));gap:10px}" |
| 1125 | ".kpi{background:var(--surface2);border:1px solid var(--line);border-radius:10px;padding:10px 12px;min-width:0}" |
| 1126 | ".kpi .k{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}" |
| 1127 | ".kpi .v{font-size:20px;font-weight:700;font-family:var(--mono);margin-top:2px;" |
| 1128 | "overflow:hidden;text-overflow:ellipsis;white-space:nowrap}" |
| 1129 | "button{background:var(--accent);color:#fff;border:0;border-radius:999px;" |
| 1130 | "padding:6px 13px;font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}" |
| 1131 | "button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}" |
| 1132 | "button.on{background:var(--accent);color:#fff;border-color:transparent}" |
| 1133 | "button:active{transform:scale(.98)}" |
| 1134 | ".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}" |
| 1135 | ".seg{display:inline-flex;gap:4px;background:var(--surface2);border:1px solid var(--line);" |
| 1136 | "border-radius:999px;padding:3px}" |
| 1137 | ".seg button{background:transparent;color:var(--muted);border:0;padding:4px 11px;font-size:12px}" |
| 1138 | ".seg button.on{background:var(--accent);color:#fff}" |
| 1139 | ".cores{display:grid;grid-template-columns:repeat(auto-fill,minmax(86px,1fr));gap:8px}" |
| 1140 | ".core{background:var(--surface2);border:1px solid var(--line);border-radius:9px;padding:7px 8px}" |
| 1141 | ".core .lbl{font-size:10px;color:var(--muted);font-family:var(--mono)}" |
| 1142 | ".core .bar{height:6px;border-radius:3px;background:rgba(255,255,255,.10);margin:5px 0 4px;overflow:hidden}" |
| 1143 | ".core .fill{height:100%;background:var(--ok);border-radius:3px;transition:width .35s}" |
| 1144 | ".core .pc{font-size:11px;font-family:var(--mono);font-weight:600}" |
| 1145 | ".gauge{height:10px;border-radius:5px;background:rgba(255,255,255,.10);overflow:hidden;margin:6px 0 4px}" |
| 1146 | ".gauge .fill{height:100%;border-radius:5px;transition:width .35s;background:var(--accent)}" |
| 1147 | ".glabel{display:flex;justify-content:space-between;font-size:11px;color:var(--muted);" |
| 1148 | "font-family:var(--mono)}" |
| 1149 | "svg.spark{display:block;width:100%;height:64px}" |
| 1150 | "table{width:100%;border-collapse:collapse;font-size:13px}" |
| 1151 | "th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.05em;" |
| 1152 | "color:var(--muted);font-weight:600;padding:6px 8px;border-bottom:1px solid var(--line);" |
| 1153 | "white-space:nowrap}" |
| 1154 | "th.num,td.num{text-align:right;font-family:var(--mono)}" |
| 1155 | "td{padding:6px 8px;border-bottom:1px solid var(--line);vertical-align:middle}" |
| 1156 | "td.nm{font-family:var(--mono);font-size:12px;word-break:break-all}" |
| 1157 | "tr:last-child td{border-bottom:0}" |
| 1158 | ".tblwrap{overflow-x:auto}" |
| 1159 | "input{background:var(--surface2);border:1px solid var(--line);border-radius:10px;" |
| 1160 | "padding:7px 11px;color:var(--text);font-size:13px;font-family:var(--mono);" |
| 1161 | "min-width:130px;flex:1}" |
| 1162 | "input:focus{outline:2px solid var(--accent);outline-offset:-1px}" |
| 1163 | ".hide{display:none!important}" |
| 1164 | ".muted{color:var(--muted)}" |
| 1165 | "@media(max-width:640px){" |
| 1166 | "body{padding:12px}" |
| 1167 | ".kpi .v{font-size:17px}" |
| 1168 | "th.hide-sm,td.hide-sm{display:none}" |
| 1169 | ".card{padding:12px;border-radius:12px}" |
| 1170 | ".cores{grid-template-columns:repeat(auto-fill,minmax(72px,1fr))}" |
| 1171 | "}", stdout); |
| 1172 | |
| 1173 | fputs("</style></head>" SX_BOT_THEME_HANDOFF "<body><div class='wrap'>", stdout); |
| 1174 | |
| 1175 | if (!embed) { |
| 1176 | fputs("<div class='top'><a href='/' style='color:var(--accent);" |
| 1177 | "text-decoration:none;font-weight:600'>← Back to Bot</a></div>", stdout); |
| 1178 | } |
| 1179 | |
| 1180 | fputs("<div class='top'>" |
| 1181 | "<h1 class='title'>sysmon</h1>" |
| 1182 | "<span class='pill' id='pHost'>—</span>" |
| 1183 | "<span class='pill' id='pPlatform'>—</span>" |
| 1184 | "<span class='spacer'></span>" |
| 1185 | "<span class='pill live' id='pState'>live 2s</span>" |
| 1186 | "<div class='seg' id='segRate'>" |
| 1187 | "<button type='button' data-ms='2000' class='on'>2s</button>" |
| 1188 | "<button type='button' data-ms='5000'>5s</button>" |
| 1189 | "<button type='button' data-ms='0'>Pause</button>" |
| 1190 | "</div></div>", stdout); |
| 1191 | |
| 1192 | /* KPI row */ |
| 1193 | fputs("<div class='card'><h2>System</h2><div class='grid'>" |
| 1194 | "<div class='kpi'><div class='k'>cpu</div><div class='v' id='kCpu'>—</div></div>" |
| 1195 | "<div class='kpi'><div class='k'>cores</div><div class='v' id='kCores'>—</div></div>" |
| 1196 | "<div class='kpi'><div class='k'>memory</div><div class='v' id='kMem'>—</div></div>" |
| 1197 | "<div class='kpi'><div class='k'>swap</div><div class='v' id='kSwap'>—</div></div>" |
| 1198 | "<div class='kpi'><div class='k'>load 1m</div><div class='v' id='kLoad'>—</div></div>" |
| 1199 | "<div class='kpi'><div class='k'>uptime</div><div class='v' id='kUp'>—</div></div>" |
| 1200 | "<div class='kpi'><div class='k'>processes</div><div class='v' id='kProc'>—</div></div>" |
| 1201 | "</div>" |
| 1202 | "<div class='sub' id='cpuModel' style='margin-top:10px'></div></div>", stdout); |
| 1203 | |
| 1204 | /* history sparkline */ |
| 1205 | fputs("<div class='card'><h2>CPU history</h2>" |
| 1206 | "<svg class='spark' id='spark' viewBox='0 0 600 64' preserveAspectRatio='none'>" |
| 1207 | "<polyline id='sparkLine' fill='none' stroke='#0a84ff' stroke-width='2' " |
| 1208 | "stroke-linejoin='round' stroke-linecap='round' points=''/>" |
| 1209 | "</svg></div>", stdout); |
| 1210 | |
| 1211 | /* per-core */ |
| 1212 | fputs("<div class='card'><h2>Per-core utilization</h2>" |
| 1213 | "<div class='cores' id='cores'></div>" |
| 1214 | "<div class='muted' id='coreNote' style='margin-top:10px'></div></div>", stdout); |
| 1215 | |
| 1216 | /* memory + swap gauges */ |
| 1217 | fputs("<div class='card'><h2>Memory & swap</h2>" |
| 1218 | "<div class='glabel'><span>memory</span><span id='memLbl'>—</span></div>" |
| 1219 | "<div class='gauge'><div class='fill' id='memFill' style='width:0'></div></div>" |
| 1220 | "<div class='glabel' style='margin-top:12px'><span>swap</span><span id='swapLbl'>—</span></div>" |
| 1221 | "<div class='gauge'><div class='fill' id='swapFill' style='width:0;background:var(--warn)'></div></div>" |
| 1222 | "<div class='sub' id='memDetail' style='margin-top:10px'></div></div>", stdout); |
| 1223 | |
| 1224 | /* processes */ |
| 1225 | fputs("<div class='card'><h2>Top processes</h2>" |
| 1226 | "<div class='row'>" |
| 1227 | "<input id='q' type='text' placeholder='filter by name or pid'>" |
| 1228 | "<div class='seg' id='segSort'>" |
| 1229 | "<button type='button' data-sort='cpu' class='on'>CPU</button>" |
| 1230 | "<button type='button' data-sort='mem'>Memory</button>" |
| 1231 | "</div></div>" |
| 1232 | "<div class='tblwrap'><table><thead><tr>" |
| 1233 | "<th class='num'>PID</th><th>Name</th>" |
| 1234 | "<th class='num'>CPU %</th><th class='num'>RSS</th>" |
| 1235 | "<th class='hide-sm'>State</th>" |
| 1236 | "</tr></thead><tbody id='rows'></tbody></table></div>" |
| 1237 | "<div id='empty' class='muted hide'>No matching processes.</div></div>", stdout); |
| 1238 | |
| 1239 | fputs("<div class='card'><h2>About this plugin</h2>" |
| 1240 | "<p class='muted' style='margin:0 0 8px'>Local node only. Reads the kernel's " |
| 1241 | "own counters (<code>/proc</code> on Linux, mach and <code>sysctl</code> on macOS, " |
| 1242 | "Win32 APIs on Windows) and makes zero outbound network requests.</p>" |
| 1243 | "<p class='muted' style='margin:0'>Two CPU samples " |
| 1244 | "80 ms apart give a live percentage; nothing is cached between requests " |
| 1245 | "and no shell command comes from user input.</p></div>", stdout); |
| 1246 | |
| 1247 | /* script */ |
| 1248 | fputs("<script>\n" |
| 1249 | "(function(){\n" |
| 1250 | " var q = new URLSearchParams(location.search);\n" |
| 1251 | " var HUB = q.get('plugin') || '';\n" |
| 1252 | " var node = q.get('node') || '';\n" |
| 1253 | " var sid = q.get('id') || '';\n" |
| 1254 | " var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n" |
| 1255 | " localStorage.getItem('bot_active_pwd') || '';\n" |
| 1256 | "\n" |
| 1257 | " /* Two routes, and getting this wrong is the classic plugin bug:\n" |
| 1258 | " page served through the hub -> call the hub proxy back\n" |
| 1259 | " page opened directly on node -> the plugin IS the route */\n" |
| 1260 | " function base(){ return HUB ? '/plugins?plugin=' + HUB : '/plugin_sysmon'; }\n" |
| 1261 | " function withCtx(u){\n" |
| 1262 | " if (node) u += '&node=' + encodeURIComponent(node);\n" |
| 1263 | " if (sid) u += '&id=' + encodeURIComponent(sid);\n" |
| 1264 | " if (pwd) u += '&pwd=' + encodeURIComponent(pwd);\n" |
| 1265 | " return u;\n" |
| 1266 | " }\n" |
| 1267 | " function hdr(){ return pwd ? {'X-Bot-Password': pwd} : {}; }\n" |
| 1268 | " function $(id){ return document.getElementById(id); }\n" |
| 1269 | " function el(tag, cls, text){\n" |
| 1270 | " var e = document.createElement(tag);\n" |
| 1271 | " if (cls) e.className = cls;\n" |
| 1272 | " if (text !== undefined && text !== null) e.textContent = String(text);\n" |
| 1273 | " return e;\n" |
| 1274 | " }\n" |
| 1275 | " function txt(id, v){\n" |
| 1276 | " var e = $(id); if (!e) return;\n" |
| 1277 | " e.textContent = (v === undefined || v === null || v === '') ? '\\u2014' : String(v);\n" |
| 1278 | " }\n" |
| 1279 | "\n" |
| 1280 | " document.documentElement.setAttribute('data-theme',\n" |
| 1281 | " localStorage.getItem('bot_theme') || 'dark');\n" |
| 1282 | "\n" |
| 1283 | "\n" |
| 1284 | " var RATE = 2000, TIMER = null, BUSY = false;\n" |
| 1285 | " var HISTORY = [], HIST_MAX = 60;\n" |
| 1286 | " var SORT = 'cpu';\n" |
| 1287 | " var DATA = null;\n" |
| 1288 | "\n" |
| 1289 | " function kb(v){\n" |
| 1290 | " if (!v && v !== 0) return '\\u2014';\n" |
| 1291 | " if (v >= 1048576) return (v / 1048576).toFixed(1) + ' GiB';\n" |
| 1292 | " if (v >= 1024) return (v / 1024).toFixed(0) + ' MiB';\n" |
| 1293 | " return v + ' KiB';\n" |
| 1294 | " }\n" |
| 1295 | " function dur(sec){\n" |
| 1296 | " if (!sec && sec !== 0) return '\\u2014';\n" |
| 1297 | " var d = Math.floor(sec / 86400), h = Math.floor((sec % 86400) / 3600),\n" |
| 1298 | " m = Math.floor((sec % 3600) / 60);\n" |
| 1299 | " if (d > 0) return d + 'd ' + h + 'h';\n" |
| 1300 | " if (h > 0) return h + 'h ' + m + 'm';\n" |
| 1301 | " return m + 'm';\n" |
| 1302 | " }\n" |
| 1303 | " function pctColor(p){\n" |
| 1304 | " if (p >= 85) return 'var(--danger)';\n" |
| 1305 | " if (p >= 60) return 'var(--warn)';\n" |
| 1306 | " return 'var(--ok)';\n" |
| 1307 | " }\n" |
| 1308 | "\n" |
| 1309 | " function renderCores(d){\n" |
| 1310 | " var host = $('cores');\n" |
| 1311 | " host.innerHTML = '';\n" |
| 1312 | " if (!d.cores || !d.cores.length){\n" |
| 1313 | " $('coreNote').textContent = 'Per-core detail is available on Linux and macOS nodes; ' +\n" |
| 1314 | " 'this platform exposes an aggregate CPU figure only.';\n" |
| 1315 | " return;\n" |
| 1316 | " }\n" |
| 1317 | " $('coreNote').textContent = '';\n" |
| 1318 | " for (var i = 0; i < d.cores.length; i++){\n" |
| 1319 | " var c = d.cores[i];\n" |
| 1320 | " var box = el('div','core');\n" |
| 1321 | " box.appendChild(el('div','lbl','cpu ' + c.core));\n" |
| 1322 | " var bar = el('div','bar'), fill = el('div','fill');\n" |
| 1323 | " fill.style.width = Math.max(0, Math.min(100, c.pct)) + '%';\n" |
| 1324 | " fill.style.background = pctColor(c.pct);\n" |
| 1325 | " bar.appendChild(fill);\n" |
| 1326 | " box.appendChild(bar);\n" |
| 1327 | " box.appendChild(el('div','pc', c.pct.toFixed(0) + '%'));\n" |
| 1328 | " host.appendChild(box);\n" |
| 1329 | " }\n" |
| 1330 | " }\n" |
| 1331 | "\n" |
| 1332 | " function renderSpark(v){\n" |
| 1333 | " HISTORY.push(Math.max(0, Math.min(100, v)));\n" |
| 1334 | " if (HISTORY.length > HIST_MAX) HISTORY.shift();\n" |
| 1335 | " if (HISTORY.length < 2) return;\n" |
| 1336 | " var pts = [];\n" |
| 1337 | " for (var i = 0; i < HISTORY.length; i++){\n" |
| 1338 | " var x = (i / (HISTORY.length - 1)) * 600;\n" |
| 1339 | " var y = 62 - (HISTORY[i] / 100) * 58;\n" |
| 1340 | " pts.push(x.toFixed(1) + ',' + y.toFixed(1));\n" |
| 1341 | " }\n" |
| 1342 | " $('sparkLine').setAttribute('points', pts.join(' '));\n" |
| 1343 | " }\n" |
| 1344 | "\n" |
| 1345 | " function renderProcs(){\n" |
| 1346 | " if (!DATA) return;\n" |
| 1347 | " var filter = ($('q').value || '').toLowerCase();\n" |
| 1348 | " var body = $('rows');\n" |
| 1349 | " body.innerHTML = '';\n" |
| 1350 | " var shown = 0;\n" |
| 1351 | " for (var i = 0; i < DATA.processes.length; i++){\n" |
| 1352 | " var p = DATA.processes[i];\n" |
| 1353 | " var hay = (p.name + ' ' + p.pid).toLowerCase();\n" |
| 1354 | " if (filter && hay.indexOf(filter) < 0) continue;\n" |
| 1355 | " var tr = el('tr');\n" |
| 1356 | " tr.appendChild(el('td','num', p.pid));\n" |
| 1357 | " tr.appendChild(el('td','nm', p.name || '\\u2014'));\n" |
| 1358 | " tr.appendChild(el('td','num', p.cpu.toFixed(1)));\n" |
| 1359 | " tr.appendChild(el('td','num', kb(p.rss_kb)));\n" |
| 1360 | " var td = el('td','hide-sm', p.state || '\\u2014');\n" |
| 1361 | " tr.appendChild(td);\n" |
| 1362 | " body.appendChild(tr);\n" |
| 1363 | " shown++;\n" |
| 1364 | " }\n" |
| 1365 | " if (shown) $('empty').classList.add('hide');\n" |
| 1366 | " else $('empty').classList.remove('hide');\n" |
| 1367 | " }\n" |
| 1368 | "\n" |
| 1369 | " function render(d){\n" |
| 1370 | " DATA = d;\n" |
| 1371 | " txt('pHost', d.host);\n" |
| 1372 | " txt('pPlatform', d.platform);\n" |
| 1373 | " txt('cpuModel', d.cpu_model);\n" |
| 1374 | " txt('kCpu', d.cpu_pct.toFixed(1) + '%');\n" |
| 1375 | " txt('kCores', d.ncores || '\\u2014');\n" |
| 1376 | " txt('kMem', (d.mem.pct).toFixed(0) + '%');\n" |
| 1377 | " txt('kSwap', d.swap.total_kb > 0 ? d.swap.pct.toFixed(0) + '%' : 'none');\n" |
| 1378 | " txt('kLoad', d.load.available ? d.load.load1.toFixed(2) : 'n/a');\n" |
| 1379 | " txt('kUp', dur(d.uptime_sec));\n" |
| 1380 | " txt('kProc', d.proc_count);\n" |
| 1381 | "\n" |
| 1382 | " $('memFill').style.width = Math.max(0, Math.min(100, d.mem.pct)) + '%';\n" |
| 1383 | " txt('memLbl', kb(d.mem.used_kb) + ' / ' + kb(d.mem.total_kb));\n" |
| 1384 | " txt('memDetail', 'free ' + kb(d.mem.free_kb) +\n" |
| 1385 | " (d.mem.cached_kb > 0 ? ' \\u00b7 cached ' + kb(d.mem.cached_kb) : ''));\n" |
| 1386 | " $('swapFill').style.width = d.swap.total_kb > 0\n" |
| 1387 | " ? Math.max(0, Math.min(100, d.swap.pct)) + '%' : '0%';\n" |
| 1388 | " txt('swapLbl', d.swap.total_kb > 0\n" |
| 1389 | " ? kb(d.swap.used_kb) + ' / ' + kb(d.swap.total_kb) : 'no swap');\n" |
| 1390 | "\n" |
| 1391 | " renderSpark(d.cpu_pct);\n" |
| 1392 | " renderCores(d);\n" |
| 1393 | " renderProcs();\n" |
| 1394 | " }\n" |
| 1395 | "\n" |
| 1396 | " function fail(msg){\n" |
| 1397 | " $('pState').textContent = 'error';\n" |
| 1398 | " $('pState').className = 'pill paused';\n" |
| 1399 | " txt('coreNote', msg);\n" |
| 1400 | " }\n" |
| 1401 | "\n" |
| 1402 | " function poll(){\n" |
| 1403 | " if (BUSY) return;\n" |
| 1404 | " BUSY = true;\n" |
| 1405 | " var u = withCtx(base() + '?action=metrics&sort=' + encodeURIComponent(SORT));\n" |
| 1406 | " fetch(u, { headers: hdr(), cache: 'no-store' })\n" |
| 1407 | " .then(function(r){ return r.json(); })\n" |
| 1408 | " .then(function(d){\n" |
| 1409 | " if (!d || d.ok === false){ fail((d && d.message) || 'sample failed'); return; }\n" |
| 1410 | " render(d);\n" |
| 1411 | " })\n" |
| 1412 | " .catch(function(e){ fail('request failed: ' + e); })\n" |
| 1413 | " .then(function(){ BUSY = false; });\n" |
| 1414 | " }\n" |
| 1415 | "\n" |
| 1416 | " function schedule(){\n" |
| 1417 | " if (TIMER) { clearInterval(TIMER); TIMER = null; }\n" |
| 1418 | " var st = $('pState');\n" |
| 1419 | " if (RATE > 0){\n" |
| 1420 | " TIMER = setInterval(poll, RATE);\n" |
| 1421 | " st.textContent = 'live ' + (RATE / 1000) + 's';\n" |
| 1422 | " st.className = 'pill live';\n" |
| 1423 | " } else {\n" |
| 1424 | " st.textContent = 'paused';\n" |
| 1425 | " st.className = 'pill paused';\n" |
| 1426 | " }\n" |
| 1427 | " }\n" |
| 1428 | "\n" |
| 1429 | " Array.prototype.forEach.call(document.querySelectorAll('#segRate button'), function(b){\n" |
| 1430 | " b.addEventListener('click', function(){\n" |
| 1431 | " Array.prototype.forEach.call(document.querySelectorAll('#segRate button'),\n" |
| 1432 | " function(x){ x.classList.remove('on'); });\n" |
| 1433 | " b.classList.add('on');\n" |
| 1434 | " RATE = parseInt(b.getAttribute('data-ms'), 10) || 0;\n" |
| 1435 | " schedule();\n" |
| 1436 | " if (RATE > 0) poll();\n" |
| 1437 | " });\n" |
| 1438 | " });\n" |
| 1439 | "\n" |
| 1440 | " Array.prototype.forEach.call(document.querySelectorAll('#segSort button'), function(b){\n" |
| 1441 | " b.addEventListener('click', function(){\n" |
| 1442 | " Array.prototype.forEach.call(document.querySelectorAll('#segSort button'),\n" |
| 1443 | " function(x){ x.classList.remove('on'); });\n" |
| 1444 | " b.classList.add('on');\n" |
| 1445 | " SORT = b.getAttribute('data-sort') || 'cpu';\n" |
| 1446 | " poll();\n" |
| 1447 | " });\n" |
| 1448 | " });\n" |
| 1449 | "\n" |
| 1450 | " $('q').addEventListener('input', renderProcs);\n" |
| 1451 | " if (document.visibilityState === 'visible') poll();\n" |
| 1452 | " document.addEventListener('visibilitychange', function(){\n" |
| 1453 | " if (document.visibilityState === 'visible') poll();\n" |
| 1454 | " });\n" |
| 1455 | " schedule();\n" |
| 1456 | "})();\n" |
| 1457 | "</script></div></body></html>\n", stdout); |
| 1458 | |
| 1459 | return 0; |
| 1460 | } |
| 1461 | |
| 1462 | /* ------------------------------------------------------------------ */ |
| 1463 | /* Entry point */ |
| 1464 | /* ------------------------------------------------------------------ */ |
| 1465 | |
| 1466 | int main(int argc, char **argv) |
| 1467 | { |
| 1468 | const char *qs; |
| 1469 | const char *method; |
| 1470 | int i; |
| 1471 | |
| 1472 | for (i = 1; i < argc; i++) { |
| 1473 | if (strcmp(argv[i], "--meta") == 0) |
| 1474 | return mode_meta(); |
| 1475 | if (strcmp(argv[i], "--version") == 0) { |
| 1476 | printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); |
| 1477 | return 0; |
| 1478 | } |
| 1479 | if (strcmp(argv[i], "--help") == 0) { |
| 1480 | printf("usage: %s [--meta] [--version] [--help]\n" |
| 1481 | " CGI mode reads QUERY_STRING:\n" |
| 1482 | " ?format=json | ?action=metrics JSON system snapshot\n" |
| 1483 | " ?action=info plugin info\n" |
| 1484 | " (no action) HTML dashboard\n", PLUGIN_ID); |
| 1485 | return 0; |
| 1486 | } |
| 1487 | } |
| 1488 | |
| 1489 | if (getenv("SX_PLUGIN_META")) |
| 1490 | return mode_meta(); |
| 1491 | |
| 1492 | require_node_auth(); |
| 1493 | |
| 1494 | qs = getenv("QUERY_STRING"); |
| 1495 | if (!qs) qs = ""; |
| 1496 | method = getenv("REQUEST_METHOD"); |
| 1497 | if (!method) method = "GET"; |
| 1498 | |
| 1499 | if (strstr(qs, "action=") || strstr(qs, "format=json")) |
| 1500 | return mode_json(qs); |
| 1501 | |
| 1502 | { |
| 1503 | char embedv[16]; |
| 1504 | embedv[0] = '\0'; |
| 1505 | if (get_query_val(qs, "embed", embedv, sizeof(embedv))) |
| 1506 | return mode_html(strcmp(embedv, "1") == 0 || strcmp(embedv, "true") == 0); |
| 1507 | } |
| 1508 | return mode_html(0); |
| 1509 | } |