| 1 | 1 | new file mode 100644 |
| index 0000000..1009830 | ||
| --- /dev/null | ||
| +++ b/Makefile | ||
| @@ -0,0 +1,55 @@ | ||
| 1 | +# plugin_sysmon - ScorpioX Bot open-source local system monitor plugin | |
| 2 | +# | |
| 3 | +# Targets: | |
| 4 | +# make native build -> ./plugin_sysmon | |
| 5 | +# make musl static musl x86_64 -> ./plugin_sysmon (fully static) | |
| 6 | +# make win64 MinGW-w64 static -> ./plugin_sysmon.exe | |
| 7 | +# make macos Apple clang -> ./plugin_sysmon (run on macOS) | |
| 8 | +# make test build + run tests/run.sh | |
| 9 | +# make clean | |
| 10 | + | |
| 11 | +CC ?= cc | |
| 12 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings | |
| 13 | +MUSL_CC ?= musl-gcc | |
| 14 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | |
| 15 | +WIN_CC ?= x86_64-w64-mingw32-gcc | |
| 16 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | |
| 17 | +WIN_LIBS := -lpsapi | |
| 18 | +SRC := src/plugin_sysmon.c | |
| 19 | +BIN := plugin_sysmon | |
| 20 | +EXE := plugin_sysmon.exe | |
| 21 | + | |
| 22 | +.PHONY: all native musl win64 macos test clean help | |
| 23 | + | |
| 24 | +all: native | |
| 25 | + | |
| 26 | +native: $(BIN) | |
| 27 | + | |
| 28 | +$(BIN): $(SRC) | |
| 29 | + @echo "==> native build ($(CC))" | |
| 30 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | |
| 31 | + | |
| 32 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | |
| 33 | +musl: $(SRC) | |
| 34 | + @echo "==> static musl build ($(MUSL_CC))" | |
| 35 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN) $(SRC) | |
| 36 | + | |
| 37 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | |
| 38 | +win64: $(SRC) | |
| 39 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | |
| 40 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) $(WIN_LIBS) | |
| 41 | + | |
| 42 | +# Apple clang build (run this on macOS) | |
| 43 | +macos: $(SRC) | |
| 44 | + @echo "==> Apple clang build" | |
| 45 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | |
| 46 | + | |
| 47 | +test: native | |
| 48 | + @sh tests/run.sh | |
| 49 | + | |
| 50 | +clean: | |
| 51 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).macos-arm64 $(BIN).macos-x86_64 | |
| 52 | + rm -rf bin | |
| 53 | + | |
| 54 | +help: | |
| 55 | + @echo "make | make musl | make win64 | make macos | make test | make clean" |
| 1 | 1 | new file mode 100755 |
| index 0000000..2c5d05d |
| 1 | 1 | new file mode 100644 |
| index 0000000..bc31c6a | ||
| --- /dev/null | ||
| +++ b/src/plugin_sysmon.c | ||
| @@ -0,0 +1,1515 @@ | ||
| 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(_WIN32) | |
| 22 | +# define _POSIX_C_SOURCE 200809L | |
| 23 | +# define _DEFAULT_SOURCE 1 | |
| 24 | +#endif | |
| 25 | + | |
| 26 | +#include <stdio.h> | |
| 27 | +#include <stdlib.h> | |
| 28 | +#include <string.h> | |
| 29 | +#include <time.h> | |
| 30 | +#include <ctype.h> | |
| 31 | +#include <errno.h> | |
| 32 | + | |
| 33 | +#if defined(_WIN32) | |
| 34 | + | |
| 35 | +# define WIN32_LEAN_AND_MEAN | |
| 36 | +# include <windows.h> | |
| 37 | +# include <psapi.h> | |
| 38 | +# include <tlhelp32.h> | |
| 39 | +# include <io.h> | |
| 40 | + | |
| 41 | +#else | |
| 42 | + | |
| 43 | +# include <unistd.h> | |
| 44 | +# include <dirent.h> | |
| 45 | +# include <sys/types.h> | |
| 46 | + | |
| 47 | +#endif | |
| 48 | + | |
| 49 | +#if defined(__APPLE__) | |
| 50 | +# include <mach/mach.h> | |
| 51 | +# include <mach/mach_host.h> | |
| 52 | +# include <sys/sysctl.h> | |
| 53 | +# include <sys/time.h> | |
| 54 | +#endif | |
| 55 | + | |
| 56 | +#define PLUGIN_SLUG "sysmon" | |
| 57 | +#define PLUGIN_ID "plugin_sysmon" | |
| 58 | +#define PLUGIN_VER "1.0.0" | |
| 59 | + | |
| 60 | +#define MAX_CORES 256 | |
| 61 | +#define MAX_PROCS 4096 | |
| 62 | +#define TOP_DEFAULT 25 | |
| 63 | +#define SAMPLE_MS 80 | |
| 64 | + | |
| 65 | +/* ------------------------------------------------------------------ */ | |
| 66 | +/* Small utilities */ | |
| 67 | +/* ------------------------------------------------------------------ */ | |
| 68 | + | |
| 69 | +/* Percent-decode in place ('+' becomes space). */ | |
| 70 | +static void url_decode(char *s) | |
| 71 | +{ | |
| 72 | + char *o = s; | |
| 73 | + if (!s) return; | |
| 74 | + while (*s) { | |
| 75 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | |
| 76 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | |
| 77 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | |
| 78 | + *o++ = (char)((hi << 4) | lo); | |
| 79 | + s += 3; | |
| 80 | + } else if (*s == '+') { | |
| 81 | + *o++ = ' '; | |
| 82 | + s++; | |
| 83 | + } else { | |
| 84 | + *o++ = *s++; | |
| 85 | + } | |
| 86 | + } | |
| 87 | + *o = '\0'; | |
| 88 | +} | |
| 89 | + | |
| 90 | +/* Read one parameter (decoded) out of a form/query string. */ | |
| 91 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | |
| 92 | +{ | |
| 93 | + size_t klen; | |
| 94 | + const char *p; | |
| 95 | + | |
| 96 | + if (!out || outsz == 0) return 0; | |
| 97 | + out[0] = '\0'; | |
| 98 | + if (!qs || !key) return 0; | |
| 99 | + klen = strlen(key); | |
| 100 | + | |
| 101 | + for (p = qs; *p; ) { | |
| 102 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | |
| 103 | + const char *v = p + klen + 1; | |
| 104 | + size_t i = 0; | |
| 105 | + while (*v && *v != '&' && i + 1 < outsz) | |
| 106 | + out[i++] = *v++; | |
| 107 | + out[i] = '\0'; | |
| 108 | + url_decode(out); | |
| 109 | + return 1; | |
| 110 | + } | |
| 111 | + p = strchr(p, '&'); | |
| 112 | + if (!p) break; | |
| 113 | + p++; | |
| 114 | + } | |
| 115 | + return 0; | |
| 116 | +} | |
| 117 | + | |
| 118 | +static void json_str(const char *s) | |
| 119 | +{ | |
| 120 | + putchar('"'); | |
| 121 | + for (; s && *s; s++) { | |
| 122 | + unsigned char c = (unsigned char)*s; | |
| 123 | + switch (c) { | |
| 124 | + case '"': fputs("\\\"", stdout); break; | |
| 125 | + case '\\': fputs("\\\\", stdout); break; | |
| 126 | + case '\n': fputs("\\n", stdout); break; | |
| 127 | + case '\r': fputs("\\r", stdout); break; | |
| 128 | + case '\t': fputs("\\t", stdout); break; | |
| 129 | + default: | |
| 130 | + if (c < 0x20) printf("\\u%04x", (unsigned)c); | |
| 131 | + else putchar((int)c); | |
| 132 | + } | |
| 133 | + } | |
| 134 | + putchar('"'); | |
| 135 | +} | |
| 136 | + | |
| 137 | +static void utc_now(char *buf, size_t sz) | |
| 138 | +{ | |
| 139 | + time_t t = time(NULL); | |
| 140 | + struct tm tmv; | |
| 141 | +#if defined(_WIN32) | |
| 142 | + gmtime_s(&tmv, &t); | |
| 143 | +#else | |
| 144 | + gmtime_r(&t, &tmv); | |
| 145 | +#endif | |
| 146 | + if (strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv) == 0) { | |
| 147 | + strncpy(buf, "1970-01-01T00:00:00Z", sz - 1); | |
| 148 | + buf[sz - 1] = '\0'; | |
| 149 | + } | |
| 150 | +} | |
| 151 | + | |
| 152 | +static long node_pid(void) | |
| 153 | +{ | |
| 154 | +#if defined(_WIN32) | |
| 155 | + return (long)GetCurrentProcessId(); | |
| 156 | +#else | |
| 157 | + return (long)getpid(); | |
| 158 | +#endif | |
| 159 | +} | |
| 160 | + | |
| 161 | +static void sx_sleep_ms(int ms) | |
| 162 | +{ | |
| 163 | +#if defined(_WIN32) | |
| 164 | + Sleep((DWORD)ms); | |
| 165 | +#else | |
| 166 | + struct timespec ts; | |
| 167 | + ts.tv_sec = ms / 1000; | |
| 168 | + ts.tv_nsec = (long)(ms % 1000) * 1000000L; | |
| 169 | + nanosleep(&ts, NULL); | |
| 170 | +#endif | |
| 171 | +} | |
| 172 | + | |
| 173 | +static double clamp_pct(double v) | |
| 174 | +{ | |
| 175 | + if (v < 0.0) return 0.0; | |
| 176 | + if (v > 100.0) return 100.0; | |
| 177 | + return v; | |
| 178 | +} | |
| 179 | + | |
| 180 | +/* ------------------------------------------------------------------ */ | |
| 181 | +/* Node authentication */ | |
| 182 | +/* ------------------------------------------------------------------ */ | |
| 183 | + | |
| 184 | +/* | |
| 185 | + * The node API on :8150 is reachable from the LAN. Every request except | |
| 186 | + * --meta discovery must prove it knows the node password. Accepted forms | |
| 187 | + * match the rest of the node API: X-Bot-Password (what bot-web proxies | |
| 188 | + * with), Authorization: Bearer, and ?pwd= (what the plugin iframe appends). | |
| 189 | + * When BOT_PASSWORD is unset the plugin is a deliberate no-op, which is how | |
| 190 | + * a developer runs it locally from a shell. | |
| 191 | + */ | |
| 192 | +static void require_node_auth(void) | |
| 193 | +{ | |
| 194 | + const char *np = getenv("BOT_PASSWORD"); | |
| 195 | + const char *xp; | |
| 196 | + const char *auth; | |
| 197 | + char qpwd[256]; | |
| 198 | + const char *qs; | |
| 199 | + | |
| 200 | + if (!np || !*np) return; | |
| 201 | + | |
| 202 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | |
| 203 | + if (xp && strcmp(xp, np) == 0) return; | |
| 204 | + | |
| 205 | + auth = getenv("HTTP_AUTHORIZATION"); | |
| 206 | + if (auth) { | |
| 207 | + while (*auth == ' ') auth++; | |
| 208 | + if (strncmp(auth, "Bearer ", 7) == 0) { | |
| 209 | + auth += 7; | |
| 210 | + while (*auth == ' ') auth++; | |
| 211 | + if (strcmp(auth, np) == 0) return; | |
| 212 | + } | |
| 213 | + } | |
| 214 | + | |
| 215 | + qs = getenv("QUERY_STRING"); | |
| 216 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) | |
| 217 | + return; | |
| 218 | + | |
| 219 | + fputs("Status: 401 Unauthorized\r\n" | |
| 220 | + "Content-Type: application/json; charset=utf-8\r\n" | |
| 221 | + "Cache-Control: no-store\r\n" | |
| 222 | + "X-Content-Type-Options: nosniff\r\n\r\n" | |
| 223 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | |
| 224 | + exit(0); | |
| 225 | +} | |
| 226 | + | |
| 227 | +/* ------------------------------------------------------------------ */ | |
| 228 | +/* Collected snapshot */ | |
| 229 | +/* ------------------------------------------------------------------ */ | |
| 230 | + | |
| 231 | +typedef struct { | |
| 232 | + int core; | |
| 233 | + double pct; | |
| 234 | +} core_t; | |
| 235 | + | |
| 236 | +typedef struct { | |
| 237 | + long pid; | |
| 238 | + char name[64]; | |
| 239 | + double cpu; /* percent of one core */ | |
| 240 | + long rss_kb; | |
| 241 | + char state; | |
| 242 | +} proc_t; | |
| 243 | + | |
| 244 | +typedef struct { | |
| 245 | + int ok; | |
| 246 | + char platform[16]; /* linux | macos | windows */ | |
| 247 | + char host[128]; | |
| 248 | + | |
| 249 | + double cpu_pct; | |
| 250 | + core_t cores[MAX_CORES]; | |
| 251 | + int ncores; | |
| 252 | + char cpu_model[128]; | |
| 253 | + | |
| 254 | + double mem_total_kb; | |
| 255 | + double mem_used_kb; | |
| 256 | + double mem_free_kb; | |
| 257 | + double mem_cached_kb; | |
| 258 | + | |
| 259 | + double swap_total_kb; | |
| 260 | + double swap_used_kb; | |
| 261 | + | |
| 262 | + double uptime_sec; | |
| 263 | + double load1, load5, load15; | |
| 264 | + int load_available; | |
| 265 | + | |
| 266 | + proc_t procs[MAX_PROCS]; | |
| 267 | + int nprocs; | |
| 268 | +} sys_t; | |
| 269 | + | |
| 270 | +/* ------------------------------------------------------------------ */ | |
| 271 | +/* Linux sampling */ | |
| 272 | +/* ------------------------------------------------------------------ */ | |
| 273 | + | |
| 274 | +#if !defined(_WIN32) && !defined(__APPLE__) | |
| 275 | + | |
| 276 | +typedef struct { | |
| 277 | + unsigned long long user, nice, system, idle, iowait, irq, softirq, steal; | |
| 278 | +} cpu_raw_t; | |
| 279 | + | |
| 280 | +/* | |
| 281 | + * /proc/stat reports st_size == 0, so seeking to the end and measuring is | |
| 282 | + * meaningless. Always stream with fgets until EOF. | |
| 283 | + */ | |
| 284 | +static int read_proc_stat(cpu_raw_t *agg, cpu_raw_t *cores, int maxcores) | |
| 285 | +{ | |
| 286 | + FILE *fp; | |
| 287 | + char line[512]; | |
| 288 | + int n = 0; | |
| 289 | + | |
| 290 | + fp = fopen("/proc/stat", "r"); | |
| 291 | + if (!fp) return -1; | |
| 292 | + | |
| 293 | + memset(agg, 0, sizeof(*agg)); | |
| 294 | + while (fgets(line, sizeof(line), fp)) { | |
| 295 | + if (strncmp(line, "cpu", 3) != 0) break; | |
| 296 | + if (line[3] == ' ') { | |
| 297 | + (void)sscanf(line + 4, "%llu %llu %llu %llu %llu %llu %llu %llu", | |
| 298 | + &agg->user, &agg->nice, &agg->system, &agg->idle, | |
| 299 | + &agg->iowait, &agg->irq, &agg->softirq, &agg->steal); | |
| 300 | + continue; | |
| 301 | + } | |
| 302 | + if (isdigit((unsigned char)line[3])) { | |
| 303 | + cpu_raw_t r; | |
| 304 | + int idx = 0; | |
| 305 | + memset(&r, 0, sizeof(r)); | |
| 306 | + if (sscanf(line + 3, "%d %llu %llu %llu %llu %llu %llu %llu %llu", | |
| 307 | + &idx, &r.user, &r.nice, &r.system, &r.idle, | |
| 308 | + &r.iowait, &r.irq, &r.softirq, &r.steal) >= 5) { | |
| 309 | + if (n < maxcores) cores[n] = r; | |
| 310 | + n++; | |
| 311 | + } | |
| 312 | + } | |
| 313 | + } | |
| 314 | + fclose(fp); | |
| 315 | + return n; | |
| 316 | +} | |
| 317 | + | |
| 318 | +static double cpu_busy_pct(const cpu_raw_t *a, const cpu_raw_t *b) | |
| 319 | +{ | |
| 320 | + unsigned long long ta = a->user + a->nice + a->system + a->idle + a->iowait | |
| 321 | + + a->irq + a->softirq + a->steal; | |
| 322 | + unsigned long long tb = b->user + b->nice + b->system + b->idle + b->iowait | |
| 323 | + + b->irq + b->softirq + b->steal; | |
| 324 | + unsigned long long ba = a->user + a->nice + a->system + a->irq + a->softirq + a->steal; | |
| 325 | + unsigned long long bb = b->user + b->nice + b->system + b->irq + b->softirq + b->steal; | |
| 326 | + unsigned long long dt, db; | |
| 327 | + | |
| 328 | + if (tb <= ta) return 0.0; | |
| 329 | + dt = tb - ta; | |
| 330 | + db = bb >= ba ? bb - ba : 0; | |
| 331 | + return clamp_pct(100.0 * (double)db / (double)dt); | |
| 332 | +} | |
| 333 | + | |
| 334 | +static void read_meminfo(sys_t *s) | |
| 335 | +{ | |
| 336 | + FILE *fp; | |
| 337 | + char line[256]; | |
| 338 | + | |
| 339 | + s->mem_total_kb = s->mem_free_kb = s->mem_cached_kb = 0.0; | |
| 340 | + s->swap_total_kb = s->swap_used_kb = 0.0; | |
| 341 | + | |
| 342 | + fp = fopen("/proc/meminfo", "r"); | |
| 343 | + if (!fp) return; | |
| 344 | + | |
| 345 | + { | |
| 346 | + unsigned long long total = 0, free_kb = 0, avail = 0, cached = 0, sreclaim = 0; | |
| 347 | + unsigned long long swap_total = 0, swap_free = 0; | |
| 348 | + | |
| 349 | + while (fgets(line, sizeof(line), fp)) { | |
| 350 | + unsigned long long v = 0; | |
| 351 | + if (sscanf(line, "MemTotal: %llu kB", &v) == 1) total = v; | |
| 352 | + else if (sscanf(line, "MemFree: %llu kB", &v) == 1) free_kb = v; | |
| 353 | + else if (sscanf(line, "MemAvailable: %llu kB", &v) == 1) avail = v; | |
| 354 | + else if (sscanf(line, "Cached: %llu kB", &v) == 1) cached = v; | |
| 355 | + else if (sscanf(line, "SReclaimable: %llu kB", &v) == 1) sreclaim = v; | |
| 356 | + else if (sscanf(line, "SwapTotal: %llu kB", &v) == 1) swap_total = v; | |
| 357 | + else if (sscanf(line, "SwapFree: %llu kB", &v) == 1) swap_free = v; | |
| 358 | + } | |
| 359 | + fclose(fp); | |
| 360 | + | |
| 361 | + s->mem_total_kb = (double)total; | |
| 362 | + s->mem_free_kb = (double)(avail ? avail : free_kb); | |
| 363 | + s->mem_cached_kb = (double)(cached + sreclaim); | |
| 364 | + s->mem_used_kb = (double)total - s->mem_free_kb; | |
| 365 | + if (s->mem_used_kb < 0.0) s->mem_used_kb = 0.0; | |
| 366 | + s->swap_total_kb = (double)swap_total; | |
| 367 | + s->swap_used_kb = (double)(swap_total > swap_free ? swap_total - swap_free : 0); | |
| 368 | + } | |
| 369 | +} | |
| 370 | + | |
| 371 | +static void read_uptime(sys_t *s) | |
| 372 | +{ | |
| 373 | + FILE *fp = fopen("/proc/uptime", "r"); | |
| 374 | + double up = 0.0; | |
| 375 | + if (fp) { | |
| 376 | + if (fscanf(fp, "%lf", &up) != 1) up = 0.0; | |
| 377 | + fclose(fp); | |
| 378 | + } | |
| 379 | + s->uptime_sec = up; | |
| 380 | +} | |
| 381 | + | |
| 382 | +static void read_load(sys_t *s) | |
| 383 | +{ | |
| 384 | + FILE *fp = fopen("/proc/loadavg", "r"); | |
| 385 | + if (fp) { | |
| 386 | + if (fscanf(fp, "%lf %lf %lf", &s->load1, &s->load5, &s->load15) == 3) | |
| 387 | + s->load_available = 1; | |
| 388 | + fclose(fp); | |
| 389 | + } | |
| 390 | +} | |
| 391 | + | |
| 392 | +static void read_cpu_model(sys_t *s) | |
| 393 | +{ | |
| 394 | + FILE *fp = fopen("/proc/cpuinfo", "r"); | |
| 395 | + char line[512]; | |
| 396 | + s->cpu_model[0] = '\0'; | |
| 397 | + if (!fp) return; | |
| 398 | + while (fgets(line, sizeof(line), fp)) { | |
| 399 | + char *colon; | |
| 400 | + if (!(strncmp(line, "model name", 10) == 0 || strncmp(line, "Model", 5) == 0)) | |
| 401 | + continue; | |
| 402 | + colon = strchr(line, ':'); | |
| 403 | + if (!colon) continue; | |
| 404 | + colon++; | |
| 405 | + while (*colon == ' ' || *colon == '\t') colon++; | |
| 406 | + { | |
| 407 | + size_t i = 0; | |
| 408 | + while (*colon && *colon != '\n' && i + 1 < sizeof(s->cpu_model)) | |
| 409 | + s->cpu_model[i++] = *colon++; | |
| 410 | + s->cpu_model[i] = '\0'; | |
| 411 | + while (i > 0 && (s->cpu_model[i - 1] == ' ' || s->cpu_model[i - 1] == '\t')) | |
| 412 | + s->cpu_model[--i] = '\0'; | |
| 413 | + } | |
| 414 | + break; | |
| 415 | + } | |
| 416 | + fclose(fp); | |
| 417 | +} | |
| 418 | + | |
| 419 | +static void read_hostname(sys_t *s) | |
| 420 | +{ | |
| 421 | + if (gethostname(s->host, sizeof(s->host)) != 0) | |
| 422 | + s->host[0] = '\0'; | |
| 423 | + s->host[sizeof(s->host) - 1] = '\0'; | |
| 424 | +} | |
| 425 | + | |
| 426 | +/* One process: utime+stime ticks, rss pages, state char. */ | |
| 427 | +static int read_pid_stat(const char *pid, unsigned long long *ticks, long *rss_pages, char *state) | |
| 428 | +{ | |
| 429 | + char path[64]; | |
| 430 | + char buf[4096]; | |
| 431 | + FILE *fp; | |
| 432 | + size_t got; | |
| 433 | + char *p; | |
| 434 | + int field; | |
| 435 | + unsigned long long utime = 0, stime = 0; | |
| 436 | + long rss = 0; | |
| 437 | + | |
| 438 | + snprintf(path, sizeof(path), "/proc/%s/stat", pid); | |
| 439 | + fp = fopen(path, "r"); | |
| 440 | + if (!fp) return 0; | |
| 441 | + got = fread(buf, 1, sizeof(buf) - 1, fp); | |
| 442 | + fclose(fp); | |
| 443 | + buf[got] = '\0'; | |
| 444 | + | |
| 445 | + p = strrchr(buf, ')'); | |
| 446 | + if (!p || !p[1]) return 0; | |
| 447 | + p++; | |
| 448 | + while (*p == ' ') p++; | |
| 449 | + if (state) *state = *p; | |
| 450 | + | |
| 451 | + /* fields after comm: state is 3, utime 14, stime 15, rss 24 */ | |
| 452 | + field = 3; | |
| 453 | + while (*p) { | |
| 454 | + char *end; | |
| 455 | + long long v; | |
| 456 | + while (*p == ' ') p++; | |
| 457 | + if (!*p) break; | |
| 458 | + if (field == 3) { | |
| 459 | + /* skip the single-letter state token */ | |
| 460 | + while (*p && *p != ' ') p++; | |
| 461 | + field++; | |
| 462 | + continue; | |
| 463 | + } | |
| 464 | + v = strtoll(p, &end, 10); | |
| 465 | + if (end == p) break; | |
| 466 | + if (field == 14) utime = (unsigned long long)v; | |
| 467 | + else if (field == 15) stime = (unsigned long long)v; | |
| 468 | + else if (field == 24) rss = (long)v; | |
| 469 | + if (field >= 24) break; | |
| 470 | + p = end; | |
| 471 | + field++; | |
| 472 | + } | |
| 473 | + | |
| 474 | + *ticks = utime + stime; | |
| 475 | + *rss_pages = rss; | |
| 476 | + return 1; | |
| 477 | +} | |
| 478 | + | |
| 479 | +static void read_pid_name(const char *pid, char *out, size_t outsz) | |
| 480 | +{ | |
| 481 | + char path[64]; | |
| 482 | + FILE *fp; | |
| 483 | + size_t n; | |
| 484 | + | |
| 485 | + out[0] = '\0'; | |
| 486 | + snprintf(path, sizeof(path), "/proc/%s/comm", pid); | |
| 487 | + fp = fopen(path, "r"); | |
| 488 | + if (!fp) return; | |
| 489 | + n = fread(out, 1, outsz - 1, fp); | |
| 490 | + fclose(fp); | |
| 491 | + out[n] = '\0'; | |
| 492 | + while (n > 0 && (out[n - 1] == '\n' || out[n - 1] == '\r')) | |
| 493 | + out[--n] = '\0'; | |
| 494 | +} | |
| 495 | + | |
| 496 | +/* | |
| 497 | + * Two-pass scan of /proc. The second pass is what produces a live CPU | |
| 498 | + * percentage, because /proc/<pid>/stat only exposes cumulative ticks. | |
| 499 | + */ | |
| 500 | +typedef struct { | |
| 501 | + long pid; | |
| 502 | + unsigned long long ticks; | |
| 503 | + long rss_pages; | |
| 504 | + char state; | |
| 505 | +} psnap_t; | |
| 506 | + | |
| 507 | +static int scan_procs_linux(psnap_t *out, int max) | |
| 508 | +{ | |
| 509 | + DIR *d; | |
| 510 | + struct dirent *e; | |
| 511 | + int n = 0; | |
| 512 | + | |
| 513 | + d = opendir("/proc"); | |
| 514 | + if (!d) return 0; | |
| 515 | + | |
| 516 | + while ((e = readdir(d)) != NULL) { | |
| 517 | + if (!isdigit((unsigned char)e->d_name[0])) continue; | |
| 518 | + if (n >= max) break; | |
| 519 | + if (!read_pid_stat(e->d_name, &out[n].ticks, &out[n].rss_pages, &out[n].state)) | |
| 520 | + continue; | |
| 521 | + out[n].pid = (long)strtol(e->d_name, NULL, 10); | |
| 522 | + n++; | |
| 523 | + } | |
| 524 | + closedir(d); | |
| 525 | + return n; | |
| 526 | +} | |
| 527 | + | |
| 528 | +static void sample_linux(sys_t *s) | |
| 529 | +{ | |
| 530 | + static psnap_t snap0[MAX_PROCS], snap1[MAX_PROCS]; | |
| 531 | + cpu_raw_t agg0, agg1; | |
| 532 | + cpu_raw_t c0[MAX_CORES], c1[MAX_CORES]; | |
| 533 | + int n0, n1, p0, p1, i, j, k; | |
| 534 | + long hz = sysconf(_SC_CLK_TCK); | |
| 535 | + long page_kb = (long)(sysconf(_SC_PAGESIZE) / 1024); | |
| 536 | + double window = (double)SAMPLE_MS / 1000.0; | |
| 537 | + | |
| 538 | + strcpy(s->platform, "linux"); | |
| 539 | + read_hostname(s); | |
| 540 | + read_cpu_model(s); | |
| 541 | + | |
| 542 | + memset(c0, 0, sizeof(c0)); | |
| 543 | + memset(c1, 0, sizeof(c1)); | |
| 544 | + | |
| 545 | + n0 = read_proc_stat(&agg0, c0, MAX_CORES); | |
| 546 | + p0 = scan_procs_linux(snap0, MAX_PROCS); | |
| 547 | + | |
| 548 | + sx_sleep_ms(SAMPLE_MS); | |
| 549 | + | |
| 550 | + n1 = read_proc_stat(&agg1, c1, MAX_CORES); | |
| 551 | + p1 = scan_procs_linux(snap1, MAX_PROCS); | |
| 552 | + | |
| 553 | + if (hz <= 0) hz = 100; | |
| 554 | + | |
| 555 | + if (n0 > 0 && n1 > 0) { | |
| 556 | + s->cpu_pct = cpu_busy_pct(&agg0, &agg1); | |
| 557 | + s->ncores = n1 < MAX_CORES ? n1 : MAX_CORES; | |
| 558 | + for (i = 0; i < s->ncores; i++) { | |
| 559 | + s->cores[i].core = i; | |
| 560 | + s->cores[i].pct = cpu_busy_pct(&c0[i], &c1[i]); | |
| 561 | + } | |
| 562 | + } | |
| 563 | + | |
| 564 | + /* Processes: RSS is instantaneous, CPU needs a delta over the window. */ | |
| 565 | + s->nprocs = 0; | |
| 566 | + for (j = 0; j < p1 && s->nprocs < MAX_PROCS; j++) { | |
| 567 | + char name[64]; | |
| 568 | + unsigned long long dt = 0; | |
| 569 | + char pidbuf[24]; | |
| 570 | + | |
| 571 | + for (k = 0; k < p0; k++) { | |
| 572 | + if (snap0[k].pid == snap1[j].pid) { | |
| 573 | + dt = snap1[j].ticks > snap0[k].ticks | |
| 574 | + ? snap1[j].ticks - snap0[k].ticks : 0; | |
| 575 | + break; | |
| 576 | + } | |
| 577 | + } | |
| 578 | + | |
| 579 | + snprintf(pidbuf, sizeof(pidbuf), "%ld", snap1[j].pid); | |
| 580 | + read_pid_name(pidbuf, name, sizeof(name)); | |
| 581 | + | |
| 582 | + s->procs[s->nprocs].pid = snap1[j].pid; | |
| 583 | + s->procs[s->nprocs].cpu = clamp_pct(100.0 * (double)dt / ((double)hz * window)); | |
| 584 | + s->procs[s->nprocs].rss_kb = snap1[j].rss_pages * page_kb; | |
| 585 | + s->procs[s->nprocs].state = snap1[j].state; | |
| 586 | + memcpy(s->procs[s->nprocs].name, name, sizeof(name)); | |
| 587 | + s->nprocs++; | |
| 588 | + } | |
| 589 | + | |
| 590 | + read_meminfo(s); | |
| 591 | + read_uptime(s); | |
| 592 | + read_load(s); | |
| 593 | + | |
| 594 | + s->ok = (s->ncores > 0); | |
| 595 | +} | |
| 596 | + | |
| 597 | +#endif /* linux */ | |
| 598 | + | |
| 599 | +/* ------------------------------------------------------------------ */ | |
| 600 | +/* macOS sampling */ | |
| 601 | +/* ------------------------------------------------------------------ */ | |
| 602 | + | |
| 603 | +#if defined(__APPLE__) | |
| 604 | + | |
| 605 | +static void sample_macos(sys_t *s) | |
| 606 | +{ | |
| 607 | + size_t sz; | |
| 608 | + char bbuf[256]; | |
| 609 | + unsigned int ncpu = 0; | |
| 610 | + uint64_t total_mem = 0; | |
| 611 | + struct timeval boot; | |
| 612 | + vm_statistics64_data_t vm; | |
| 613 | + mach_msg_type_number_t vmcount = HOST_VM_INFO64_COUNT; | |
| 614 | + integer_t *cpu0 = NULL, *cpu1 = NULL; | |
| 615 | + natural_t ncpu0 = 0, ncpu1 = 0; | |
| 616 | + unsigned long long page_kb; | |
| 617 | + unsigned long long tick_hz = 1000ULL; /* we time the window ourselves */ | |
| 618 | + double window; | |
| 619 | + | |
| 620 | + strcpy(s->platform, "macos"); | |
| 621 | + | |
| 622 | + sz = sizeof(bbuf); | |
| 623 | + if (sysctlbyname("kern.hostname", bbuf, &sz, NULL, 0) == 0) | |
| 624 | + snprintf(s->host, sizeof(s->host), "%s", bbuf); | |
| 625 | + else | |
| 626 | + s->host[0] = '\0'; | |
| 627 | + | |
| 628 | + s->cpu_model[0] = '\0'; | |
| 629 | + sz = sizeof(bbuf); | |
| 630 | + if (sysctlbyname("machdep.cpu.brand_string", bbuf, &sz, NULL, 0) == 0) | |
| 631 | + snprintf(s->cpu_model, sizeof(s->cpu_model), "%s", bbuf); | |
| 632 | + | |
| 633 | + sz = sizeof(ncpu); | |
| 634 | + if (sysctlbyname("hw.logicalcpu", &ncpu, &sz, NULL, 0) != 0 || | |
| 635 | + sysctlbyname("hw.ncpu", &ncpu, &sz, NULL, 0) != 0) | |
| 636 | + ncpu = 1; | |
| 637 | + | |
| 638 | + /* aggregate + per-core tick capture, twice */ | |
| 639 | + { | |
| 640 | + natural_t c0 = 0, c1 = 0; | |
| 641 | + if (host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, | |
| 642 | + &ncpu0, &cpu0, &c0) != KERN_SUCCESS) | |
| 643 | + cpu0 = NULL; | |
| 644 | + | |
| 645 | + sx_sleep_ms(SAMPLE_MS); | |
| 646 | + | |
| 647 | + if (host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, | |
| 648 | + &ncpu1, &cpu1, &c1) != KERN_SUCCESS) | |
| 649 | + cpu1 = NULL; | |
| 650 | + } | |
| 651 | + | |
| 652 | + window = (double)SAMPLE_MS / 1000.0; | |
| 653 | + | |
| 654 | + if (cpu0 && cpu1) { | |
| 655 | + natural_t i; | |
| 656 | + natural_t n = ncpu1 < ncpu0 ? ncpu1 : ncpu0; | |
| 657 | + unsigned long long t_idle = 0, t_total = 0; | |
| 658 | + | |
| 659 | + s->ncores = 0; | |
| 660 | + for (i = 0; i < n && s->ncores < MAX_CORES; i++) { | |
| 661 | + unsigned long long a_idle = (unsigned long long)cpu0[i * CPU_STATE_MAX + CPU_STATE_IDLE]; | |
| 662 | + unsigned long long a_usr = (unsigned long long)cpu0[i * CPU_STATE_MAX + CPU_STATE_USER]; | |
| 663 | + unsigned long long a_sys = (unsigned long long)cpu0[i * CPU_STATE_MAX + CPU_STATE_SYSTEM]; | |
| 664 | + unsigned long long a_nice = (unsigned long long)cpu0[i * CPU_STATE_MAX + CPU_STATE_NICE]; | |
| 665 | + unsigned long long b_idle = (unsigned long long)cpu1[i * CPU_STATE_MAX + CPU_STATE_IDLE]; | |
| 666 | + unsigned long long b_usr = (unsigned long long)cpu1[i * CPU_STATE_MAX + CPU_STATE_USER]; | |
| 667 | + unsigned long long b_sys = (unsigned long long)cpu1[i * CPU_STATE_MAX + CPU_STATE_SYSTEM]; | |
| 668 | + unsigned long long b_nice = (unsigned long long)cpu1[i * CPU_STATE_MAX + CPU_STATE_NICE]; | |
| 669 | + unsigned long long ta = a_idle + a_usr + a_sys + a_nice; | |
| 670 | + unsigned long long tb = b_idle + b_usr + b_sys + b_nice; | |
| 671 | + unsigned long long di = b_idle > a_idle ? b_idle - a_idle : 0; | |
| 672 | + unsigned long long dt = tb > ta ? tb - ta : 0; | |
| 673 | + | |
| 674 | + s->cores[s->ncores].core = (int)i; | |
| 675 | + s->cores[s->ncores].pct = dt ? clamp_pct(100.0 - 100.0 * (double)di / (double)dt) : 0.0; | |
| 676 | + s->ncores++; | |
| 677 | + | |
| 678 | + t_idle += di; | |
| 679 | + t_total += dt; | |
| 680 | + } | |
| 681 | + s->cpu_pct = t_total ? clamp_pct(100.0 - 100.0 * (double)t_idle / (double)t_total) : 0.0; | |
| 682 | + } | |
| 683 | + | |
| 684 | + if (cpu0) { | |
| 685 | + vm_size_t freed = 0; | |
| 686 | + (void)vm_deallocate(mach_task_self(), (vm_address_t)cpu0, | |
| 687 | + (vm_size_t)(ncpu0 * CPU_STATE_MAX * sizeof(integer_t))); | |
| 688 | + } | |
| 689 | + if (cpu1) { | |
| 690 | + vm_size_t freed = 0; | |
| 691 | + (void)vm_deallocate(mach_task_self(), (vm_address_t)cpu1, | |
| 692 | + (vm_size_t)(ncpu1 * CPU_STATE_MAX * sizeof(integer_t))); | |
| 693 | + } | |
| 694 | + | |
| 695 | + sz = sizeof(total_mem); | |
| 696 | + if (sysctlbyname("hw.memsize", &total_mem, &sz, NULL, 0) != 0) | |
| 697 | + total_mem = 0; | |
| 698 | + | |
| 699 | + if (host_statistics64(mach_host_self(), HOST_VM_INFO64, | |
| 700 | + (host_info64_t)&vm, &vmcount) == KERN_SUCCESS) { | |
| 701 | + vm_size_t pagesz = 0; | |
| 702 | + host_page_size(mach_host_self(), &pagesz); | |
| 703 | + page_kb = (unsigned long long)(pagesz / 1024ULL); | |
| 704 | + s->mem_total_kb = (double)(total_mem / 1024ULL); | |
| 705 | + s->mem_free_kb = (double)(((unsigned long long)vm.free_count | |
| 706 | + + (unsigned long long)vm.inactive_count | |
| 707 | + + (unsigned long long)vm.speculative_count) * page_kb); | |
| 708 | + s->mem_cached_kb = (double)((unsigned long long)vm.purgeable_count * page_kb); | |
| 709 | + s->mem_used_kb = (double)(((unsigned long long)(vm.active_count | |
| 710 | + + vm.wire_count) * page_kb)); | |
| 711 | + } | |
| 712 | + | |
| 713 | + { | |
| 714 | + struct xsw_usage xs; | |
| 715 | + sz = sizeof(xs); | |
| 716 | + if (sysctlbyname("vm.swapusage", &xs, &sz, NULL, 0) == 0) { | |
| 717 | + s->swap_total_kb = (double)(xs.xsu_total / 1024ULL); | |
| 718 | + s->swap_used_kb = (double)(xs.xsu_used / 1024ULL); | |
| 719 | + } | |
| 720 | + } | |
| 721 | + | |
| 722 | + sz = sizeof(boot); | |
| 723 | + if (sysctlbyname("kern.boottime", &boot, &sz, NULL, 0) == 0) { | |
| 724 | + time_t now = time(NULL); | |
| 725 | + s->uptime_sec = (double)now - (double)boot.tv_sec; | |
| 726 | + if (s->uptime_sec < 0.0) s->uptime_sec = 0.0; | |
| 727 | + } | |
| 728 | + | |
| 729 | + { | |
| 730 | + double loads[3]; | |
| 731 | + if (getloadavg(loads, 3) == 3) { | |
| 732 | + s->load1 = loads[0]; | |
| 733 | + s->load5 = loads[1]; | |
| 734 | + s->load15 = loads[2]; | |
| 735 | + s->load_available = 1; | |
| 736 | + } | |
| 737 | + } | |
| 738 | + | |
| 739 | + /* Process list: the kernel exposes it most simply through ps. */ | |
| 740 | + { | |
| 741 | + FILE *fp = popen("ps -Ao pid=,pcpu=,rss=,comm=", "r"); | |
| 742 | + if (fp) { | |
| 743 | + char line[600]; | |
| 744 | + s->nprocs = 0; | |
| 745 | + while (fgets(line, sizeof(line), fp) && s->nprocs < MAX_PROCS) { | |
| 746 | + long pid = 0; | |
| 747 | + double pcpu = 0.0; | |
| 748 | + long rss = 0; | |
| 749 | + char comm[256]; | |
| 750 | + if (sscanf(line, "%ld %lf %ld %255[^\n]", &pid, &pcpu, &rss, comm) != 4) | |
| 751 | + continue; | |
| 752 | + s->procs[s->nprocs].pid = pid; | |
| 753 | + s->procs[s->nprocs].cpu = clamp_pct(pcpu); | |
| 754 | + s->procs[s->nprocs].rss_kb = rss; | |
| 755 | + s->procs[s->nprocs].state = 'R'; | |
| 756 | + { | |
| 757 | + const char *base = strrchr(comm, '/'); | |
| 758 | + base = base ? base + 1 : comm; | |
| 759 | + snprintf(s->procs[s->nprocs].name, sizeof(s->procs[s->nprocs].name), | |
| 760 | + "%s", base); | |
| 761 | + } | |
| 762 | + s->nprocs++; | |
| 763 | + } | |
| 764 | + pclose(fp); | |
| 765 | + } | |
| 766 | + } | |
| 767 | + | |
| 768 | + s->ok = (s->ncores > 0 && s->mem_total_kb > 0.0); | |
| 769 | + (void)tick_hz; | |
| 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 | + li.QuadPart = GetTickCount64(); | |
| 860 | + s->uptime_sec = (double)li.QuadPart / 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><style>", stdout); | |
| 1104 | + | |
| 1105 | + fputs( | |
| 1106 | +":root{color-scheme:dark light;" | |
| 1107 | + "--bg:#0b0b0e;--surface:#141419;--surface2:#1c1c22;--text:#f5f5f7;" | |
| 1108 | + "--muted:#8e8e96;--line:rgba(255,255,255,.10);--accent:#0a84ff;" | |
| 1109 | + "--ok:#30d158;--warn:#ffd60a;--danger:#ff453a;" | |
| 1110 | + "--mono:ui-monospace,SFMono-Regular,Menlo,monospace}" | |
| 1111 | +"html[data-theme=light]{--bg:#f2f2f6;--surface:#ffffff;--surface2:#f0f0f4;" | |
| 1112 | + "--text:#1c1c1e;--muted:#6b6b73;--line:rgba(0,0,0,.10)}" | |
| 1113 | +"*{box-sizing:border-box}" | |
| 1114 | +"body{margin:0;padding:16px;background:var(--bg);color:var(--text);" | |
| 1115 | + "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;" | |
| 1116 | + "font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}" | |
| 1117 | +".wrap{max-width:1120px;margin:0 auto}" | |
| 1118 | +".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}" | |
| 1119 | +".title{font-size:20px;font-weight:700;margin:0}" | |
| 1120 | +".sub{color:var(--muted);font-size:12px;font-family:var(--mono)}" | |
| 1121 | +".spacer{flex:1}" | |
| 1122 | +".pill{font-size:11px;font-weight:600;padding:2px 9px;border-radius:999px;" | |
| 1123 | + "background:var(--surface2);color:var(--muted);border:1px solid var(--line);white-space:nowrap}" | |
| 1124 | +".pill.live{color:var(--ok);border-color:rgba(48,209,88,.4)}" | |
| 1125 | +".pill.paused{color:var(--warn);border-color:rgba(255,214,10,.4)}" | |
| 1126 | +".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;" | |
| 1127 | + "padding:16px;margin-bottom:14px}" | |
| 1128 | +".card h2{margin:0 0 12px;font-size:12px;letter-spacing:.06em;text-transform:uppercase;" | |
| 1129 | + "color:var(--muted);font-weight:600}" | |
| 1130 | +".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(132px,1fr));gap:10px}" | |
| 1131 | +".kpi{background:var(--surface2);border:1px solid var(--line);border-radius:10px;padding:10px 12px;min-width:0}" | |
| 1132 | +".kpi .k{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}" | |
| 1133 | +".kpi .v{font-size:20px;font-weight:700;font-family:var(--mono);margin-top:2px;" | |
| 1134 | + "overflow:hidden;text-overflow:ellipsis;white-space:nowrap}" | |
| 1135 | +"button{background:var(--accent);color:#fff;border:0;border-radius:999px;" | |
| 1136 | + "padding:6px 13px;font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}" | |
| 1137 | +"button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}" | |
| 1138 | +"button.on{background:var(--accent);color:#fff;border-color:transparent}" | |
| 1139 | +"button:active{transform:scale(.98)}" | |
| 1140 | +".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}" | |
| 1141 | +".seg{display:inline-flex;gap:4px;background:var(--surface2);border:1px solid var(--line);" | |
| 1142 | + "border-radius:999px;padding:3px}" | |
| 1143 | +".seg button{background:transparent;color:var(--muted);border:0;padding:4px 11px;font-size:12px}" | |
| 1144 | +".seg button.on{background:var(--accent);color:#fff}" | |
| 1145 | +".cores{display:grid;grid-template-columns:repeat(auto-fill,minmax(86px,1fr));gap:8px}" | |
| 1146 | +".core{background:var(--surface2);border:1px solid var(--line);border-radius:9px;padding:7px 8px}" | |
| 1147 | +".core .lbl{font-size:10px;color:var(--muted);font-family:var(--mono)}" | |
| 1148 | +".core .bar{height:6px;border-radius:3px;background:rgba(255,255,255,.10);margin:5px 0 4px;overflow:hidden}" | |
| 1149 | +".core .fill{height:100%;background:var(--ok);border-radius:3px;transition:width .35s}" | |
| 1150 | +".core .pc{font-size:11px;font-family:var(--mono);font-weight:600}" | |
| 1151 | +".gauge{height:10px;border-radius:5px;background:rgba(255,255,255,.10);overflow:hidden;margin:6px 0 4px}" | |
| 1152 | +".gauge .fill{height:100%;border-radius:5px;transition:width .35s;background:var(--accent)}" | |
| 1153 | +".glabel{display:flex;justify-content:space-between;font-size:11px;color:var(--muted);" | |
| 1154 | + "font-family:var(--mono)}" | |
| 1155 | +"svg.spark{display:block;width:100%;height:64px}" | |
| 1156 | +"table{width:100%;border-collapse:collapse;font-size:13px}" | |
| 1157 | +"th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.05em;" | |
| 1158 | + "color:var(--muted);font-weight:600;padding:6px 8px;border-bottom:1px solid var(--line);" | |
| 1159 | + "white-space:nowrap}" | |
| 1160 | +"th.num,td.num{text-align:right;font-family:var(--mono)}" | |
| 1161 | +"td{padding:6px 8px;border-bottom:1px solid var(--line);vertical-align:middle}" | |
| 1162 | +"td.nm{font-family:var(--mono);font-size:12px;word-break:break-all}" | |
| 1163 | +"tr:last-child td{border-bottom:0}" | |
| 1164 | +".tblwrap{overflow-x:auto}" | |
| 1165 | +"input{background:var(--surface2);border:1px solid var(--line);border-radius:10px;" | |
| 1166 | + "padding:7px 11px;color:var(--text);font-size:13px;font-family:var(--mono);" | |
| 1167 | + "min-width:130px;flex:1}" | |
| 1168 | +"input:focus{outline:2px solid var(--accent);outline-offset:-1px}" | |
| 1169 | +".hide{display:none!important}" | |
| 1170 | +".muted{color:var(--muted)}" | |
| 1171 | +"@media(max-width:640px){" | |
| 1172 | + "body{padding:12px}" | |
| 1173 | + ".kpi .v{font-size:17px}" | |
| 1174 | + "th.hide-sm,td.hide-sm{display:none}" | |
| 1175 | + ".card{padding:12px;border-radius:12px}" | |
| 1176 | + ".cores{grid-template-columns:repeat(auto-fill,minmax(72px,1fr))}" | |
| 1177 | +"}", stdout); | |
| 1178 | + | |
| 1179 | + fputs("</style></head><body><div class='wrap'>", stdout); | |
| 1180 | + | |
| 1181 | + if (!embed) { | |
| 1182 | + fputs("<div class='top'><a href='/' style='color:var(--accent);" | |
| 1183 | + "text-decoration:none;font-weight:600'>← Back to Bot</a></div>", stdout); | |
| 1184 | + } | |
| 1185 | + | |
| 1186 | + fputs("<div class='top'>" | |
| 1187 | + "<h1 class='title'>sysmon</h1>" | |
| 1188 | + "<span class='pill' id='pHost'>—</span>" | |
| 1189 | + "<span class='pill' id='pPlatform'>—</span>" | |
| 1190 | + "<span class='spacer'></span>" | |
| 1191 | + "<span class='pill live' id='pState'>live 2s</span>" | |
| 1192 | + "<div class='seg' id='segRate'>" | |
| 1193 | + "<button type='button' data-ms='2000' class='on'>2s</button>" | |
| 1194 | + "<button type='button' data-ms='5000'>5s</button>" | |
| 1195 | + "<button type='button' data-ms='0'>Pause</button>" | |
| 1196 | + "</div></div>", stdout); | |
| 1197 | + | |
| 1198 | + /* KPI row */ | |
| 1199 | + fputs("<div class='card'><h2>System</h2><div class='grid'>" | |
| 1200 | + "<div class='kpi'><div class='k'>cpu</div><div class='v' id='kCpu'>—</div></div>" | |
| 1201 | + "<div class='kpi'><div class='k'>cores</div><div class='v' id='kCores'>—</div></div>" | |
| 1202 | + "<div class='kpi'><div class='k'>memory</div><div class='v' id='kMem'>—</div></div>" | |
| 1203 | + "<div class='kpi'><div class='k'>swap</div><div class='v' id='kSwap'>—</div></div>" | |
| 1204 | + "<div class='kpi'><div class='k'>load 1m</div><div class='v' id='kLoad'>—</div></div>" | |
| 1205 | + "<div class='kpi'><div class='k'>uptime</div><div class='v' id='kUp'>—</div></div>" | |
| 1206 | + "<div class='kpi'><div class='k'>processes</div><div class='v' id='kProc'>—</div></div>" | |
| 1207 | + "</div>" | |
| 1208 | + "<div class='sub' id='cpuModel' style='margin-top:10px'></div></div>", stdout); | |
| 1209 | + | |
| 1210 | + /* history sparkline */ | |
| 1211 | + fputs("<div class='card'><h2>CPU history</h2>" | |
| 1212 | + "<svg class='spark' id='spark' viewBox='0 0 600 64' preserveAspectRatio='none'>" | |
| 1213 | + "<polyline id='sparkLine' fill='none' stroke='#0a84ff' stroke-width='2' " | |
| 1214 | + "stroke-linejoin='round' stroke-linecap='round' points=''/>" | |
| 1215 | + "</svg></div>", stdout); | |
| 1216 | + | |
| 1217 | + /* per-core */ | |
| 1218 | + fputs("<div class='card'><h2>Per-core utilization</h2>" | |
| 1219 | + "<div class='cores' id='cores'></div>" | |
| 1220 | + "<div class='muted' id='coreNote' style='margin-top:10px'></div></div>", stdout); | |
| 1221 | + | |
| 1222 | + /* memory + swap gauges */ | |
| 1223 | + fputs("<div class='card'><h2>Memory & swap</h2>" | |
| 1224 | + "<div class='glabel'><span>memory</span><span id='memLbl'>—</span></div>" | |
| 1225 | + "<div class='gauge'><div class='fill' id='memFill' style='width:0'></div></div>" | |
| 1226 | + "<div class='glabel' style='margin-top:12px'><span>swap</span><span id='swapLbl'>—</span></div>" | |
| 1227 | + "<div class='gauge'><div class='fill' id='swapFill' style='width:0;background:var(--warn)'></div></div>" | |
| 1228 | + "<div class='sub' id='memDetail' style='margin-top:10px'></div></div>", stdout); | |
| 1229 | + | |
| 1230 | + /* processes */ | |
| 1231 | + fputs("<div class='card'><h2>Top processes</h2>" | |
| 1232 | + "<div class='row'>" | |
| 1233 | + "<input id='q' type='text' placeholder='filter by name or pid'>" | |
| 1234 | + "<div class='seg' id='segSort'>" | |
| 1235 | + "<button type='button' data-sort='cpu' class='on'>CPU</button>" | |
| 1236 | + "<button type='button' data-sort='mem'>Memory</button>" | |
| 1237 | + "</div></div>" | |
| 1238 | + "<div class='tblwrap'><table><thead><tr>" | |
| 1239 | + "<th class='num'>PID</th><th>Name</th>" | |
| 1240 | + "<th class='num'>CPU %</th><th class='num'>RSS</th>" | |
| 1241 | + "<th class='hide-sm'>State</th>" | |
| 1242 | + "</tr></thead><tbody id='rows'></tbody></table></div>" | |
| 1243 | + "<div id='empty' class='muted hide'>No matching processes.</div></div>", stdout); | |
| 1244 | + | |
| 1245 | + fputs("<div class='card'><h2>About this plugin</h2>" | |
| 1246 | + "<p class='muted' style='margin:0 0 8px'>Local node only. Reads the kernel's " | |
| 1247 | + "own counters (<code>/proc</code> on Linux, mach and <code>sysctl</code> on macOS, " | |
| 1248 | + "Win32 APIs on Windows) and makes zero outbound network requests.</p>" | |
| 1249 | + "<p class='muted' style='margin:0'>Two CPU samples " | |
| 1250 | + "80 ms apart give a live percentage; nothing is cached between requests " | |
| 1251 | + "and no shell command comes from user input.</p></div>", stdout); | |
| 1252 | + | |
| 1253 | + /* script */ | |
| 1254 | + fputs("<script>\n" | |
| 1255 | +"(function(){\n" | |
| 1256 | +" var q = new URLSearchParams(location.search);\n" | |
| 1257 | +" var HUB = q.get('plugin') || '';\n" | |
| 1258 | +" var node = q.get('node') || '';\n" | |
| 1259 | +" var sid = q.get('id') || '';\n" | |
| 1260 | +" var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n" | |
| 1261 | +" localStorage.getItem('bot_active_pwd') || '';\n" | |
| 1262 | +"\n" | |
| 1263 | +" /* Two routes, and getting this wrong is the classic plugin bug:\n" | |
| 1264 | +" page served through the hub -> call the hub proxy back\n" | |
| 1265 | +" page opened directly on node -> the plugin IS the route */\n" | |
| 1266 | +" function base(){ return HUB ? '/plugins?plugin=' + HUB : '/plugin_sysmon'; }\n" | |
| 1267 | +" function withCtx(u){\n" | |
| 1268 | +" if (node) u += '&node=' + encodeURIComponent(node);\n" | |
| 1269 | +" if (sid) u += '&id=' + encodeURIComponent(sid);\n" | |
| 1270 | +" if (pwd) u += '&pwd=' + encodeURIComponent(pwd);\n" | |
| 1271 | +" return u;\n" | |
| 1272 | +" }\n" | |
| 1273 | +" function hdr(){ return pwd ? {'X-Bot-Password': pwd} : {}; }\n" | |
| 1274 | +" function $(id){ return document.getElementById(id); }\n" | |
| 1275 | +" function el(tag, cls, text){\n" | |
| 1276 | +" var e = document.createElement(tag);\n" | |
| 1277 | +" if (cls) e.className = cls;\n" | |
| 1278 | +" if (text !== undefined && text !== null) e.textContent = String(text);\n" | |
| 1279 | +" return e;\n" | |
| 1280 | +" }\n" | |
| 1281 | +" function txt(id, v){\n" | |
| 1282 | +" var e = $(id); if (!e) return;\n" | |
| 1283 | +" e.textContent = (v === undefined || v === null || v === '') ? '\\u2014' : String(v);\n" | |
| 1284 | +" }\n" | |
| 1285 | +"\n" | |
| 1286 | +" document.documentElement.setAttribute('data-theme',\n" | |
| 1287 | +" localStorage.getItem('bot_theme') || 'dark');\n" | |
| 1288 | +"\n" | |
| 1289 | +"\n" | |
| 1290 | +" var RATE = 2000, TIMER = null, BUSY = false;\n" | |
| 1291 | +" var HISTORY = [], HIST_MAX = 60;\n" | |
| 1292 | +" var SORT = 'cpu';\n" | |
| 1293 | +" var DATA = null;\n" | |
| 1294 | +"\n" | |
| 1295 | +" function kb(v){\n" | |
| 1296 | +" if (!v && v !== 0) return '\\u2014';\n" | |
| 1297 | +" if (v >= 1048576) return (v / 1048576).toFixed(1) + ' GiB';\n" | |
| 1298 | +" if (v >= 1024) return (v / 1024).toFixed(0) + ' MiB';\n" | |
| 1299 | +" return v + ' KiB';\n" | |
| 1300 | +" }\n" | |
| 1301 | +" function dur(sec){\n" | |
| 1302 | +" if (!sec && sec !== 0) return '\\u2014';\n" | |
| 1303 | +" var d = Math.floor(sec / 86400), h = Math.floor((sec % 86400) / 3600),\n" | |
| 1304 | +" m = Math.floor((sec % 3600) / 60);\n" | |
| 1305 | +" if (d > 0) return d + 'd ' + h + 'h';\n" | |
| 1306 | +" if (h > 0) return h + 'h ' + m + 'm';\n" | |
| 1307 | +" return m + 'm';\n" | |
| 1308 | +" }\n" | |
| 1309 | +" function pctColor(p){\n" | |
| 1310 | +" if (p >= 85) return 'var(--danger)';\n" | |
| 1311 | +" if (p >= 60) return 'var(--warn)';\n" | |
| 1312 | +" return 'var(--ok)';\n" | |
| 1313 | +" }\n" | |
| 1314 | +"\n" | |
| 1315 | +" function renderCores(d){\n" | |
| 1316 | +" var host = $('cores');\n" | |
| 1317 | +" host.innerHTML = '';\n" | |
| 1318 | +" if (!d.cores || !d.cores.length){\n" | |
| 1319 | +" $('coreNote').textContent = 'Per-core detail is available on Linux and macOS nodes; ' +\n" | |
| 1320 | +" 'this platform exposes an aggregate CPU figure only.';\n" | |
| 1321 | +" return;\n" | |
| 1322 | +" }\n" | |
| 1323 | +" $('coreNote').textContent = '';\n" | |
| 1324 | +" for (var i = 0; i < d.cores.length; i++){\n" | |
| 1325 | +" var c = d.cores[i];\n" | |
| 1326 | +" var box = el('div','core');\n" | |
| 1327 | +" box.appendChild(el('div','lbl','cpu ' + c.core));\n" | |
| 1328 | +" var bar = el('div','bar'), fill = el('div','fill');\n" | |
| 1329 | +" fill.style.width = Math.max(0, Math.min(100, c.pct)) + '%';\n" | |
| 1330 | +" fill.style.background = pctColor(c.pct);\n" | |
| 1331 | +" bar.appendChild(fill);\n" | |
| 1332 | +" box.appendChild(bar);\n" | |
| 1333 | +" box.appendChild(el('div','pc', c.pct.toFixed(0) + '%'));\n" | |
| 1334 | +" host.appendChild(box);\n" | |
| 1335 | +" }\n" | |
| 1336 | +" }\n" | |
| 1337 | +"\n" | |
| 1338 | +" function renderSpark(v){\n" | |
| 1339 | +" HISTORY.push(Math.max(0, Math.min(100, v)));\n" | |
| 1340 | +" if (HISTORY.length > HIST_MAX) HISTORY.shift();\n" | |
| 1341 | +" if (HISTORY.length < 2) return;\n" | |
| 1342 | +" var pts = [];\n" | |
| 1343 | +" for (var i = 0; i < HISTORY.length; i++){\n" | |
| 1344 | +" var x = (i / (HISTORY.length - 1)) * 600;\n" | |
| 1345 | +" var y = 62 - (HISTORY[i] / 100) * 58;\n" | |
| 1346 | +" pts.push(x.toFixed(1) + ',' + y.toFixed(1));\n" | |
| 1347 | +" }\n" | |
| 1348 | +" $('sparkLine').setAttribute('points', pts.join(' '));\n" | |
| 1349 | +" }\n" | |
| 1350 | +"\n" | |
| 1351 | +" function renderProcs(){\n" | |
| 1352 | +" if (!DATA) return;\n" | |
| 1353 | +" var filter = ($('q').value || '').toLowerCase();\n" | |
| 1354 | +" var body = $('rows');\n" | |
| 1355 | +" body.innerHTML = '';\n" | |
| 1356 | +" var shown = 0;\n" | |
| 1357 | +" for (var i = 0; i < DATA.processes.length; i++){\n" | |
| 1358 | +" var p = DATA.processes[i];\n" | |
| 1359 | +" var hay = (p.name + ' ' + p.pid).toLowerCase();\n" | |
| 1360 | +" if (filter && hay.indexOf(filter) < 0) continue;\n" | |
| 1361 | +" var tr = el('tr');\n" | |
| 1362 | +" tr.appendChild(el('td','num', p.pid));\n" | |
| 1363 | +" tr.appendChild(el('td','nm', p.name || '\\u2014'));\n" | |
| 1364 | +" tr.appendChild(el('td','num', p.cpu.toFixed(1)));\n" | |
| 1365 | +" tr.appendChild(el('td','num', kb(p.rss_kb)));\n" | |
| 1366 | +" var td = el('td','hide-sm', p.state || '\\u2014');\n" | |
| 1367 | +" tr.appendChild(td);\n" | |
| 1368 | +" body.appendChild(tr);\n" | |
| 1369 | +" shown++;\n" | |
| 1370 | +" }\n" | |
| 1371 | +" if (shown) $('empty').classList.add('hide');\n" | |
| 1372 | +" else $('empty').classList.remove('hide');\n" | |
| 1373 | +" }\n" | |
| 1374 | +"\n" | |
| 1375 | +" function render(d){\n" | |
| 1376 | +" DATA = d;\n" | |
| 1377 | +" txt('pHost', d.host);\n" | |
| 1378 | +" txt('pPlatform', d.platform);\n" | |
| 1379 | +" txt('cpuModel', d.cpu_model);\n" | |
| 1380 | +" txt('kCpu', d.cpu_pct.toFixed(1) + '%');\n" | |
| 1381 | +" txt('kCores', d.ncores || '\\u2014');\n" | |
| 1382 | +" txt('kMem', (d.mem.pct).toFixed(0) + '%');\n" | |
| 1383 | +" txt('kSwap', d.swap.total_kb > 0 ? d.swap.pct.toFixed(0) + '%' : 'none');\n" | |
| 1384 | +" txt('kLoad', d.load.available ? d.load.load1.toFixed(2) : 'n/a');\n" | |
| 1385 | +" txt('kUp', dur(d.uptime_sec));\n" | |
| 1386 | +" txt('kProc', d.proc_count);\n" | |
| 1387 | +"\n" | |
| 1388 | +" $('memFill').style.width = Math.max(0, Math.min(100, d.mem.pct)) + '%';\n" | |
| 1389 | +" txt('memLbl', kb(d.mem.used_kb) + ' / ' + kb(d.mem.total_kb));\n" | |
| 1390 | +" txt('memDetail', 'free ' + kb(d.mem.free_kb) +\n" | |
| 1391 | +" (d.mem.cached_kb > 0 ? ' \\u00b7 cached ' + kb(d.mem.cached_kb) : ''));\n" | |
| 1392 | +" $('swapFill').style.width = d.swap.total_kb > 0\n" | |
| 1393 | +" ? Math.max(0, Math.min(100, d.swap.pct)) + '%' : '0%';\n" | |
| 1394 | +" txt('swapLbl', d.swap.total_kb > 0\n" | |
| 1395 | +" ? kb(d.swap.used_kb) + ' / ' + kb(d.swap.total_kb) : 'no swap');\n" | |
| 1396 | +"\n" | |
| 1397 | +" renderSpark(d.cpu_pct);\n" | |
| 1398 | +" renderCores(d);\n" | |
| 1399 | +" renderProcs();\n" | |
| 1400 | +" }\n" | |
| 1401 | +"\n" | |
| 1402 | +" function fail(msg){\n" | |
| 1403 | +" $('pState').textContent = 'error';\n" | |
| 1404 | +" $('pState').className = 'pill paused';\n" | |
| 1405 | +" txt('coreNote', msg);\n" | |
| 1406 | +" }\n" | |
| 1407 | +"\n" | |
| 1408 | +" function poll(){\n" | |
| 1409 | +" if (BUSY) return;\n" | |
| 1410 | +" BUSY = true;\n" | |
| 1411 | +" var u = withCtx(base() + '?action=metrics&sort=' + encodeURIComponent(SORT));\n" | |
| 1412 | +" fetch(u, { headers: hdr(), cache: 'no-store' })\n" | |
| 1413 | +" .then(function(r){ return r.json(); })\n" | |
| 1414 | +" .then(function(d){\n" | |
| 1415 | +" if (!d || d.ok === false){ fail((d && d.message) || 'sample failed'); return; }\n" | |
| 1416 | +" render(d);\n" | |
| 1417 | +" })\n" | |
| 1418 | +" .catch(function(e){ fail('request failed: ' + e); })\n" | |
| 1419 | +" .then(function(){ BUSY = false; });\n" | |
| 1420 | +" }\n" | |
| 1421 | +"\n" | |
| 1422 | +" function schedule(){\n" | |
| 1423 | +" if (TIMER) { clearInterval(TIMER); TIMER = null; }\n" | |
| 1424 | +" var st = $('pState');\n" | |
| 1425 | +" if (RATE > 0){\n" | |
| 1426 | +" TIMER = setInterval(poll, RATE);\n" | |
| 1427 | +" st.textContent = 'live ' + (RATE / 1000) + 's';\n" | |
| 1428 | +" st.className = 'pill live';\n" | |
| 1429 | +" } else {\n" | |
| 1430 | +" st.textContent = 'paused';\n" | |
| 1431 | +" st.className = 'pill paused';\n" | |
| 1432 | +" }\n" | |
| 1433 | +" }\n" | |
| 1434 | +"\n" | |
| 1435 | +" Array.prototype.forEach.call(document.querySelectorAll('#segRate button'), function(b){\n" | |
| 1436 | +" b.addEventListener('click', function(){\n" | |
| 1437 | +" Array.prototype.forEach.call(document.querySelectorAll('#segRate button'),\n" | |
| 1438 | +" function(x){ x.classList.remove('on'); });\n" | |
| 1439 | +" b.classList.add('on');\n" | |
| 1440 | +" RATE = parseInt(b.getAttribute('data-ms'), 10) || 0;\n" | |
| 1441 | +" schedule();\n" | |
| 1442 | +" if (RATE > 0) poll();\n" | |
| 1443 | +" });\n" | |
| 1444 | +" });\n" | |
| 1445 | +"\n" | |
| 1446 | +" Array.prototype.forEach.call(document.querySelectorAll('#segSort button'), function(b){\n" | |
| 1447 | +" b.addEventListener('click', function(){\n" | |
| 1448 | +" Array.prototype.forEach.call(document.querySelectorAll('#segSort button'),\n" | |
| 1449 | +" function(x){ x.classList.remove('on'); });\n" | |
| 1450 | +" b.classList.add('on');\n" | |
| 1451 | +" SORT = b.getAttribute('data-sort') || 'cpu';\n" | |
| 1452 | +" poll();\n" | |
| 1453 | +" });\n" | |
| 1454 | +" });\n" | |
| 1455 | +"\n" | |
| 1456 | +" $('q').addEventListener('input', renderProcs);\n" | |
| 1457 | +" if (document.visibilityState === 'visible') poll();\n" | |
| 1458 | +" document.addEventListener('visibilitychange', function(){\n" | |
| 1459 | +" if (document.visibilityState === 'visible') poll();\n" | |
| 1460 | +" });\n" | |
| 1461 | +" schedule();\n" | |
| 1462 | +"})();\n" | |
| 1463 | +"</script></div></body></html>\n", stdout); | |
| 1464 | + | |
| 1465 | + return 0; | |
| 1466 | +} | |
| 1467 | + | |
| 1468 | +/* ------------------------------------------------------------------ */ | |
| 1469 | +/* Entry point */ | |
| 1470 | +/* ------------------------------------------------------------------ */ | |
| 1471 | + | |
| 1472 | +int main(int argc, char **argv) | |
| 1473 | +{ | |
| 1474 | + const char *qs; | |
| 1475 | + const char *method; | |
| 1476 | + int i; | |
| 1477 | + | |
| 1478 | + for (i = 1; i < argc; i++) { | |
| 1479 | + if (strcmp(argv[i], "--meta") == 0) | |
| 1480 | + return mode_meta(); | |
| 1481 | + if (strcmp(argv[i], "--version") == 0) { | |
| 1482 | + printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); | |
| 1483 | + return 0; | |
| 1484 | + } | |
| 1485 | + if (strcmp(argv[i], "--help") == 0) { | |
| 1486 | + printf("usage: %s [--meta] [--version] [--help]\n" | |
| 1487 | + " CGI mode reads QUERY_STRING:\n" | |
| 1488 | + " ?format=json | ?action=metrics JSON system snapshot\n" | |
| 1489 | + " ?action=info plugin info\n" | |
| 1490 | + " (no action) HTML dashboard\n", PLUGIN_ID); | |
| 1491 | + return 0; | |
| 1492 | + } | |
| 1493 | + } | |
| 1494 | + | |
| 1495 | + if (getenv("SX_PLUGIN_META")) | |
| 1496 | + return mode_meta(); | |
| 1497 | + | |
| 1498 | + require_node_auth(); | |
| 1499 | + | |
| 1500 | + qs = getenv("QUERY_STRING"); | |
| 1501 | + if (!qs) qs = ""; | |
| 1502 | + method = getenv("REQUEST_METHOD"); | |
| 1503 | + if (!method) method = "GET"; | |
| 1504 | + | |
| 1505 | + if (strstr(qs, "action=") || strstr(qs, "format=json")) | |
| 1506 | + return mode_json(qs); | |
| 1507 | + | |
| 1508 | + { | |
| 1509 | + char embedv[16]; | |
| 1510 | + embedv[0] = '\0'; | |
| 1511 | + if (get_query_val(qs, "embed", embedv, sizeof(embedv))) | |
| 1512 | + return mode_html(strcmp(embedv, "1") == 0 || strcmp(embedv, "true") == 0); | |
| 1513 | + } | |
| 1514 | + return mode_html(0); | |
| 1515 | +} | |
| 0 | 1516 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..1009830 | index 0000000..1009830 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/Makefile | +++ b/Makefile | ||
| @@ -0,0 +1,55 @@ | @@ -0,0 +1,55 @@ | ||
| 1 | +# plugin_sysmon - ScorpioX Bot open-source local system monitor plugin | ||
| 2 | +# | ||
| 3 | +# Targets: | ||
| 4 | +# make native build -> ./plugin_sysmon | ||
| 5 | +# make musl static musl x86_64 -> ./plugin_sysmon (fully static) | ||
| 6 | +# make win64 MinGW-w64 static -> ./plugin_sysmon.exe | ||
| 7 | +# make macos Apple clang -> ./plugin_sysmon (run on macOS) | ||
| 8 | +# make test build + run tests/run.sh | ||
| 9 | +# make clean | ||
| 10 | + | ||
| 11 | +CC ?= cc | ||
| 12 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings | ||
| 13 | +MUSL_CC ?= musl-gcc | ||
| 14 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | ||
| 15 | +WIN_CC ?= x86_64-w64-mingw32-gcc | ||
| 16 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | ||
| 17 | +WIN_LIBS := -lpsapi | ||
| 18 | +SRC := src/plugin_sysmon.c | ||
| 19 | +BIN := plugin_sysmon | ||
| 20 | +EXE := plugin_sysmon.exe | ||
| 21 | + | ||
| 22 | +.PHONY: all native musl win64 macos test clean help | ||
| 23 | + | ||
| 24 | +all: native | ||
| 25 | + | ||
| 26 | +native: $(BIN) | ||
| 27 | + | ||
| 28 | +$(BIN): $(SRC) | ||
| 29 | + @echo "==> native build ($(CC))" | ||
| 30 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | ||
| 31 | + | ||
| 32 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | ||
| 33 | +musl: $(SRC) | ||
| 34 | + @echo "==> static musl build ($(MUSL_CC))" | ||
| 35 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN) $(SRC) | ||
| 36 | + | ||
| 37 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | ||
| 38 | +win64: $(SRC) | ||
| 39 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | ||
| 40 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) $(WIN_LIBS) | ||
| 41 | + | ||
| 42 | +# Apple clang build (run this on macOS) | ||
| 43 | +macos: $(SRC) | ||
| 44 | + @echo "==> Apple clang build" | ||
| 45 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | ||
| 46 | + | ||
| 47 | +test: native | ||
| 48 | + @sh tests/run.sh | ||
| 49 | + | ||
| 50 | +clean: | ||
| 51 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).macos-arm64 $(BIN).macos-x86_64 | ||
| 52 | + rm -rf bin | ||
| 53 | + | ||
| 54 | +help: | ||
| 55 | + @echo "make | make musl | make win64 | make macos | make test | make clean" |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..2c5d05d | index 0000000..2c5d05d |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..bc31c6a | index 0000000..bc31c6a | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/plugin_sysmon.c | +++ b/src/plugin_sysmon.c | ||
| @@ -0,0 +1,1515 @@ | @@ -0,0 +1,1515 @@ | ||
| 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(_WIN32) | ||
| 22 | +# define _POSIX_C_SOURCE 200809L | ||
| 23 | +# define _DEFAULT_SOURCE 1 | ||
| 24 | +#endif | ||
| 25 | + | ||
| 26 | +#include <stdio.h> | ||
| 27 | +#include <stdlib.h> | ||
| 28 | +#include <string.h> | ||
| 29 | +#include <time.h> | ||
| 30 | +#include <ctype.h> | ||
| 31 | +#include <errno.h> | ||
| 32 | + | ||
| 33 | +#if defined(_WIN32) | ||
| 34 | + | ||
| 35 | +# define WIN32_LEAN_AND_MEAN | ||
| 36 | +# include <windows.h> | ||
| 37 | +# include <psapi.h> | ||
| 38 | +# include <tlhelp32.h> | ||
| 39 | +# include <io.h> | ||
| 40 | + | ||
| 41 | +#else | ||
| 42 | + | ||
| 43 | +# include <unistd.h> | ||
| 44 | +# include <dirent.h> | ||
| 45 | +# include <sys/types.h> | ||
| 46 | + | ||
| 47 | +#endif | ||
| 48 | + | ||
| 49 | +#if defined(__APPLE__) | ||
| 50 | +# include <mach/mach.h> | ||
| 51 | +# include <mach/mach_host.h> | ||
| 52 | +# include <sys/sysctl.h> | ||
| 53 | +# include <sys/time.h> | ||
| 54 | +#endif | ||
| 55 | + | ||
| 56 | +#define PLUGIN_SLUG "sysmon" | ||
| 57 | +#define PLUGIN_ID "plugin_sysmon" | ||
| 58 | +#define PLUGIN_VER "1.0.0" | ||
| 59 | + | ||
| 60 | +#define MAX_CORES 256 | ||
| 61 | +#define MAX_PROCS 4096 | ||
| 62 | +#define TOP_DEFAULT 25 | ||
| 63 | +#define SAMPLE_MS 80 | ||
| 64 | + | ||
| 65 | +/* ------------------------------------------------------------------ */ | ||
| 66 | +/* Small utilities */ | ||
| 67 | +/* ------------------------------------------------------------------ */ | ||
| 68 | + | ||
| 69 | +/* Percent-decode in place ('+' becomes space). */ | ||
| 70 | +static void url_decode(char *s) | ||
| 71 | +{ | ||
| 72 | + char *o = s; | ||
| 73 | + if (!s) return; | ||
| 74 | + while (*s) { | ||
| 75 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | ||
| 76 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | ||
| 77 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | ||
| 78 | + *o++ = (char)((hi << 4) | lo); | ||
| 79 | + s += 3; | ||
| 80 | + } else if (*s == '+') { | ||
| 81 | + *o++ = ' '; | ||
| 82 | + s++; | ||
| 83 | + } else { | ||
| 84 | + *o++ = *s++; | ||
| 85 | + } | ||
| 86 | + } | ||
| 87 | + *o = '\0'; | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +/* Read one parameter (decoded) out of a form/query string. */ | ||
| 91 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | ||
| 92 | +{ | ||
| 93 | + size_t klen; | ||
| 94 | + const char *p; | ||
| 95 | + | ||
| 96 | + if (!out || outsz == 0) return 0; | ||
| 97 | + out[0] = '\0'; | ||
| 98 | + if (!qs || !key) return 0; | ||
| 99 | + klen = strlen(key); | ||
| 100 | + | ||
| 101 | + for (p = qs; *p; ) { | ||
| 102 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | ||
| 103 | + const char *v = p + klen + 1; | ||
| 104 | + size_t i = 0; | ||
| 105 | + while (*v && *v != '&' && i + 1 < outsz) | ||
| 106 | + out[i++] = *v++; | ||
| 107 | + out[i] = '\0'; | ||
| 108 | + url_decode(out); | ||
| 109 | + return 1; | ||
| 110 | + } | ||
| 111 | + p = strchr(p, '&'); | ||
| 112 | + if (!p) break; | ||
| 113 | + p++; | ||
| 114 | + } | ||
| 115 | + return 0; | ||
| 116 | +} | ||
| 117 | + | ||
| 118 | +static void json_str(const char *s) | ||
| 119 | +{ | ||
| 120 | + putchar('"'); | ||
| 121 | + for (; s && *s; s++) { | ||
| 122 | + unsigned char c = (unsigned char)*s; | ||
| 123 | + switch (c) { | ||
| 124 | + case '"': fputs("\\\"", stdout); break; | ||
| 125 | + case '\\': fputs("\\\\", stdout); break; | ||
| 126 | + case '\n': fputs("\\n", stdout); break; | ||
| 127 | + case '\r': fputs("\\r", stdout); break; | ||
| 128 | + case '\t': fputs("\\t", stdout); break; | ||
| 129 | + default: | ||
| 130 | + if (c < 0x20) printf("\\u%04x", (unsigned)c); | ||
| 131 | + else putchar((int)c); | ||
| 132 | + } | ||
| 133 | + } | ||
| 134 | + putchar('"'); | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +static void utc_now(char *buf, size_t sz) | ||
| 138 | +{ | ||
| 139 | + time_t t = time(NULL); | ||
| 140 | + struct tm tmv; | ||
| 141 | +#if defined(_WIN32) | ||
| 142 | + gmtime_s(&tmv, &t); | ||
| 143 | +#else | ||
| 144 | + gmtime_r(&t, &tmv); | ||
| 145 | +#endif | ||
| 146 | + if (strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv) == 0) { | ||
| 147 | + strncpy(buf, "1970-01-01T00:00:00Z", sz - 1); | ||
| 148 | + buf[sz - 1] = '\0'; | ||
| 149 | + } | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +static long node_pid(void) | ||
| 153 | +{ | ||
| 154 | +#if defined(_WIN32) | ||
| 155 | + return (long)GetCurrentProcessId(); | ||
| 156 | +#else | ||
| 157 | + return (long)getpid(); | ||
| 158 | +#endif | ||
| 159 | +} | ||
| 160 | + | ||
| 161 | +static void sx_sleep_ms(int ms) | ||
| 162 | +{ | ||
| 163 | +#if defined(_WIN32) | ||
| 164 | + Sleep((DWORD)ms); | ||
| 165 | +#else | ||
| 166 | + struct timespec ts; | ||
| 167 | + ts.tv_sec = ms / 1000; | ||
| 168 | + ts.tv_nsec = (long)(ms % 1000) * 1000000L; | ||
| 169 | + nanosleep(&ts, NULL); | ||
| 170 | +#endif | ||
| 171 | +} | ||
| 172 | + | ||
| 173 | +static double clamp_pct(double v) | ||
| 174 | +{ | ||
| 175 | + if (v < 0.0) return 0.0; | ||
| 176 | + if (v > 100.0) return 100.0; | ||
| 177 | + return v; | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +/* ------------------------------------------------------------------ */ | ||
| 181 | +/* Node authentication */ | ||
| 182 | +/* ------------------------------------------------------------------ */ | ||
| 183 | + | ||
| 184 | +/* | ||
| 185 | + * The node API on :8150 is reachable from the LAN. Every request except | ||
| 186 | + * --meta discovery must prove it knows the node password. Accepted forms | ||
| 187 | + * match the rest of the node API: X-Bot-Password (what bot-web proxies | ||
| 188 | + * with), Authorization: Bearer, and ?pwd= (what the plugin iframe appends). | ||
| 189 | + * When BOT_PASSWORD is unset the plugin is a deliberate no-op, which is how | ||
| 190 | + * a developer runs it locally from a shell. | ||
| 191 | + */ | ||
| 192 | +static void require_node_auth(void) | ||
| 193 | +{ | ||
| 194 | + const char *np = getenv("BOT_PASSWORD"); | ||
| 195 | + const char *xp; | ||
| 196 | + const char *auth; | ||
| 197 | + char qpwd[256]; | ||
| 198 | + const char *qs; | ||
| 199 | + | ||
| 200 | + if (!np || !*np) return; | ||
| 201 | + | ||
| 202 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | ||
| 203 | + if (xp && strcmp(xp, np) == 0) return; | ||
| 204 | + | ||
| 205 | + auth = getenv("HTTP_AUTHORIZATION"); | ||
| 206 | + if (auth) { | ||
| 207 | + while (*auth == ' ') auth++; | ||
| 208 | + if (strncmp(auth, "Bearer ", 7) == 0) { | ||
| 209 | + auth += 7; | ||
| 210 | + while (*auth == ' ') auth++; | ||
| 211 | + if (strcmp(auth, np) == 0) return; | ||
| 212 | + } | ||
| 213 | + } | ||
| 214 | + | ||
| 215 | + qs = getenv("QUERY_STRING"); | ||
| 216 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) | ||
| 217 | + return; | ||
| 218 | + | ||
| 219 | + fputs("Status: 401 Unauthorized\r\n" | ||
| 220 | + "Content-Type: application/json; charset=utf-8\r\n" | ||
| 221 | + "Cache-Control: no-store\r\n" | ||
| 222 | + "X-Content-Type-Options: nosniff\r\n\r\n" | ||
| 223 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | ||
| 224 | + exit(0); | ||
| 225 | +} | ||
| 226 | + | ||
| 227 | +/* ------------------------------------------------------------------ */ | ||
| 228 | +/* Collected snapshot */ | ||
| 229 | +/* ------------------------------------------------------------------ */ | ||
| 230 | + | ||
| 231 | +typedef struct { | ||
| 232 | + int core; | ||
| 233 | + double pct; | ||
| 234 | +} core_t; | ||
| 235 | + | ||
| 236 | +typedef struct { | ||
| 237 | + long pid; | ||
| 238 | + char name[64]; | ||
| 239 | + double cpu; /* percent of one core */ | ||
| 240 | + long rss_kb; | ||
| 241 | + char state; | ||
| 242 | +} proc_t; | ||
| 243 | + | ||
| 244 | +typedef struct { | ||
| 245 | + int ok; | ||
| 246 | + char platform[16]; /* linux | macos | windows */ | ||
| 247 | + char host[128]; | ||
| 248 | + | ||
| 249 | + double cpu_pct; | ||
| 250 | + core_t cores[MAX_CORES]; | ||
| 251 | + int ncores; | ||
| 252 | + char cpu_model[128]; | ||
| 253 | + | ||
| 254 | + double mem_total_kb; | ||
| 255 | + double mem_used_kb; | ||
| 256 | + double mem_free_kb; | ||
| 257 | + double mem_cached_kb; | ||
| 258 | + | ||
| 259 | + double swap_total_kb; | ||
| 260 | + double swap_used_kb; | ||
| 261 | + | ||
| 262 | + double uptime_sec; | ||
| 263 | + double load1, load5, load15; | ||
| 264 | + int load_available; | ||
| 265 | + | ||
| 266 | + proc_t procs[MAX_PROCS]; | ||
| 267 | + int nprocs; | ||
| 268 | +} sys_t; | ||
| 269 | + | ||
| 270 | +/* ------------------------------------------------------------------ */ | ||
| 271 | +/* Linux sampling */ | ||
| 272 | +/* ------------------------------------------------------------------ */ | ||
| 273 | + | ||
| 274 | +#if !defined(_WIN32) && !defined(__APPLE__) | ||
| 275 | + | ||
| 276 | +typedef struct { | ||
| 277 | + unsigned long long user, nice, system, idle, iowait, irq, softirq, steal; | ||
| 278 | +} cpu_raw_t; | ||
| 279 | + | ||
| 280 | +/* | ||
| 281 | + * /proc/stat reports st_size == 0, so seeking to the end and measuring is | ||
| 282 | + * meaningless. Always stream with fgets until EOF. | ||
| 283 | + */ | ||
| 284 | +static int read_proc_stat(cpu_raw_t *agg, cpu_raw_t *cores, int maxcores) | ||
| 285 | +{ | ||
| 286 | + FILE *fp; | ||
| 287 | + char line[512]; | ||
| 288 | + int n = 0; | ||
| 289 | + | ||
| 290 | + fp = fopen("/proc/stat", "r"); | ||
| 291 | + if (!fp) return -1; | ||
| 292 | + | ||
| 293 | + memset(agg, 0, sizeof(*agg)); | ||
| 294 | + while (fgets(line, sizeof(line), fp)) { | ||
| 295 | + if (strncmp(line, "cpu", 3) != 0) break; | ||
| 296 | + if (line[3] == ' ') { | ||
| 297 | + (void)sscanf(line + 4, "%llu %llu %llu %llu %llu %llu %llu %llu", | ||
| 298 | + &agg->user, &agg->nice, &agg->system, &agg->idle, | ||
| 299 | + &agg->iowait, &agg->irq, &agg->softirq, &agg->steal); | ||
| 300 | + continue; | ||
| 301 | + } | ||
| 302 | + if (isdigit((unsigned char)line[3])) { | ||
| 303 | + cpu_raw_t r; | ||
| 304 | + int idx = 0; | ||
| 305 | + memset(&r, 0, sizeof(r)); | ||
| 306 | + if (sscanf(line + 3, "%d %llu %llu %llu %llu %llu %llu %llu %llu", | ||
| 307 | + &idx, &r.user, &r.nice, &r.system, &r.idle, | ||
| 308 | + &r.iowait, &r.irq, &r.softirq, &r.steal) >= 5) { | ||
| 309 | + if (n < maxcores) cores[n] = r; | ||
| 310 | + n++; | ||
| 311 | + } | ||
| 312 | + } | ||
| 313 | + } | ||
| 314 | + fclose(fp); | ||
| 315 | + return n; | ||
| 316 | +} | ||
| 317 | + | ||
| 318 | +static double cpu_busy_pct(const cpu_raw_t *a, const cpu_raw_t *b) | ||
| 319 | +{ | ||
| 320 | + unsigned long long ta = a->user + a->nice + a->system + a->idle + a->iowait | ||
| 321 | + + a->irq + a->softirq + a->steal; | ||
| 322 | + unsigned long long tb = b->user + b->nice + b->system + b->idle + b->iowait | ||
| 323 | + + b->irq + b->softirq + b->steal; | ||
| 324 | + unsigned long long ba = a->user + a->nice + a->system + a->irq + a->softirq + a->steal; | ||
| 325 | + unsigned long long bb = b->user + b->nice + b->system + b->irq + b->softirq + b->steal; | ||
| 326 | + unsigned long long dt, db; | ||
| 327 | + | ||
| 328 | + if (tb <= ta) return 0.0; | ||
| 329 | + dt = tb - ta; | ||
| 330 | + db = bb >= ba ? bb - ba : 0; | ||
| 331 | + return clamp_pct(100.0 * (double)db / (double)dt); | ||
| 332 | +} | ||
| 333 | + | ||
| 334 | +static void read_meminfo(sys_t *s) | ||
| 335 | +{ | ||
| 336 | + FILE *fp; | ||
| 337 | + char line[256]; | ||
| 338 | + | ||
| 339 | + s->mem_total_kb = s->mem_free_kb = s->mem_cached_kb = 0.0; | ||
| 340 | + s->swap_total_kb = s->swap_used_kb = 0.0; | ||
| 341 | + | ||
| 342 | + fp = fopen("/proc/meminfo", "r"); | ||
| 343 | + if (!fp) return; | ||
| 344 | + | ||
| 345 | + { | ||
| 346 | + unsigned long long total = 0, free_kb = 0, avail = 0, cached = 0, sreclaim = 0; | ||
| 347 | + unsigned long long swap_total = 0, swap_free = 0; | ||
| 348 | + | ||
| 349 | + while (fgets(line, sizeof(line), fp)) { | ||
| 350 | + unsigned long long v = 0; | ||
| 351 | + if (sscanf(line, "MemTotal: %llu kB", &v) == 1) total = v; | ||
| 352 | + else if (sscanf(line, "MemFree: %llu kB", &v) == 1) free_kb = v; | ||
| 353 | + else if (sscanf(line, "MemAvailable: %llu kB", &v) == 1) avail = v; | ||
| 354 | + else if (sscanf(line, "Cached: %llu kB", &v) == 1) cached = v; | ||
| 355 | + else if (sscanf(line, "SReclaimable: %llu kB", &v) == 1) sreclaim = v; | ||
| 356 | + else if (sscanf(line, "SwapTotal: %llu kB", &v) == 1) swap_total = v; | ||
| 357 | + else if (sscanf(line, "SwapFree: %llu kB", &v) == 1) swap_free = v; | ||
| 358 | + } | ||
| 359 | + fclose(fp); | ||
| 360 | + | ||
| 361 | + s->mem_total_kb = (double)total; | ||
| 362 | + s->mem_free_kb = (double)(avail ? avail : free_kb); | ||
| 363 | + s->mem_cached_kb = (double)(cached + sreclaim); | ||
| 364 | + s->mem_used_kb = (double)total - s->mem_free_kb; | ||
| 365 | + if (s->mem_used_kb < 0.0) s->mem_used_kb = 0.0; | ||
| 366 | + s->swap_total_kb = (double)swap_total; | ||
| 367 | + s->swap_used_kb = (double)(swap_total > swap_free ? swap_total - swap_free : 0); | ||
| 368 | + } | ||
| 369 | +} | ||
| 370 | + | ||
| 371 | +static void read_uptime(sys_t *s) | ||
| 372 | +{ | ||
| 373 | + FILE *fp = fopen("/proc/uptime", "r"); | ||
| 374 | + double up = 0.0; | ||
| 375 | + if (fp) { | ||
| 376 | + if (fscanf(fp, "%lf", &up) != 1) up = 0.0; | ||
| 377 | + fclose(fp); | ||
| 378 | + } | ||
| 379 | + s->uptime_sec = up; | ||
| 380 | +} | ||
| 381 | + | ||
| 382 | +static void read_load(sys_t *s) | ||
| 383 | +{ | ||
| 384 | + FILE *fp = fopen("/proc/loadavg", "r"); | ||
| 385 | + if (fp) { | ||
| 386 | + if (fscanf(fp, "%lf %lf %lf", &s->load1, &s->load5, &s->load15) == 3) | ||
| 387 | + s->load_available = 1; | ||
| 388 | + fclose(fp); | ||
| 389 | + } | ||
| 390 | +} | ||
| 391 | + | ||
| 392 | +static void read_cpu_model(sys_t *s) | ||
| 393 | +{ | ||
| 394 | + FILE *fp = fopen("/proc/cpuinfo", "r"); | ||
| 395 | + char line[512]; | ||
| 396 | + s->cpu_model[0] = '\0'; | ||
| 397 | + if (!fp) return; | ||
| 398 | + while (fgets(line, sizeof(line), fp)) { | ||
| 399 | + char *colon; | ||
| 400 | + if (!(strncmp(line, "model name", 10) == 0 || strncmp(line, "Model", 5) == 0)) | ||
| 401 | + continue; | ||
| 402 | + colon = strchr(line, ':'); | ||
| 403 | + if (!colon) continue; | ||
| 404 | + colon++; | ||
| 405 | + while (*colon == ' ' || *colon == '\t') colon++; | ||
| 406 | + { | ||
| 407 | + size_t i = 0; | ||
| 408 | + while (*colon && *colon != '\n' && i + 1 < sizeof(s->cpu_model)) | ||
| 409 | + s->cpu_model[i++] = *colon++; | ||
| 410 | + s->cpu_model[i] = '\0'; | ||
| 411 | + while (i > 0 && (s->cpu_model[i - 1] == ' ' || s->cpu_model[i - 1] == '\t')) | ||
| 412 | + s->cpu_model[--i] = '\0'; | ||
| 413 | + } | ||
| 414 | + break; | ||
| 415 | + } | ||
| 416 | + fclose(fp); | ||
| 417 | +} | ||
| 418 | + | ||
| 419 | +static void read_hostname(sys_t *s) | ||
| 420 | +{ | ||
| 421 | + if (gethostname(s->host, sizeof(s->host)) != 0) | ||
| 422 | + s->host[0] = '\0'; | ||
| 423 | + s->host[sizeof(s->host) - 1] = '\0'; | ||
| 424 | +} | ||
| 425 | + | ||
| 426 | +/* One process: utime+stime ticks, rss pages, state char. */ | ||
| 427 | +static int read_pid_stat(const char *pid, unsigned long long *ticks, long *rss_pages, char *state) | ||
| 428 | +{ | ||
| 429 | + char path[64]; | ||
| 430 | + char buf[4096]; | ||
| 431 | + FILE *fp; | ||
| 432 | + size_t got; | ||
| 433 | + char *p; | ||
| 434 | + int field; | ||
| 435 | + unsigned long long utime = 0, stime = 0; | ||
| 436 | + long rss = 0; | ||
| 437 | + | ||
| 438 | + snprintf(path, sizeof(path), "/proc/%s/stat", pid); | ||
| 439 | + fp = fopen(path, "r"); | ||
| 440 | + if (!fp) return 0; | ||
| 441 | + got = fread(buf, 1, sizeof(buf) - 1, fp); | ||
| 442 | + fclose(fp); | ||
| 443 | + buf[got] = '\0'; | ||
| 444 | + | ||
| 445 | + p = strrchr(buf, ')'); | ||
| 446 | + if (!p || !p[1]) return 0; | ||
| 447 | + p++; | ||
| 448 | + while (*p == ' ') p++; | ||
| 449 | + if (state) *state = *p; | ||
| 450 | + | ||
| 451 | + /* fields after comm: state is 3, utime 14, stime 15, rss 24 */ | ||
| 452 | + field = 3; | ||
| 453 | + while (*p) { | ||
| 454 | + char *end; | ||
| 455 | + long long v; | ||
| 456 | + while (*p == ' ') p++; | ||
| 457 | + if (!*p) break; | ||
| 458 | + if (field == 3) { | ||
| 459 | + /* skip the single-letter state token */ | ||
| 460 | + while (*p && *p != ' ') p++; | ||
| 461 | + field++; | ||
| 462 | + continue; | ||
| 463 | + } | ||
| 464 | + v = strtoll(p, &end, 10); | ||
| 465 | + if (end == p) break; | ||
| 466 | + if (field == 14) utime = (unsigned long long)v; | ||
| 467 | + else if (field == 15) stime = (unsigned long long)v; | ||
| 468 | + else if (field == 24) rss = (long)v; | ||
| 469 | + if (field >= 24) break; | ||
| 470 | + p = end; | ||
| 471 | + field++; | ||
| 472 | + } | ||
| 473 | + | ||
| 474 | + *ticks = utime + stime; | ||
| 475 | + *rss_pages = rss; | ||
| 476 | + return 1; | ||
| 477 | +} | ||
| 478 | + | ||
| 479 | +static void read_pid_name(const char *pid, char *out, size_t outsz) | ||
| 480 | +{ | ||
| 481 | + char path[64]; | ||
| 482 | + FILE *fp; | ||
| 483 | + size_t n; | ||
| 484 | + | ||
| 485 | + out[0] = '\0'; | ||
| 486 | + snprintf(path, sizeof(path), "/proc/%s/comm", pid); | ||
| 487 | + fp = fopen(path, "r"); | ||
| 488 | + if (!fp) return; | ||
| 489 | + n = fread(out, 1, outsz - 1, fp); | ||
| 490 | + fclose(fp); | ||
| 491 | + out[n] = '\0'; | ||
| 492 | + while (n > 0 && (out[n - 1] == '\n' || out[n - 1] == '\r')) | ||
| 493 | + out[--n] = '\0'; | ||
| 494 | +} | ||
| 495 | + | ||
| 496 | +/* | ||
| 497 | + * Two-pass scan of /proc. The second pass is what produces a live CPU | ||
| 498 | + * percentage, because /proc/<pid>/stat only exposes cumulative ticks. | ||
| 499 | + */ | ||
| 500 | +typedef struct { | ||
| 501 | + long pid; | ||
| 502 | + unsigned long long ticks; | ||
| 503 | + long rss_pages; | ||
| 504 | + char state; | ||
| 505 | +} psnap_t; | ||
| 506 | + | ||
| 507 | +static int scan_procs_linux(psnap_t *out, int max) | ||
| 508 | +{ | ||
| 509 | + DIR *d; | ||
| 510 | + struct dirent *e; | ||
| 511 | + int n = 0; | ||
| 512 | + | ||
| 513 | + d = opendir("/proc"); | ||
| 514 | + if (!d) return 0; | ||
| 515 | + | ||
| 516 | + while ((e = readdir(d)) != NULL) { | ||
| 517 | + if (!isdigit((unsigned char)e->d_name[0])) continue; | ||
| 518 | + if (n >= max) break; | ||
| 519 | + if (!read_pid_stat(e->d_name, &out[n].ticks, &out[n].rss_pages, &out[n].state)) | ||
| 520 | + continue; | ||
| 521 | + out[n].pid = (long)strtol(e->d_name, NULL, 10); | ||
| 522 | + n++; | ||
| 523 | + } | ||
| 524 | + closedir(d); | ||
| 525 | + return n; | ||
| 526 | +} | ||
| 527 | + | ||
| 528 | +static void sample_linux(sys_t *s) | ||
| 529 | +{ | ||
| 530 | + static psnap_t snap0[MAX_PROCS], snap1[MAX_PROCS]; | ||
| 531 | + cpu_raw_t agg0, agg1; | ||
| 532 | + cpu_raw_t c0[MAX_CORES], c1[MAX_CORES]; | ||
| 533 | + int n0, n1, p0, p1, i, j, k; | ||
| 534 | + long hz = sysconf(_SC_CLK_TCK); | ||
| 535 | + long page_kb = (long)(sysconf(_SC_PAGESIZE) / 1024); | ||
| 536 | + double window = (double)SAMPLE_MS / 1000.0; | ||
| 537 | + | ||
| 538 | + strcpy(s->platform, "linux"); | ||
| 539 | + read_hostname(s); | ||
| 540 | + read_cpu_model(s); | ||
| 541 | + | ||
| 542 | + memset(c0, 0, sizeof(c0)); | ||
| 543 | + memset(c1, 0, sizeof(c1)); | ||
| 544 | + | ||
| 545 | + n0 = read_proc_stat(&agg0, c0, MAX_CORES); | ||
| 546 | + p0 = scan_procs_linux(snap0, MAX_PROCS); | ||
| 547 | + | ||
| 548 | + sx_sleep_ms(SAMPLE_MS); | ||
| 549 | + | ||
| 550 | + n1 = read_proc_stat(&agg1, c1, MAX_CORES); | ||
| 551 | + p1 = scan_procs_linux(snap1, MAX_PROCS); | ||
| 552 | + | ||
| 553 | + if (hz <= 0) hz = 100; | ||
| 554 | + | ||
| 555 | + if (n0 > 0 && n1 > 0) { | ||
| 556 | + s->cpu_pct = cpu_busy_pct(&agg0, &agg1); | ||
| 557 | + s->ncores = n1 < MAX_CORES ? n1 : MAX_CORES; | ||
| 558 | + for (i = 0; i < s->ncores; i++) { | ||
| 559 | + s->cores[i].core = i; | ||
| 560 | + s->cores[i].pct = cpu_busy_pct(&c0[i], &c1[i]); | ||
| 561 | + } | ||
| 562 | + } | ||
| 563 | + | ||
| 564 | + /* Processes: RSS is instantaneous, CPU needs a delta over the window. */ | ||
| 565 | + s->nprocs = 0; | ||
| 566 | + for (j = 0; j < p1 && s->nprocs < MAX_PROCS; j++) { | ||
| 567 | + char name[64]; | ||
| 568 | + unsigned long long dt = 0; | ||
| 569 | + char pidbuf[24]; | ||
| 570 | + | ||
| 571 | + for (k = 0; k < p0; k++) { | ||
| 572 | + if (snap0[k].pid == snap1[j].pid) { | ||
| 573 | + dt = snap1[j].ticks > snap0[k].ticks | ||
| 574 | + ? snap1[j].ticks - snap0[k].ticks : 0; | ||
| 575 | + break; | ||
| 576 | + } | ||
| 577 | + } | ||
| 578 | + | ||
| 579 | + snprintf(pidbuf, sizeof(pidbuf), "%ld", snap1[j].pid); | ||
| 580 | + read_pid_name(pidbuf, name, sizeof(name)); | ||
| 581 | + | ||
| 582 | + s->procs[s->nprocs].pid = snap1[j].pid; | ||
| 583 | + s->procs[s->nprocs].cpu = clamp_pct(100.0 * (double)dt / ((double)hz * window)); | ||
| 584 | + s->procs[s->nprocs].rss_kb = snap1[j].rss_pages * page_kb; | ||
| 585 | + s->procs[s->nprocs].state = snap1[j].state; | ||
| 586 | + memcpy(s->procs[s->nprocs].name, name, sizeof(name)); | ||
| 587 | + s->nprocs++; | ||
| 588 | + } | ||
| 589 | + | ||
| 590 | + read_meminfo(s); | ||
| 591 | + read_uptime(s); | ||
| 592 | + read_load(s); | ||
| 593 | + | ||
| 594 | + s->ok = (s->ncores > 0); | ||
| 595 | +} | ||
| 596 | + | ||
| 597 | +#endif /* linux */ | ||
| 598 | + | ||
| 599 | +/* ------------------------------------------------------------------ */ | ||
| 600 | +/* macOS sampling */ | ||
| 601 | +/* ------------------------------------------------------------------ */ | ||
| 602 | + | ||
| 603 | +#if defined(__APPLE__) | ||
| 604 | + | ||
| 605 | +static void sample_macos(sys_t *s) | ||
| 606 | +{ | ||
| 607 | + size_t sz; | ||
| 608 | + char bbuf[256]; | ||
| 609 | + unsigned int ncpu = 0; | ||
| 610 | + uint64_t total_mem = 0; | ||
| 611 | + struct timeval boot; | ||
| 612 | + vm_statistics64_data_t vm; | ||
| 613 | + mach_msg_type_number_t vmcount = HOST_VM_INFO64_COUNT; | ||
| 614 | + integer_t *cpu0 = NULL, *cpu1 = NULL; | ||
| 615 | + natural_t ncpu0 = 0, ncpu1 = 0; | ||
| 616 | + unsigned long long page_kb; | ||
| 617 | + unsigned long long tick_hz = 1000ULL; /* we time the window ourselves */ | ||
| 618 | + double window; | ||
| 619 | + | ||
| 620 | + strcpy(s->platform, "macos"); | ||
| 621 | + | ||
| 622 | + sz = sizeof(bbuf); | ||
| 623 | + if (sysctlbyname("kern.hostname", bbuf, &sz, NULL, 0) == 0) | ||
| 624 | + snprintf(s->host, sizeof(s->host), "%s", bbuf); | ||
| 625 | + else | ||
| 626 | + s->host[0] = '\0'; | ||
| 627 | + | ||
| 628 | + s->cpu_model[0] = '\0'; | ||
| 629 | + sz = sizeof(bbuf); | ||
| 630 | + if (sysctlbyname("machdep.cpu.brand_string", bbuf, &sz, NULL, 0) == 0) | ||
| 631 | + snprintf(s->cpu_model, sizeof(s->cpu_model), "%s", bbuf); | ||
| 632 | + | ||
| 633 | + sz = sizeof(ncpu); | ||
| 634 | + if (sysctlbyname("hw.logicalcpu", &ncpu, &sz, NULL, 0) != 0 || | ||
| 635 | + sysctlbyname("hw.ncpu", &ncpu, &sz, NULL, 0) != 0) | ||
| 636 | + ncpu = 1; | ||
| 637 | + | ||
| 638 | + /* aggregate + per-core tick capture, twice */ | ||
| 639 | + { | ||
| 640 | + natural_t c0 = 0, c1 = 0; | ||
| 641 | + if (host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, | ||
| 642 | + &ncpu0, &cpu0, &c0) != KERN_SUCCESS) | ||
| 643 | + cpu0 = NULL; | ||
| 644 | + | ||
| 645 | + sx_sleep_ms(SAMPLE_MS); | ||
| 646 | + | ||
| 647 | + if (host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, | ||
| 648 | + &ncpu1, &cpu1, &c1) != KERN_SUCCESS) | ||
| 649 | + cpu1 = NULL; | ||
| 650 | + } | ||
| 651 | + | ||
| 652 | + window = (double)SAMPLE_MS / 1000.0; | ||
| 653 | + | ||
| 654 | + if (cpu0 && cpu1) { | ||
| 655 | + natural_t i; | ||
| 656 | + natural_t n = ncpu1 < ncpu0 ? ncpu1 : ncpu0; | ||
| 657 | + unsigned long long t_idle = 0, t_total = 0; | ||
| 658 | + | ||
| 659 | + s->ncores = 0; | ||
| 660 | + for (i = 0; i < n && s->ncores < MAX_CORES; i++) { | ||
| 661 | + unsigned long long a_idle = (unsigned long long)cpu0[i * CPU_STATE_MAX + CPU_STATE_IDLE]; | ||
| 662 | + unsigned long long a_usr = (unsigned long long)cpu0[i * CPU_STATE_MAX + CPU_STATE_USER]; | ||
| 663 | + unsigned long long a_sys = (unsigned long long)cpu0[i * CPU_STATE_MAX + CPU_STATE_SYSTEM]; | ||
| 664 | + unsigned long long a_nice = (unsigned long long)cpu0[i * CPU_STATE_MAX + CPU_STATE_NICE]; | ||
| 665 | + unsigned long long b_idle = (unsigned long long)cpu1[i * CPU_STATE_MAX + CPU_STATE_IDLE]; | ||
| 666 | + unsigned long long b_usr = (unsigned long long)cpu1[i * CPU_STATE_MAX + CPU_STATE_USER]; | ||
| 667 | + unsigned long long b_sys = (unsigned long long)cpu1[i * CPU_STATE_MAX + CPU_STATE_SYSTEM]; | ||
| 668 | + unsigned long long b_nice = (unsigned long long)cpu1[i * CPU_STATE_MAX + CPU_STATE_NICE]; | ||
| 669 | + unsigned long long ta = a_idle + a_usr + a_sys + a_nice; | ||
| 670 | + unsigned long long tb = b_idle + b_usr + b_sys + b_nice; | ||
| 671 | + unsigned long long di = b_idle > a_idle ? b_idle - a_idle : 0; | ||
| 672 | + unsigned long long dt = tb > ta ? tb - ta : 0; | ||
| 673 | + | ||
| 674 | + s->cores[s->ncores].core = (int)i; | ||
| 675 | + s->cores[s->ncores].pct = dt ? clamp_pct(100.0 - 100.0 * (double)di / (double)dt) : 0.0; | ||
| 676 | + s->ncores++; | ||
| 677 | + | ||
| 678 | + t_idle += di; | ||
| 679 | + t_total += dt; | ||
| 680 | + } | ||
| 681 | + s->cpu_pct = t_total ? clamp_pct(100.0 - 100.0 * (double)t_idle / (double)t_total) : 0.0; | ||
| 682 | + } | ||
| 683 | + | ||
| 684 | + if (cpu0) { | ||
| 685 | + vm_size_t freed = 0; | ||
| 686 | + (void)vm_deallocate(mach_task_self(), (vm_address_t)cpu0, | ||
| 687 | + (vm_size_t)(ncpu0 * CPU_STATE_MAX * sizeof(integer_t))); | ||
| 688 | + } | ||
| 689 | + if (cpu1) { | ||
| 690 | + vm_size_t freed = 0; | ||
| 691 | + (void)vm_deallocate(mach_task_self(), (vm_address_t)cpu1, | ||
| 692 | + (vm_size_t)(ncpu1 * CPU_STATE_MAX * sizeof(integer_t))); | ||
| 693 | + } | ||
| 694 | + | ||
| 695 | + sz = sizeof(total_mem); | ||
| 696 | + if (sysctlbyname("hw.memsize", &total_mem, &sz, NULL, 0) != 0) | ||
| 697 | + total_mem = 0; | ||
| 698 | + | ||
| 699 | + if (host_statistics64(mach_host_self(), HOST_VM_INFO64, | ||
| 700 | + (host_info64_t)&vm, &vmcount) == KERN_SUCCESS) { | ||
| 701 | + vm_size_t pagesz = 0; | ||
| 702 | + host_page_size(mach_host_self(), &pagesz); | ||
| 703 | + page_kb = (unsigned long long)(pagesz / 1024ULL); | ||
| 704 | + s->mem_total_kb = (double)(total_mem / 1024ULL); | ||
| 705 | + s->mem_free_kb = (double)(((unsigned long long)vm.free_count | ||
| 706 | + + (unsigned long long)vm.inactive_count | ||
| 707 | + + (unsigned long long)vm.speculative_count) * page_kb); | ||
| 708 | + s->mem_cached_kb = (double)((unsigned long long)vm.purgeable_count * page_kb); | ||
| 709 | + s->mem_used_kb = (double)(((unsigned long long)(vm.active_count | ||
| 710 | + + vm.wire_count) * page_kb)); | ||
| 711 | + } | ||
| 712 | + | ||
| 713 | + { | ||
| 714 | + struct xsw_usage xs; | ||
| 715 | + sz = sizeof(xs); | ||
| 716 | + if (sysctlbyname("vm.swapusage", &xs, &sz, NULL, 0) == 0) { | ||
| 717 | + s->swap_total_kb = (double)(xs.xsu_total / 1024ULL); | ||
| 718 | + s->swap_used_kb = (double)(xs.xsu_used / 1024ULL); | ||
| 719 | + } | ||
| 720 | + } | ||
| 721 | + | ||
| 722 | + sz = sizeof(boot); | ||
| 723 | + if (sysctlbyname("kern.boottime", &boot, &sz, NULL, 0) == 0) { | ||
| 724 | + time_t now = time(NULL); | ||
| 725 | + s->uptime_sec = (double)now - (double)boot.tv_sec; | ||
| 726 | + if (s->uptime_sec < 0.0) s->uptime_sec = 0.0; | ||
| 727 | + } | ||
| 728 | + | ||
| 729 | + { | ||
| 730 | + double loads[3]; | ||
| 731 | + if (getloadavg(loads, 3) == 3) { | ||
| 732 | + s->load1 = loads[0]; | ||
| 733 | + s->load5 = loads[1]; | ||
| 734 | + s->load15 = loads[2]; | ||
| 735 | + s->load_available = 1; | ||
| 736 | + } | ||
| 737 | + } | ||
| 738 | + | ||
| 739 | + /* Process list: the kernel exposes it most simply through ps. */ | ||
| 740 | + { | ||
| 741 | + FILE *fp = popen("ps -Ao pid=,pcpu=,rss=,comm=", "r"); | ||
| 742 | + if (fp) { | ||
| 743 | + char line[600]; | ||
| 744 | + s->nprocs = 0; | ||
| 745 | + while (fgets(line, sizeof(line), fp) && s->nprocs < MAX_PROCS) { | ||
| 746 | + long pid = 0; | ||
| 747 | + double pcpu = 0.0; | ||
| 748 | + long rss = 0; | ||
| 749 | + char comm[256]; | ||
| 750 | + if (sscanf(line, "%ld %lf %ld %255[^\n]", &pid, &pcpu, &rss, comm) != 4) | ||
| 751 | + continue; | ||
| 752 | + s->procs[s->nprocs].pid = pid; | ||
| 753 | + s->procs[s->nprocs].cpu = clamp_pct(pcpu); | ||
| 754 | + s->procs[s->nprocs].rss_kb = rss; | ||
| 755 | + s->procs[s->nprocs].state = 'R'; | ||
| 756 | + { | ||
| 757 | + const char *base = strrchr(comm, '/'); | ||
| 758 | + base = base ? base + 1 : comm; | ||
| 759 | + snprintf(s->procs[s->nprocs].name, sizeof(s->procs[s->nprocs].name), | ||
| 760 | + "%s", base); | ||
| 761 | + } | ||
| 762 | + s->nprocs++; | ||
| 763 | + } | ||
| 764 | + pclose(fp); | ||
| 765 | + } | ||
| 766 | + } | ||
| 767 | + | ||
| 768 | + s->ok = (s->ncores > 0 && s->mem_total_kb > 0.0); | ||
| 769 | + (void)tick_hz; | ||
| 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 | + li.QuadPart = GetTickCount64(); | ||
| 860 | + s->uptime_sec = (double)li.QuadPart / 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><style>", stdout); | ||
| 1104 | + | ||
| 1105 | + fputs( | ||
| 1106 | +":root{color-scheme:dark light;" | ||
| 1107 | + "--bg:#0b0b0e;--surface:#141419;--surface2:#1c1c22;--text:#f5f5f7;" | ||
| 1108 | + "--muted:#8e8e96;--line:rgba(255,255,255,.10);--accent:#0a84ff;" | ||
| 1109 | + "--ok:#30d158;--warn:#ffd60a;--danger:#ff453a;" | ||
| 1110 | + "--mono:ui-monospace,SFMono-Regular,Menlo,monospace}" | ||
| 1111 | +"html[data-theme=light]{--bg:#f2f2f6;--surface:#ffffff;--surface2:#f0f0f4;" | ||
| 1112 | + "--text:#1c1c1e;--muted:#6b6b73;--line:rgba(0,0,0,.10)}" | ||
| 1113 | +"*{box-sizing:border-box}" | ||
| 1114 | +"body{margin:0;padding:16px;background:var(--bg);color:var(--text);" | ||
| 1115 | + "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;" | ||
| 1116 | + "font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}" | ||
| 1117 | +".wrap{max-width:1120px;margin:0 auto}" | ||
| 1118 | +".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}" | ||
| 1119 | +".title{font-size:20px;font-weight:700;margin:0}" | ||
| 1120 | +".sub{color:var(--muted);font-size:12px;font-family:var(--mono)}" | ||
| 1121 | +".spacer{flex:1}" | ||
| 1122 | +".pill{font-size:11px;font-weight:600;padding:2px 9px;border-radius:999px;" | ||
| 1123 | + "background:var(--surface2);color:var(--muted);border:1px solid var(--line);white-space:nowrap}" | ||
| 1124 | +".pill.live{color:var(--ok);border-color:rgba(48,209,88,.4)}" | ||
| 1125 | +".pill.paused{color:var(--warn);border-color:rgba(255,214,10,.4)}" | ||
| 1126 | +".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;" | ||
| 1127 | + "padding:16px;margin-bottom:14px}" | ||
| 1128 | +".card h2{margin:0 0 12px;font-size:12px;letter-spacing:.06em;text-transform:uppercase;" | ||
| 1129 | + "color:var(--muted);font-weight:600}" | ||
| 1130 | +".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(132px,1fr));gap:10px}" | ||
| 1131 | +".kpi{background:var(--surface2);border:1px solid var(--line);border-radius:10px;padding:10px 12px;min-width:0}" | ||
| 1132 | +".kpi .k{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}" | ||
| 1133 | +".kpi .v{font-size:20px;font-weight:700;font-family:var(--mono);margin-top:2px;" | ||
| 1134 | + "overflow:hidden;text-overflow:ellipsis;white-space:nowrap}" | ||
| 1135 | +"button{background:var(--accent);color:#fff;border:0;border-radius:999px;" | ||
| 1136 | + "padding:6px 13px;font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}" | ||
| 1137 | +"button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}" | ||
| 1138 | +"button.on{background:var(--accent);color:#fff;border-color:transparent}" | ||
| 1139 | +"button:active{transform:scale(.98)}" | ||
| 1140 | +".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}" | ||
| 1141 | +".seg{display:inline-flex;gap:4px;background:var(--surface2);border:1px solid var(--line);" | ||
| 1142 | + "border-radius:999px;padding:3px}" | ||
| 1143 | +".seg button{background:transparent;color:var(--muted);border:0;padding:4px 11px;font-size:12px}" | ||
| 1144 | +".seg button.on{background:var(--accent);color:#fff}" | ||
| 1145 | +".cores{display:grid;grid-template-columns:repeat(auto-fill,minmax(86px,1fr));gap:8px}" | ||
| 1146 | +".core{background:var(--surface2);border:1px solid var(--line);border-radius:9px;padding:7px 8px}" | ||
| 1147 | +".core .lbl{font-size:10px;color:var(--muted);font-family:var(--mono)}" | ||
| 1148 | +".core .bar{height:6px;border-radius:3px;background:rgba(255,255,255,.10);margin:5px 0 4px;overflow:hidden}" | ||
| 1149 | +".core .fill{height:100%;background:var(--ok);border-radius:3px;transition:width .35s}" | ||
| 1150 | +".core .pc{font-size:11px;font-family:var(--mono);font-weight:600}" | ||
| 1151 | +".gauge{height:10px;border-radius:5px;background:rgba(255,255,255,.10);overflow:hidden;margin:6px 0 4px}" | ||
| 1152 | +".gauge .fill{height:100%;border-radius:5px;transition:width .35s;background:var(--accent)}" | ||
| 1153 | +".glabel{display:flex;justify-content:space-between;font-size:11px;color:var(--muted);" | ||
| 1154 | + "font-family:var(--mono)}" | ||
| 1155 | +"svg.spark{display:block;width:100%;height:64px}" | ||
| 1156 | +"table{width:100%;border-collapse:collapse;font-size:13px}" | ||
| 1157 | +"th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.05em;" | ||
| 1158 | + "color:var(--muted);font-weight:600;padding:6px 8px;border-bottom:1px solid var(--line);" | ||
| 1159 | + "white-space:nowrap}" | ||
| 1160 | +"th.num,td.num{text-align:right;font-family:var(--mono)}" | ||
| 1161 | +"td{padding:6px 8px;border-bottom:1px solid var(--line);vertical-align:middle}" | ||
| 1162 | +"td.nm{font-family:var(--mono);font-size:12px;word-break:break-all}" | ||
| 1163 | +"tr:last-child td{border-bottom:0}" | ||
| 1164 | +".tblwrap{overflow-x:auto}" | ||
| 1165 | +"input{background:var(--surface2);border:1px solid var(--line);border-radius:10px;" | ||
| 1166 | + "padding:7px 11px;color:var(--text);font-size:13px;font-family:var(--mono);" | ||
| 1167 | + "min-width:130px;flex:1}" | ||
| 1168 | +"input:focus{outline:2px solid var(--accent);outline-offset:-1px}" | ||
| 1169 | +".hide{display:none!important}" | ||
| 1170 | +".muted{color:var(--muted)}" | ||
| 1171 | +"@media(max-width:640px){" | ||
| 1172 | + "body{padding:12px}" | ||
| 1173 | + ".kpi .v{font-size:17px}" | ||
| 1174 | + "th.hide-sm,td.hide-sm{display:none}" | ||
| 1175 | + ".card{padding:12px;border-radius:12px}" | ||
| 1176 | + ".cores{grid-template-columns:repeat(auto-fill,minmax(72px,1fr))}" | ||
| 1177 | +"}", stdout); | ||
| 1178 | + | ||
| 1179 | + fputs("</style></head><body><div class='wrap'>", stdout); | ||
| 1180 | + | ||
| 1181 | + if (!embed) { | ||
| 1182 | + fputs("<div class='top'><a href='/' style='color:var(--accent);" | ||
| 1183 | + "text-decoration:none;font-weight:600'>← Back to Bot</a></div>", stdout); | ||
| 1184 | + } | ||
| 1185 | + | ||
| 1186 | + fputs("<div class='top'>" | ||
| 1187 | + "<h1 class='title'>sysmon</h1>" | ||
| 1188 | + "<span class='pill' id='pHost'>—</span>" | ||
| 1189 | + "<span class='pill' id='pPlatform'>—</span>" | ||
| 1190 | + "<span class='spacer'></span>" | ||
| 1191 | + "<span class='pill live' id='pState'>live 2s</span>" | ||
| 1192 | + "<div class='seg' id='segRate'>" | ||
| 1193 | + "<button type='button' data-ms='2000' class='on'>2s</button>" | ||
| 1194 | + "<button type='button' data-ms='5000'>5s</button>" | ||
| 1195 | + "<button type='button' data-ms='0'>Pause</button>" | ||
| 1196 | + "</div></div>", stdout); | ||
| 1197 | + | ||
| 1198 | + /* KPI row */ | ||
| 1199 | + fputs("<div class='card'><h2>System</h2><div class='grid'>" | ||
| 1200 | + "<div class='kpi'><div class='k'>cpu</div><div class='v' id='kCpu'>—</div></div>" | ||
| 1201 | + "<div class='kpi'><div class='k'>cores</div><div class='v' id='kCores'>—</div></div>" | ||
| 1202 | + "<div class='kpi'><div class='k'>memory</div><div class='v' id='kMem'>—</div></div>" | ||
| 1203 | + "<div class='kpi'><div class='k'>swap</div><div class='v' id='kSwap'>—</div></div>" | ||
| 1204 | + "<div class='kpi'><div class='k'>load 1m</div><div class='v' id='kLoad'>—</div></div>" | ||
| 1205 | + "<div class='kpi'><div class='k'>uptime</div><div class='v' id='kUp'>—</div></div>" | ||
| 1206 | + "<div class='kpi'><div class='k'>processes</div><div class='v' id='kProc'>—</div></div>" | ||
| 1207 | + "</div>" | ||
| 1208 | + "<div class='sub' id='cpuModel' style='margin-top:10px'></div></div>", stdout); | ||
| 1209 | + | ||
| 1210 | + /* history sparkline */ | ||
| 1211 | + fputs("<div class='card'><h2>CPU history</h2>" | ||
| 1212 | + "<svg class='spark' id='spark' viewBox='0 0 600 64' preserveAspectRatio='none'>" | ||
| 1213 | + "<polyline id='sparkLine' fill='none' stroke='#0a84ff' stroke-width='2' " | ||
| 1214 | + "stroke-linejoin='round' stroke-linecap='round' points=''/>" | ||
| 1215 | + "</svg></div>", stdout); | ||
| 1216 | + | ||
| 1217 | + /* per-core */ | ||
| 1218 | + fputs("<div class='card'><h2>Per-core utilization</h2>" | ||
| 1219 | + "<div class='cores' id='cores'></div>" | ||
| 1220 | + "<div class='muted' id='coreNote' style='margin-top:10px'></div></div>", stdout); | ||
| 1221 | + | ||
| 1222 | + /* memory + swap gauges */ | ||
| 1223 | + fputs("<div class='card'><h2>Memory & swap</h2>" | ||
| 1224 | + "<div class='glabel'><span>memory</span><span id='memLbl'>—</span></div>" | ||
| 1225 | + "<div class='gauge'><div class='fill' id='memFill' style='width:0'></div></div>" | ||
| 1226 | + "<div class='glabel' style='margin-top:12px'><span>swap</span><span id='swapLbl'>—</span></div>" | ||
| 1227 | + "<div class='gauge'><div class='fill' id='swapFill' style='width:0;background:var(--warn)'></div></div>" | ||
| 1228 | + "<div class='sub' id='memDetail' style='margin-top:10px'></div></div>", stdout); | ||
| 1229 | + | ||
| 1230 | + /* processes */ | ||
| 1231 | + fputs("<div class='card'><h2>Top processes</h2>" | ||
| 1232 | + "<div class='row'>" | ||
| 1233 | + "<input id='q' type='text' placeholder='filter by name or pid'>" | ||
| 1234 | + "<div class='seg' id='segSort'>" | ||
| 1235 | + "<button type='button' data-sort='cpu' class='on'>CPU</button>" | ||
| 1236 | + "<button type='button' data-sort='mem'>Memory</button>" | ||
| 1237 | + "</div></div>" | ||
| 1238 | + "<div class='tblwrap'><table><thead><tr>" | ||
| 1239 | + "<th class='num'>PID</th><th>Name</th>" | ||
| 1240 | + "<th class='num'>CPU %</th><th class='num'>RSS</th>" | ||
| 1241 | + "<th class='hide-sm'>State</th>" | ||
| 1242 | + "</tr></thead><tbody id='rows'></tbody></table></div>" | ||
| 1243 | + "<div id='empty' class='muted hide'>No matching processes.</div></div>", stdout); | ||
| 1244 | + | ||
| 1245 | + fputs("<div class='card'><h2>About this plugin</h2>" | ||
| 1246 | + "<p class='muted' style='margin:0 0 8px'>Local node only. Reads the kernel's " | ||
| 1247 | + "own counters (<code>/proc</code> on Linux, mach and <code>sysctl</code> on macOS, " | ||
| 1248 | + "Win32 APIs on Windows) and makes zero outbound network requests.</p>" | ||
| 1249 | + "<p class='muted' style='margin:0'>Two CPU samples " | ||
| 1250 | + "80 ms apart give a live percentage; nothing is cached between requests " | ||
| 1251 | + "and no shell command comes from user input.</p></div>", stdout); | ||
| 1252 | + | ||
| 1253 | + /* script */ | ||
| 1254 | + fputs("<script>\n" | ||
| 1255 | +"(function(){\n" | ||
| 1256 | +" var q = new URLSearchParams(location.search);\n" | ||
| 1257 | +" var HUB = q.get('plugin') || '';\n" | ||
| 1258 | +" var node = q.get('node') || '';\n" | ||
| 1259 | +" var sid = q.get('id') || '';\n" | ||
| 1260 | +" var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n" | ||
| 1261 | +" localStorage.getItem('bot_active_pwd') || '';\n" | ||
| 1262 | +"\n" | ||
| 1263 | +" /* Two routes, and getting this wrong is the classic plugin bug:\n" | ||
| 1264 | +" page served through the hub -> call the hub proxy back\n" | ||
| 1265 | +" page opened directly on node -> the plugin IS the route */\n" | ||
| 1266 | +" function base(){ return HUB ? '/plugins?plugin=' + HUB : '/plugin_sysmon'; }\n" | ||
| 1267 | +" function withCtx(u){\n" | ||
| 1268 | +" if (node) u += '&node=' + encodeURIComponent(node);\n" | ||
| 1269 | +" if (sid) u += '&id=' + encodeURIComponent(sid);\n" | ||
| 1270 | +" if (pwd) u += '&pwd=' + encodeURIComponent(pwd);\n" | ||
| 1271 | +" return u;\n" | ||
| 1272 | +" }\n" | ||
| 1273 | +" function hdr(){ return pwd ? {'X-Bot-Password': pwd} : {}; }\n" | ||
| 1274 | +" function $(id){ return document.getElementById(id); }\n" | ||
| 1275 | +" function el(tag, cls, text){\n" | ||
| 1276 | +" var e = document.createElement(tag);\n" | ||
| 1277 | +" if (cls) e.className = cls;\n" | ||
| 1278 | +" if (text !== undefined && text !== null) e.textContent = String(text);\n" | ||
| 1279 | +" return e;\n" | ||
| 1280 | +" }\n" | ||
| 1281 | +" function txt(id, v){\n" | ||
| 1282 | +" var e = $(id); if (!e) return;\n" | ||
| 1283 | +" e.textContent = (v === undefined || v === null || v === '') ? '\\u2014' : String(v);\n" | ||
| 1284 | +" }\n" | ||
| 1285 | +"\n" | ||
| 1286 | +" document.documentElement.setAttribute('data-theme',\n" | ||
| 1287 | +" localStorage.getItem('bot_theme') || 'dark');\n" | ||
| 1288 | +"\n" | ||
| 1289 | +"\n" | ||
| 1290 | +" var RATE = 2000, TIMER = null, BUSY = false;\n" | ||
| 1291 | +" var HISTORY = [], HIST_MAX = 60;\n" | ||
| 1292 | +" var SORT = 'cpu';\n" | ||
| 1293 | +" var DATA = null;\n" | ||
| 1294 | +"\n" | ||
| 1295 | +" function kb(v){\n" | ||
| 1296 | +" if (!v && v !== 0) return '\\u2014';\n" | ||
| 1297 | +" if (v >= 1048576) return (v / 1048576).toFixed(1) + ' GiB';\n" | ||
| 1298 | +" if (v >= 1024) return (v / 1024).toFixed(0) + ' MiB';\n" | ||
| 1299 | +" return v + ' KiB';\n" | ||
| 1300 | +" }\n" | ||
| 1301 | +" function dur(sec){\n" | ||
| 1302 | +" if (!sec && sec !== 0) return '\\u2014';\n" | ||
| 1303 | +" var d = Math.floor(sec / 86400), h = Math.floor((sec % 86400) / 3600),\n" | ||
| 1304 | +" m = Math.floor((sec % 3600) / 60);\n" | ||
| 1305 | +" if (d > 0) return d + 'd ' + h + 'h';\n" | ||
| 1306 | +" if (h > 0) return h + 'h ' + m + 'm';\n" | ||
| 1307 | +" return m + 'm';\n" | ||
| 1308 | +" }\n" | ||
| 1309 | +" function pctColor(p){\n" | ||
| 1310 | +" if (p >= 85) return 'var(--danger)';\n" | ||
| 1311 | +" if (p >= 60) return 'var(--warn)';\n" | ||
| 1312 | +" return 'var(--ok)';\n" | ||
| 1313 | +" }\n" | ||
| 1314 | +"\n" | ||
| 1315 | +" function renderCores(d){\n" | ||
| 1316 | +" var host = $('cores');\n" | ||
| 1317 | +" host.innerHTML = '';\n" | ||
| 1318 | +" if (!d.cores || !d.cores.length){\n" | ||
| 1319 | +" $('coreNote').textContent = 'Per-core detail is available on Linux and macOS nodes; ' +\n" | ||
| 1320 | +" 'this platform exposes an aggregate CPU figure only.';\n" | ||
| 1321 | +" return;\n" | ||
| 1322 | +" }\n" | ||
| 1323 | +" $('coreNote').textContent = '';\n" | ||
| 1324 | +" for (var i = 0; i < d.cores.length; i++){\n" | ||
| 1325 | +" var c = d.cores[i];\n" | ||
| 1326 | +" var box = el('div','core');\n" | ||
| 1327 | +" box.appendChild(el('div','lbl','cpu ' + c.core));\n" | ||
| 1328 | +" var bar = el('div','bar'), fill = el('div','fill');\n" | ||
| 1329 | +" fill.style.width = Math.max(0, Math.min(100, c.pct)) + '%';\n" | ||
| 1330 | +" fill.style.background = pctColor(c.pct);\n" | ||
| 1331 | +" bar.appendChild(fill);\n" | ||
| 1332 | +" box.appendChild(bar);\n" | ||
| 1333 | +" box.appendChild(el('div','pc', c.pct.toFixed(0) + '%'));\n" | ||
| 1334 | +" host.appendChild(box);\n" | ||
| 1335 | +" }\n" | ||
| 1336 | +" }\n" | ||
| 1337 | +"\n" | ||
| 1338 | +" function renderSpark(v){\n" | ||
| 1339 | +" HISTORY.push(Math.max(0, Math.min(100, v)));\n" | ||
| 1340 | +" if (HISTORY.length > HIST_MAX) HISTORY.shift();\n" | ||
| 1341 | +" if (HISTORY.length < 2) return;\n" | ||
| 1342 | +" var pts = [];\n" | ||
| 1343 | +" for (var i = 0; i < HISTORY.length; i++){\n" | ||
| 1344 | +" var x = (i / (HISTORY.length - 1)) * 600;\n" | ||
| 1345 | +" var y = 62 - (HISTORY[i] / 100) * 58;\n" | ||
| 1346 | +" pts.push(x.toFixed(1) + ',' + y.toFixed(1));\n" | ||
| 1347 | +" }\n" | ||
| 1348 | +" $('sparkLine').setAttribute('points', pts.join(' '));\n" | ||
| 1349 | +" }\n" | ||
| 1350 | +"\n" | ||
| 1351 | +" function renderProcs(){\n" | ||
| 1352 | +" if (!DATA) return;\n" | ||
| 1353 | +" var filter = ($('q').value || '').toLowerCase();\n" | ||
| 1354 | +" var body = $('rows');\n" | ||
| 1355 | +" body.innerHTML = '';\n" | ||
| 1356 | +" var shown = 0;\n" | ||
| 1357 | +" for (var i = 0; i < DATA.processes.length; i++){\n" | ||
| 1358 | +" var p = DATA.processes[i];\n" | ||
| 1359 | +" var hay = (p.name + ' ' + p.pid).toLowerCase();\n" | ||
| 1360 | +" if (filter && hay.indexOf(filter) < 0) continue;\n" | ||
| 1361 | +" var tr = el('tr');\n" | ||
| 1362 | +" tr.appendChild(el('td','num', p.pid));\n" | ||
| 1363 | +" tr.appendChild(el('td','nm', p.name || '\\u2014'));\n" | ||
| 1364 | +" tr.appendChild(el('td','num', p.cpu.toFixed(1)));\n" | ||
| 1365 | +" tr.appendChild(el('td','num', kb(p.rss_kb)));\n" | ||
| 1366 | +" var td = el('td','hide-sm', p.state || '\\u2014');\n" | ||
| 1367 | +" tr.appendChild(td);\n" | ||
| 1368 | +" body.appendChild(tr);\n" | ||
| 1369 | +" shown++;\n" | ||
| 1370 | +" }\n" | ||
| 1371 | +" if (shown) $('empty').classList.add('hide');\n" | ||
| 1372 | +" else $('empty').classList.remove('hide');\n" | ||
| 1373 | +" }\n" | ||
| 1374 | +"\n" | ||
| 1375 | +" function render(d){\n" | ||
| 1376 | +" DATA = d;\n" | ||
| 1377 | +" txt('pHost', d.host);\n" | ||
| 1378 | +" txt('pPlatform', d.platform);\n" | ||
| 1379 | +" txt('cpuModel', d.cpu_model);\n" | ||
| 1380 | +" txt('kCpu', d.cpu_pct.toFixed(1) + '%');\n" | ||
| 1381 | +" txt('kCores', d.ncores || '\\u2014');\n" | ||
| 1382 | +" txt('kMem', (d.mem.pct).toFixed(0) + '%');\n" | ||
| 1383 | +" txt('kSwap', d.swap.total_kb > 0 ? d.swap.pct.toFixed(0) + '%' : 'none');\n" | ||
| 1384 | +" txt('kLoad', d.load.available ? d.load.load1.toFixed(2) : 'n/a');\n" | ||
| 1385 | +" txt('kUp', dur(d.uptime_sec));\n" | ||
| 1386 | +" txt('kProc', d.proc_count);\n" | ||
| 1387 | +"\n" | ||
| 1388 | +" $('memFill').style.width = Math.max(0, Math.min(100, d.mem.pct)) + '%';\n" | ||
| 1389 | +" txt('memLbl', kb(d.mem.used_kb) + ' / ' + kb(d.mem.total_kb));\n" | ||
| 1390 | +" txt('memDetail', 'free ' + kb(d.mem.free_kb) +\n" | ||
| 1391 | +" (d.mem.cached_kb > 0 ? ' \\u00b7 cached ' + kb(d.mem.cached_kb) : ''));\n" | ||
| 1392 | +" $('swapFill').style.width = d.swap.total_kb > 0\n" | ||
| 1393 | +" ? Math.max(0, Math.min(100, d.swap.pct)) + '%' : '0%';\n" | ||
| 1394 | +" txt('swapLbl', d.swap.total_kb > 0\n" | ||
| 1395 | +" ? kb(d.swap.used_kb) + ' / ' + kb(d.swap.total_kb) : 'no swap');\n" | ||
| 1396 | +"\n" | ||
| 1397 | +" renderSpark(d.cpu_pct);\n" | ||
| 1398 | +" renderCores(d);\n" | ||
| 1399 | +" renderProcs();\n" | ||
| 1400 | +" }\n" | ||
| 1401 | +"\n" | ||
| 1402 | +" function fail(msg){\n" | ||
| 1403 | +" $('pState').textContent = 'error';\n" | ||
| 1404 | +" $('pState').className = 'pill paused';\n" | ||
| 1405 | +" txt('coreNote', msg);\n" | ||
| 1406 | +" }\n" | ||
| 1407 | +"\n" | ||
| 1408 | +" function poll(){\n" | ||
| 1409 | +" if (BUSY) return;\n" | ||
| 1410 | +" BUSY = true;\n" | ||
| 1411 | +" var u = withCtx(base() + '?action=metrics&sort=' + encodeURIComponent(SORT));\n" | ||
| 1412 | +" fetch(u, { headers: hdr(), cache: 'no-store' })\n" | ||
| 1413 | +" .then(function(r){ return r.json(); })\n" | ||
| 1414 | +" .then(function(d){\n" | ||
| 1415 | +" if (!d || d.ok === false){ fail((d && d.message) || 'sample failed'); return; }\n" | ||
| 1416 | +" render(d);\n" | ||
| 1417 | +" })\n" | ||
| 1418 | +" .catch(function(e){ fail('request failed: ' + e); })\n" | ||
| 1419 | +" .then(function(){ BUSY = false; });\n" | ||
| 1420 | +" }\n" | ||
| 1421 | +"\n" | ||
| 1422 | +" function schedule(){\n" | ||
| 1423 | +" if (TIMER) { clearInterval(TIMER); TIMER = null; }\n" | ||
| 1424 | +" var st = $('pState');\n" | ||
| 1425 | +" if (RATE > 0){\n" | ||
| 1426 | +" TIMER = setInterval(poll, RATE);\n" | ||
| 1427 | +" st.textContent = 'live ' + (RATE / 1000) + 's';\n" | ||
| 1428 | +" st.className = 'pill live';\n" | ||
| 1429 | +" } else {\n" | ||
| 1430 | +" st.textContent = 'paused';\n" | ||
| 1431 | +" st.className = 'pill paused';\n" | ||
| 1432 | +" }\n" | ||
| 1433 | +" }\n" | ||
| 1434 | +"\n" | ||
| 1435 | +" Array.prototype.forEach.call(document.querySelectorAll('#segRate button'), function(b){\n" | ||
| 1436 | +" b.addEventListener('click', function(){\n" | ||
| 1437 | +" Array.prototype.forEach.call(document.querySelectorAll('#segRate button'),\n" | ||
| 1438 | +" function(x){ x.classList.remove('on'); });\n" | ||
| 1439 | +" b.classList.add('on');\n" | ||
| 1440 | +" RATE = parseInt(b.getAttribute('data-ms'), 10) || 0;\n" | ||
| 1441 | +" schedule();\n" | ||
| 1442 | +" if (RATE > 0) poll();\n" | ||
| 1443 | +" });\n" | ||
| 1444 | +" });\n" | ||
| 1445 | +"\n" | ||
| 1446 | +" Array.prototype.forEach.call(document.querySelectorAll('#segSort button'), function(b){\n" | ||
| 1447 | +" b.addEventListener('click', function(){\n" | ||
| 1448 | +" Array.prototype.forEach.call(document.querySelectorAll('#segSort button'),\n" | ||
| 1449 | +" function(x){ x.classList.remove('on'); });\n" | ||
| 1450 | +" b.classList.add('on');\n" | ||
| 1451 | +" SORT = b.getAttribute('data-sort') || 'cpu';\n" | ||
| 1452 | +" poll();\n" | ||
| 1453 | +" });\n" | ||
| 1454 | +" });\n" | ||
| 1455 | +"\n" | ||
| 1456 | +" $('q').addEventListener('input', renderProcs);\n" | ||
| 1457 | +" if (document.visibilityState === 'visible') poll();\n" | ||
| 1458 | +" document.addEventListener('visibilitychange', function(){\n" | ||
| 1459 | +" if (document.visibilityState === 'visible') poll();\n" | ||
| 1460 | +" });\n" | ||
| 1461 | +" schedule();\n" | ||
| 1462 | +"})();\n" | ||
| 1463 | +"</script></div></body></html>\n", stdout); | ||
| 1464 | + | ||
| 1465 | + return 0; | ||
| 1466 | +} | ||
| 1467 | + | ||
| 1468 | +/* ------------------------------------------------------------------ */ | ||
| 1469 | +/* Entry point */ | ||
| 1470 | +/* ------------------------------------------------------------------ */ | ||
| 1471 | + | ||
| 1472 | +int main(int argc, char **argv) | ||
| 1473 | +{ | ||
| 1474 | + const char *qs; | ||
| 1475 | + const char *method; | ||
| 1476 | + int i; | ||
| 1477 | + | ||
| 1478 | + for (i = 1; i < argc; i++) { | ||
| 1479 | + if (strcmp(argv[i], "--meta") == 0) | ||
| 1480 | + return mode_meta(); | ||
| 1481 | + if (strcmp(argv[i], "--version") == 0) { | ||
| 1482 | + printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); | ||
| 1483 | + return 0; | ||
| 1484 | + } | ||
| 1485 | + if (strcmp(argv[i], "--help") == 0) { | ||
| 1486 | + printf("usage: %s [--meta] [--version] [--help]\n" | ||
| 1487 | + " CGI mode reads QUERY_STRING:\n" | ||
| 1488 | + " ?format=json | ?action=metrics JSON system snapshot\n" | ||
| 1489 | + " ?action=info plugin info\n" | ||
| 1490 | + " (no action) HTML dashboard\n", PLUGIN_ID); | ||
| 1491 | + return 0; | ||
| 1492 | + } | ||
| 1493 | + } | ||
| 1494 | + | ||
| 1495 | + if (getenv("SX_PLUGIN_META")) | ||
| 1496 | + return mode_meta(); | ||
| 1497 | + | ||
| 1498 | + require_node_auth(); | ||
| 1499 | + | ||
| 1500 | + qs = getenv("QUERY_STRING"); | ||
| 1501 | + if (!qs) qs = ""; | ||
| 1502 | + method = getenv("REQUEST_METHOD"); | ||
| 1503 | + if (!method) method = "GET"; | ||
| 1504 | + | ||
| 1505 | + if (strstr(qs, "action=") || strstr(qs, "format=json")) | ||
| 1506 | + return mode_json(qs); | ||
| 1507 | + | ||
| 1508 | + { | ||
| 1509 | + char embedv[16]; | ||
| 1510 | + embedv[0] = '\0'; | ||
| 1511 | + if (get_query_val(qs, "embed", embedv, sizeof(embedv))) | ||
| 1512 | + return mode_html(strcmp(embedv, "1") == 0 || strcmp(embedv, "true") == 0); | ||
| 1513 | + } | ||
| 1514 | + return mode_html(0); | ||
| 1515 | +} | ||
| 0 | 1516 |