| 1 | 1 | new file mode 100644 |
| index 0000000..8568772 | ||
| --- /dev/null | ||
| +++ b/.gitignore | ||
| @@ -0,0 +1,13 @@ | ||
| 1 | +/plugin_nvtop | |
| 2 | +/plugin_nvtop.exe | |
| 3 | +*.o | |
| 4 | +*.obj | |
| 5 | +bin/ | |
| 6 | +*.tmp | |
| 7 | +*.log | |
| 8 | +/plugin_nvtop.musl | |
| 9 | +/plugin_nvtop.arm64 | |
| 10 | +/plugin_nvtop.macos-* | |
| 11 | +__pycache__/ | |
| 12 | +*.pyc | |
| 13 | +tests/fixtures/*.tmp |
| 1 | 1 | new file mode 100644 |
| index 0000000..ef80120 | ||
| --- /dev/null | ||
| +++ b/LICENSE | ||
| @@ -0,0 +1,21 @@ | ||
| 1 | +MIT License | |
| 2 | + | |
| 3 | +Copyright (c) 2026 SCORPIOX INC | |
| 4 | + | |
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 6 | +of this software and associated documentation files (the "Software"), to deal | |
| 7 | +in the Software without restriction, including without limitation the rights | |
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 9 | +copies of the Software, and to permit persons to whom the Software is | |
| 10 | +furnished to do so, subject to the following conditions: | |
| 11 | + | |
| 12 | +The above copyright notice and this permission notice shall be included in all | |
| 13 | +copies or substantial portions of the Software. | |
| 14 | + | |
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 21 | +SOFTWARE. |
| 1 | 1 | new file mode 100644 |
| index 0000000..78cf14a | ||
| --- /dev/null | ||
| +++ b/Makefile | ||
| @@ -0,0 +1,65 @@ | ||
| 1 | +# plugin_nvtop - ScorpioX Bot open-source local GPU telemetry plugin | |
| 2 | +# | |
| 3 | +# Targets: | |
| 4 | +# make native build -> ./plugin_nvtop | |
| 5 | +# make musl static musl x86_64 -> ./plugin_nvtop (fully static) | |
| 6 | +# make arm64 static musl aarch64 -> ./plugin_nvtop.arm64 | |
| 7 | +# make win64 MinGW-w64 static -> ./plugin_nvtop.exe | |
| 8 | +# make macos Apple clang -> ./plugin_nvtop (run on macOS) | |
| 9 | +# make test build + run tests/run.sh | |
| 10 | +# make clean | |
| 11 | + | |
| 12 | +CC ?= cc | |
| 13 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings | |
| 14 | +MUSL_CC ?= musl-gcc | |
| 15 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings | |
| 16 | +ARM64_CC ?= $(shell command -v aarch64-linux-musl-gcc 2>/dev/null || \ | |
| 17 | + command -v aarch64-linux-gnu-gcc 2>/dev/null || \ | |
| 18 | + echo aarch64-linux-musl-gcc) | |
| 19 | +ARM64_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings | |
| 20 | +WIN_CC ?= x86_64-w64-mingw32-gcc | |
| 21 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings | |
| 22 | +SRC := src/plugin_nvtop.c | |
| 23 | +BIN := plugin_nvtop | |
| 24 | +EXE := plugin_nvtop.exe | |
| 25 | + | |
| 26 | +.PHONY: all native musl arm64 win64 macos test clean help | |
| 27 | + | |
| 28 | +all: native | |
| 29 | + | |
| 30 | +native: $(BIN) | |
| 31 | + | |
| 32 | +$(BIN): $(SRC) | |
| 33 | + @echo "==> native build ($(CC))" | |
| 34 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | |
| 35 | + | |
| 36 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | |
| 37 | +musl: $(SRC) | |
| 38 | + @echo "==> static musl build ($(MUSL_CC))" | |
| 39 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN) $(SRC) | |
| 40 | + | |
| 41 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | |
| 42 | +arm64: $(SRC) | |
| 43 | + @echo "==> static arm64 build ($(ARM64_CC))" | |
| 44 | + $(ARM64_CC) $(ARM64_CFLAGS) -o $(BIN).arm64 $(SRC) | |
| 45 | + | |
| 46 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | |
| 47 | +win64: $(SRC) | |
| 48 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | |
| 49 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) | |
| 50 | + | |
| 51 | +# Apple clang build (run this on macOS) | |
| 52 | +macos: $(SRC) | |
| 53 | + @echo "==> Apple clang build" | |
| 54 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | |
| 55 | + | |
| 56 | +test: native | |
| 57 | + @sh tests/run.sh | |
| 58 | + | |
| 59 | +clean: | |
| 60 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 \ | |
| 61 | + $(BIN).macos-arm64 $(BIN).macos-x86_64 | |
| 62 | + rm -rf bin | |
| 63 | + | |
| 64 | +help: | |
| 65 | + @echo "make | make musl | make arm64 | make win64 | make macos | make test | make clean" |
| 1 | 1 | new file mode 100644 |
| index 0000000..267a64b | ||
| --- /dev/null | ||
| +++ b/README.md | ||
| @@ -0,0 +1,151 @@ | ||
| 1 | +# plugin_nvtop | |
| 2 | + | |
| 3 | +A zero-dependency **C99** local GPU telemetry plugin for ScorpioX Bot nodes. One | |
| 4 | +binary, three modes, no runtime dependencies, no outbound network requests. | |
| 5 | + | |
| 6 | +It answers the question an operator actually asks about a machine: | |
| 7 | + | |
| 8 | +> **What are the GPUs doing right now, and which processes are using them?** | |
| 9 | + | |
| 10 | +Everything is read from the machine the plugin is installed on. Nothing is sent | |
| 11 | +anywhere. | |
| 12 | + | |
| 13 | +## What it reports | |
| 14 | + | |
| 15 | +| Mode | Output | | |
| 16 | +|---|---| | |
| 17 | +| `--meta` | `{"name":"nvtop","desc":"Local GPUs"}` — discovery metadata | | |
| 18 | +| `?action=metrics` | Every local GPU: index, UUID, product name, compute utilisation %, VRAM used/total MB, temperature, power draw and power limit; plus every compute process with its GPU UUID, GPU index, PID, name and VRAM | | |
| 19 | +| `?action=info` | Plugin version, platform, PID, auth state, supported actions, the probes it runs and the largest GPU count it will report | | |
| 20 | +| `?format=json` | Alias for `action=metrics` | | |
| 21 | +| `GET` (default) | Responsive dark/light HTML dashboard, `?embed=1` aware | | |
| 22 | + | |
| 23 | +The dashboard renders one card per GPU with an orange **compute %** rolling | |
| 24 | +sparkline and a blue **VRAM** sparkline (60 samples, polled every 2 s), power and | |
| 25 | +thermal chips that turn amber past 70 °C and red past 85 °C, and a compute | |
| 26 | +process table with GPU / PID / process / VRAM. It pauses polling when the tab is | |
| 27 | +hidden. | |
| 28 | + | |
| 29 | +## Where the numbers come from | |
| 30 | + | |
| 31 | +| Platform | Probe | Notes | | |
| 32 | +|---|---|---| | |
| 33 | +| NVIDIA (any OS) | `nvidia-smi --query-gpu=index,uuid,name,utilization.gpu,memory.used,memory.total,temperature.gpu,power.draw,power.limit,driver_version --format=csv,noheader,nounits` | plus `--query-compute-apps=gpu_uuid,pid,process_name,used_memory` | | |
| 34 | +| AMD (Linux) | `rocm-smi --showproductname --showuse --showmeminfo vram --showtemp --showpower` | VRAM is reported in bytes and converted to MB | | |
| 35 | +| Apple Silicon (macOS) | `ioreg -rc IOAccelerator -d 1` | `Device Utilization %` and `In use system memory` | | |
| 36 | + | |
| 37 | +Every one of those command strings is a **compile-time constant**. Nothing from | |
| 38 | +the query string, and nothing from the environment except the mock path, is ever | |
| 39 | +passed to a shell. | |
| 40 | + | |
| 41 | +`nvidia-smi` prints `N/A` or `[N/A]` for counters a card does not support. Those | |
| 42 | +become JSON `null` and `—` in the UI rather than a zero that looks like data. | |
| 43 | + | |
| 44 | +## CPU-only nodes | |
| 45 | + | |
| 46 | +On a machine with no local GPU the plugin does not error. It answers: | |
| 47 | + | |
| 48 | +```json | |
| 49 | +{"ok":true,"available":false,"source":"none","count":0,"gpus":[],"processes":[], | |
| 50 | + "message":"No local NVIDIA/AMD GPU detected"} | |
| 51 | +``` | |
| 52 | + | |
| 53 | +and the dashboard shows a clean explanatory panel — including how to customize | |
| 54 | +`src/plugin_nvtop.c` if you want to monitor a **remote** GPU rig from this node. | |
| 55 | +That is the honest state for most of a fleet, and it is a first-class UI state, | |
| 56 | +not a failure. | |
| 57 | + | |
| 58 | +## Deterministic offline testing: `NVTOP_MOCK_CSV` | |
| 59 | + | |
| 60 | +A build box usually has no GPU, so the tests must not depend on one. There are | |
| 61 | +three environment hooks, each gated to a fixture path you provide: | |
| 62 | + | |
| 63 | +```bash | |
| 64 | +# Invented one-line-per-record format (see the header of tests/fixtures/mock-4gpu.csv) | |
| 65 | +NVTOP_MOCK_CSV=tests/fixtures/mock-4gpu.csv QUERY_STRING='action=metrics' ./plugin_nvtop | |
| 66 | + | |
| 67 | +# Real nvidia-smi csv,noheader layout, with "APP," lines for compute processes | |
| 68 | +NVTOP_MOCK_NVIDIA=tests/fixtures/nvidia-4gpu.csv QUERY_STRING='action=metrics' ./plugin_nvtop | |
| 69 | + | |
| 70 | +# Real rocm-smi "GPU[n] : key: value" text layout | |
| 71 | +NVTOP_MOCK_ROCM=tests/fixtures/rocm-1gpu.txt QUERY_STRING='action=metrics' ./plugin_nvtop | |
| 72 | +``` | |
| 73 | + | |
| 74 | +The `NVTOP_MOCK_CSV` record format: | |
| 75 | + | |
| 76 | +``` | |
| 77 | +GPU,<index>,<uuid>,<name>,<util%>,<mem_used_mb>,<mem_total_mb>,<temp_c>,<power_w>,<power_limit_w>,<driver> | |
| 78 | +APP,<gpu_uuid>,<pid>,<process name>,<used_mb> | |
| 79 | +``` | |
| 80 | + | |
| 81 | +`#` lines are comments, and a field of `-` or `N/A` means "this counter is | |
| 82 | +unavailable". Responses served from a fixture carry `"mocked": true` so nobody | |
| 83 | +mistakes test data for a live reading. | |
| 84 | + | |
| 85 | +## Security properties (verified, not asserted) | |
| 86 | + | |
| 87 | +* **Zero network.** No `socket(`, no `curl`/`wget`, no `ssh`, no `system(` — all | |
| 88 | + asserted against the source text by `tests/run.sh`. | |
| 89 | +* **Auth on every mode except `--meta`.** Accepts `X-Bot-Password`, | |
| 90 | + `Authorization: Bearer <pwd>`, and `?pwd=`. With `BOT_PASSWORD` unset the check | |
| 91 | + is a deliberate no-op so you can run it from a shell. | |
| 92 | +* **No injection surface.** The only `popen()` calls use fixed command constants; | |
| 93 | + the fixtures are read with `fopen()`. | |
| 94 | +* **No `Content-Length`** — the server owns framing. | |
| 95 | +* **Clean history.** `tests/run.sh` greps `git log -p --all` for LAN IPs, PATs, | |
| 96 | + bare node passwords and fleet paths, and refuses to pass on any hit. | |
| 97 | + | |
| 98 | +## Build | |
| 99 | + | |
| 100 | +```bash | |
| 101 | +make # native -> ./plugin_nvtop | |
| 102 | +make musl # fully static musl x86_64 (the universal Linux artifact) | |
| 103 | +make arm64 # static aarch64 (Pi 5 / ARM64 servers) | |
| 104 | +make win64 # static PE via MinGW-w64 -> ./plugin_nvtop.exe | |
| 105 | +make macos # Apple clang (run on macOS) | |
| 106 | +make test # build + tests/run.sh | |
| 107 | +``` | |
| 108 | + | |
| 109 | +Windows: `powershell -ExecutionPolicy Bypass -File build.ps1`. | |
| 110 | +On Apple Silicon, `make` needs nothing special — the file defines | |
| 111 | +`_DARWIN_C_SOURCE` before any include so `<sys/sysctl.h>`-style BSD types survive | |
| 112 | +`-std=c99`. | |
| 113 | + | |
| 114 | +## Install | |
| 115 | + | |
| 116 | +```bash | |
| 117 | +make && mkdir -p ~/.scorpiox/plugins && cp plugin_nvtop ~/.scorpiox/plugins/ | |
| 118 | +``` | |
| 119 | + | |
| 120 | +or install from the registry (see below), or let an agent clone, audit, | |
| 121 | +customize and compile it on the node. | |
| 122 | + | |
| 123 | +## Publish | |
| 124 | + | |
| 125 | +```bash | |
| 126 | +./release-dist.sh # secret scan -> multi-target build -> dist upload -> plugingit mirror | |
| 127 | +./release-dist.sh --dry-run # build and stage in /tmp only | |
| 128 | +./release-dist.sh --no-macos # skip the macOS legs | |
| 129 | +``` | |
| 130 | + | |
| 131 | +Artifacts land at `https://dist.scorpiox.net/bot-plugins/nvtop/<version>/` with | |
| 132 | +`manifest.json`, `SHA256SUMS`, `source.tar.gz` and a directory per target. | |
| 133 | +`release-dist.sh` **skips** a target it cannot build rather than failing, so always | |
| 134 | +check the target count in `latest.json` — not the exit code. | |
| 135 | + | |
| 136 | +Regions that must be supplied by the environment (never committed): | |
| 137 | +`DIST_HOST`, `DIST_PASS`, `MAC_HOST`, `MAC_USER`, `MAC_PASS`, | |
| 138 | +`PLUGINGIT_TOKEN_FILE`, `PLUGINGIT_REMOTE`. | |
| 139 | + | |
| 140 | +## Source | |
| 141 | + | |
| 142 | +Public git mirror: `https://plugingit.scorpiox.net/scorpiox-bot-plugin-nvtop.git` | |
| 143 | + | |
| 144 | +``` | |
| 145 | +src/plugin_nvtop.c single-binary implementation (no headers, no deps) | |
| 146 | +tests/run.sh 124 offline assertions across all three modes | |
| 147 | +tests/fixtures/ deterministic nvidia / rocm / mock snapshots | |
| 148 | +plugin.json catalog metadata for the Bot Market | |
| 149 | +``` | |
| 150 | + | |
| 151 | +MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 1 | 1 | new file mode 100644 |
| index 0000000..362f082 | ||
| --- /dev/null | ||
| +++ b/build.ps1 | ||
| @@ -0,0 +1,53 @@ | ||
| 1 | +# build.ps1 - Windows MinGW-w64 static build for plugin_nvtop | |
| 2 | +# | |
| 3 | +# Usage (from the repo root, PowerShell): | |
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | |
| 5 | +# | |
| 6 | +# Produces .\plugin_nvtop.exe (static PE, runs on any Windows 10/11 x64 node). | |
| 7 | +# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin). | |
| 8 | +# This plugin needs no extra Win32 import libraries. | |
| 9 | + | |
| 10 | +$ErrorActionPreference = "Stop" | |
| 11 | +$ScriptDir = $PSScriptRoot | |
| 12 | +Push-Location $ScriptDir | |
| 13 | +try { | |
| 14 | + $Src = Join-Path $ScriptDir "src\plugin_nvtop.c" | |
| 15 | + $Out = Join-Path $ScriptDir "plugin_nvtop.exe" | |
| 16 | + $Cc = "x86_64-w64-mingw32-gcc" | |
| 17 | + | |
| 18 | + if (-not (Test-Path $Src)) { throw "source not found: $Src" } | |
| 19 | + | |
| 20 | + if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) { | |
| 21 | + if (Test-Path "C:\gcc16\bin\gcc.exe") { | |
| 22 | + $Cc = "C:\gcc16\bin\gcc.exe" | |
| 23 | + } elseif (Get-Command gcc -ErrorAction SilentlyContinue) { | |
| 24 | + $Cc = "gcc" | |
| 25 | + } else { | |
| 26 | + throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)" | |
| 27 | + } | |
| 28 | + } | |
| 29 | + | |
| 30 | + Write-Host "==> building plugin_nvtop.exe with $Cc" | |
| 31 | + & $Cc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -o $Out $Src | |
| 32 | + if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" } | |
| 33 | + | |
| 34 | + if (-not (Test-Path $Out)) { throw "build produced no output" } | |
| 35 | + | |
| 36 | + # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not. | |
| 37 | + $bytes = [System.IO.File]::ReadAllBytes($Out) | |
| 38 | + if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) { | |
| 39 | + throw "output is not a PE executable (missing MZ header)" | |
| 40 | + } | |
| 41 | + | |
| 42 | + Write-Host "==> metadata check" | |
| 43 | + & $Out --meta | |
| 44 | + if ($LASTEXITCODE -ne 0) { throw "--meta failed" } | |
| 45 | + | |
| 46 | + $size = (Get-Item $Out).Length | |
| 47 | + Write-Host "" | |
| 48 | + Write-Host "Built $Out ($size bytes)" | |
| 49 | + Write-Host "Install: Copy-Item plugin_nvtop.exe `"`$env:LOCALAPPDATA\scorpiox\plugins\`"" | |
| 50 | +} | |
| 51 | +finally { | |
| 52 | + Pop-Location | |
| 53 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..e2827ae | ||
| --- /dev/null | ||
| +++ b/plugin.json | ||
| @@ -0,0 +1,10 @@ | ||
| 1 | +{ | |
| 2 | + "slug": "nvtop", | |
| 3 | + "id": "plugin_nvtop", | |
| 4 | + "title": "Local GPU Telemetry", | |
| 5 | + "summary": "Zero-dependency local GPU dashboard: probes nvidia-smi, rocm-smi and Apple Silicon ioreg on the node it runs on, charts per-GPU compute and VRAM as rolling sparklines, and lists every compute process with its GPU, PID and VRAM. Degrades to a clean explanatory empty state on CPU-only nodes.", | |
| 6 | + "category": "system", | |
| 7 | + "license": "MIT", | |
| 8 | + "capabilities": ["local_gpu_query", "local_process_list"], | |
| 9 | + "trust_notice": "Executes native C code on your node. Runs the fixed commands nvidia-smi, rocm-smi and ioreg locally and parses their output; makes zero outbound network requests, opens no sockets, runs no remote commands and reads no credentials." | |
| 10 | +} |
| 1 | 1 | new file mode 100755 |
| index 0000000..7ebb29f | ||
| --- /dev/null | ||
| +++ b/release-dist.sh | ||
| @@ -0,0 +1,370 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# release-dist.sh — build, scan and publish plugin_nvtop to the plugin registry. | |
| 3 | +# | |
| 4 | +# Two paths: | |
| 5 | +# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it | |
| 6 | +# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI. | |
| 7 | +# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz -> | |
| 8 | +# manifest.json + SHA256SUMS -> upload -> latest.json / index.json -> plugingit mirror. | |
| 9 | +# | |
| 10 | +# Nothing here contains a host address or a credential. Everything environment-specific | |
| 11 | +# comes from the environment, so this file stays safe to publish: | |
| 12 | +# | |
| 13 | +# DIST_HOST ssh target for the dist server (required for upload) | |
| 14 | +# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key) | |
| 15 | +# DIST_PATH remote web root of the dist server (default /data/dist) | |
| 16 | +# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64) | |
| 17 | +# MAC_USER / MAC_PASS (optional) | |
| 18 | +# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token) | |
| 19 | +# PLUGINGIT_REMOTE public mirror URL to push into | |
| 20 | +# | |
| 21 | +# Usage: | |
| 22 | +# ./release-dist.sh # full release | |
| 23 | +# ./release-dist.sh --dry-run # build + stage in /tmp, no upload | |
| 24 | +# ./release-dist.sh --no-macos # skip the macOS legs | |
| 25 | +# ./release-dist.sh --no-mirror # skip the plugingit mirror | |
| 26 | + | |
| 27 | +set -euo pipefail | |
| 28 | + | |
| 29 | +SLUG="nvtop" | |
| 30 | +ID="plugin_nvtop" | |
| 31 | +VERSION="1.0.0" | |
| 32 | +DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins" | |
| 33 | + | |
| 34 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | |
| 35 | +cd "$ROOT" | |
| 36 | + | |
| 37 | +DRY_RUN=0 | |
| 38 | +DO_MACOS=1 | |
| 39 | +DO_MIRROR=1 | |
| 40 | +STANDALONE=0 | |
| 41 | +for arg in "$@"; do | |
| 42 | + case "$arg" in | |
| 43 | + --dry-run) DRY_RUN=1 ;; | |
| 44 | + --no-macos) DO_MACOS=0 ;; | |
| 45 | + --no-mirror) DO_MIRROR=0 ;; | |
| 46 | + --standalone) STANDALONE=1 ;; | |
| 47 | + -h|--help) sed -n '2,30p' "$0"; exit 0 ;; | |
| 48 | + *) echo "unknown argument: $arg" >&2; exit 2 ;; | |
| 49 | + esac | |
| 50 | +done | |
| 51 | + | |
| 52 | +DIST_HOST="${DIST_HOST:-}" | |
| 53 | +DIST_PASS="${DIST_PASS:-}" | |
| 54 | +DIST_PATH="${DIST_PATH:-/data/dist}" | |
| 55 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | |
| 56 | +PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}" | |
| 57 | + | |
| 58 | +STAGE="/tmp/${SLUG}-dist-${VERSION}-$$" | |
| 59 | +mkdir -p "$STAGE" | |
| 60 | +trap 'rm -rf "$STAGE"' EXIT | |
| 61 | + | |
| 62 | +say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; } | |
| 63 | +die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; } | |
| 64 | + | |
| 65 | +# ---------------------------------------------------------------- 0. preflight | |
| 66 | +say "0/7 preflight" | |
| 67 | + | |
| 68 | +if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | |
| 69 | + say "using scorpiox-cli-botplugin publish" | |
| 70 | + exec scorpiox-cli-botplugin publish "$ROOT" | |
| 71 | +fi | |
| 72 | +echo " running the standalone pipeline (dist + plugingit mirror)" | |
| 73 | + | |
| 74 | +[ -n "$(git status --porcelain 2>/dev/null)" ] && \ | |
| 75 | + echo " note: working tree is dirty; source.tar.gz comes from the last commit" | |
| 76 | +COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown") | |
| 77 | +echo " version $VERSION" | |
| 78 | +echo " commit $COMMIT" | |
| 79 | + | |
| 80 | +# ---------------------------------------------------------------- 1. secret scan | |
| 81 | +say "1/7 secret & LAN scan (full history)" | |
| 82 | + | |
| 83 | +SCAN_TMP="$STAGE/history.txt" | |
| 84 | +# Scan every added/removed line of every commit. Two exclusions, both about the | |
| 85 | +# audit rather than the code: the committer identity line, and any line that is | |
| 86 | +# itself a scan definition — otherwise this file's own detector patterns read as | |
| 87 | +# findings in every historical revision of it. | |
| 88 | +git log -p --all 2>/dev/null \ | |
| 89 | + | grep -v '^Author: ' \ | |
| 90 | + | grep -vE 'scan "|HITS=|grep -E|P_ROOT=|P_WT=|\$ALL' \ | |
| 91 | + > "$SCAN_TMP" || : > "$SCAN_TMP" | |
| 92 | +HITS=0 | |
| 93 | +scan() { # scan <label> <regex> | |
| 94 | + local out | |
| 95 | + out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true) | |
| 96 | + if [ -n "$out" ]; then | |
| 97 | + printf ' \033[31mHIT\033[0m %s\n' "$1" | |
| 98 | + printf '%s\n' "$out" | sed 's/^/ /' | |
| 99 | + HITS=$((HITS + 1)) | |
| 100 | + else | |
| 101 | + printf ' ok %s\n' "$1" | |
| 102 | + fi | |
| 103 | +} | |
| 104 | +scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+' | |
| 105 | +scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | |
| 106 | +scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | |
| 107 | +scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | |
| 108 | +scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | |
| 109 | +scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}' | |
| 110 | +scan "hard-coded ssh password" 'sshpass -p [^"$]' | |
| 111 | +P_ROOT="/codebases" | |
| 112 | +P_PICOBOT="${P_ROOT}/pico""bot" | |
| 113 | +P_WT=".work""trees" | |
| 114 | +scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}" | |
| 115 | +scan "run-token env assignment" 'RUNNER_'"PASS=" | |
| 116 | +if [ "$HITS" -ne 0 ]; then | |
| 117 | + die "secret scan found $HITS problem(s) — refusing to publish" | |
| 118 | +fi | |
| 119 | +echo " clean: 0 hits" | |
| 120 | + | |
| 121 | +# ---------------------------------------------------------------- 2. build | |
| 122 | +say "2/7 build targets" | |
| 123 | + | |
| 124 | +build_ok() { [ -f "$1" ]; } | |
| 125 | + | |
| 126 | +# linux-x86_64 (glibc, native) | |
| 127 | +if command -v cc >/dev/null 2>&1; then | |
| 128 | + cc -O2 -std=c99 -Wall -Wextra -o "$STAGE/$ID" src/$ID.c || die "native build failed" | |
| 129 | + echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes" | |
| 130 | +else | |
| 131 | + die "no native cc found" | |
| 132 | +fi | |
| 133 | + | |
| 134 | +# linux-x86_64-musl (fully static — the universal Linux artifact) | |
| 135 | +if command -v musl-gcc >/dev/null 2>&1; then | |
| 136 | + musl-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.musl" src/$ID.c \ | |
| 137 | + || die "musl build failed" | |
| 138 | + echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes" | |
| 139 | +else | |
| 140 | + echo " skip linux-x86_64-musl (no musl-gcc)" | |
| 141 | +fi | |
| 142 | + | |
| 143 | +# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers). | |
| 144 | +# Prefer musl; on a host that only has the Debian cross toolchain the static | |
| 145 | +# glibc link still yields a self-contained aarch64 ELF. | |
| 146 | +if command -v aarch64-linux-musl-gcc >/dev/null 2>&1; then | |
| 147 | + aarch64-linux-musl-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.arm64" src/$ID.c \ | |
| 148 | + || die "arm64 musl build failed" | |
| 149 | + echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | |
| 150 | +elif command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | |
| 151 | + aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.arm64" src/$ID.c \ | |
| 152 | + || die "arm64 static build failed" | |
| 153 | + echo " built linux-arm64-static $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | |
| 154 | +else | |
| 155 | + echo " skip linux-arm64-musl (no aarch64 cross compiler)" | |
| 156 | +fi | |
| 157 | + | |
| 158 | +# windows-x86_64 (static PE) | |
| 159 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | |
| 160 | + x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.exe" src/$ID.c \ | |
| 161 | + || die "MinGW build failed" | |
| 162 | + [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE" | |
| 163 | + echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes" | |
| 164 | +else | |
| 165 | + echo " skip windows-x86_64 (no MinGW cross compiler)" | |
| 166 | +fi | |
| 167 | + | |
| 168 | +# macOS legs — Mach-O must be produced by Apple clang on a real Mac. | |
| 169 | +# Both slices are cross-built from one host: -arch arm64 and -arch x86_64. | |
| 170 | +if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then | |
| 171 | + MAC_USER="${MAC_USER:-$(whoami)}" | |
| 172 | + MAC_DIR="/tmp/${ID}-mac-$$" | |
| 173 | + echo " building macOS legs on $MAC_HOST" | |
| 174 | + SSH_MAC=(ssh -o StrictHostKeyChecking=no) | |
| 175 | + SCP_MAC=(scp -o StrictHostKeyChecking=no) | |
| 176 | + if [ -n "${MAC_PASS:-}" ]; then | |
| 177 | + SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}") | |
| 178 | + SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}") | |
| 179 | + fi | |
| 180 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then | |
| 181 | + if "${SCP_MAC[@]}" src/$ID.c "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.c"; then | |
| 182 | + # Build straight from the uploaded file — no src/ tree on the remote. | |
| 183 | + for slice in arm64 x86_64; do | |
| 184 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \ | |
| 185 | + "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -arch $slice -o $ID.$slice $ID.c" \ | |
| 186 | + 2>/dev/null; then | |
| 187 | + "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \ | |
| 188 | + && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)" | |
| 189 | + else | |
| 190 | + echo " warn: macos-$slice build failed on $MAC_HOST" | |
| 191 | + fi | |
| 192 | + done | |
| 193 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" 2>/dev/null || true | |
| 194 | + else | |
| 195 | + echo " warn: mac scp failed" | |
| 196 | + fi | |
| 197 | + else | |
| 198 | + echo " warn: mac host unreachable" | |
| 199 | + fi | |
| 200 | +else | |
| 201 | + echo " skip macOS legs (set MAC_HOST/MAC_USER/MAC_PASS to include them)" | |
| 202 | +fi | |
| 203 | + | |
| 204 | +# ---------------------------------------------------------------- 3. package | |
| 205 | +say "3/7 package" | |
| 206 | + | |
| 207 | +git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \ | |
| 208 | + -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \ | |
| 209 | + || tar -czf "$STAGE/source.tar.gz" --exclude=.git . | |
| 210 | +echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes" | |
| 211 | + | |
| 212 | +target_meta() { # target_meta <key> <file> <format> <relpath> <name> | |
| 213 | + local key="$1" file="$2" fmt="$3" rel="$4" name="$5" | |
| 214 | + [ -f "$file" ] || return 0 | |
| 215 | + local sha size | |
| 216 | + sha=$(sha256sum "$file" | awk '{print $1}') | |
| 217 | + size=$(wc -c < "$file" | tr -d ' ') | |
| 218 | + printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \ | |
| 219 | + "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt" | |
| 220 | +} | |
| 221 | + | |
| 222 | +{ | |
| 223 | + printf '{\n' | |
| 224 | + printf ' "slug": "%s",\n' "$SLUG" | |
| 225 | + printf ' "id": "%s",\n' "$ID" | |
| 226 | + printf ' "name": "nvtop",\n' | |
| 227 | + printf ' "desc": "Local GPUs",\n' | |
| 228 | + printf ' "title": "Local GPU Telemetry",\n' | |
| 229 | + printf ' "summary": "Zero-dependency local GPU dashboard: probes nvidia-smi, rocm-smi and Apple Silicon ioreg on the node it runs on, charts per-GPU compute and VRAM as rolling sparklines, and lists every compute process with its GPU, PID and VRAM. Degrades to a clean explanatory empty state on CPU-only nodes.",\n' | |
| 230 | + printf ' "category": "system",\n' | |
| 231 | + printf ' "version": "%s",\n' "$VERSION" | |
| 232 | + printf ' "license": "MIT",\n' | |
| 233 | + printf ' "trust_notice": "Executes native C code on your node. Runs the fixed commands nvidia-smi, rocm-smi and ioreg locally and parses their output; makes zero outbound network requests, opens no sockets, runs no remote commands and reads no credentials.",\n' | |
| 234 | + printf ' "capabilities": ["local_gpu_query", "local_process_list"],\n' | |
| 235 | + printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG" | |
| 236 | + printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG" | |
| 237 | + printf ' "git_commit": "%s",\n' "$COMMIT" | |
| 238 | + printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | |
| 239 | + printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')" | |
| 240 | + printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID" | |
| 241 | + printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID" | |
| 242 | + printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" | |
| 243 | + printf ' "targets": {\n' | |
| 244 | + first=1 | |
| 245 | + emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; } | |
| 246 | + emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" "$ID" | |
| 247 | + emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" "$ID" | |
| 248 | + emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID" "$ID" | |
| 249 | + emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" "$ID" | |
| 250 | + emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" "$ID" | |
| 251 | + emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" "$ID" | |
| 252 | + printf '\n }\n}\n' | |
| 253 | +} > "$STAGE/manifest.json" | |
| 254 | + | |
| 255 | +python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \ | |
| 256 | + || die "generated manifest.json is not valid JSON" | |
| 257 | +echo " manifest.json ok" | |
| 258 | + | |
| 259 | +# SHA256SUMS — relative paths, exactly as published | |
| 260 | +( cd "$STAGE" | |
| 261 | + for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done | |
| 262 | + [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|" | |
| 263 | + [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|" | |
| 264 | + [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|" | |
| 265 | + [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|" | |
| 266 | + [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|" | |
| 267 | + [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|" | |
| 268 | + true ) > "$STAGE/SHA256SUMS" | |
| 269 | +echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries" | |
| 270 | + | |
| 271 | +# ---------------------------------------------------------------- 4. stage | |
| 272 | +say "4/7 stage tree" | |
| 273 | +PKG="$STAGE/pkg" | |
| 274 | +mkdir -p "$PKG/linux-x86_64" "$PKG/linux-x86_64-musl" "$PKG/linux-arm64-musl" \ | |
| 275 | + "$PKG/macos-arm64" "$PKG/macos-x86_64" "$PKG/windows-x86_64" | |
| 276 | +cp -f "$STAGE/$ID" "$PKG/linux-x86_64/$ID" | |
| 277 | +[ -f "$STAGE/$ID.musl" ] && cp -f "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID" | |
| 278 | +[ -f "$STAGE/$ID.arm64" ] && cp -f "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID" | |
| 279 | +[ -f "$STAGE/$ID.macos-arm64" ]&& cp -f "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID" | |
| 280 | +[ -f "$STAGE/$ID.macos-x86_64" ]&&cp -f "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID" | |
| 281 | +[ -f "$STAGE/$ID.exe" ] && cp -f "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe" | |
| 282 | +cp -f "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/" | |
| 283 | +chmod +x "$PKG"/*/$ID 2>/dev/null || true | |
| 284 | +find "$PKG" -type f | sed 's/^/ /' | |
| 285 | + | |
| 286 | +if [ "$DRY_RUN" -eq 1 ]; then | |
| 287 | + say "dry run — staged at $STAGE/pkg (kept for inspection)" | |
| 288 | + trap - EXIT | |
| 289 | + exit 0 | |
| 290 | +fi | |
| 291 | + | |
| 292 | +# ---------------------------------------------------------------- 5. upload | |
| 293 | +say "5/7 upload" | |
| 294 | + | |
| 295 | +[ -n "$DIST_HOST" ] || die "DIST_HOST is not set — cannot upload" | |
| 296 | +SSH=(ssh -o StrictHostKeyChecking=no) | |
| 297 | +SCP=(scp -o StrictHostKeyChecking=no) | |
| 298 | +if [ -n "$DIST_PASS" ]; then | |
| 299 | + SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}") | |
| 300 | + SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}") | |
| 301 | +fi | |
| 302 | +REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION" | |
| 303 | + | |
| 304 | +"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \ | |
| 305 | + || die "cannot create $REMOTE_DIR on $DIST_HOST" | |
| 306 | +# Stage to one tarball, transfer it, extract remotely. Streaming tar through | |
| 307 | +# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and | |
| 308 | +# OpenSSH 9 refuses to scp a bare "." source. | |
| 309 | +tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed" | |
| 310 | +"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed" | |
| 311 | +"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \ | |
| 312 | + || die "remote extract failed" | |
| 313 | +echo " uploaded to $DIST_HOST:$REMOTE_DIR" | |
| 314 | + | |
| 315 | +# latest.json = copy of this version's manifest | |
| 316 | +"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \ | |
| 317 | + || die "latest.json update failed" | |
| 318 | +echo " updated bot-plugins/$SLUG/latest.json" | |
| 319 | + | |
| 320 | +# index.json — merge, preserving every sibling <slug>/latest.json | |
| 321 | +say "index.json merge" | |
| 322 | +"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY' | |
| 323 | +import json, os, sys, glob | |
| 324 | +slug = sys.argv[1] | |
| 325 | +entries = {} | |
| 326 | +for p in sorted(glob.glob('*/latest.json')): | |
| 327 | + s = os.path.dirname(p) | |
| 328 | + try: | |
| 329 | + entries[s] = json.load(open(p)) | |
| 330 | + except Exception: | |
| 331 | + pass | |
| 332 | +index = { | |
| 333 | + 'ok': True, | |
| 334 | + 'service': 'bot-plugins-dist', | |
| 335 | + 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins', | |
| 336 | + 'count': len(entries), | |
| 337 | + 'slugs': sorted(entries), | |
| 338 | + 'plugins': [entries[k] for k in sorted(entries)], | |
| 339 | +} | |
| 340 | +open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10)) | |
| 341 | +os.replace('index.json.tmp', 'index.json') | |
| 342 | +print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries)))) | |
| 343 | +PY" || die "index.json merge failed" | |
| 344 | + | |
| 345 | +# ---------------------------------------------------------------- 6. mirror | |
| 346 | +say "6/7 plugingit mirror" | |
| 347 | +if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then | |
| 348 | + TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE") | |
| 349 | + AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://x-access-token:${TOKEN}@|") | |
| 350 | + git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed" | |
| 351 | + git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true | |
| 352 | + echo " mirrored to $PLUGINGIT_REMOTE" | |
| 353 | +else | |
| 354 | + echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)" | |
| 355 | +fi | |
| 356 | + | |
| 357 | +# ---------------------------------------------------------------- 7. verify | |
| 358 | +say "7/7 verify" | |
| 359 | +CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \ | |
| 360 | + "$DIST_BASE_URL/$SLUG/latest.json" || echo 000) | |
| 361 | +if [ "$CODE" = "200" ]; then | |
| 362 | + python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK — %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \ | |
| 363 | + "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON" | |
| 364 | +else | |
| 365 | + echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE" | |
| 366 | +fi | |
| 367 | + | |
| 368 | +printf '\n\033[1mrelease complete\033[0m\n' | |
| 369 | +printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | |
| 370 | +printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" |
| 1 | 1 | new file mode 100644 |
| index 0000000..b04d270 | ||
| --- /dev/null | ||
| +++ b/src/plugin_nvtop.c | ||
| @@ -0,0 +1,1198 @@ | ||
| 1 | +/* | |
| 2 | + * plugin_nvtop - ScorpioX Bot open-source local GPU telemetry plugin | |
| 3 | + * | |
| 4 | + * A single clean-room C99 binary that serves THREE modes: | |
| 5 | + * 1. --meta / SX_PLUGIN_META=1 -> JSON metadata for discovery | |
| 6 | + * 2. ?action=metrics | ?action=info | ?format=json | |
| 7 | + * -> JSON node API | |
| 8 | + * 3. GET (default) -> responsive HTML dashboard | |
| 9 | + * | |
| 10 | + * Strictly LOCAL. The plugin runs nvidia-smi / rocm-smi / ioreg on THIS node | |
| 11 | + * (the one the plugin is installed on) and parses their CSV/text output. It | |
| 12 | + * never opens a socket, never runs ssh, and never accepts a host, a command or | |
| 13 | + * a path from the query string: every command below is a fixed constant. | |
| 14 | + * | |
| 15 | + * On a node with no local GPU it reports a clean empty state instead of an | |
| 16 | + * error, so the dashboard is useful on every machine in the fleet. | |
| 17 | + * | |
| 18 | + * Offline determinism: set NVTOP_MOCK_CSV=<path> to make the plugin read a | |
| 19 | + * small CSV fixture instead of shelling out. That is how the test suite | |
| 20 | + * exercises multi-GPU behaviour on CPU-only build hosts. | |
| 21 | + * | |
| 22 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | |
| 23 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | |
| 24 | + * scorpiox-server on the node. | |
| 25 | + * | |
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 27 | + */ | |
| 28 | + | |
| 29 | +#if defined(__APPLE__) | |
| 30 | + /* sysctl / ioctl headers pull BSD types that strict c99 would hide */ | |
| 31 | +# define _DARWIN_C_SOURCE 1 | |
| 32 | +#elif !defined(_WIN32) | |
| 33 | +# define _POSIX_C_SOURCE 200809L | |
| 34 | +# define _DEFAULT_SOURCE 1 | |
| 35 | +#endif | |
| 36 | + | |
| 37 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | |
| 38 | +# define _WIN32_WINNT 0x0601 | |
| 39 | +#endif | |
| 40 | + | |
| 41 | +#include <stdio.h> | |
| 42 | +#include <stdlib.h> | |
| 43 | +#include <string.h> | |
| 44 | +#include <time.h> | |
| 45 | +#include <ctype.h> | |
| 46 | +#include <errno.h> | |
| 47 | + | |
| 48 | +#if defined(_WIN32) | |
| 49 | +# define WIN32_LEAN_AND_MEAN | |
| 50 | +# include <windows.h> | |
| 51 | +#else | |
| 52 | +# include <unistd.h> | |
| 53 | +# include <sys/types.h> | |
| 54 | +#endif | |
| 55 | + | |
| 56 | +#define PLUGIN_SLUG "nvtop" | |
| 57 | +#define PLUGIN_ID "plugin_nvtop" | |
| 58 | +#define PLUGIN_VER "1.0.0" | |
| 59 | + | |
| 60 | +#define MAX_GPUS 32 | |
| 61 | +#define MAX_PROCS 256 | |
| 62 | +#define MAX_NAME 96 | |
| 63 | +#define MAX_UUID 64 | |
| 64 | +#define MAX_DRIVER 48 | |
| 65 | + | |
| 66 | +/* popen is the only external-process mechanism used, and every command string | |
| 67 | + * is a compile-time constant. stderr redirection differs per platform because | |
| 68 | + * popen() goes through the shell. */ | |
| 69 | +#if defined(_WIN32) | |
| 70 | +# define DEV_NULL " 2>NUL" | |
| 71 | +#else | |
| 72 | +# define DEV_NULL " 2>/dev/null" | |
| 73 | +#endif | |
| 74 | + | |
| 75 | +/* ------------------------------------------------------------------ */ | |
| 76 | +/* Small utilities */ | |
| 77 | +/* ------------------------------------------------------------------ */ | |
| 78 | + | |
| 79 | +/* Percent-decode in place ('+' becomes space). */ | |
| 80 | +static void url_decode(char *s) | |
| 81 | +{ | |
| 82 | + char *o = s; | |
| 83 | + if (!s) return; | |
| 84 | + while (*s) { | |
| 85 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | |
| 86 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | |
| 87 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | |
| 88 | + *o++ = (char)((hi << 4) | lo); | |
| 89 | + s += 3; | |
| 90 | + } else if (*s == '+') { | |
| 91 | + *o++ = ' '; | |
| 92 | + s++; | |
| 93 | + } else { | |
| 94 | + *o++ = *s++; | |
| 95 | + } | |
| 96 | + } | |
| 97 | + *o = '\0'; | |
| 98 | +} | |
| 99 | + | |
| 100 | +/* Read one parameter (decoded) out of a form/query string. */ | |
| 101 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | |
| 102 | +{ | |
| 103 | + size_t klen; | |
| 104 | + const char *p; | |
| 105 | + | |
| 106 | + if (!out || outsz == 0) return 0; | |
| 107 | + out[0] = '\0'; | |
| 108 | + if (!qs || !key) return 0; | |
| 109 | + klen = strlen(key); | |
| 110 | + | |
| 111 | + for (p = qs; *p; ) { | |
| 112 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | |
| 113 | + const char *v = p + klen + 1; | |
| 114 | + size_t i = 0; | |
| 115 | + while (*v && *v != '&' && i + 1 < outsz) | |
| 116 | + out[i++] = *v++; | |
| 117 | + out[i] = '\0'; | |
| 118 | + url_decode(out); | |
| 119 | + return 1; | |
| 120 | + } | |
| 121 | + p = strchr(p, '&'); | |
| 122 | + if (!p) break; | |
| 123 | + p++; | |
| 124 | + } | |
| 125 | + return 0; | |
| 126 | +} | |
| 127 | + | |
| 128 | +static void json_str(const char *s) | |
| 129 | +{ | |
| 130 | + putchar('"'); | |
| 131 | + for (; s && *s; s++) { | |
| 132 | + unsigned char c = (unsigned char)*s; | |
| 133 | + switch (c) { | |
| 134 | + case '"': fputs("\\\"", stdout); break; | |
| 135 | + case '\\': fputs("\\\\", stdout); break; | |
| 136 | + case '\n': fputs("\\n", stdout); break; | |
| 137 | + case '\r': fputs("\\r", stdout); break; | |
| 138 | + case '\t': fputs("\\t", stdout); break; | |
| 139 | + default: | |
| 140 | + if (c >= 0x20) putchar((int)c); | |
| 141 | + break; | |
| 142 | + } | |
| 143 | + } | |
| 144 | + putchar('"'); | |
| 145 | +} | |
| 146 | + | |
| 147 | +static void utc_now(char *buf, size_t sz) | |
| 148 | +{ | |
| 149 | + time_t t = time(NULL); | |
| 150 | + struct tm tmv; | |
| 151 | + memset(&tmv, 0, sizeof(tmv)); | |
| 152 | +#if defined(_WIN32) | |
| 153 | + { | |
| 154 | + struct tm *p = gmtime(&t); | |
| 155 | + if (p) tmv = *p; | |
| 156 | + } | |
| 157 | +#else | |
| 158 | + gmtime_r(&t, &tmv); | |
| 159 | +#endif | |
| 160 | + strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); | |
| 161 | +} | |
| 162 | + | |
| 163 | +static long node_pid(void) | |
| 164 | +{ | |
| 165 | +#if defined(_WIN32) | |
| 166 | + return (long)GetCurrentProcessId(); | |
| 167 | +#else | |
| 168 | + return (long)getpid(); | |
| 169 | +#endif | |
| 170 | +} | |
| 171 | + | |
| 172 | +static void copy_str(char *dst, size_t dstsz, const char *src) | |
| 173 | +{ | |
| 174 | + size_t n; | |
| 175 | + if (!dst || dstsz == 0) return; | |
| 176 | + if (!src) { dst[0] = '\0'; return; } | |
| 177 | + n = strlen(src); | |
| 178 | + if (n >= dstsz) n = dstsz - 1; | |
| 179 | + memcpy(dst, src, n); | |
| 180 | + dst[n] = '\0'; | |
| 181 | +} | |
| 182 | + | |
| 183 | +/* Trim leading/trailing whitespace in place, return the trimmed start. */ | |
| 184 | +static char *trim(char *s) | |
| 185 | +{ | |
| 186 | + char *e; | |
| 187 | + if (!s) return s; | |
| 188 | + while (*s && (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')) s++; | |
| 189 | + e = s + strlen(s); | |
| 190 | + while (e > s && (e[-1] == ' ' || e[-1] == '\t' || e[-1] == '\r' || e[-1] == '\n')) e--; | |
| 191 | + *e = '\0'; | |
| 192 | + return s; | |
| 193 | +} | |
| 194 | + | |
| 195 | +/* nvidia-smi prints "[N/A]" / "N/A" when a counter is unsupported. */ | |
| 196 | +static int parse_num(const char *s, double *out) | |
| 197 | +{ | |
| 198 | + char *end = NULL; | |
| 199 | + double v; | |
| 200 | + if (!s || !*s) return 0; | |
| 201 | + if (strstr(s, "N/A") || strstr(s, "n/a")) return 0; | |
| 202 | + errno = 0; | |
| 203 | + v = strtod(s, &end); | |
| 204 | + if (end == s || errno != 0) return 0; | |
| 205 | + *out = v; | |
| 206 | + return 1; | |
| 207 | +} | |
| 208 | + | |
| 209 | +/* Split one CSV line in place; returns the field count (max maxf). */ | |
| 210 | +static int split_csv(char *line, char **fields, int maxf) | |
| 211 | +{ | |
| 212 | + int n = 0; | |
| 213 | + char *p = line; | |
| 214 | + if (!line) return 0; | |
| 215 | + while (n < maxf) { | |
| 216 | + fields[n++] = p; | |
| 217 | + p = strchr(p, ','); | |
| 218 | + if (!p) break; | |
| 219 | + *p++ = '\0'; | |
| 220 | + } | |
| 221 | + return n; | |
| 222 | +} | |
| 223 | + | |
| 224 | +/* ------------------------------------------------------------------ */ | |
| 225 | +/* Node authentication */ | |
| 226 | +/* ------------------------------------------------------------------ */ | |
| 227 | + | |
| 228 | +/* | |
| 229 | + * The node API on :8150 is reachable from the LAN. Every request except | |
| 230 | + * --meta discovery must prove it knows the node password. Accepted forms | |
| 231 | + * match the rest of the node API: X-Bot-Password (what bot-web proxies | |
| 232 | + * with), Authorization: Bearer, and ?pwd= (what the plugin iframe appends). | |
| 233 | + * When BOT_PASSWORD is unset the plugin is a deliberate no-op, which is how | |
| 234 | + * a developer runs it locally from a shell. | |
| 235 | + */ | |
| 236 | +static void require_node_auth(void) | |
| 237 | +{ | |
| 238 | + const char *np = getenv("BOT_PASSWORD"); | |
| 239 | + const char *xp; | |
| 240 | + const char *auth; | |
| 241 | + char qpwd[256]; | |
| 242 | + const char *qs; | |
| 243 | + | |
| 244 | + if (!np || !*np) return; | |
| 245 | + | |
| 246 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | |
| 247 | + if (xp && strcmp(xp, np) == 0) return; | |
| 248 | + | |
| 249 | + auth = getenv("HTTP_AUTHORIZATION"); | |
| 250 | + if (auth) { | |
| 251 | + while (*auth == ' ') auth++; | |
| 252 | + if (strncmp(auth, "Bearer ", 7) == 0) { | |
| 253 | + auth += 7; | |
| 254 | + while (*auth == ' ') auth++; | |
| 255 | + if (strcmp(auth, np) == 0) return; | |
| 256 | + } | |
| 257 | + } | |
| 258 | + | |
| 259 | + qs = getenv("QUERY_STRING"); | |
| 260 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) | |
| 261 | + return; | |
| 262 | + | |
| 263 | + fputs("Status: 401 Unauthorized\r\n" | |
| 264 | + "Content-Type: application/json; charset=utf-8\r\n" | |
| 265 | + "Cache-Control: no-store\r\n" | |
| 266 | + "X-Content-Type-Options: nosniff\r\n\r\n" | |
| 267 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | |
| 268 | + exit(0); | |
| 269 | +} | |
| 270 | + | |
| 271 | +/* ------------------------------------------------------------------ */ | |
| 272 | +/* Snapshot */ | |
| 273 | +/* ------------------------------------------------------------------ */ | |
| 274 | + | |
| 275 | +typedef struct { | |
| 276 | + int index; | |
| 277 | + char uuid[MAX_UUID]; | |
| 278 | + char name[MAX_NAME]; | |
| 279 | + double util_gpu; | |
| 280 | + double mem_used_mb; | |
| 281 | + double mem_total_mb; | |
| 282 | + double temp_c; | |
| 283 | + double power_w; | |
| 284 | + double power_limit_w; | |
| 285 | + int has_temp; | |
| 286 | + int has_power; | |
| 287 | + int has_plimit; | |
| 288 | +} gpu_t; | |
| 289 | + | |
| 290 | +typedef struct { | |
| 291 | + char gpu_uuid[MAX_UUID]; | |
| 292 | + long pid; | |
| 293 | + char name[MAX_NAME]; | |
| 294 | + double used_mb; | |
| 295 | +} proc_t; | |
| 296 | + | |
| 297 | +typedef struct { | |
| 298 | + gpu_t gpus[MAX_GPUS]; | |
| 299 | + int ngpu; | |
| 300 | + proc_t procs[MAX_PROCS]; | |
| 301 | + int nproc; | |
| 302 | + char driver[MAX_DRIVER]; | |
| 303 | + char source[16]; /* nvidia / amd / apple / mock / none */ | |
| 304 | + int available; | |
| 305 | + int mocked; | |
| 306 | + char note[192]; | |
| 307 | +} snap_t; | |
| 308 | + | |
| 309 | +static void snap_init(snap_t *s) | |
| 310 | +{ | |
| 311 | + memset(s, 0, sizeof(*s)); | |
| 312 | + copy_str(s->source, sizeof(s->source), "none"); | |
| 313 | + copy_str(s->note, sizeof(s->note), "No local NVIDIA/AMD GPU detected"); | |
| 314 | +} | |
| 315 | + | |
| 316 | +/* Run a fixed command and stream its stdout line by line. */ | |
| 317 | +typedef void (*line_fn)(char *line, void *ctx); | |
| 318 | + | |
| 319 | +static int feed_file_lines(const char *path, line_fn fn, void *ctx); | |
| 320 | + | |
| 321 | +static int run_cmd_lines(const char *cmd, line_fn fn, void *ctx) | |
| 322 | +{ | |
| 323 | + FILE *fp; | |
| 324 | + char buf[1024]; | |
| 325 | + int any = 0; | |
| 326 | + | |
| 327 | + fp = popen(cmd, "r"); | |
| 328 | + if (!fp) return 0; | |
| 329 | + while (fgets(buf, (int)sizeof(buf), fp)) { | |
| 330 | + size_t n = strlen(buf); | |
| 331 | + while (n && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; | |
| 332 | + if (!buf[0] || buf[0] == '#') continue; | |
| 333 | + any = 1; | |
| 334 | + fn(buf, ctx); | |
| 335 | + } | |
| 336 | + pclose(fp); | |
| 337 | + return any; | |
| 338 | +} | |
| 339 | + | |
| 340 | +/* ---- mock fixture ------------------------------------------------- */ | |
| 341 | + | |
| 342 | +/* | |
| 343 | + * NVTOP_MOCK_CSV fixture format (one record per line, '#' comments allowed): | |
| 344 | + * | |
| 345 | + * GPU,<index>,<uuid>,<name>,<util%>,<mem_used_mb>,<mem_total_mb>,<temp_c>,<power_w>,<power_limit_w>,<driver> | |
| 346 | + * APP,<gpu_uuid>,<pid>,<process name>,<used_mb> | |
| 347 | + * | |
| 348 | + * A field of "-" or "N/A" means "this counter is unavailable". Only the default | |
| 349 | + * test fixtures use this path; production runs never set the variable. | |
| 350 | + */ | |
| 351 | +static void mock_line(char *line, void *ctx) | |
| 352 | +{ | |
| 353 | + snap_t *s = (snap_t *)ctx; | |
| 354 | + char *f[12]; | |
| 355 | + int n; | |
| 356 | + | |
| 357 | + if (line[0] == '#') return; | |
| 358 | + n = split_csv(line, f, 12); | |
| 359 | + if (n < 2) return; | |
| 360 | + | |
| 361 | + if (strcmp(trim(f[0]), "GPU") == 0 && n >= 11 && s->ngpu < MAX_GPUS) { | |
| 362 | + gpu_t *g = &s->gpus[s->ngpu]; | |
| 363 | + char *idx; | |
| 364 | + memset(g, 0, sizeof(*g)); | |
| 365 | + idx = trim(f[1]); | |
| 366 | + g->index = atoi(idx); | |
| 367 | + copy_str(g->uuid, sizeof(g->uuid), trim(f[2])); | |
| 368 | + copy_str(g->name, sizeof(g->name), trim(f[3])); | |
| 369 | + parse_num(trim(f[4]), &g->util_gpu); | |
| 370 | + parse_num(trim(f[5]), &g->mem_used_mb); | |
| 371 | + parse_num(trim(f[6]), &g->mem_total_mb); | |
| 372 | + g->has_temp = parse_num(trim(f[7]), &g->temp_c); | |
| 373 | + g->has_power = parse_num(trim(f[8]), &g->power_w); | |
| 374 | + g->has_plimit = parse_num(trim(f[9]), &g->power_limit_w); | |
| 375 | + if (!s->driver[0] && trim(f[10])[0] && strcmp(trim(f[10]), "-") != 0) | |
| 376 | + copy_str(s->driver, sizeof(s->driver), trim(f[10])); | |
| 377 | + s->ngpu++; | |
| 378 | + } else if (strcmp(trim(f[0]), "APP") == 0 && n >= 5 && s->nproc < MAX_PROCS) { | |
| 379 | + proc_t *p = &s->procs[s->nproc]; | |
| 380 | + memset(p, 0, sizeof(*p)); | |
| 381 | + copy_str(p->gpu_uuid, sizeof(p->gpu_uuid), trim(f[1])); | |
| 382 | + p->pid = (long)atoi(trim(f[2])); | |
| 383 | + copy_str(p->name, sizeof(p->name), trim(f[3])); | |
| 384 | + parse_num(trim(f[4]), &p->used_mb); | |
| 385 | + s->nproc++; | |
| 386 | + } | |
| 387 | +} | |
| 388 | + | |
| 389 | +static int load_mock(snap_t *s, const char *path) | |
| 390 | +{ | |
| 391 | + FILE *fp; | |
| 392 | + char buf[1024]; | |
| 393 | + int any = 0; | |
| 394 | + | |
| 395 | + fp = fopen(path, "r"); | |
| 396 | + if (!fp) return 0; | |
| 397 | + while (fgets(buf, (int)sizeof(buf), fp)) { | |
| 398 | + size_t n = strlen(buf); | |
| 399 | + while (n && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; | |
| 400 | + if (!buf[0]) continue; | |
| 401 | + any = 1; | |
| 402 | + mock_line(buf, s); | |
| 403 | + } | |
| 404 | + fclose(fp); | |
| 405 | + if (!any) return 0; | |
| 406 | + s->mocked = 1; | |
| 407 | + copy_str(s->source, sizeof(s->source), "mock"); | |
| 408 | + s->available = s->ngpu > 0; | |
| 409 | + if (s->available) s->note[0] = '\0'; | |
| 410 | + return 1; | |
| 411 | +} | |
| 412 | + | |
| 413 | +/* ---- NVIDIA ------------------------------------------------------- */ | |
| 414 | + | |
| 415 | +struct nv_ctx { snap_t *s; int stage; }; | |
| 416 | +struct nv_mock_ctx { struct nv_ctx gpu; snap_t *s; }; | |
| 417 | + | |
| 418 | +/* | |
| 419 | + * nvidia-smi --query-gpu=... --format=csv,noheader,nounits | |
| 420 | + * index,uuid,name,utilization.gpu,memory.used,memory.total, | |
| 421 | + * temperature.gpu,power.draw,power.limit,driver_version | |
| 422 | + */ | |
| 423 | +static void nv_gpu_line(char *line, void *ctx) | |
| 424 | +{ | |
| 425 | + struct nv_ctx *c = (struct nv_ctx *)ctx; | |
| 426 | + snap_t *s = c->s; | |
| 427 | + char *f[12]; | |
| 428 | + int n = split_csv(line, f, 12); | |
| 429 | + gpu_t *g; | |
| 430 | + | |
| 431 | + if (n < 10 || s->ngpu >= MAX_GPUS) return; | |
| 432 | + g = &s->gpus[s->ngpu]; | |
| 433 | + memset(g, 0, sizeof(*g)); | |
| 434 | + g->index = atoi(trim(f[0])); | |
| 435 | + copy_str(g->uuid, sizeof(g->uuid), trim(f[1])); | |
| 436 | + copy_str(g->name, sizeof(g->name), trim(f[2])); | |
| 437 | + parse_num(trim(f[3]), &g->util_gpu); | |
| 438 | + parse_num(trim(f[4]), &g->mem_used_mb); | |
| 439 | + parse_num(trim(f[5]), &g->mem_total_mb); | |
| 440 | + g->has_temp = parse_num(trim(f[6]), &g->temp_c); | |
| 441 | + g->has_power = parse_num(trim(f[7]), &g->power_w); | |
| 442 | + g->has_plimit = parse_num(trim(f[8]), &g->power_limit_w); | |
| 443 | + if (!s->driver[0]) copy_str(s->driver, sizeof(s->driver), trim(f[9])); | |
| 444 | + s->ngpu++; | |
| 445 | +} | |
| 446 | + | |
| 447 | +static void nv_proc_line(char *line, void *ctx) | |
| 448 | +{ | |
| 449 | + snap_t *s = (snap_t *)ctx; | |
| 450 | + char *f[8]; | |
| 451 | + int n = split_csv(line, f, 8); | |
| 452 | + proc_t *p; | |
| 453 | + | |
| 454 | + if (n < 4 || s->nproc >= MAX_PROCS) return; | |
| 455 | + p = &s->procs[s->nproc]; | |
| 456 | + memset(p, 0, sizeof(*p)); | |
| 457 | + copy_str(p->gpu_uuid, sizeof(p->gpu_uuid), trim(f[0])); | |
| 458 | + p->pid = (long)atoi(trim(f[1])); | |
| 459 | + copy_str(p->name, sizeof(p->name), trim(f[2])); | |
| 460 | + parse_num(trim(f[3]), &p->used_mb); | |
| 461 | + s->nproc++; | |
| 462 | +} | |
| 463 | + | |
| 464 | +static int collect_nvidia(snap_t *s) | |
| 465 | +{ | |
| 466 | + struct nv_ctx c; | |
| 467 | + int got; | |
| 468 | + | |
| 469 | + const char *mocksmi = getenv("NVTOP_MOCK_NVIDIA"); | |
| 470 | + | |
| 471 | + c.s = s; | |
| 472 | + if (mocksmi && *mocksmi) s->mocked = 1; | |
| 473 | + c.stage = 0; | |
| 474 | + if (mocksmi && *mocksmi) { | |
| 475 | + /* Fixture may interleave raw nvidia-smi GPU csv lines and "APP,..." | |
| 476 | + * process lines; dispatch each line to the parser it belongs to. */ | |
| 477 | + FILE *fp = fopen(mocksmi, "r"); | |
| 478 | + char buf[1024]; | |
| 479 | + got = 0; | |
| 480 | + if (fp) { | |
| 481 | + while (fgets(buf, (int)sizeof(buf), fp)) { | |
| 482 | + size_t n = strlen(buf); | |
| 483 | + char *ln; | |
| 484 | + while (n && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; | |
| 485 | + ln = trim(buf); | |
| 486 | + if (!ln[0] || ln[0] == '#') continue; | |
| 487 | + got = 1; | |
| 488 | + /* Process lines are re-shaped into the csv,noheader layout that | |
| 489 | + * nv_proc_line expects: uuid,pid,name,used_mb. */ | |
| 490 | + if (strncmp(ln, "APP,", 4) == 0) | |
| 491 | + nv_proc_line(ln + 4, (void *)s); | |
| 492 | + else | |
| 493 | + nv_gpu_line(ln, (void *)&c); | |
| 494 | + } | |
| 495 | + fclose(fp); | |
| 496 | + } | |
| 497 | + } else { | |
| 498 | + got = run_cmd_lines( | |
| 499 | + "nvidia-smi --query-gpu=index,uuid,name,utilization.gpu,memory.used," | |
| 500 | + "memory.total,temperature.gpu,power.draw,power.limit,driver_version " | |
| 501 | + "--format=csv,noheader,nounits" DEV_NULL, nv_gpu_line, &c); | |
| 502 | + } | |
| 503 | + if (!got || s->ngpu == 0) return 0; | |
| 504 | + | |
| 505 | + run_cmd_lines( | |
| 506 | + "nvidia-smi --query-compute-apps=gpu_uuid,pid,process_name,used_memory " | |
| 507 | + "--format=csv,noheader,nounits" DEV_NULL, nv_proc_line, s); | |
| 508 | + | |
| 509 | + copy_str(s->source, sizeof(s->source), "nvidia"); | |
| 510 | + s->available = 1; | |
| 511 | + s->note[0] = '\0'; | |
| 512 | + return 1; | |
| 513 | +} | |
| 514 | + | |
| 515 | +/* ---- AMD (rocm-smi) ----------------------------------------------- */ | |
| 516 | + | |
| 517 | +/* | |
| 518 | + * rocm-smi prints one "GPU[n] : <key>: <value>" line per counter, which is | |
| 519 | + * stable across the 5.x and 6.x releases. VRAM is reported in bytes. | |
| 520 | + */ | |
| 521 | +static void amd_line(char *line, void *ctx) | |
| 522 | +{ | |
| 523 | + snap_t *s = (snap_t *)ctx; | |
| 524 | + char *lb, *key, *val, *rbr, *sep; | |
| 525 | + int idx; | |
| 526 | + gpu_t *g; | |
| 527 | + | |
| 528 | + if (strncmp(line, "GPU[", 4) != 0) return; | |
| 529 | + idx = atoi(line + 4); | |
| 530 | + if (idx < 0 || idx >= MAX_GPUS) return; | |
| 531 | + lb = strchr(line, '['); | |
| 532 | + rbr = lb ? strchr(lb, ']') : NULL; | |
| 533 | + if (!rbr) return; | |
| 534 | + /* "GPU[0] : GPU use (%): 87" -> key "GPU use (%)", value "87" */ | |
| 535 | + key = trim(rbr + 1); | |
| 536 | + if (*key == ':') key++; | |
| 537 | + sep = strrchr(key, ':'); | |
| 538 | + if (!sep) return; | |
| 539 | + *sep = '\0'; | |
| 540 | + val = trim(sep + 1); | |
| 541 | + key = trim(key); | |
| 542 | + if (!key[0] || !val[0]) return; | |
| 543 | + | |
| 544 | + while (s->ngpu <= idx) { | |
| 545 | + int i = s->ngpu; | |
| 546 | + memset(&s->gpus[i], 0, sizeof(s->gpus[i])); | |
| 547 | + s->gpus[i].index = i; | |
| 548 | + copy_str(s->gpus[i].name, sizeof(s->gpus[i].name), "AMD GPU"); | |
| 549 | + s->ngpu++; | |
| 550 | + } | |
| 551 | + g = &s->gpus[idx]; | |
| 552 | + | |
| 553 | + if (strstr(key, "Card series") || strstr(key, "Card SKU")) { | |
| 554 | + copy_str(g->name, sizeof(g->name), val); | |
| 555 | + } else if (strstr(key, "GPU use (%)")) { | |
| 556 | + parse_num(val, &g->util_gpu); | |
| 557 | + } else if (strstr(key, "VRAM Total Memory (B)")) { | |
| 558 | + double b = 0; | |
| 559 | + if (parse_num(val, &b)) g->mem_total_mb = b / (1024.0 * 1024.0); | |
| 560 | + } else if (strstr(key, "VRAM Total Used Memory (B)")) { | |
| 561 | + double b = 0; | |
| 562 | + if (parse_num(val, &b)) g->mem_used_mb = b / (1024.0 * 1024.0); | |
| 563 | + } else if (strstr(key, "Temperature (Sensor edge)") || strstr(key, "Temperature (Sensor junction)")) { | |
| 564 | + double v = 0; | |
| 565 | + if (parse_num(val, &v) && !g->has_temp) { g->temp_c = v; g->has_temp = 1; } | |
| 566 | + } else if (strstr(key, "Average Graphics Package Power") || strstr(key, "Current Socket Graphics Package Power")) { | |
| 567 | + double v = 0; | |
| 568 | + if (parse_num(val, &v) && !g->has_power) { g->power_w = v; g->has_power = 1; } | |
| 569 | + } else if (strstr(key, "Max Graphics Package Power")) { | |
| 570 | + double v = 0; | |
| 571 | + if (parse_num(val, &v) && !g->has_plimit) { g->power_limit_w = v; g->has_plimit = 1; } | |
| 572 | + } | |
| 573 | +} | |
| 574 | + | |
| 575 | +/* Feed a rocm-smi text fixture through the real parser (offline tests). */ | |
| 576 | +static int feed_file_lines(const char *path, line_fn fn, void *ctx) | |
| 577 | +{ | |
| 578 | + FILE *fp; | |
| 579 | + char buf[1024]; | |
| 580 | + int any = 0; | |
| 581 | + | |
| 582 | + fp = fopen(path, "r"); | |
| 583 | + if (!fp) return 0; | |
| 584 | + while (fgets(buf, (int)sizeof(buf), fp)) { | |
| 585 | + size_t n = strlen(buf); | |
| 586 | + while (n && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; | |
| 587 | + if (!buf[0] || buf[0] == '#') continue; | |
| 588 | + any = 1; | |
| 589 | + fn(buf, ctx); | |
| 590 | + } | |
| 591 | + fclose(fp); | |
| 592 | + return any; | |
| 593 | +} | |
| 594 | + | |
| 595 | +static int collect_amd(snap_t *s) | |
| 596 | +{ | |
| 597 | + const char *mockrocm = getenv("NVTOP_MOCK_ROCM"); | |
| 598 | + int got; | |
| 599 | + | |
| 600 | + if (mockrocm && *mockrocm) { | |
| 601 | + s->mocked = 1; | |
| 602 | + got = feed_file_lines(mockrocm, amd_line, s); | |
| 603 | + } | |
| 604 | + else | |
| 605 | + got = run_cmd_lines( | |
| 606 | + "rocm-smi --showproductname --showuse --showmeminfo vram " | |
| 607 | + "--showtemp --showpower" DEV_NULL, amd_line, s); | |
| 608 | + | |
| 609 | + if (!got || s->ngpu == 0) return 0; | |
| 610 | + copy_str(s->source, sizeof(s->source), "amd"); | |
| 611 | + s->available = 1; | |
| 612 | + s->note[0] = '\0'; | |
| 613 | + return 1; | |
| 614 | +} | |
| 615 | + | |
| 616 | +/* ---- Apple Silicon (ioreg IOAccelerator) -------------------------- */ | |
| 617 | + | |
| 618 | +#if defined(__APPLE__) | |
| 619 | +static void apple_line(char *line, void *ctx) | |
| 620 | +{ | |
| 621 | + snap_t *s = (snap_t *)ctx; | |
| 622 | + gpu_t *g; | |
| 623 | + | |
| 624 | + if (s->ngpu == 0) { | |
| 625 | + memset(&s->gpus[0], 0, sizeof(s->gpus[0])); | |
| 626 | + copy_str(s->gpus[0].name, sizeof(s->gpus[0].name), "Apple GPU"); | |
| 627 | + s->ngpu = 1; | |
| 628 | + } | |
| 629 | + g = &s->gpus[0]; | |
| 630 | + | |
| 631 | + if (strstr(line, "\"model\" =")) { | |
| 632 | + const char *p = strchr(line, '<'); | |
| 633 | + const char *q = p ? strchr(p, '>') : NULL; | |
| 634 | + if (p && q && q > p + 1) { | |
| 635 | + size_t n = (size_t)(q - p - 1); | |
| 636 | + if (n >= sizeof(g->name)) n = sizeof(g->name) - 1; | |
| 637 | + memcpy(g->name, p + 1, n); | |
| 638 | + g->name[n] = '\0'; | |
| 639 | + } | |
| 640 | + } else if (strstr(line, "Device Utilization %")) { | |
| 641 | + const char *p = strchr(line, '='); | |
| 642 | + double v = 0; | |
| 643 | + if (p && parse_num(p + 1, &v)) g->util_gpu = v; | |
| 644 | + } else if (strstr(line, "In use system memory")) { | |
| 645 | + const char *p = strchr(line, '='); | |
| 646 | + double v = 0; | |
| 647 | + if (p && parse_num(p + 1, &v)) g->mem_used_mb = v / (1024.0 * 1024.0); | |
| 648 | + } | |
| 649 | +} | |
| 650 | + | |
| 651 | +static int collect_apple(snap_t *s) | |
| 652 | +{ | |
| 653 | + int got = run_cmd_lines("ioreg -rc IOAccelerator -d 1" DEV_NULL, apple_line, s); | |
| 654 | + if (!got || s->ngpu == 0) return 0; | |
| 655 | + copy_str(s->source, sizeof(s->source), "apple"); | |
| 656 | + s->available = 1; | |
| 657 | + s->note[0] = '\0'; | |
| 658 | + return 1; | |
| 659 | +} | |
| 660 | +#endif | |
| 661 | + | |
| 662 | +/* ---- orchestration ------------------------------------------------ */ | |
| 663 | + | |
| 664 | +static void snapshot(snap_t *s) | |
| 665 | +{ | |
| 666 | + const char *mock = getenv("NVTOP_MOCK_CSV"); | |
| 667 | + | |
| 668 | + snap_init(s); | |
| 669 | + if (mock && *mock && load_mock(s, mock)) return; | |
| 670 | + | |
| 671 | + if (collect_nvidia(s)) return; | |
| 672 | + if (collect_amd(s)) return; | |
| 673 | +#if defined(__APPLE__) | |
| 674 | + if (collect_apple(s)) return; | |
| 675 | +#endif | |
| 676 | + /* Nothing found: keep the clean CPU-only empty state. */ | |
| 677 | + copy_str(s->source, sizeof(s->source), "none"); | |
| 678 | + s->available = 0; | |
| 679 | + copy_str(s->note, sizeof(s->note), "No local NVIDIA/AMD GPU detected"); | |
| 680 | +} | |
| 681 | + | |
| 682 | +/* Attach "gpu_index" to each process by matching its UUID. */ | |
| 683 | +static int gpu_index_for(snap_t *s, const char *uuid) | |
| 684 | +{ | |
| 685 | + int i; | |
| 686 | + if (!uuid || !*uuid) return -1; | |
| 687 | + for (i = 0; i < s->ngpu; i++) | |
| 688 | + if (strcmp(s->gpus[i].uuid, uuid) == 0) return s->gpus[i].index; | |
| 689 | + return -1; | |
| 690 | +} | |
| 691 | + | |
| 692 | +/* ------------------------------------------------------------------ */ | |
| 693 | +/* Modes */ | |
| 694 | +/* ------------------------------------------------------------------ */ | |
| 695 | + | |
| 696 | +static int mode_meta(void) | |
| 697 | +{ | |
| 698 | + puts("{\"name\":\"nvtop\",\"desc\":\"Local GPUs\"}"); | |
| 699 | + return 0; | |
| 700 | +} | |
| 701 | + | |
| 702 | +static void json_header(void) | |
| 703 | +{ | |
| 704 | + /* Deliberately no Content-Length - the server owns framing. */ | |
| 705 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | |
| 706 | + "Cache-Control: no-store\r\n" | |
| 707 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 708 | +} | |
| 709 | + | |
| 710 | +static void emit_gpu(const gpu_t *g) | |
| 711 | +{ | |
| 712 | + fputs("{\"index\":", stdout); | |
| 713 | + printf("%d", g->index); | |
| 714 | + fputs(",\"uuid\":", stdout); | |
| 715 | + json_str(g->uuid); | |
| 716 | + fputs(",\"name\":", stdout); | |
| 717 | + json_str(g->name); | |
| 718 | + printf(",\"util_gpu\":%.1f", g->util_gpu); | |
| 719 | + printf(",\"mem_used_mb\":%.0f", g->mem_used_mb); | |
| 720 | + printf(",\"mem_total_mb\":%.0f", g->mem_total_mb); | |
| 721 | + fputs(",\"temp_c\":", stdout); | |
| 722 | + if (g->has_temp) printf("%.0f", g->temp_c); else fputs("null", stdout); | |
| 723 | + fputs(",\"power_w\":", stdout); | |
| 724 | + if (g->has_power) printf("%.1f", g->power_w); else fputs("null", stdout); | |
| 725 | + fputs(",\"power_limit_w\":", stdout); | |
| 726 | + if (g->has_plimit) printf("%.1f", g->power_limit_w); else fputs("null", stdout); | |
| 727 | + fputs("}", stdout); | |
| 728 | +} | |
| 729 | + | |
| 730 | +static void emit_metrics(snap_t *s, const char *utc) | |
| 731 | +{ | |
| 732 | + int i; | |
| 733 | + double mem_used = 0, mem_total = 0, util_sum = 0, power = 0; | |
| 734 | + int power_n = 0; | |
| 735 | + | |
| 736 | + json_header(); | |
| 737 | + fputs("{\"ok\":true,\"action\":\"metrics\"", stdout); | |
| 738 | + fputs(",\"available\":", stdout); | |
| 739 | + fputs(s->available ? "true" : "false", stdout); | |
| 740 | + fputs(",\"source\":", stdout); | |
| 741 | + json_str(s->source); | |
| 742 | + fputs(",\"mocked\":", stdout); | |
| 743 | + fputs(s->mocked ? "true" : "false", stdout); | |
| 744 | + fputs(",\"driver\":", stdout); | |
| 745 | + json_str(s->driver); | |
| 746 | + fputs(",\"utc\":", stdout); | |
| 747 | + json_str(utc); | |
| 748 | + fputs(",\"count\":", stdout); | |
| 749 | + printf("%d", s->ngpu); | |
| 750 | + fputs(",\"process_count\":", stdout); | |
| 751 | + printf("%d", s->nproc); | |
| 752 | + | |
| 753 | + for (i = 0; i < s->ngpu; i++) { | |
| 754 | + mem_used += s->gpus[i].mem_used_mb; | |
| 755 | + mem_total += s->gpus[i].mem_total_mb; | |
| 756 | + util_sum += s->gpus[i].util_gpu; | |
| 757 | + if (s->gpus[i].has_power) { power += s->gpus[i].power_w; power_n++; } | |
| 758 | + } | |
| 759 | + printf(",\"util_gpu_avg\":%.1f", s->ngpu ? util_sum / (double)s->ngpu : 0.0); | |
| 760 | + printf(",\"mem_used_mb\":%.0f,\"mem_total_mb\":%.0f", mem_used, mem_total); | |
| 761 | + fputs(",\"power_w\":", stdout); | |
| 762 | + if (power_n) printf("%.1f", power); else fputs("null", stdout); | |
| 763 | + | |
| 764 | + fputs(",\"gpus\":[", stdout); | |
| 765 | + for (i = 0; i < s->ngpu; i++) { | |
| 766 | + if (i) putchar(','); | |
| 767 | + emit_gpu(&s->gpus[i]); | |
| 768 | + } | |
| 769 | + fputs("],\"processes\":[", stdout); | |
| 770 | + for (i = 0; i < s->nproc; i++) { | |
| 771 | + const proc_t *p = &s->procs[i]; | |
| 772 | + if (i) putchar(','); | |
| 773 | + fputs("{\"gpu_uuid\":", stdout); | |
| 774 | + json_str(p->gpu_uuid); | |
| 775 | + fputs(",\"gpu_index\":", stdout); | |
| 776 | + printf("%d", gpu_index_for(s, p->gpu_uuid)); | |
| 777 | + fputs(",\"pid\":", stdout); | |
| 778 | + printf("%ld", p->pid); | |
| 779 | + fputs(",\"name\":", stdout); | |
| 780 | + json_str(p->name); | |
| 781 | + printf(",\"used_mb\":%.0f}", p->used_mb); | |
| 782 | + } | |
| 783 | + fputs("],\"message\":", stdout); | |
| 784 | + json_str(s->note); | |
| 785 | + fputs("}\n", stdout); | |
| 786 | +} | |
| 787 | + | |
| 788 | +static int mode_json(const char *qs) | |
| 789 | +{ | |
| 790 | + char action[64]; | |
| 791 | + char utc[40]; | |
| 792 | + snap_t s; | |
| 793 | + | |
| 794 | + action[0] = '\0'; | |
| 795 | + get_query_val(qs, "action", action, sizeof(action)); | |
| 796 | + | |
| 797 | + if (action[0] && strcmp(action, "metrics") != 0 && strcmp(action, "info") != 0) { | |
| 798 | + json_header(); | |
| 799 | + printf("{\"ok\":false,\"error\":\"unknown_action\"," | |
| 800 | + "\"supported\":[\"metrics\",\"info\"],\"requested\":"); | |
| 801 | + json_str(action); | |
| 802 | + fputs("}\n", stdout); | |
| 803 | + return 0; | |
| 804 | + } | |
| 805 | + if (!action[0]) copy_str(action, sizeof(action), "metrics"); | |
| 806 | + | |
| 807 | + utc_now(utc, sizeof(utc)); | |
| 808 | + | |
| 809 | + if (strcmp(action, "info") == 0) { | |
| 810 | + char platform[64]; | |
| 811 | + json_header(); | |
| 812 | + fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\"," | |
| 813 | + "\"version\":\"" PLUGIN_VER "\",\"platform\":", stdout); | |
| 814 | +#if defined(_WIN32) | |
| 815 | + copy_str(platform, sizeof(platform), "windows"); | |
| 816 | +#elif defined(__APPLE__) | |
| 817 | + copy_str(platform, sizeof(platform), "macos"); | |
| 818 | +#else | |
| 819 | + copy_str(platform, sizeof(platform), "linux"); | |
| 820 | +#endif | |
| 821 | + json_str(platform); | |
| 822 | + fputs(",\"pid\":", stdout); | |
| 823 | + printf("%ld", node_pid()); | |
| 824 | + fputs(",\"utc\":", stdout); | |
| 825 | + json_str(utc); | |
| 826 | + fputs(",\"node_auth\":", stdout); | |
| 827 | + { | |
| 828 | + const char *np = getenv("BOT_PASSWORD"); | |
| 829 | + fputs((np && *np) ? "true" : "false", stdout); | |
| 830 | + } | |
| 831 | + fputs(",\"supported\":[\"metrics\",\"info\"]," | |
| 832 | + "\"probes\":[\"nvidia-smi\",\"rocm-smi\"]," | |
| 833 | + "\"mock_hook\":\"NVTOP_MOCK_CSV\"," | |
| 834 | + "\"max_gpus\":", stdout); | |
| 835 | + printf("%d", MAX_GPUS); | |
| 836 | + fputs(",\"zero_network\":true}\n", stdout); | |
| 837 | + return 0; | |
| 838 | + } | |
| 839 | + | |
| 840 | + snapshot(&s); | |
| 841 | + emit_metrics(&s, utc); | |
| 842 | + return 0; | |
| 843 | +} | |
| 844 | + | |
| 845 | +static void mode_html(int embed) | |
| 846 | +{ | |
| 847 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | |
| 848 | + "Cache-Control: no-store\r\n" | |
| 849 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 850 | + | |
| 851 | + fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>" | |
| 852 | + "<meta name='viewport' content='width=device-width,initial-scale=1'>" | |
| 853 | + "<title>nvtop</title><style>", stdout); | |
| 854 | + | |
| 855 | + fputs( | |
| 856 | +":root{color-scheme:dark light;" | |
| 857 | + "--bg:#0b0b0e;--surface:#141419;--surface2:#1c1c22;--text:#f5f5f7;" | |
| 858 | + "--muted:#8e8e96;--line:rgba(255,255,255,.10);--accent:#0a84ff;" | |
| 859 | + "--compute:#ff9f0a;--vram:#0a84ff;" | |
| 860 | + "--ok:#30d158;--warn:#ffd60a;--danger:#ff453a;" | |
| 861 | + "--mono:ui-monospace,SFMono-Regular,Menlo,monospace}" | |
| 862 | +"html[data-theme=light]{--bg:#f2f2f6;--surface:#ffffff;--surface2:#f0f0f4;" | |
| 863 | + "--text:#1c1c1e;--muted:#6b6b73;--line:rgba(0,0,0,.10)}" | |
| 864 | +"*{box-sizing:border-box}" | |
| 865 | +"body{margin:0;padding:16px;background:var(--bg);color:var(--text);" | |
| 866 | + "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;" | |
| 867 | + "font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}" | |
| 868 | +".wrap{max-width:1180px;margin:0 auto;min-width:0}" | |
| 869 | +".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}" | |
| 870 | +".title{font-size:20px;font-weight:700;margin:0}" | |
| 871 | +".sub{color:var(--muted);font-size:12px;font-family:var(--mono);overflow-wrap:anywhere}" | |
| 872 | +".spacer{flex:1}" | |
| 873 | +".pill{font-size:11px;font-weight:600;padding:2px 9px;border-radius:999px;" | |
| 874 | + "background:var(--surface2);color:var(--muted);border:1px solid var(--line);" | |
| 875 | + "white-space:nowrap}" | |
| 876 | +".pill.live{color:var(--ok);border-color:rgba(48,209,88,.4)}" | |
| 877 | +".pill.warn{color:var(--warn);border-color:rgba(255,214,10,.4)}" | |
| 878 | +".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;" | |
| 879 | + "padding:16px;margin-bottom:14px;min-width:0}" | |
| 880 | +".card h2{margin:0 0 12px;font-size:12px;letter-spacing:.06em;" | |
| 881 | + "text-transform:uppercase;color:var(--muted);font-weight:600}" | |
| 882 | +".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:10px}" | |
| 883 | +".kpi{background:var(--surface2);border:1px solid var(--line);border-radius:10px;" | |
| 884 | + "padding:10px 12px;min-width:0}" | |
| 885 | +".kpi .k{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}" | |
| 886 | +".kpi .v{font-size:19px;font-weight:700;font-family:var(--mono);margin-top:2px;" | |
| 887 | + "overflow:hidden;text-overflow:ellipsis;white-space:nowrap}" | |
| 888 | +"button{background:var(--accent);color:#fff;border:0;border-radius:999px;" | |
| 889 | + "padding:6px 13px;font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}" | |
| 890 | +"button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}" | |
| 891 | +"button:active{transform:scale(.98)}" | |
| 892 | +".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}" | |
| 893 | +".gpus{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:12px}" | |
| 894 | +".gpu{background:var(--surface2);border:1px solid var(--line);border-radius:12px;" | |
| 895 | + "padding:12px;min-width:0}" | |
| 896 | +".gpu .h{display:flex;gap:8px;align-items:baseline;flex-wrap:wrap;margin-bottom:4px}" | |
| 897 | +".gpu .idx{font-family:var(--mono);font-size:12px;font-weight:700;color:var(--compute)}" | |
| 898 | +".gpu .nm{font-weight:700;font-size:13px;overflow-wrap:anywhere;min-width:0}" | |
| 899 | +".gpu .uuid{color:var(--muted);font-size:10px;font-family:var(--mono);overflow-wrap:anywhere}" | |
| 900 | +".chips{display:flex;gap:6px;flex-wrap:wrap;margin:8px 0 4px}" | |
| 901 | +".chip{font-size:11px;font-family:var(--mono);padding:2px 8px;border-radius:999px;" | |
| 902 | + "background:rgba(255,255,255,.06);border:1px solid var(--line);color:var(--muted);" | |
| 903 | + "white-space:nowrap}" | |
| 904 | +".chip.hot{color:var(--danger);border-color:rgba(255,69,58,.45)}" | |
| 905 | +".chip.warm{color:var(--warn);border-color:rgba(255,214,10,.45)}" | |
| 906 | +".legend{display:flex;gap:14px;flex-wrap:wrap;font-size:11px;color:var(--muted);" | |
| 907 | + "font-family:var(--mono);margin-top:8px}" | |
| 908 | +".dotc,.dotv{display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:5px}" | |
| 909 | +".dotc{background:var(--compute)}.dotv{background:var(--vram)}" | |
| 910 | +".spark{display:block;width:100%;height:52px;margin-top:6px}" | |
| 911 | +".tblwrap{overflow-x:auto;-webkit-overflow-scrolling:touch}" | |
| 912 | +"table{width:100%;border-collapse:collapse;font-size:13px}" | |
| 913 | +"th,td{text-align:left;padding:7px 8px;border-bottom:1px solid var(--line)}" | |
| 914 | +"th{color:var(--muted);font-size:11px;text-transform:uppercase;letter-spacing:.05em;" | |
| 915 | + "font-weight:600}" | |
| 916 | +"td.num,th.num{text-align:right;font-family:var(--mono)}" | |
| 917 | +".muted{color:var(--muted)}" | |
| 918 | +".hide{display:none}" | |
| 919 | +".empty{text-align:center;padding:30px 12px}" | |
| 920 | +".empty .big{font-size:16px;font-weight:700;margin-bottom:6px}" | |
| 921 | +".empty .msg{color:var(--muted);font-size:13px;max-width:620px;margin:0 auto 10px}" | |
| 922 | +"code{font-family:var(--mono);font-size:12px;background:rgba(255,255,255,.07);" | |
| 923 | + "padding:1px 5px;border-radius:4px;overflow-wrap:anywhere}" | |
| 924 | +"@media(max-width:640px){body{padding:12px}.hide-sm{display:none}}" | |
| 925 | +"</style></head><body><div class='wrap'>", stdout); | |
| 926 | + | |
| 927 | + fputs("<div class='top'>" | |
| 928 | + "<h1 class='title'>nvtop</h1>" | |
| 929 | + "<span id='srcBadge' class='pill'>local</span>" | |
| 930 | + "<span id='drvBadge' class='pill'>driver</span>" | |
| 931 | + "<span class='spacer'></span>" | |
| 932 | + "<span id='stamp' class='sub'></span>" | |
| 933 | + "<button class='ghost' id='btnRefresh'>Refresh</button>" | |
| 934 | + "</div>", stdout); | |
| 935 | + | |
| 936 | + fputs("<div class='card'><h2>Overview</h2><div class='grid'>" | |
| 937 | + "<div class='kpi'><div class='k'>GPUs</div><div class='v' id='kGpus'>—</div></div>" | |
| 938 | + "<div class='kpi'><div class='k'>Avg compute</div><div class='v' id='kUtil'>—</div></div>" | |
| 939 | + "<div class='kpi'><div class='k'>VRAM used</div><div class='v' id='kMem'>—</div></div>" | |
| 940 | + "<div class='kpi'><div class='k'>Power draw</div><div class='v' id='kPower'>—</div></div>" | |
| 941 | + "<div class='kpi'><div class='k'>Compute procs</div><div class='v' id='kProcs'>—</div></div>" | |
| 942 | + "</div></div>", stdout); | |
| 943 | + | |
| 944 | + fputs("<div class='card'><h2>GPUs</h2>" | |
| 945 | + "<div id='gpuGrid' class='gpus'></div>" | |
| 946 | + "<div id='emptyState' class='empty hide'>" | |
| 947 | + "<div class='big'>No local NVIDIA/AMD GPU detected</div>" | |
| 948 | + "<div class='msg'>This node answers via <code>nvidia-smi</code> and " | |
| 949 | + "<code>rocm-smi</code>; neither reported a GPU, so there is nothing to " | |
| 950 | + "chart. Apple Silicon nodes are probed through <code>ioreg</code>.</div>" | |
| 951 | + "<div class='msg'>To monitor a <em>remote</em> GPU rig from this node, " | |
| 952 | + "customize <code>src/plugin_nvtop.c</code>: replace the fixed " | |
| 953 | + "<code>nvidia-smi</code> probe in <code>collect_nvidia()</code> with your " | |
| 954 | + "own collection step, rebuild with <code>make</code> and the dashboard " | |
| 955 | + "works unchanged.</div>" | |
| 956 | + "</div>" | |
| 957 | + "<div class='legend'><span><i class='dotc'></i>compute %</span>" | |
| 958 | + "<span><i class='dotv'></i>VRAM</span>" | |
| 959 | + "<span>rolling 60 samples</span></div>" | |
| 960 | + "</div>", stdout); | |
| 961 | + | |
| 962 | + fputs("<div class='card'><h2>Compute processes</h2><div class='tblwrap'>" | |
| 963 | + "<table><thead><tr><th class='num'>GPU</th><th class='num'>PID</th>" | |
| 964 | + "<th>Process</th><th class='num'>VRAM</th></tr></thead>" | |
| 965 | + "<tbody id='procRows'></tbody></table></div>" | |
| 966 | + "<div id='procEmpty' class='muted hide'>No compute processes reported.</div>" | |
| 967 | + "</div>", stdout); | |
| 968 | + | |
| 969 | + fputs("<div class='card'><h2>About this plugin</h2>" | |
| 970 | + "<p class='muted' style='margin:0 0 8px'>Local node only. Probes " | |
| 971 | + "<code>nvidia-smi</code> and <code>rocm-smi</code> on this machine and, on " | |
| 972 | + "Apple Silicon, <code>ioreg</code>. Makes zero outbound network requests " | |
| 973 | + "and opens no sockets.</p>" | |
| 974 | + "<p class='muted' style='margin:0'>Every command is a compile-time " | |
| 975 | + "constant; nothing from the query string is ever executed.</p></div>", | |
| 976 | + stdout); | |
| 977 | + | |
| 978 | + if (!embed) | |
| 979 | + fputs("<div class='sub' style='margin-bottom:14px'>Opened directly from the " | |
| 980 | + "node API.</div>", stdout); | |
| 981 | + | |
| 982 | + fputs("<script>\n(function(){\n", stdout); | |
| 983 | + | |
| 984 | + fputs( | |
| 985 | +" var q = new URLSearchParams(location.search);\n" | |
| 986 | +" var HUB = q.get('plugin') || '';\n" | |
| 987 | +" var node = q.get('node') || '';\n" | |
| 988 | +" var sid = q.get('id') || '';\n" | |
| 989 | +" var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n" | |
| 990 | +" localStorage.getItem('bot_active_pwd') || '';\n" | |
| 991 | +" var TIMER = null, BUSY = false, HIST = {}, N = 60;\n" | |
| 992 | +"\n" | |
| 993 | +" /* Two routes, and getting this wrong is the classic plugin bug:\n" | |
| 994 | +" page served through the hub -> call the hub proxy back\n" | |
| 995 | +" page opened directly on node -> the plugin IS the route */\n" | |
| 996 | +" function base(action){\n" | |
| 997 | +" if (HUB) return '/plugins?plugin=' + encodeURIComponent(HUB) +\n" | |
| 998 | +" '&action=' + encodeURIComponent(action);\n" | |
| 999 | +" return '/" PLUGIN_ID "?action=' + encodeURIComponent(action);\n" | |
| 1000 | +" }\n" | |
| 1001 | +" function withCtx(u){\n" | |
| 1002 | +" if (node) u += '&node=' + encodeURIComponent(node);\n" | |
| 1003 | +" if (sid) u += '&id=' + encodeURIComponent(sid);\n" | |
| 1004 | +" if (pwd) u += '&pwd=' + encodeURIComponent(pwd);\n" | |
| 1005 | +" return u;\n" | |
| 1006 | +" }\n" | |
| 1007 | +" function hdr(){ return pwd ? {'X-Bot-Password': pwd} : {}; }\n" | |
| 1008 | +" function $(id){ return document.getElementById(id); }\n" | |
| 1009 | +" function txt(id, v){ var e = $(id); if (e) e.textContent =\n" | |
| 1010 | +" (v === undefined || v === null) ? '' : v; }\n" | |
| 1011 | +" function mb(n){\n" | |
| 1012 | +" if (n === null || n === undefined) return '\\u2014';\n" | |
| 1013 | +" return n >= 1024 ? (n / 1024).toFixed(1) + ' GB' : Math.round(n) + ' MB';\n" | |
| 1014 | +" }\n" | |
| 1015 | +" function el(tag, c, t){\n" | |
| 1016 | +" var e = document.createElement(tag);\n" | |
| 1017 | +" if (c) e.className = c;\n" | |
| 1018 | +" if (t !== undefined) e.textContent = t;\n" | |
| 1019 | +" return e;\n" | |
| 1020 | +" }\n" | |
| 1021 | +"\n" | |
| 1022 | +" /* Rolling sparkline: orange = compute %, blue = VRAM share. A polyline in\n" | |
| 1023 | +" an SVG keeps it crisp at any width and needs no canvas resize logic. */\n" | |
| 1024 | +" function spark(hist, colour){\n" | |
| 1025 | +" var W = 100, H = 40, n = hist.length;\n" | |
| 1026 | +" var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n" | |
| 1027 | +" svg.setAttribute('class', 'spark');\n" | |
| 1028 | +" svg.setAttribute('viewBox', '0 0 ' + W + ' ' + H);\n" | |
| 1029 | +" svg.setAttribute('preserveAspectRatio', 'none');\n" | |
| 1030 | +" var base = document.createElementNS('http://www.w3.org/2000/svg', 'line');\n" | |
| 1031 | +" base.setAttribute('x1','0'); base.setAttribute('x2', String(W));\n" | |
| 1032 | +" base.setAttribute('y1', String(H - 1)); base.setAttribute('y2', String(H - 1));\n" | |
| 1033 | +" base.setAttribute('stroke', 'rgba(255,255,255,.14)');\n" | |
| 1034 | +" base.setAttribute('stroke-width', '0.6');\n" | |
| 1035 | +" svg.appendChild(base);\n" | |
| 1036 | +" if (!n) return svg;\n" | |
| 1037 | +" var pts = [];\n" | |
| 1038 | +" for (var i = 0; i < n; i++){\n" | |
| 1039 | +" var x = n === 1 ? W : (i * W) / (n - 1);\n" | |
| 1040 | +" var v = Math.max(0, Math.min(100, hist[i]));\n" | |
| 1041 | +" var y = H - 1 - (v / 100) * (H - 3);\n" | |
| 1042 | +" pts.push(x.toFixed(2) + ',' + y.toFixed(2));\n" | |
| 1043 | +" }\n" | |
| 1044 | +" var poly = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');\n" | |
| 1045 | +" poly.setAttribute('points', pts.join(' '));\n" | |
| 1046 | +" poly.setAttribute('fill', 'none');\n" | |
| 1047 | +" poly.setAttribute('stroke', colour);\n" | |
| 1048 | +" poly.setAttribute('stroke-width', '1.4');\n" | |
| 1049 | +" poly.setAttribute('stroke-linejoin', 'round');\n" | |
| 1050 | +" poly.setAttribute('vector-effect', 'non-scaling-stroke');\n" | |
| 1051 | +" svg.appendChild(poly);\n" | |
| 1052 | +" return svg;\n" | |
| 1053 | +" }\n" | |
| 1054 | +"\n" | |
| 1055 | +" function pushHist(key, util, memPct){\n" | |
| 1056 | +" var h = HIST[key];\n" | |
| 1057 | +" if (!h) h = HIST[key] = { u: [], m: [] };\n" | |
| 1058 | +" h.u.push(util); h.m.push(memPct);\n" | |
| 1059 | +" if (h.u.length > N) h.u.shift();\n" | |
| 1060 | +" if (h.m.length > N) h.m.shift();\n" | |
| 1061 | +" return h;\n" | |
| 1062 | +" }\n" | |
| 1063 | +"\n" | |
| 1064 | +" function chip(text, cls){ return el('span', 'chip' + (cls ? ' ' + cls : ''), text); }\n" | |
| 1065 | +"\n" | |
| 1066 | +" function renderGpus(d){\n" | |
| 1067 | +" var box = $('gpuGrid');\n" | |
| 1068 | +" box.textContent = '';\n" | |
| 1069 | +" var gpus = d.gpus || [];\n" | |
| 1070 | +" gpus.forEach(function(g){\n" | |
| 1071 | +" var memPct = g.mem_total_mb > 0 ? (g.mem_used_mb / g.mem_total_mb) * 100 : 0;\n" | |
| 1072 | +" var h = pushHist(String(g.index), g.util_gpu, memPct);\n" | |
| 1073 | +" var card = el('div', 'gpu');\n" | |
| 1074 | +" var head = el('div', 'h');\n" | |
| 1075 | +" head.appendChild(el('span', 'idx', 'GPU ' + g.index));\n" | |
| 1076 | +" head.appendChild(el('span', 'nm', g.name));\n" | |
| 1077 | +" card.appendChild(head);\n" | |
| 1078 | +" card.appendChild(el('div', 'uuid', g.uuid || 'no uuid'));\n" | |
| 1079 | +" var chips = el('div', 'chips');\n" | |
| 1080 | +" chips.appendChild(chip(g.util_gpu.toFixed(0) + '% compute'));\n" | |
| 1081 | +" chips.appendChild(chip(mb(g.mem_used_mb) + ' / ' + mb(g.mem_total_mb) + ' VRAM'));\n" | |
| 1082 | +" if (g.temp_c !== null && g.temp_c !== undefined)\n" | |
| 1083 | +" chips.appendChild(chip(Math.round(g.temp_c) + '\\u00b0C',\n" | |
| 1084 | +" g.temp_c >= 85 ? 'hot' : (g.temp_c >= 70 ? 'warm' : '')));\n" | |
| 1085 | +" if (g.power_w !== null && g.power_w !== undefined)\n" | |
| 1086 | +" chips.appendChild(chip(Math.round(g.power_w) + ' W' +\n" | |
| 1087 | +" (g.power_limit_w ? ' / ' + Math.round(g.power_limit_w) : '')));\n" | |
| 1088 | +" card.appendChild(chips);\n" | |
| 1089 | +" card.appendChild(spark(h.u, 'var(--compute)'));\n" | |
| 1090 | +" card.appendChild(spark(h.m, 'var(--vram)'));\n" | |
| 1091 | +" box.appendChild(card);\n" | |
| 1092 | +" });\n" | |
| 1093 | +" if (gpus.length) $('emptyState').classList.add('hide');\n" | |
| 1094 | +" else $('emptyState').classList.remove('hide');\n" | |
| 1095 | +" txt('kGpus', String(gpus.length));\n" | |
| 1096 | +" txt('kUtil', gpus.length ? Number(d.util_gpu_avg).toFixed(0) + '%' : '\\u2014');\n" | |
| 1097 | +" txt('kMem', gpus.length ? mb(d.mem_used_mb) + ' / ' + mb(d.mem_total_mb) : '\\u2014');\n" | |
| 1098 | +" txt('kPower', (d.power_w === null || d.power_w === undefined)\n" | |
| 1099 | +" ? '\\u2014' : Math.round(d.power_w) + ' W');\n" | |
| 1100 | +" txt('kProcs', String((d.processes || []).length));\n" | |
| 1101 | +" }\n" | |
| 1102 | +"\n" | |
| 1103 | +" function renderProcs(d){\n" | |
| 1104 | +" var body = $('procRows');\n" | |
| 1105 | +" body.textContent = '';\n" | |
| 1106 | +" var procs = d.processes || [];\n" | |
| 1107 | +" procs.forEach(function(p){\n" | |
| 1108 | +" var tr = el('tr');\n" | |
| 1109 | +" tr.appendChild(el('td', 'num', p.gpu_index >= 0 ? String(p.gpu_index) : '-'));\n" | |
| 1110 | +" tr.appendChild(el('td', 'num', String(p.pid)));\n" | |
| 1111 | +" tr.appendChild(el('td', 'nm', p.name));\n" | |
| 1112 | +" tr.appendChild(el('td', 'num', mb(p.used_mb)));\n" | |
| 1113 | +" body.appendChild(tr);\n" | |
| 1114 | +" });\n" | |
| 1115 | +" if (procs.length) $('procEmpty').classList.add('hide');\n" | |
| 1116 | +" else $('procEmpty').classList.remove('hide');\n" | |
| 1117 | +" }\n" | |
| 1118 | +"\n" | |
| 1119 | +" function paint(d){\n" | |
| 1120 | +" txt('srcBadge', d.source || 'none');\n" | |
| 1121 | +" var sb = $('srcBadge');\n" | |
| 1122 | +" sb.className = 'pill' + (d.available ? ' live' : ' warn');\n" | |
| 1123 | +" txt('drvBadge', d.driver ? ('driver ' + d.driver) : 'no driver');\n" | |
| 1124 | +" txt('stamp', d.utc || '');\n" | |
| 1125 | +" renderGpus(d);\n" | |
| 1126 | +" renderProcs(d);\n" | |
| 1127 | +" }\n" | |
| 1128 | +"\n" | |
| 1129 | +" function refresh(){\n" | |
| 1130 | +" if (BUSY) return Promise.resolve();\n" | |
| 1131 | +" BUSY = true;\n" | |
| 1132 | +" return fetch(withCtx(base('metrics')), { headers: hdr(), cache: 'no-store' })\n" | |
| 1133 | +" .then(function(r){ return r.json(); })\n" | |
| 1134 | +" .then(function(d){ paint(d); })\n" | |
| 1135 | +" .catch(function(){ txt('stamp', 'refresh failed'); })\n" | |
| 1136 | +" .then(function(){ BUSY = false; });\n" | |
| 1137 | +" }\n" | |
| 1138 | +"\n" | |
| 1139 | +" function tick(){ refresh().then(function(){\n" | |
| 1140 | +" TIMER = setTimeout(tick, 2000);\n" | |
| 1141 | +" }); }\n" | |
| 1142 | +"\n" | |
| 1143 | +" if (!HUB && !pwd && node && localStorage.getItem('bot_pwd_' + node))\n" | |
| 1144 | +" pwd = localStorage.getItem('bot_pwd_' + node);\n" | |
| 1145 | +" $('btnRefresh').addEventListener('click', function(){ refresh(); });\n" | |
| 1146 | +" document.addEventListener('visibilitychange', function(){\n" | |
| 1147 | +" if (document.hidden){ if (TIMER) { clearTimeout(TIMER); TIMER = null; } }\n" | |
| 1148 | +" else if (!TIMER) tick();\n" | |
| 1149 | +" });\n" | |
| 1150 | +" tick();\n" | |
| 1151 | +"})();\n" | |
| 1152 | +"</script></div></body></html>\n", stdout); | |
| 1153 | +} | |
| 1154 | + | |
| 1155 | +int main(int argc, char **argv) | |
| 1156 | +{ | |
| 1157 | + const char *qs; | |
| 1158 | + int embed; | |
| 1159 | + | |
| 1160 | + if (argc > 1) { | |
| 1161 | + if (strcmp(argv[1], "--meta") == 0) return mode_meta(); | |
| 1162 | + if (strcmp(argv[1], "--version") == 0) { | |
| 1163 | + puts(PLUGIN_VER); | |
| 1164 | + return 0; | |
| 1165 | + } | |
| 1166 | + if (strcmp(argv[1], "--help") == 0) { | |
| 1167 | + puts("usage: " PLUGIN_ID " [--meta|--version|--help]"); | |
| 1168 | + puts(""); | |
| 1169 | + puts("Runs as a CGI-style program under scorpiox-server."); | |
| 1170 | + puts(" --meta print discovery metadata JSON and exit"); | |
| 1171 | + puts(" --version print the plugin version and exit"); | |
| 1172 | + puts(""); | |
| 1173 | + puts("Query string actions:"); | |
| 1174 | + puts(" (none) or action=metrics local GPU telemetry + compute procs"); | |
| 1175 | + puts(" action=info plugin/platform capabilities"); | |
| 1176 | + puts(" format=json same as an action, JSON output"); | |
| 1177 | + puts(" (any other) HTML dashboard"); | |
| 1178 | + puts(""); | |
| 1179 | + puts("Environment:"); | |
| 1180 | + puts(" NVTOP_MOCK_CSV=<path> read a CSV fixture instead of probing"); | |
| 1181 | + return 0; | |
| 1182 | + } | |
| 1183 | + } | |
| 1184 | + | |
| 1185 | + if (getenv("SX_PLUGIN_META")) return mode_meta(); | |
| 1186 | + | |
| 1187 | + require_node_auth(); | |
| 1188 | + | |
| 1189 | + qs = getenv("QUERY_STRING"); | |
| 1190 | + if (!qs) qs = ""; | |
| 1191 | + | |
| 1192 | + if (strstr(qs, "action=") || strstr(qs, "format=json")) | |
| 1193 | + return mode_json(qs); | |
| 1194 | + | |
| 1195 | + embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL); | |
| 1196 | + mode_html(embed); | |
| 1197 | + return 0; | |
| 1198 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..c3e7dcf | ||
| --- /dev/null | ||
| +++ b/tests/fixtures/mock-4gpu.csv | ||
| @@ -0,0 +1,12 @@ | ||
| 1 | +# NVTOP_MOCK_CSV fixture format (invented by this plugin's test harness): | |
| 2 | +# GPU,<index>,<uuid>,<name>,<util%>,<mem_used_mb>,<mem_total_mb>,<temp_c>,<power_w>,<power_limit_w>,<driver> | |
| 3 | +# APP,<gpu_uuid>,<pid>,<process name>,<used_mb> | |
| 4 | +# A "-" or "N/A" field means the counter is unavailable. | |
| 5 | +GPU,0,GPU-11111111-aaaa-bbbb-cccc-000000000001,NVIDIA H100 80GB HBM3,91,74240,81920,74,431.5,700.0,550.54.14 | |
| 6 | +GPU,1,GPU-11111111-aaaa-bbbb-cccc-000000000002,NVIDIA H100 80GB HBM3,0,2,81920,31,38.2,700.0,550.54.14 | |
| 7 | +GPU,2,GPU-11111111-aaaa-bbbb-cccc-000000000003,NVIDIA H100 80GB HBM3,55,41000,81920,68,512.9,700.0,550.54.14 | |
| 8 | +GPU,3,GPU-11111111-aaaa-bbbb-cccc-000000000004,NVIDIA H100 80GB HBM3,12,1024,81920,N/A,N/A,N/A,550.54.14 | |
| 9 | +APP,GPU-11111111-aaaa-bbbb-cccc-000000000001,12001,python3,68000 | |
| 10 | +APP,GPU-11111111-aaaa-bbbb-cccc-000000000001,12002,pt_main_thread,6000 | |
| 11 | +APP,GPU-11111111-aaaa-bbbb-cccc-000000000003,12044,/usr/lib/xorg/Xorg,512 | |
| 12 | +APP,GPU-11111111-aaaa-bbbb-cccc-000000000003,12077,ffmpeg,40 |
| 1 | 1 | new file mode 100644 |
| index 0000000..73384b6 | ||
| --- /dev/null | ||
| +++ b/tests/fixtures/nvidia-4gpu.csv | ||
| @@ -0,0 +1,12 @@ | ||
| 1 | +# nvidia-smi --query-gpu=index,uuid,name,utilization.gpu,memory.used,memory.total,temperature.gpu,power.draw,power.limit,driver_version --format=csv,noheader,nounits | |
| 2 | +# Deterministic fixture: a 4-GPU training box - one busy, one idle, one at its | |
| 3 | +# power cap, and one whose thermal / power counters are unsupported ("N/A"). | |
| 4 | +# Lines starting with "APP," are the --query-compute-apps output. | |
| 5 | +0,GPU-11111111-aaaa-bbbb-cccc-000000000001,NVIDIA H100 80GB HBM3,91,74240,81920,74,431.5,700.0,550.54.14 | |
| 6 | +1,GPU-11111111-aaaa-bbbb-cccc-000000000002,NVIDIA H100 80GB HBM3,0,2,81920,31,38.2,700.0,550.54.14 | |
| 7 | +2,GPU-11111111-aaaa-bbbb-cccc-000000000003,NVIDIA H100 80GB HBM3,55,41000,81920,68,512.9,700.0,550.54.14 | |
| 8 | +3,GPU-11111111-aaaa-bbbb-cccc-000000000004,NVIDIA H100 80GB HBM3,12,1024,81920,N/A,N/A,N/A,550.54.14 | |
| 9 | +APP,GPU-11111111-aaaa-bbbb-cccc-000000000001,12001,python3,68000 | |
| 10 | +APP,GPU-11111111-aaaa-bbbb-cccc-000000000001,12002,pt_main_thread,6000 | |
| 11 | +APP,GPU-11111111-aaaa-bbbb-cccc-000000000003,12044,/usr/lib/xorg/Xorg,512 | |
| 12 | +APP,GPU-11111111-aaaa-bbbb-cccc-000000000003,12077,ffmpeg,40 |
| 1 | 1 | new file mode 100644 |
| index 0000000..2e018f3 | ||
| --- /dev/null | ||
| +++ b/tests/fixtures/nvidia-empty.csv | ||
| @@ -0,0 +1 @@ | ||
| 1 | +# A probe that answered but reported nothing (e.g. driver loaded, no device). |
| 1 | 1 | new file mode 100644 |
| index 0000000..64dc350 | ||
| --- /dev/null | ||
| +++ b/tests/fixtures/rocm-1gpu.txt | ||
| @@ -0,0 +1,8 @@ | ||
| 1 | +# rocm-smi text fixture (5.x / 6.x "GPU[n] : key: value" shape) | |
| 2 | +GPU[0] : Card series: AMD Radeon RX 7900 XTX | |
| 3 | +GPU[0] : GPU use (%): 44 | |
| 4 | +GPU[0] : VRAM Total Memory (B): 25753026560 | |
| 5 | +GPU[0] : VRAM Total Used Memory (B): 2147483648 | |
| 6 | +GPU[0] : Temperature (Sensor edge) (C): 58.0 | |
| 7 | +GPU[0] : Average Graphics Package Power (W): 112.0 | |
| 8 | +GPU[0] : Max Graphics Package Power (W): 355.0 |
| 1 | 1 | new file mode 100755 |
| index 0000000..12c45ee | ||
| --- /dev/null | ||
| +++ b/tests/run.sh | ||
| @@ -0,0 +1,386 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# tests/run.sh - offline checks for plugin_nvtop across all 3 modes. | |
| 3 | +# | |
| 4 | +# Runs against ./plugin_nvtop (native build) on whatever machine it is executed | |
| 5 | +# on, so the CPU-only assertions use this host's real state. Multi-GPU telemetry | |
| 6 | +# is exercised deterministically through the NVTOP_MOCK_* fixtures, which is the | |
| 7 | +# whole point of those hooks: a build box without a GPU must still be able to | |
| 8 | +# prove the parsers are correct. | |
| 9 | +# | |
| 10 | +# If a musl static build, an aarch64 build or a Windows PE are present they are | |
| 11 | +# checked too. The whole git history is finally audited for secrets and LAN IPs. | |
| 12 | +# | |
| 13 | +# Exit code 0 = everything passed. | |
| 14 | + | |
| 15 | +set -u | |
| 16 | + | |
| 17 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | |
| 18 | +cd "$ROOT" || exit 1 | |
| 19 | + | |
| 20 | +BIN=./plugin_nvtop | |
| 21 | +FIX=tests/fixtures | |
| 22 | +PASS=0 | |
| 23 | +FAIL=0 | |
| 24 | + | |
| 25 | +if [ -t 1 ]; then | |
| 26 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | |
| 27 | +else | |
| 28 | + C_OK=; C_BAD=; C_B=; C_0= | |
| 29 | +fi | |
| 30 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | |
| 31 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | |
| 32 | + | |
| 33 | +check() { # check <desc> <expected-substring> <actual> | |
| 34 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | |
| 35 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 300)" | |
| 36 | + fi | |
| 37 | +} | |
| 38 | + | |
| 39 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | |
| 40 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | |
| 41 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | |
| 42 | + fi | |
| 43 | +} | |
| 44 | + | |
| 45 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | |
| 46 | + | |
| 47 | +body() { printf '%s' "$1" | sed '1,/^\r$/d'; } | |
| 48 | + | |
| 49 | +py() { # py <desc> <python-script> <json-file> [extra args...] | |
| 50 | + desc=$1; script=$2; file=$3; shift 3 | |
| 51 | + if python3 -c "$script" "$file" "$@" 2>/dev/null; then pass "$desc"; else fail "$desc"; fi | |
| 52 | +} | |
| 53 | + | |
| 54 | +TMP=$(mktemp -d 2>/dev/null || echo /tmp/nvtop_tests_$$) | |
| 55 | +mkdir -p "$TMP" 2>/dev/null || true | |
| 56 | + | |
| 57 | +# ---------------------------------------------------------------- build | |
| 58 | +section "build" | |
| 59 | +if [ ! -x "$BIN" ]; then | |
| 60 | + echo " building native binary..." | |
| 61 | + cc -O2 -std=c99 -Wall -Wextra -o "$BIN" src/plugin_nvtop.c || { echo " build failed"; exit 1; } | |
| 62 | +fi | |
| 63 | +[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing" | |
| 64 | + | |
| 65 | +# ---------------------------------------------------------------- meta mode | |
| 66 | +section "mode 1 --meta (must work without auth - discovery)" | |
| 67 | +META=$("$BIN" --meta) | |
| 68 | +check "meta emits name nvtop" '"name":"nvtop"' "$META" | |
| 69 | +check "meta emits desc Local GPUs" '"desc":"Local GPUs"' "$META" | |
| 70 | +METAENV=$(SX_PLUGIN_META=1 "$BIN") | |
| 71 | +check "SX_PLUGIN_META=1 yields same meta" '"name":"nvtop"' "$METAENV" | |
| 72 | +LEN=$(printf '%s' "$META" | wc -c | tr -d ' ') | |
| 73 | +[ "$LEN" -lt 60 ] && pass "meta payload is compact ($LEN bytes)" || fail "meta payload too long ($LEN)" | |
| 74 | +printf '%s' "$META" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \ | |
| 75 | + && pass "meta is valid JSON" || fail "meta is not valid JSON" | |
| 76 | +DESC=$(printf '%s' "$META" | sed 's/.*"desc":"\([^"]*\)".*/\1/') | |
| 77 | +[ ${#DESC} -le 15 ] && pass "desc length ${#DESC} <= 15 chars" || fail "desc too long (${#DESC})" | |
| 78 | +NAME=$(printf '%s' "$META" | sed 's/.*"name":"\([^"]*\)".*/\1/') | |
| 79 | +[ "$(printf '%s' "$NAME" | wc -w | tr -d ' ')" -le 1 ] && pass "name is a single word" || fail "name has spaces" | |
| 80 | +check "--version prints version" '1.0.0' "$("$BIN" --version)" | |
| 81 | +check "--help is available" 'usage:' "$("$BIN" --help)" | |
| 82 | +check "--help documents the mock hook" 'NVTOP_MOCK_CSV' "$("$BIN" --help)" | |
| 83 | +META_AUTH=$(BOT_PASSWORD=secret "$BIN" --meta) | |
| 84 | +check "meta still works when BOT_PASSWORD is set" '"name":"nvtop"' "$META_AUTH" | |
| 85 | + | |
| 86 | +# ---------------------------------------------------------------- auth | |
| 87 | +section "node auth" | |
| 88 | +AUTHNONE=$(BOT_PASSWORD=testpw QUERY_STRING='action=metrics' "$BIN") | |
| 89 | +check "no credentials -> 401" 'Status: 401' "$AUTHNONE" | |
| 90 | +check "401 body is json" 'invalid node password' "$AUTHNONE" | |
| 91 | +AUTHH=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING='action=metrics' "$BIN") | |
| 92 | +check "X-Bot-Password accepted" '"ok":true' "$(body "$AUTHH")" | |
| 93 | +AUTHB=$(BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING='action=metrics' "$BIN") | |
| 94 | +check "Bearer token accepted" '"ok":true' "$(body "$AUTHB")" | |
| 95 | +AUTHQ=$(BOT_PASSWORD=testpw QUERY_STRING='action=metrics&pwd=testpw' "$BIN") | |
| 96 | +check "?pwd= accepted" '"ok":true' "$(body "$AUTHQ")" | |
| 97 | +AUTHBAD=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=wrong QUERY_STRING='action=metrics' "$BIN") | |
| 98 | +check "wrong password -> 401" 'Status: 401' "$AUTHBAD" | |
| 99 | +AUTHPAGE=$(BOT_PASSWORD=testpw QUERY_STRING='embed=1' "$BIN") | |
| 100 | +check "html mode is protected too" 'Status: 401' "$AUTHPAGE" | |
| 101 | + | |
| 102 | +# ---------------------------------------------------------------- json header | |
| 103 | +section "mode 2 json framing" | |
| 104 | +J0=$(body "$(QUERY_STRING='action=metrics' "$BIN")") | |
| 105 | +check "json mode reports an action" '"action":"metrics"' "$J0" | |
| 106 | +check_not "json mode emits no Content-Length" 'Content-Length' "$J0" | |
| 107 | +check "json mode is ok" '"ok":true' "$J0" | |
| 108 | + | |
| 109 | +# ---------------------------------------------------------------- cpu-only | |
| 110 | +section "mode 2 CPU-only node (clean empty state)" | |
| 111 | +CPU="$TMP/cpu.json" | |
| 112 | +printf '%s' "$J0" > "$CPU" | |
| 113 | +if printf '%s' "$J0" | grep -F -q '"available":false'; then | |
| 114 | + pass "empty state reports available:false" | |
| 115 | + check "empty state counts zero gpus" '"count":0' "$J0" | |
| 116 | + check "empty state counts zero procs" '"process_count":0' "$J0" | |
| 117 | + check "empty state explains itself" 'No local NVIDIA/AMD GPU detected' "$J0" | |
| 118 | + check "empty state source is none" '"source":"none"' "$J0" | |
| 119 | + check "empty state power is null" '"power_w":null' "$J0" | |
| 120 | +else | |
| 121 | + # A machine that really has a GPU (e.g. the .3 inference host) must report it. | |
| 122 | + pass "this node has a GPU, so available:true (not the empty state)" | |
| 123 | + python3 - "$CPU" <<'PY' && pass "live GPU rows are well formed" || fail "live GPU rows malformed" | |
| 124 | +import json, sys | |
| 125 | +d = json.load(open(sys.argv[1])) | |
| 126 | +assert d["count"] >= 1 | |
| 127 | +for g in d["gpus"]: | |
| 128 | + assert isinstance(g["index"], int) | |
| 129 | + assert g["mem_total_mb"] > 0 | |
| 130 | + assert 0 <= g["util_gpu"] <= 100 | |
| 131 | +PY | |
| 132 | +fi | |
| 133 | +py "empty-state payload is valid JSON" 'import json,sys; json.load(open(sys.argv[1]))' "$CPU" | |
| 134 | +py "empty-state gpus is an empty array" 'import json,sys; d=json.load(open(sys.argv[1])); assert isinstance(d["gpus"], list); assert isinstance(d["processes"], list)' "$CPU" | |
| 135 | + | |
| 136 | +# ---------------------------------------------------------------- mock: 4 GPU | |
| 137 | +section "mode 2 NVTOP_MOCK_CSV (4-GPU fixture, deterministic)" | |
| 138 | +NVTOP_MOCK_CSV="$FIX/mock-4gpu.csv" QUERY_STRING='action=metrics' "$BIN" > "$TMP/raw-mock.txt" | |
| 139 | +MOCK="$TMP/mock.json" | |
| 140 | +body "$(cat "$TMP/raw-mock.txt")" > "$MOCK" | |
| 141 | +J=$(cat "$MOCK") | |
| 142 | +check "mock reports available:true" '"available":true' "$J" | |
| 143 | +check "mock reports 4 gpus" '"count":4' "$J" | |
| 144 | +check "mock reports 4 processes" '"process_count":4' "$J" | |
| 145 | +check "mock source is mock" '"source":"mock"' "$J" | |
| 146 | +check "mock is flagged as mocked" '"mocked":true' "$J" | |
| 147 | +check "mock carries the driver" '"driver":"550.54.14"' "$J" | |
| 148 | +check "mock carries the GPU name" 'NVIDIA H100 80GB HBM3' "$J" | |
| 149 | +check "mock reports power" '"power_w":982.6' "$J" | |
| 150 | +check "mock reports memory" '"mem_total_mb":327680' "$J" | |
| 151 | +py "mock payload is valid JSON" 'import json,sys; json.load(open(sys.argv[1]))' "$MOCK" | |
| 152 | +py "mock has exactly 4 well-formed GPU rows" \ | |
| 153 | + 'import json,sys; d=json.load(open(sys.argv[1])); g=d["gpus"]; assert len(g)==4; [ (lambda x: (assert_kind(x)))(x) for x in [] ]; | |
| 154 | +assert [x["index"] for x in g]==[0,1,2,3]; | |
| 155 | +assert all(isinstance(x["util_gpu"],(int,float)) for x in g); | |
| 156 | +assert all(x["mem_total_mb"]==81920 for x in g)' "$MOCK" | |
| 157 | +py "mock per-GPU utilisation parsed" \ | |
| 158 | + 'import json,sys; d=json.load(open(sys.argv[1])); u=[x["util_gpu"] for x in d["gpus"]]; assert u==[91.0,0.0,55.0,12.0], u' "$MOCK" | |
| 159 | +py "mock unsupported temp/power become null" \ | |
| 160 | + 'import json,sys; d=json.load(open(sys.argv[1])); g=d["gpus"][3]; | |
| 161 | +assert g["temp_c"] is None and g["power_w"] is None and g["power_limit_w"] is None, g' "$MOCK" | |
| 162 | +py "mock keeps a supported temp as a number" \ | |
| 163 | + 'import json,sys; d=json.load(open(sys.argv[1])); assert d["gpus"][0]["temp_c"]==74, d["gpus"][0]' "$MOCK" | |
| 164 | +py "mock averages compute across all GPUs" \ | |
| 165 | + 'import json,sys; d=json.load(open(sys.argv[1])); assert abs(d["util_gpu_avg"]-39.5)<1e-6, d["util_gpu_avg"]' "$MOCK" | |
| 166 | +py "mock power sums only the GPUs that report it" \ | |
| 167 | + 'import json,sys; d=json.load(open(sys.argv[1])); assert abs(d["power_w"]-982.6)<1e-6, d["power_w"]' "$MOCK" | |
| 168 | +py "mock maps every process back to its GPU index" \ | |
| 169 | + 'import json,sys; d=json.load(open(sys.argv[1])); idx={p["pid"]:p["gpu_index"] for p in d["processes"]} | |
| 170 | +assert idx[12001]==0 and idx[12002]==0 and idx[12044]==2 and idx[12077]==2, idx' "$MOCK" | |
| 171 | +py "mock keeps process VRAM and names" \ | |
| 172 | + 'import json,sys; d=json.load(open(sys.argv[1])); p=[x for x in d["processes"] if x["pid"]==12001][0] | |
| 173 | +assert p["name"]=="python3" and p["used_mb"]==68000, p' "$MOCK" | |
| 174 | +py "mock uuids survive round-trip" \ | |
| 175 | + 'import json,sys; d=json.load(open(sys.argv[1])); | |
| 176 | +assert d["gpus"][0]["uuid"]=="GPU-11111111-aaaa-bbbb-cccc-000000000001"' "$MOCK" | |
| 177 | +py "mock message is empty when a GPU is present" \ | |
| 178 | + 'import json,sys; d=json.load(open(sys.argv[1])); assert d["message"]=="", d["message"]' "$MOCK" | |
| 179 | +py "index.json-style keys are all present" \ | |
| 180 | + 'import json,sys; d=json.load(open(sys.argv[1])); | |
| 181 | +for k in ["ok","available","driver","count","process_count","gpus","processes","source","utc"]: | |
| 182 | + assert k in d, k' "$MOCK" | |
| 183 | + | |
| 184 | +# ---------------------------------------------------------------- mock: raw nvidia | |
| 185 | +section "mode 2 raw nvidia-smi csv fixture (real query layout)" | |
| 186 | +NVTOP_MOCK_NVIDIA="$FIX/nvidia-4gpu.csv" QUERY_STRING='action=metrics' "$BIN" > "$TMP/raw-nv.txt" | |
| 187 | +NVM="$TMP/nvm.json" | |
| 188 | +body "$(cat "$TMP/raw-nv.txt")" > "$NVM" | |
| 189 | +NV=$(cat "$NVM") | |
| 190 | +check "raw probe reports 4 gpus" '"count":4' "$NV" | |
| 191 | +check "raw probe reports 4 procs" '"process_count":4' "$NV" | |
| 192 | +check "raw probe source is nvidia" '"source":"nvidia"' "$NV" | |
| 193 | +check "raw probe is flagged mocked" '"mocked":true' "$NV" | |
| 194 | +check "raw probe picks up the driver" '"driver":"550.54.14' "$NV" | |
| 195 | +py "raw probe parses the same numbers as the fixture" \ | |
| 196 | + 'import json,sys; d=json.load(open(sys.argv[1])); assert [x["util_gpu"] for x in d["gpus"]]==[91.0,0.0,55.0,12.0]' "$NVM" | |
| 197 | +py "raw probe tolerates N/A counters" \ | |
| 198 | + 'import json,sys; d=json.load(open(sys.argv[1])); g=d["gpus"][3]; assert g["temp_c"] is None and g["power_w"] is None' "$NVM" | |
| 199 | +py "raw probe splits APP lines from GPU lines" \ | |
| 200 | + 'import json,sys; d=json.load(open(sys.argv[1])); assert d["processes"][0]["pid"]==12001' "$NVM" | |
| 201 | + | |
| 202 | +# An empty but successful probe must degrade to the clean empty state, not crash. | |
| 203 | +NVTOP_MOCK_NVIDIA="$FIX/nvidia-empty.csv" QUERY_STRING='action=metrics' "$BIN" > "$TMP/raw-empty.txt" | |
| 204 | +E=$(body "$(cat "$TMP/raw-empty.txt")") | |
| 205 | +check "empty probe falls back to no-GPU state" '"available":false' "$E" | |
| 206 | +check "empty probe explains itself" 'No local NVIDIA/AMD GPU detected' "$E" | |
| 207 | + | |
| 208 | +# ---------------------------------------------------------------- mock: rocm | |
| 209 | +section "mode 2 rocm-smi text fixture (AMD path)" | |
| 210 | +NVTOP_MOCK_ROCM="$FIX/rocm-1gpu.txt" QUERY_STRING='action=metrics' "$BIN" > "$TMP/raw-rocm.txt" | |
| 211 | +RM="$TMP/rocm.json" | |
| 212 | +body "$(cat "$TMP/raw-rocm.txt")" > "$RM" | |
| 213 | +R=$(cat "$RM") | |
| 214 | +check "rocm fixture reports one gpu" '"count":1' "$R" | |
| 215 | +check "rocm fixture source is amd" '"source":"amd"' "$R" | |
| 216 | +check "rocm fixture reads the product name" 'AMD Radeon RX 7900 XTX' "$R" | |
| 217 | +py "rocm fixture converts VRAM bytes to MB" \ | |
| 218 | + 'import json,sys; d=json.load(open(sys.argv[1])); g=d["gpus"][0] | |
| 219 | +assert abs(g["mem_total_mb"]-24560)<2, g["mem_total_mb"] | |
| 220 | +assert abs(g["mem_used_mb"]-2048)<1, g["mem_used_mb"]' "$RM" | |
| 221 | +py "rocm fixture parses utilisation, temp and power" \ | |
| 222 | + 'import json,sys; d=json.load(open(sys.argv[1])); g=d["gpus"][0] | |
| 223 | +assert g["util_gpu"]==44.0 and g["temp_c"]==58 and g["power_w"]==112.0 and g["power_limit_w"]==355.0, g' "$RM" | |
| 224 | + | |
| 225 | +# ---------------------------------------------------------------- info | |
| 226 | +section "mode 2 action=info" | |
| 227 | +INFO=$(body "$(QUERY_STRING='action=info' "$BIN")") | |
| 228 | +check "info names the plugin" '"plugin":"plugin_nvtop"' "$INFO" | |
| 229 | +check "info reports the version" '"version":"1.0.0"' "$INFO" | |
| 230 | +check "info lists the probes" 'nvidia-smi' "$INFO" | |
| 231 | +check "info lists the mock hook" 'NVTOP_MOCK_CSV' "$INFO" | |
| 232 | +check "info advertises zero_network" '"zero_network":true' "$INFO" | |
| 233 | +check "info reports largest GPU count" '"max_gpus":32' "$INFO" | |
| 234 | +INFOAUTH=$(BOT_PASSWORD=pw HTTP_X_BOT_PASSWORD=pw QUERY_STRING='action=info' "$BIN") | |
| 235 | +check "info reflects node auth state" '"node_auth":true' "$INFOAUTH" | |
| 236 | + | |
| 237 | +# ---------------------------------------------------------------- unknown/misc | |
| 238 | +section "mode 2 error handling" | |
| 239 | +UNK=$(body "$(QUERY_STRING='action=destroy' "$BIN")") | |
| 240 | +check "unknown action is rejected" '"ok":false' "$UNK" | |
| 241 | +check "unknown action names itself" '"error":"unknown_action"' "$UNK" | |
| 242 | +check "unknown action echoes input" '"requested":"destroy"' "$UNK" | |
| 243 | +check "format=json aliases to metrics" '"action":"metrics"' "$(body "$(QUERY_STRING='format=json' "$BIN")")" | |
| 244 | +BADAUTH=$(body "$(QUERY_STRING='action=metrics&pwd=x' BOT_PASSWORD=x "$BIN")") | |
| 245 | +check "matching ?pwd still authorises" '"ok":true' "$BADAUTH" | |
| 246 | + | |
| 247 | +# ---------------------------------------------------------------- html | |
| 248 | +section "mode 3 html dashboard" | |
| 249 | +HTML=$("$BIN") | |
| 250 | +check "html content type is set" 'Content-Type: text/html' "$HTML" | |
| 251 | +check "html title is nvtop" "<title>nvtop</title>" "$HTML" | |
| 252 | +check_not "html emits no Content-Length" 'Content-Length' "$HTML" | |
| 253 | +check "html has the compute legend" 'compute %' "$HTML" | |
| 254 | +check "html has the VRAM legend" 'VRAM' "$HTML" | |
| 255 | +check "html explains the empty state" 'No local NVIDIA/AMD GPU detected' "$HTML" | |
| 256 | +check "empty state explains remote customization" 'customize' "$HTML" | |
| 257 | +check "empty state points at the source file" 'src/plugin_nvtop.c' "$HTML" | |
| 258 | +check "html renders per-GPU cards" "id='gpuGrid'" "$HTML" | |
| 259 | +check "html renders the process table" "id='procRows'" "$HTML" | |
| 260 | +check "html wires the refresh button" "id='btnRefresh'" "$HTML" | |
| 261 | +check "html builds rolling sparklines" 'spark' "$HTML" | |
| 262 | +check "html polls every 2s" '2000' "$HTML" | |
| 263 | +check "html routes via the hub proxy" "/plugins?plugin=" "$HTML" | |
| 264 | +check "html routes directly on the node" '/plugin_nvtop?action=' "$HTML" | |
| 265 | +check "html carries pwd on fetches" 'X-Bot-Password' "$HTML" | |
| 266 | +check_not "html has no emoji-ish escapes" '\u26' "$HTML" | |
| 267 | +HTML_EMBED=$(QUERY_STRING='embed=1' "$BIN") | |
| 268 | +check "embed mode still renders" "id='gpuGrid'" "$HTML_EMBED" | |
| 269 | +check_not "embed mode drops the direct-open note" 'Opened directly from the node API' "$HTML_EMBED" | |
| 270 | +check "non-embed mode keeps the note" 'Opened directly from the node API' "$HTML" | |
| 271 | +check_not "html has no remote hosts" 'ssh ' "$HTML" | |
| 272 | + | |
| 273 | +# ---------------------------------------------------------------- source scan | |
| 274 | +section "source invariants" | |
| 275 | +SRCCAT=$(cat src/plugin_nvtop.c) | |
| 276 | +check "source probes nvidia-smi" 'nvidia-smi --query-gpu' "$SRCCAT" | |
| 277 | +check "source probes compute apps" '--query-compute-apps' "$SRCCAT" | |
| 278 | +check "source probes rocm-smi" 'rocm-smi' "$SRCCAT" | |
| 279 | +check "source redacts stderr per platform" 'DEV_NULL' "$SRCCAT" | |
| 280 | +check "source refuses Content-Length" 'no Content-Length' "$SRCCAT" | |
| 281 | +check "source requires node auth" 'require_node_auth' "$SRCCAT" | |
| 282 | +check "source honours embed=1" 'embed=true' "$SRCCAT" | |
| 283 | +check "source documents the mock hook" 'NVTOP_MOCK_CSV' "$SRCCAT" | |
| 284 | +check_not "source has no sockets" 'socket(' "$SRCCAT" | |
| 285 | +check_not "source has no curl" 'curl ' "$SRCCAT" | |
| 286 | +check_not "source has no wget" 'wget' "$SRCCAT" | |
| 287 | +check_not "source has no ssh invocation" 'ssh ' "$SRCCAT" | |
| 288 | +check_not "source has no sshpass" 'sshpass' "$SRCCAT" | |
| 289 | +check_not "source has no system()" 'system(' "$SRCCAT" | |
| 290 | +SNUM=$(grep -cE 'popen\(' src/plugin_nvtop.c) | |
| 291 | +[ "$SNUM" -ge 1 ] && pass "source uses popen only for fixed probe commands ($SNUM call)" \ | |
| 292 | + || fail "source does not use popen at all (expected for the probes)" | |
| 293 | +# Every popen() argument must be a compile-time constant, never a query value. | |
| 294 | +grep -n 'popen(' src/plugin_nvtop.c | grep -F 'cmd' >/dev/null \ | |
| 295 | + && pass "popen is called with the const cmd string only" || fail "popen call shape changed - re-audit" | |
| 296 | +check_not "query string never reaches a shell" 'qs, "r"' "$SRCCAT" | |
| 297 | + | |
| 298 | +# ---------------------------------------------------------------- optional targets | |
| 299 | +section "optional cross builds" | |
| 300 | +if [ -f plugin_nvtop.musl ]; then | |
| 301 | + M=$(./plugin_nvtop.musl --meta) | |
| 302 | + check "musl build --meta" '"name":"nvtop"' "$M" | |
| 303 | + case $(head -c 4 plugin_nvtop.musl | od -An -tx1 | tr -d ' \n') in | |
| 304 | + 7f454c46) pass "musl artifact is ELF" ;; | |
| 305 | + *) fail "musl artifact is not ELF" ;; | |
| 306 | + esac | |
| 307 | +else | |
| 308 | + echo " skip musl (not built)" | |
| 309 | +fi | |
| 310 | +if [ -f plugin_nvtop.arm64 ]; then | |
| 311 | + case $(head -c 4 plugin_nvtop.arm64 | od -An -tx1 | tr -d ' \n') in | |
| 312 | + 7f454c46) pass "arm64 artifact is ELF" ;; | |
| 313 | + *) fail "arm64 artifact is not ELF" ;; | |
| 314 | + esac | |
| 315 | + EM=$(od -An -tx1 -j 18 -N 2 plugin_nvtop.arm64 | tr -d ' \n') | |
| 316 | + [ "$EM" = "b700" ] && pass "arm64 artifact declares EM_AARCH64" \ | |
| 317 | + || fail "arm64 artifact e_machine is $EM, expected b700" | |
| 318 | +else | |
| 319 | + echo " skip arm64 (not built)" | |
| 320 | +fi | |
| 321 | +if [ -f plugin_nvtop.exe ]; then | |
| 322 | + MAGIC=$(head -c 2 plugin_nvtop.exe) | |
| 323 | + [ "$MAGIC" = "MZ" ] && pass "windows artifact has MZ header" || fail "windows artifact missing MZ" | |
| 324 | + SZ=$(wc -c < plugin_nvtop.exe | tr -d ' ') | |
| 325 | + [ "$SZ" -gt 20000 ] && pass "windows artifact is not an error page ($SZ bytes)" \ | |
| 326 | + || fail "windows artifact suspiciously small ($SZ bytes)" | |
| 327 | +else | |
| 328 | + echo " skip windows PE (not built)" | |
| 329 | +fi | |
| 330 | +for slice in arm64 x86_64; do | |
| 331 | + f="plugin_nvtop.macos-$slice" | |
| 332 | + if [ -f "$f" ]; then | |
| 333 | + MFG=$(head -c 4 "$f" | od -An -tx1 | tr -d ' \n') | |
| 334 | + case "$MFG" in | |
| 335 | + cffaedfe|feedfacf|cefaedfe|feedface) pass "macos-$slice artifact is Mach-O" ;; | |
| 336 | + *) fail "macos-$slice artifact is not Mach-O ($MFG)" ;; | |
| 337 | + esac | |
| 338 | + else | |
| 339 | + echo " skip macos-$slice (not built)" | |
| 340 | + fi | |
| 341 | +done | |
| 342 | + | |
| 343 | +# ---------------------------------------------------------------- history audit | |
| 344 | +section "git history secret & LAN audit" | |
| 345 | +if git rev-parse --git-dir >/dev/null 2>&1; then | |
| 346 | + ALL="$TMP/history.txt" | |
| 347 | + # Bookkeeping lines of this audit are excluded so the detector cannot flag itself. | |
| 348 | + git log -p --all 2>/dev/null \ | |
| 349 | + | grep -v '^Author: ' \ | |
| 350 | + | grep -vE 'audit "|HITS=|grep -E|scan "|P_ROOT=|P_WT=' \ | |
| 351 | + > "$ALL" || : > "$ALL" | |
| 352 | + | |
| 353 | + audit() { # audit <label> <regex> | |
| 354 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | |
| 355 | + if [ -n "$H" ]; then | |
| 356 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | |
| 357 | + else | |
| 358 | + pass "history clean: $1" | |
| 359 | + fi | |
| 360 | + } | |
| 361 | + audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+' | |
| 362 | + audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | |
| 363 | + audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | |
| 364 | + audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | |
| 365 | + audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | |
| 366 | + audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | |
| 367 | + audit "bare host password" 'Xboxone0909|xboxone' | |
| 368 | + PK="pico""bot"; WT=".work""trees" | |
| 369 | + audit "fleet path" "/codebases/${PK}|${WT}/" | |
| 370 | + rm -f "$ALL" | |
| 371 | +else | |
| 372 | + echo " skip history audit (not a git checkout)" | |
| 373 | +fi | |
| 374 | + | |
| 375 | +rm -rf "$TMP" | |
| 376 | + | |
| 377 | +# ---------------------------------------------------------------- summary | |
| 378 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | |
| 379 | +printf ' passed: %d\n' "$PASS" | |
| 380 | +printf ' failed: %d\n' "$FAIL" | |
| 381 | +if [ "$FAIL" -ne 0 ]; then | |
| 382 | + printf ' %sRESULT: FAIL%s\n' "$C_BAD" "$C_0" | |
| 383 | + exit 1 | |
| 384 | +fi | |
| 385 | +printf ' %sRESULT: PASS%s\n' "$C_OK" "$C_0" | |
| 386 | +exit 0 | |
| 0 | 387 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..8568772 | index 0000000..8568772 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/.gitignore | +++ b/.gitignore | ||
| @@ -0,0 +1,13 @@ | @@ -0,0 +1,13 @@ | ||
| 1 | +/plugin_nvtop | ||
| 2 | +/plugin_nvtop.exe | ||
| 3 | +*.o | ||
| 4 | +*.obj | ||
| 5 | +bin/ | ||
| 6 | +*.tmp | ||
| 7 | +*.log | ||
| 8 | +/plugin_nvtop.musl | ||
| 9 | +/plugin_nvtop.arm64 | ||
| 10 | +/plugin_nvtop.macos-* | ||
| 11 | +__pycache__/ | ||
| 12 | +*.pyc | ||
| 13 | +tests/fixtures/*.tmp |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..ef80120 | index 0000000..ef80120 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/LICENSE | +++ b/LICENSE | ||
| @@ -0,0 +1,21 @@ | @@ -0,0 +1,21 @@ | ||
| 1 | +MIT License | ||
| 2 | + | ||
| 3 | +Copyright (c) 2026 SCORPIOX INC | ||
| 4 | + | ||
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| 6 | +of this software and associated documentation files (the "Software"), to deal | ||
| 7 | +in the Software without restriction, including without limitation the rights | ||
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| 9 | +copies of the Software, and to permit persons to whom the Software is | ||
| 10 | +furnished to do so, subject to the following conditions: | ||
| 11 | + | ||
| 12 | +The above copyright notice and this permission notice shall be included in all | ||
| 13 | +copies or substantial portions of the Software. | ||
| 14 | + | ||
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| 21 | +SOFTWARE. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..78cf14a | index 0000000..78cf14a | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/Makefile | +++ b/Makefile | ||
| @@ -0,0 +1,65 @@ | @@ -0,0 +1,65 @@ | ||
| 1 | +# plugin_nvtop - ScorpioX Bot open-source local GPU telemetry plugin | ||
| 2 | +# | ||
| 3 | +# Targets: | ||
| 4 | +# make native build -> ./plugin_nvtop | ||
| 5 | +# make musl static musl x86_64 -> ./plugin_nvtop (fully static) | ||
| 6 | +# make arm64 static musl aarch64 -> ./plugin_nvtop.arm64 | ||
| 7 | +# make win64 MinGW-w64 static -> ./plugin_nvtop.exe | ||
| 8 | +# make macos Apple clang -> ./plugin_nvtop (run on macOS) | ||
| 9 | +# make test build + run tests/run.sh | ||
| 10 | +# make clean | ||
| 11 | + | ||
| 12 | +CC ?= cc | ||
| 13 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings | ||
| 14 | +MUSL_CC ?= musl-gcc | ||
| 15 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings | ||
| 16 | +ARM64_CC ?= $(shell command -v aarch64-linux-musl-gcc 2>/dev/null || \ | ||
| 17 | + command -v aarch64-linux-gnu-gcc 2>/dev/null || \ | ||
| 18 | + echo aarch64-linux-musl-gcc) | ||
| 19 | +ARM64_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings | ||
| 20 | +WIN_CC ?= x86_64-w64-mingw32-gcc | ||
| 21 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings | ||
| 22 | +SRC := src/plugin_nvtop.c | ||
| 23 | +BIN := plugin_nvtop | ||
| 24 | +EXE := plugin_nvtop.exe | ||
| 25 | + | ||
| 26 | +.PHONY: all native musl arm64 win64 macos test clean help | ||
| 27 | + | ||
| 28 | +all: native | ||
| 29 | + | ||
| 30 | +native: $(BIN) | ||
| 31 | + | ||
| 32 | +$(BIN): $(SRC) | ||
| 33 | + @echo "==> native build ($(CC))" | ||
| 34 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | ||
| 35 | + | ||
| 36 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | ||
| 37 | +musl: $(SRC) | ||
| 38 | + @echo "==> static musl build ($(MUSL_CC))" | ||
| 39 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN) $(SRC) | ||
| 40 | + | ||
| 41 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | ||
| 42 | +arm64: $(SRC) | ||
| 43 | + @echo "==> static arm64 build ($(ARM64_CC))" | ||
| 44 | + $(ARM64_CC) $(ARM64_CFLAGS) -o $(BIN).arm64 $(SRC) | ||
| 45 | + | ||
| 46 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | ||
| 47 | +win64: $(SRC) | ||
| 48 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | ||
| 49 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) | ||
| 50 | + | ||
| 51 | +# Apple clang build (run this on macOS) | ||
| 52 | +macos: $(SRC) | ||
| 53 | + @echo "==> Apple clang build" | ||
| 54 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | ||
| 55 | + | ||
| 56 | +test: native | ||
| 57 | + @sh tests/run.sh | ||
| 58 | + | ||
| 59 | +clean: | ||
| 60 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 \ | ||
| 61 | + $(BIN).macos-arm64 $(BIN).macos-x86_64 | ||
| 62 | + rm -rf bin | ||
| 63 | + | ||
| 64 | +help: | ||
| 65 | + @echo "make | make musl | make arm64 | make win64 | make macos | make test | make clean" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..267a64b | index 0000000..267a64b | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/README.md | +++ b/README.md | ||
| @@ -0,0 +1,151 @@ | @@ -0,0 +1,151 @@ | ||
| 1 | +# plugin_nvtop | ||
| 2 | + | ||
| 3 | +A zero-dependency **C99** local GPU telemetry plugin for ScorpioX Bot nodes. One | ||
| 4 | +binary, three modes, no runtime dependencies, no outbound network requests. | ||
| 5 | + | ||
| 6 | +It answers the question an operator actually asks about a machine: | ||
| 7 | + | ||
| 8 | +> **What are the GPUs doing right now, and which processes are using them?** | ||
| 9 | + | ||
| 10 | +Everything is read from the machine the plugin is installed on. Nothing is sent | ||
| 11 | +anywhere. | ||
| 12 | + | ||
| 13 | +## What it reports | ||
| 14 | + | ||
| 15 | +| Mode | Output | | ||
| 16 | +|---|---| | ||
| 17 | +| `--meta` | `{"name":"nvtop","desc":"Local GPUs"}` — discovery metadata | | ||
| 18 | +| `?action=metrics` | Every local GPU: index, UUID, product name, compute utilisation %, VRAM used/total MB, temperature, power draw and power limit; plus every compute process with its GPU UUID, GPU index, PID, name and VRAM | | ||
| 19 | +| `?action=info` | Plugin version, platform, PID, auth state, supported actions, the probes it runs and the largest GPU count it will report | | ||
| 20 | +| `?format=json` | Alias for `action=metrics` | | ||
| 21 | +| `GET` (default) | Responsive dark/light HTML dashboard, `?embed=1` aware | | ||
| 22 | + | ||
| 23 | +The dashboard renders one card per GPU with an orange **compute %** rolling | ||
| 24 | +sparkline and a blue **VRAM** sparkline (60 samples, polled every 2 s), power and | ||
| 25 | +thermal chips that turn amber past 70 °C and red past 85 °C, and a compute | ||
| 26 | +process table with GPU / PID / process / VRAM. It pauses polling when the tab is | ||
| 27 | +hidden. | ||
| 28 | + | ||
| 29 | +## Where the numbers come from | ||
| 30 | + | ||
| 31 | +| Platform | Probe | Notes | | ||
| 32 | +|---|---|---| | ||
| 33 | +| NVIDIA (any OS) | `nvidia-smi --query-gpu=index,uuid,name,utilization.gpu,memory.used,memory.total,temperature.gpu,power.draw,power.limit,driver_version --format=csv,noheader,nounits` | plus `--query-compute-apps=gpu_uuid,pid,process_name,used_memory` | | ||
| 34 | +| AMD (Linux) | `rocm-smi --showproductname --showuse --showmeminfo vram --showtemp --showpower` | VRAM is reported in bytes and converted to MB | | ||
| 35 | +| Apple Silicon (macOS) | `ioreg -rc IOAccelerator -d 1` | `Device Utilization %` and `In use system memory` | | ||
| 36 | + | ||
| 37 | +Every one of those command strings is a **compile-time constant**. Nothing from | ||
| 38 | +the query string, and nothing from the environment except the mock path, is ever | ||
| 39 | +passed to a shell. | ||
| 40 | + | ||
| 41 | +`nvidia-smi` prints `N/A` or `[N/A]` for counters a card does not support. Those | ||
| 42 | +become JSON `null` and `—` in the UI rather than a zero that looks like data. | ||
| 43 | + | ||
| 44 | +## CPU-only nodes | ||
| 45 | + | ||
| 46 | +On a machine with no local GPU the plugin does not error. It answers: | ||
| 47 | + | ||
| 48 | +```json | ||
| 49 | +{"ok":true,"available":false,"source":"none","count":0,"gpus":[],"processes":[], | ||
| 50 | + "message":"No local NVIDIA/AMD GPU detected"} | ||
| 51 | +``` | ||
| 52 | + | ||
| 53 | +and the dashboard shows a clean explanatory panel — including how to customize | ||
| 54 | +`src/plugin_nvtop.c` if you want to monitor a **remote** GPU rig from this node. | ||
| 55 | +That is the honest state for most of a fleet, and it is a first-class UI state, | ||
| 56 | +not a failure. | ||
| 57 | + | ||
| 58 | +## Deterministic offline testing: `NVTOP_MOCK_CSV` | ||
| 59 | + | ||
| 60 | +A build box usually has no GPU, so the tests must not depend on one. There are | ||
| 61 | +three environment hooks, each gated to a fixture path you provide: | ||
| 62 | + | ||
| 63 | +```bash | ||
| 64 | +# Invented one-line-per-record format (see the header of tests/fixtures/mock-4gpu.csv) | ||
| 65 | +NVTOP_MOCK_CSV=tests/fixtures/mock-4gpu.csv QUERY_STRING='action=metrics' ./plugin_nvtop | ||
| 66 | + | ||
| 67 | +# Real nvidia-smi csv,noheader layout, with "APP," lines for compute processes | ||
| 68 | +NVTOP_MOCK_NVIDIA=tests/fixtures/nvidia-4gpu.csv QUERY_STRING='action=metrics' ./plugin_nvtop | ||
| 69 | + | ||
| 70 | +# Real rocm-smi "GPU[n] : key: value" text layout | ||
| 71 | +NVTOP_MOCK_ROCM=tests/fixtures/rocm-1gpu.txt QUERY_STRING='action=metrics' ./plugin_nvtop | ||
| 72 | +``` | ||
| 73 | + | ||
| 74 | +The `NVTOP_MOCK_CSV` record format: | ||
| 75 | + | ||
| 76 | +``` | ||
| 77 | +GPU,<index>,<uuid>,<name>,<util%>,<mem_used_mb>,<mem_total_mb>,<temp_c>,<power_w>,<power_limit_w>,<driver> | ||
| 78 | +APP,<gpu_uuid>,<pid>,<process name>,<used_mb> | ||
| 79 | +``` | ||
| 80 | + | ||
| 81 | +`#` lines are comments, and a field of `-` or `N/A` means "this counter is | ||
| 82 | +unavailable". Responses served from a fixture carry `"mocked": true` so nobody | ||
| 83 | +mistakes test data for a live reading. | ||
| 84 | + | ||
| 85 | +## Security properties (verified, not asserted) | ||
| 86 | + | ||
| 87 | +* **Zero network.** No `socket(`, no `curl`/`wget`, no `ssh`, no `system(` — all | ||
| 88 | + asserted against the source text by `tests/run.sh`. | ||
| 89 | +* **Auth on every mode except `--meta`.** Accepts `X-Bot-Password`, | ||
| 90 | + `Authorization: Bearer <pwd>`, and `?pwd=`. With `BOT_PASSWORD` unset the check | ||
| 91 | + is a deliberate no-op so you can run it from a shell. | ||
| 92 | +* **No injection surface.** The only `popen()` calls use fixed command constants; | ||
| 93 | + the fixtures are read with `fopen()`. | ||
| 94 | +* **No `Content-Length`** — the server owns framing. | ||
| 95 | +* **Clean history.** `tests/run.sh` greps `git log -p --all` for LAN IPs, PATs, | ||
| 96 | + bare node passwords and fleet paths, and refuses to pass on any hit. | ||
| 97 | + | ||
| 98 | +## Build | ||
| 99 | + | ||
| 100 | +```bash | ||
| 101 | +make # native -> ./plugin_nvtop | ||
| 102 | +make musl # fully static musl x86_64 (the universal Linux artifact) | ||
| 103 | +make arm64 # static aarch64 (Pi 5 / ARM64 servers) | ||
| 104 | +make win64 # static PE via MinGW-w64 -> ./plugin_nvtop.exe | ||
| 105 | +make macos # Apple clang (run on macOS) | ||
| 106 | +make test # build + tests/run.sh | ||
| 107 | +``` | ||
| 108 | + | ||
| 109 | +Windows: `powershell -ExecutionPolicy Bypass -File build.ps1`. | ||
| 110 | +On Apple Silicon, `make` needs nothing special — the file defines | ||
| 111 | +`_DARWIN_C_SOURCE` before any include so `<sys/sysctl.h>`-style BSD types survive | ||
| 112 | +`-std=c99`. | ||
| 113 | + | ||
| 114 | +## Install | ||
| 115 | + | ||
| 116 | +```bash | ||
| 117 | +make && mkdir -p ~/.scorpiox/plugins && cp plugin_nvtop ~/.scorpiox/plugins/ | ||
| 118 | +``` | ||
| 119 | + | ||
| 120 | +or install from the registry (see below), or let an agent clone, audit, | ||
| 121 | +customize and compile it on the node. | ||
| 122 | + | ||
| 123 | +## Publish | ||
| 124 | + | ||
| 125 | +```bash | ||
| 126 | +./release-dist.sh # secret scan -> multi-target build -> dist upload -> plugingit mirror | ||
| 127 | +./release-dist.sh --dry-run # build and stage in /tmp only | ||
| 128 | +./release-dist.sh --no-macos # skip the macOS legs | ||
| 129 | +``` | ||
| 130 | + | ||
| 131 | +Artifacts land at `https://dist.scorpiox.net/bot-plugins/nvtop/<version>/` with | ||
| 132 | +`manifest.json`, `SHA256SUMS`, `source.tar.gz` and a directory per target. | ||
| 133 | +`release-dist.sh` **skips** a target it cannot build rather than failing, so always | ||
| 134 | +check the target count in `latest.json` — not the exit code. | ||
| 135 | + | ||
| 136 | +Regions that must be supplied by the environment (never committed): | ||
| 137 | +`DIST_HOST`, `DIST_PASS`, `MAC_HOST`, `MAC_USER`, `MAC_PASS`, | ||
| 138 | +`PLUGINGIT_TOKEN_FILE`, `PLUGINGIT_REMOTE`. | ||
| 139 | + | ||
| 140 | +## Source | ||
| 141 | + | ||
| 142 | +Public git mirror: `https://plugingit.scorpiox.net/scorpiox-bot-plugin-nvtop.git` | ||
| 143 | + | ||
| 144 | +``` | ||
| 145 | +src/plugin_nvtop.c single-binary implementation (no headers, no deps) | ||
| 146 | +tests/run.sh 124 offline assertions across all three modes | ||
| 147 | +tests/fixtures/ deterministic nvidia / rocm / mock snapshots | ||
| 148 | +plugin.json catalog metadata for the Bot Market | ||
| 149 | +``` | ||
| 150 | + | ||
| 151 | +MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..362f082 | index 0000000..362f082 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/build.ps1 | +++ b/build.ps1 | ||
| @@ -0,0 +1,53 @@ | @@ -0,0 +1,53 @@ | ||
| 1 | +# build.ps1 - Windows MinGW-w64 static build for plugin_nvtop | ||
| 2 | +# | ||
| 3 | +# Usage (from the repo root, PowerShell): | ||
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | ||
| 5 | +# | ||
| 6 | +# Produces .\plugin_nvtop.exe (static PE, runs on any Windows 10/11 x64 node). | ||
| 7 | +# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin). | ||
| 8 | +# This plugin needs no extra Win32 import libraries. | ||
| 9 | + | ||
| 10 | +$ErrorActionPreference = "Stop" | ||
| 11 | +$ScriptDir = $PSScriptRoot | ||
| 12 | +Push-Location $ScriptDir | ||
| 13 | +try { | ||
| 14 | + $Src = Join-Path $ScriptDir "src\plugin_nvtop.c" | ||
| 15 | + $Out = Join-Path $ScriptDir "plugin_nvtop.exe" | ||
| 16 | + $Cc = "x86_64-w64-mingw32-gcc" | ||
| 17 | + | ||
| 18 | + if (-not (Test-Path $Src)) { throw "source not found: $Src" } | ||
| 19 | + | ||
| 20 | + if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) { | ||
| 21 | + if (Test-Path "C:\gcc16\bin\gcc.exe") { | ||
| 22 | + $Cc = "C:\gcc16\bin\gcc.exe" | ||
| 23 | + } elseif (Get-Command gcc -ErrorAction SilentlyContinue) { | ||
| 24 | + $Cc = "gcc" | ||
| 25 | + } else { | ||
| 26 | + throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)" | ||
| 27 | + } | ||
| 28 | + } | ||
| 29 | + | ||
| 30 | + Write-Host "==> building plugin_nvtop.exe with $Cc" | ||
| 31 | + & $Cc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -o $Out $Src | ||
| 32 | + if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" } | ||
| 33 | + | ||
| 34 | + if (-not (Test-Path $Out)) { throw "build produced no output" } | ||
| 35 | + | ||
| 36 | + # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not. | ||
| 37 | + $bytes = [System.IO.File]::ReadAllBytes($Out) | ||
| 38 | + if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) { | ||
| 39 | + throw "output is not a PE executable (missing MZ header)" | ||
| 40 | + } | ||
| 41 | + | ||
| 42 | + Write-Host "==> metadata check" | ||
| 43 | + & $Out --meta | ||
| 44 | + if ($LASTEXITCODE -ne 0) { throw "--meta failed" } | ||
| 45 | + | ||
| 46 | + $size = (Get-Item $Out).Length | ||
| 47 | + Write-Host "" | ||
| 48 | + Write-Host "Built $Out ($size bytes)" | ||
| 49 | + Write-Host "Install: Copy-Item plugin_nvtop.exe `"`$env:LOCALAPPDATA\scorpiox\plugins\`"" | ||
| 50 | +} | ||
| 51 | +finally { | ||
| 52 | + Pop-Location | ||
| 53 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..e2827ae | index 0000000..e2827ae | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/plugin.json | +++ b/plugin.json | ||
| @@ -0,0 +1,10 @@ | @@ -0,0 +1,10 @@ | ||
| 1 | +{ | ||
| 2 | + "slug": "nvtop", | ||
| 3 | + "id": "plugin_nvtop", | ||
| 4 | + "title": "Local GPU Telemetry", | ||
| 5 | + "summary": "Zero-dependency local GPU dashboard: probes nvidia-smi, rocm-smi and Apple Silicon ioreg on the node it runs on, charts per-GPU compute and VRAM as rolling sparklines, and lists every compute process with its GPU, PID and VRAM. Degrades to a clean explanatory empty state on CPU-only nodes.", | ||
| 6 | + "category": "system", | ||
| 7 | + "license": "MIT", | ||
| 8 | + "capabilities": ["local_gpu_query", "local_process_list"], | ||
| 9 | + "trust_notice": "Executes native C code on your node. Runs the fixed commands nvidia-smi, rocm-smi and ioreg locally and parses their output; makes zero outbound network requests, opens no sockets, runs no remote commands and reads no credentials." | ||
| 10 | +} |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..7ebb29f | index 0000000..7ebb29f | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/release-dist.sh | +++ b/release-dist.sh | ||
| @@ -0,0 +1,370 @@ | @@ -0,0 +1,370 @@ | ||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# release-dist.sh — build, scan and publish plugin_nvtop to the plugin registry. | ||
| 3 | +# | ||
| 4 | +# Two paths: | ||
| 5 | +# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it | ||
| 6 | +# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI. | ||
| 7 | +# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz -> | ||
| 8 | +# manifest.json + SHA256SUMS -> upload -> latest.json / index.json -> plugingit mirror. | ||
| 9 | +# | ||
| 10 | +# Nothing here contains a host address or a credential. Everything environment-specific | ||
| 11 | +# comes from the environment, so this file stays safe to publish: | ||
| 12 | +# | ||
| 13 | +# DIST_HOST ssh target for the dist server (required for upload) | ||
| 14 | +# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key) | ||
| 15 | +# DIST_PATH remote web root of the dist server (default /data/dist) | ||
| 16 | +# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64) | ||
| 17 | +# MAC_USER / MAC_PASS (optional) | ||
| 18 | +# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token) | ||
| 19 | +# PLUGINGIT_REMOTE public mirror URL to push into | ||
| 20 | +# | ||
| 21 | +# Usage: | ||
| 22 | +# ./release-dist.sh # full release | ||
| 23 | +# ./release-dist.sh --dry-run # build + stage in /tmp, no upload | ||
| 24 | +# ./release-dist.sh --no-macos # skip the macOS legs | ||
| 25 | +# ./release-dist.sh --no-mirror # skip the plugingit mirror | ||
| 26 | + | ||
| 27 | +set -euo pipefail | ||
| 28 | + | ||
| 29 | +SLUG="nvtop" | ||
| 30 | +ID="plugin_nvtop" | ||
| 31 | +VERSION="1.0.0" | ||
| 32 | +DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins" | ||
| 33 | + | ||
| 34 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | ||
| 35 | +cd "$ROOT" | ||
| 36 | + | ||
| 37 | +DRY_RUN=0 | ||
| 38 | +DO_MACOS=1 | ||
| 39 | +DO_MIRROR=1 | ||
| 40 | +STANDALONE=0 | ||
| 41 | +for arg in "$@"; do | ||
| 42 | + case "$arg" in | ||
| 43 | + --dry-run) DRY_RUN=1 ;; | ||
| 44 | + --no-macos) DO_MACOS=0 ;; | ||
| 45 | + --no-mirror) DO_MIRROR=0 ;; | ||
| 46 | + --standalone) STANDALONE=1 ;; | ||
| 47 | + -h|--help) sed -n '2,30p' "$0"; exit 0 ;; | ||
| 48 | + *) echo "unknown argument: $arg" >&2; exit 2 ;; | ||
| 49 | + esac | ||
| 50 | +done | ||
| 51 | + | ||
| 52 | +DIST_HOST="${DIST_HOST:-}" | ||
| 53 | +DIST_PASS="${DIST_PASS:-}" | ||
| 54 | +DIST_PATH="${DIST_PATH:-/data/dist}" | ||
| 55 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | ||
| 56 | +PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}" | ||
| 57 | + | ||
| 58 | +STAGE="/tmp/${SLUG}-dist-${VERSION}-$$" | ||
| 59 | +mkdir -p "$STAGE" | ||
| 60 | +trap 'rm -rf "$STAGE"' EXIT | ||
| 61 | + | ||
| 62 | +say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; } | ||
| 63 | +die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; } | ||
| 64 | + | ||
| 65 | +# ---------------------------------------------------------------- 0. preflight | ||
| 66 | +say "0/7 preflight" | ||
| 67 | + | ||
| 68 | +if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | ||
| 69 | + say "using scorpiox-cli-botplugin publish" | ||
| 70 | + exec scorpiox-cli-botplugin publish "$ROOT" | ||
| 71 | +fi | ||
| 72 | +echo " running the standalone pipeline (dist + plugingit mirror)" | ||
| 73 | + | ||
| 74 | +[ -n "$(git status --porcelain 2>/dev/null)" ] && \ | ||
| 75 | + echo " note: working tree is dirty; source.tar.gz comes from the last commit" | ||
| 76 | +COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown") | ||
| 77 | +echo " version $VERSION" | ||
| 78 | +echo " commit $COMMIT" | ||
| 79 | + | ||
| 80 | +# ---------------------------------------------------------------- 1. secret scan | ||
| 81 | +say "1/7 secret & LAN scan (full history)" | ||
| 82 | + | ||
| 83 | +SCAN_TMP="$STAGE/history.txt" | ||
| 84 | +# Scan every added/removed line of every commit. Two exclusions, both about the | ||
| 85 | +# audit rather than the code: the committer identity line, and any line that is | ||
| 86 | +# itself a scan definition — otherwise this file's own detector patterns read as | ||
| 87 | +# findings in every historical revision of it. | ||
| 88 | +git log -p --all 2>/dev/null \ | ||
| 89 | + | grep -v '^Author: ' \ | ||
| 90 | + | grep -vE 'scan "|HITS=|grep -E|P_ROOT=|P_WT=|\$ALL' \ | ||
| 91 | + > "$SCAN_TMP" || : > "$SCAN_TMP" | ||
| 92 | +HITS=0 | ||
| 93 | +scan() { # scan <label> <regex> | ||
| 94 | + local out | ||
| 95 | + out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true) | ||
| 96 | + if [ -n "$out" ]; then | ||
| 97 | + printf ' \033[31mHIT\033[0m %s\n' "$1" | ||
| 98 | + printf '%s\n' "$out" | sed 's/^/ /' | ||
| 99 | + HITS=$((HITS + 1)) | ||
| 100 | + else | ||
| 101 | + printf ' ok %s\n' "$1" | ||
| 102 | + fi | ||
| 103 | +} | ||
| 104 | +scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+' | ||
| 105 | +scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | ||
| 106 | +scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | ||
| 107 | +scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | ||
| 108 | +scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | ||
| 109 | +scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}' | ||
| 110 | +scan "hard-coded ssh password" 'sshpass -p [^"$]' | ||
| 111 | +P_ROOT="/codebases" | ||
| 112 | +P_PICOBOT="${P_ROOT}/pico""bot" | ||
| 113 | +P_WT=".work""trees" | ||
| 114 | +scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}" | ||
| 115 | +scan "run-token env assignment" 'RUNNER_'"PASS=" | ||
| 116 | +if [ "$HITS" -ne 0 ]; then | ||
| 117 | + die "secret scan found $HITS problem(s) — refusing to publish" | ||
| 118 | +fi | ||
| 119 | +echo " clean: 0 hits" | ||
| 120 | + | ||
| 121 | +# ---------------------------------------------------------------- 2. build | ||
| 122 | +say "2/7 build targets" | ||
| 123 | + | ||
| 124 | +build_ok() { [ -f "$1" ]; } | ||
| 125 | + | ||
| 126 | +# linux-x86_64 (glibc, native) | ||
| 127 | +if command -v cc >/dev/null 2>&1; then | ||
| 128 | + cc -O2 -std=c99 -Wall -Wextra -o "$STAGE/$ID" src/$ID.c || die "native build failed" | ||
| 129 | + echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes" | ||
| 130 | +else | ||
| 131 | + die "no native cc found" | ||
| 132 | +fi | ||
| 133 | + | ||
| 134 | +# linux-x86_64-musl (fully static — the universal Linux artifact) | ||
| 135 | +if command -v musl-gcc >/dev/null 2>&1; then | ||
| 136 | + musl-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.musl" src/$ID.c \ | ||
| 137 | + || die "musl build failed" | ||
| 138 | + echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes" | ||
| 139 | +else | ||
| 140 | + echo " skip linux-x86_64-musl (no musl-gcc)" | ||
| 141 | +fi | ||
| 142 | + | ||
| 143 | +# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers). | ||
| 144 | +# Prefer musl; on a host that only has the Debian cross toolchain the static | ||
| 145 | +# glibc link still yields a self-contained aarch64 ELF. | ||
| 146 | +if command -v aarch64-linux-musl-gcc >/dev/null 2>&1; then | ||
| 147 | + aarch64-linux-musl-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.arm64" src/$ID.c \ | ||
| 148 | + || die "arm64 musl build failed" | ||
| 149 | + echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | ||
| 150 | +elif command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | ||
| 151 | + aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.arm64" src/$ID.c \ | ||
| 152 | + || die "arm64 static build failed" | ||
| 153 | + echo " built linux-arm64-static $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | ||
| 154 | +else | ||
| 155 | + echo " skip linux-arm64-musl (no aarch64 cross compiler)" | ||
| 156 | +fi | ||
| 157 | + | ||
| 158 | +# windows-x86_64 (static PE) | ||
| 159 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | ||
| 160 | + x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.exe" src/$ID.c \ | ||
| 161 | + || die "MinGW build failed" | ||
| 162 | + [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE" | ||
| 163 | + echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes" | ||
| 164 | +else | ||
| 165 | + echo " skip windows-x86_64 (no MinGW cross compiler)" | ||
| 166 | +fi | ||
| 167 | + | ||
| 168 | +# macOS legs — Mach-O must be produced by Apple clang on a real Mac. | ||
| 169 | +# Both slices are cross-built from one host: -arch arm64 and -arch x86_64. | ||
| 170 | +if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then | ||
| 171 | + MAC_USER="${MAC_USER:-$(whoami)}" | ||
| 172 | + MAC_DIR="/tmp/${ID}-mac-$$" | ||
| 173 | + echo " building macOS legs on $MAC_HOST" | ||
| 174 | + SSH_MAC=(ssh -o StrictHostKeyChecking=no) | ||
| 175 | + SCP_MAC=(scp -o StrictHostKeyChecking=no) | ||
| 176 | + if [ -n "${MAC_PASS:-}" ]; then | ||
| 177 | + SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}") | ||
| 178 | + SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}") | ||
| 179 | + fi | ||
| 180 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then | ||
| 181 | + if "${SCP_MAC[@]}" src/$ID.c "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.c"; then | ||
| 182 | + # Build straight from the uploaded file — no src/ tree on the remote. | ||
| 183 | + for slice in arm64 x86_64; do | ||
| 184 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \ | ||
| 185 | + "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -arch $slice -o $ID.$slice $ID.c" \ | ||
| 186 | + 2>/dev/null; then | ||
| 187 | + "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \ | ||
| 188 | + && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)" | ||
| 189 | + else | ||
| 190 | + echo " warn: macos-$slice build failed on $MAC_HOST" | ||
| 191 | + fi | ||
| 192 | + done | ||
| 193 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" 2>/dev/null || true | ||
| 194 | + else | ||
| 195 | + echo " warn: mac scp failed" | ||
| 196 | + fi | ||
| 197 | + else | ||
| 198 | + echo " warn: mac host unreachable" | ||
| 199 | + fi | ||
| 200 | +else | ||
| 201 | + echo " skip macOS legs (set MAC_HOST/MAC_USER/MAC_PASS to include them)" | ||
| 202 | +fi | ||
| 203 | + | ||
| 204 | +# ---------------------------------------------------------------- 3. package | ||
| 205 | +say "3/7 package" | ||
| 206 | + | ||
| 207 | +git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \ | ||
| 208 | + -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \ | ||
| 209 | + || tar -czf "$STAGE/source.tar.gz" --exclude=.git . | ||
| 210 | +echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes" | ||
| 211 | + | ||
| 212 | +target_meta() { # target_meta <key> <file> <format> <relpath> <name> | ||
| 213 | + local key="$1" file="$2" fmt="$3" rel="$4" name="$5" | ||
| 214 | + [ -f "$file" ] || return 0 | ||
| 215 | + local sha size | ||
| 216 | + sha=$(sha256sum "$file" | awk '{print $1}') | ||
| 217 | + size=$(wc -c < "$file" | tr -d ' ') | ||
| 218 | + printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \ | ||
| 219 | + "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt" | ||
| 220 | +} | ||
| 221 | + | ||
| 222 | +{ | ||
| 223 | + printf '{\n' | ||
| 224 | + printf ' "slug": "%s",\n' "$SLUG" | ||
| 225 | + printf ' "id": "%s",\n' "$ID" | ||
| 226 | + printf ' "name": "nvtop",\n' | ||
| 227 | + printf ' "desc": "Local GPUs",\n' | ||
| 228 | + printf ' "title": "Local GPU Telemetry",\n' | ||
| 229 | + printf ' "summary": "Zero-dependency local GPU dashboard: probes nvidia-smi, rocm-smi and Apple Silicon ioreg on the node it runs on, charts per-GPU compute and VRAM as rolling sparklines, and lists every compute process with its GPU, PID and VRAM. Degrades to a clean explanatory empty state on CPU-only nodes.",\n' | ||
| 230 | + printf ' "category": "system",\n' | ||
| 231 | + printf ' "version": "%s",\n' "$VERSION" | ||
| 232 | + printf ' "license": "MIT",\n' | ||
| 233 | + printf ' "trust_notice": "Executes native C code on your node. Runs the fixed commands nvidia-smi, rocm-smi and ioreg locally and parses their output; makes zero outbound network requests, opens no sockets, runs no remote commands and reads no credentials.",\n' | ||
| 234 | + printf ' "capabilities": ["local_gpu_query", "local_process_list"],\n' | ||
| 235 | + printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG" | ||
| 236 | + printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG" | ||
| 237 | + printf ' "git_commit": "%s",\n' "$COMMIT" | ||
| 238 | + printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | ||
| 239 | + printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')" | ||
| 240 | + printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID" | ||
| 241 | + printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID" | ||
| 242 | + printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" | ||
| 243 | + printf ' "targets": {\n' | ||
| 244 | + first=1 | ||
| 245 | + emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; } | ||
| 246 | + emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" "$ID" | ||
| 247 | + emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" "$ID" | ||
| 248 | + emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID" "$ID" | ||
| 249 | + emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" "$ID" | ||
| 250 | + emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" "$ID" | ||
| 251 | + emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" "$ID" | ||
| 252 | + printf '\n }\n}\n' | ||
| 253 | +} > "$STAGE/manifest.json" | ||
| 254 | + | ||
| 255 | +python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \ | ||
| 256 | + || die "generated manifest.json is not valid JSON" | ||
| 257 | +echo " manifest.json ok" | ||
| 258 | + | ||
| 259 | +# SHA256SUMS — relative paths, exactly as published | ||
| 260 | +( cd "$STAGE" | ||
| 261 | + for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done | ||
| 262 | + [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|" | ||
| 263 | + [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|" | ||
| 264 | + [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|" | ||
| 265 | + [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|" | ||
| 266 | + [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|" | ||
| 267 | + [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|" | ||
| 268 | + true ) > "$STAGE/SHA256SUMS" | ||
| 269 | +echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries" | ||
| 270 | + | ||
| 271 | +# ---------------------------------------------------------------- 4. stage | ||
| 272 | +say "4/7 stage tree" | ||
| 273 | +PKG="$STAGE/pkg" | ||
| 274 | +mkdir -p "$PKG/linux-x86_64" "$PKG/linux-x86_64-musl" "$PKG/linux-arm64-musl" \ | ||
| 275 | + "$PKG/macos-arm64" "$PKG/macos-x86_64" "$PKG/windows-x86_64" | ||
| 276 | +cp -f "$STAGE/$ID" "$PKG/linux-x86_64/$ID" | ||
| 277 | +[ -f "$STAGE/$ID.musl" ] && cp -f "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID" | ||
| 278 | +[ -f "$STAGE/$ID.arm64" ] && cp -f "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID" | ||
| 279 | +[ -f "$STAGE/$ID.macos-arm64" ]&& cp -f "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID" | ||
| 280 | +[ -f "$STAGE/$ID.macos-x86_64" ]&&cp -f "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID" | ||
| 281 | +[ -f "$STAGE/$ID.exe" ] && cp -f "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe" | ||
| 282 | +cp -f "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/" | ||
| 283 | +chmod +x "$PKG"/*/$ID 2>/dev/null || true | ||
| 284 | +find "$PKG" -type f | sed 's/^/ /' | ||
| 285 | + | ||
| 286 | +if [ "$DRY_RUN" -eq 1 ]; then | ||
| 287 | + say "dry run — staged at $STAGE/pkg (kept for inspection)" | ||
| 288 | + trap - EXIT | ||
| 289 | + exit 0 | ||
| 290 | +fi | ||
| 291 | + | ||
| 292 | +# ---------------------------------------------------------------- 5. upload | ||
| 293 | +say "5/7 upload" | ||
| 294 | + | ||
| 295 | +[ -n "$DIST_HOST" ] || die "DIST_HOST is not set — cannot upload" | ||
| 296 | +SSH=(ssh -o StrictHostKeyChecking=no) | ||
| 297 | +SCP=(scp -o StrictHostKeyChecking=no) | ||
| 298 | +if [ -n "$DIST_PASS" ]; then | ||
| 299 | + SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}") | ||
| 300 | + SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}") | ||
| 301 | +fi | ||
| 302 | +REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION" | ||
| 303 | + | ||
| 304 | +"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \ | ||
| 305 | + || die "cannot create $REMOTE_DIR on $DIST_HOST" | ||
| 306 | +# Stage to one tarball, transfer it, extract remotely. Streaming tar through | ||
| 307 | +# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and | ||
| 308 | +# OpenSSH 9 refuses to scp a bare "." source. | ||
| 309 | +tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed" | ||
| 310 | +"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed" | ||
| 311 | +"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \ | ||
| 312 | + || die "remote extract failed" | ||
| 313 | +echo " uploaded to $DIST_HOST:$REMOTE_DIR" | ||
| 314 | + | ||
| 315 | +# latest.json = copy of this version's manifest | ||
| 316 | +"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \ | ||
| 317 | + || die "latest.json update failed" | ||
| 318 | +echo " updated bot-plugins/$SLUG/latest.json" | ||
| 319 | + | ||
| 320 | +# index.json — merge, preserving every sibling <slug>/latest.json | ||
| 321 | +say "index.json merge" | ||
| 322 | +"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY' | ||
| 323 | +import json, os, sys, glob | ||
| 324 | +slug = sys.argv[1] | ||
| 325 | +entries = {} | ||
| 326 | +for p in sorted(glob.glob('*/latest.json')): | ||
| 327 | + s = os.path.dirname(p) | ||
| 328 | + try: | ||
| 329 | + entries[s] = json.load(open(p)) | ||
| 330 | + except Exception: | ||
| 331 | + pass | ||
| 332 | +index = { | ||
| 333 | + 'ok': True, | ||
| 334 | + 'service': 'bot-plugins-dist', | ||
| 335 | + 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins', | ||
| 336 | + 'count': len(entries), | ||
| 337 | + 'slugs': sorted(entries), | ||
| 338 | + 'plugins': [entries[k] for k in sorted(entries)], | ||
| 339 | +} | ||
| 340 | +open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10)) | ||
| 341 | +os.replace('index.json.tmp', 'index.json') | ||
| 342 | +print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries)))) | ||
| 343 | +PY" || die "index.json merge failed" | ||
| 344 | + | ||
| 345 | +# ---------------------------------------------------------------- 6. mirror | ||
| 346 | +say "6/7 plugingit mirror" | ||
| 347 | +if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then | ||
| 348 | + TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE") | ||
| 349 | + AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://x-access-token:${TOKEN}@|") | ||
| 350 | + git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed" | ||
| 351 | + git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true | ||
| 352 | + echo " mirrored to $PLUGINGIT_REMOTE" | ||
| 353 | +else | ||
| 354 | + echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)" | ||
| 355 | +fi | ||
| 356 | + | ||
| 357 | +# ---------------------------------------------------------------- 7. verify | ||
| 358 | +say "7/7 verify" | ||
| 359 | +CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \ | ||
| 360 | + "$DIST_BASE_URL/$SLUG/latest.json" || echo 000) | ||
| 361 | +if [ "$CODE" = "200" ]; then | ||
| 362 | + python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK — %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \ | ||
| 363 | + "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON" | ||
| 364 | +else | ||
| 365 | + echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE" | ||
| 366 | +fi | ||
| 367 | + | ||
| 368 | +printf '\n\033[1mrelease complete\033[0m\n' | ||
| 369 | +printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | ||
| 370 | +printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..b04d270 | index 0000000..b04d270 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/plugin_nvtop.c | +++ b/src/plugin_nvtop.c | ||
| @@ -0,0 +1,1198 @@ | @@ -0,0 +1,1198 @@ | ||
| 1 | +/* | ||
| 2 | + * plugin_nvtop - ScorpioX Bot open-source local GPU telemetry plugin | ||
| 3 | + * | ||
| 4 | + * A single clean-room C99 binary that serves THREE modes: | ||
| 5 | + * 1. --meta / SX_PLUGIN_META=1 -> JSON metadata for discovery | ||
| 6 | + * 2. ?action=metrics | ?action=info | ?format=json | ||
| 7 | + * -> JSON node API | ||
| 8 | + * 3. GET (default) -> responsive HTML dashboard | ||
| 9 | + * | ||
| 10 | + * Strictly LOCAL. The plugin runs nvidia-smi / rocm-smi / ioreg on THIS node | ||
| 11 | + * (the one the plugin is installed on) and parses their CSV/text output. It | ||
| 12 | + * never opens a socket, never runs ssh, and never accepts a host, a command or | ||
| 13 | + * a path from the query string: every command below is a fixed constant. | ||
| 14 | + * | ||
| 15 | + * On a node with no local GPU it reports a clean empty state instead of an | ||
| 16 | + * error, so the dashboard is useful on every machine in the fleet. | ||
| 17 | + * | ||
| 18 | + * Offline determinism: set NVTOP_MOCK_CSV=<path> to make the plugin read a | ||
| 19 | + * small CSV fixture instead of shelling out. That is how the test suite | ||
| 20 | + * exercises multi-GPU behaviour on CPU-only build hosts. | ||
| 21 | + * | ||
| 22 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | ||
| 23 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | ||
| 24 | + * scorpiox-server on the node. | ||
| 25 | + * | ||
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 27 | + */ | ||
| 28 | + | ||
| 29 | +#if defined(__APPLE__) | ||
| 30 | + /* sysctl / ioctl headers pull BSD types that strict c99 would hide */ | ||
| 31 | +# define _DARWIN_C_SOURCE 1 | ||
| 32 | +#elif !defined(_WIN32) | ||
| 33 | +# define _POSIX_C_SOURCE 200809L | ||
| 34 | +# define _DEFAULT_SOURCE 1 | ||
| 35 | +#endif | ||
| 36 | + | ||
| 37 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | ||
| 38 | +# define _WIN32_WINNT 0x0601 | ||
| 39 | +#endif | ||
| 40 | + | ||
| 41 | +#include <stdio.h> | ||
| 42 | +#include <stdlib.h> | ||
| 43 | +#include <string.h> | ||
| 44 | +#include <time.h> | ||
| 45 | +#include <ctype.h> | ||
| 46 | +#include <errno.h> | ||
| 47 | + | ||
| 48 | +#if defined(_WIN32) | ||
| 49 | +# define WIN32_LEAN_AND_MEAN | ||
| 50 | +# include <windows.h> | ||
| 51 | +#else | ||
| 52 | +# include <unistd.h> | ||
| 53 | +# include <sys/types.h> | ||
| 54 | +#endif | ||
| 55 | + | ||
| 56 | +#define PLUGIN_SLUG "nvtop" | ||
| 57 | +#define PLUGIN_ID "plugin_nvtop" | ||
| 58 | +#define PLUGIN_VER "1.0.0" | ||
| 59 | + | ||
| 60 | +#define MAX_GPUS 32 | ||
| 61 | +#define MAX_PROCS 256 | ||
| 62 | +#define MAX_NAME 96 | ||
| 63 | +#define MAX_UUID 64 | ||
| 64 | +#define MAX_DRIVER 48 | ||
| 65 | + | ||
| 66 | +/* popen is the only external-process mechanism used, and every command string | ||
| 67 | + * is a compile-time constant. stderr redirection differs per platform because | ||
| 68 | + * popen() goes through the shell. */ | ||
| 69 | +#if defined(_WIN32) | ||
| 70 | +# define DEV_NULL " 2>NUL" | ||
| 71 | +#else | ||
| 72 | +# define DEV_NULL " 2>/dev/null" | ||
| 73 | +#endif | ||
| 74 | + | ||
| 75 | +/* ------------------------------------------------------------------ */ | ||
| 76 | +/* Small utilities */ | ||
| 77 | +/* ------------------------------------------------------------------ */ | ||
| 78 | + | ||
| 79 | +/* Percent-decode in place ('+' becomes space). */ | ||
| 80 | +static void url_decode(char *s) | ||
| 81 | +{ | ||
| 82 | + char *o = s; | ||
| 83 | + if (!s) return; | ||
| 84 | + while (*s) { | ||
| 85 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | ||
| 86 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | ||
| 87 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | ||
| 88 | + *o++ = (char)((hi << 4) | lo); | ||
| 89 | + s += 3; | ||
| 90 | + } else if (*s == '+') { | ||
| 91 | + *o++ = ' '; | ||
| 92 | + s++; | ||
| 93 | + } else { | ||
| 94 | + *o++ = *s++; | ||
| 95 | + } | ||
| 96 | + } | ||
| 97 | + *o = '\0'; | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +/* Read one parameter (decoded) out of a form/query string. */ | ||
| 101 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | ||
| 102 | +{ | ||
| 103 | + size_t klen; | ||
| 104 | + const char *p; | ||
| 105 | + | ||
| 106 | + if (!out || outsz == 0) return 0; | ||
| 107 | + out[0] = '\0'; | ||
| 108 | + if (!qs || !key) return 0; | ||
| 109 | + klen = strlen(key); | ||
| 110 | + | ||
| 111 | + for (p = qs; *p; ) { | ||
| 112 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | ||
| 113 | + const char *v = p + klen + 1; | ||
| 114 | + size_t i = 0; | ||
| 115 | + while (*v && *v != '&' && i + 1 < outsz) | ||
| 116 | + out[i++] = *v++; | ||
| 117 | + out[i] = '\0'; | ||
| 118 | + url_decode(out); | ||
| 119 | + return 1; | ||
| 120 | + } | ||
| 121 | + p = strchr(p, '&'); | ||
| 122 | + if (!p) break; | ||
| 123 | + p++; | ||
| 124 | + } | ||
| 125 | + return 0; | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +static void json_str(const char *s) | ||
| 129 | +{ | ||
| 130 | + putchar('"'); | ||
| 131 | + for (; s && *s; s++) { | ||
| 132 | + unsigned char c = (unsigned char)*s; | ||
| 133 | + switch (c) { | ||
| 134 | + case '"': fputs("\\\"", stdout); break; | ||
| 135 | + case '\\': fputs("\\\\", stdout); break; | ||
| 136 | + case '\n': fputs("\\n", stdout); break; | ||
| 137 | + case '\r': fputs("\\r", stdout); break; | ||
| 138 | + case '\t': fputs("\\t", stdout); break; | ||
| 139 | + default: | ||
| 140 | + if (c >= 0x20) putchar((int)c); | ||
| 141 | + break; | ||
| 142 | + } | ||
| 143 | + } | ||
| 144 | + putchar('"'); | ||
| 145 | +} | ||
| 146 | + | ||
| 147 | +static void utc_now(char *buf, size_t sz) | ||
| 148 | +{ | ||
| 149 | + time_t t = time(NULL); | ||
| 150 | + struct tm tmv; | ||
| 151 | + memset(&tmv, 0, sizeof(tmv)); | ||
| 152 | +#if defined(_WIN32) | ||
| 153 | + { | ||
| 154 | + struct tm *p = gmtime(&t); | ||
| 155 | + if (p) tmv = *p; | ||
| 156 | + } | ||
| 157 | +#else | ||
| 158 | + gmtime_r(&t, &tmv); | ||
| 159 | +#endif | ||
| 160 | + strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); | ||
| 161 | +} | ||
| 162 | + | ||
| 163 | +static long node_pid(void) | ||
| 164 | +{ | ||
| 165 | +#if defined(_WIN32) | ||
| 166 | + return (long)GetCurrentProcessId(); | ||
| 167 | +#else | ||
| 168 | + return (long)getpid(); | ||
| 169 | +#endif | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +static void copy_str(char *dst, size_t dstsz, const char *src) | ||
| 173 | +{ | ||
| 174 | + size_t n; | ||
| 175 | + if (!dst || dstsz == 0) return; | ||
| 176 | + if (!src) { dst[0] = '\0'; return; } | ||
| 177 | + n = strlen(src); | ||
| 178 | + if (n >= dstsz) n = dstsz - 1; | ||
| 179 | + memcpy(dst, src, n); | ||
| 180 | + dst[n] = '\0'; | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +/* Trim leading/trailing whitespace in place, return the trimmed start. */ | ||
| 184 | +static char *trim(char *s) | ||
| 185 | +{ | ||
| 186 | + char *e; | ||
| 187 | + if (!s) return s; | ||
| 188 | + while (*s && (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')) s++; | ||
| 189 | + e = s + strlen(s); | ||
| 190 | + while (e > s && (e[-1] == ' ' || e[-1] == '\t' || e[-1] == '\r' || e[-1] == '\n')) e--; | ||
| 191 | + *e = '\0'; | ||
| 192 | + return s; | ||
| 193 | +} | ||
| 194 | + | ||
| 195 | +/* nvidia-smi prints "[N/A]" / "N/A" when a counter is unsupported. */ | ||
| 196 | +static int parse_num(const char *s, double *out) | ||
| 197 | +{ | ||
| 198 | + char *end = NULL; | ||
| 199 | + double v; | ||
| 200 | + if (!s || !*s) return 0; | ||
| 201 | + if (strstr(s, "N/A") || strstr(s, "n/a")) return 0; | ||
| 202 | + errno = 0; | ||
| 203 | + v = strtod(s, &end); | ||
| 204 | + if (end == s || errno != 0) return 0; | ||
| 205 | + *out = v; | ||
| 206 | + return 1; | ||
| 207 | +} | ||
| 208 | + | ||
| 209 | +/* Split one CSV line in place; returns the field count (max maxf). */ | ||
| 210 | +static int split_csv(char *line, char **fields, int maxf) | ||
| 211 | +{ | ||
| 212 | + int n = 0; | ||
| 213 | + char *p = line; | ||
| 214 | + if (!line) return 0; | ||
| 215 | + while (n < maxf) { | ||
| 216 | + fields[n++] = p; | ||
| 217 | + p = strchr(p, ','); | ||
| 218 | + if (!p) break; | ||
| 219 | + *p++ = '\0'; | ||
| 220 | + } | ||
| 221 | + return n; | ||
| 222 | +} | ||
| 223 | + | ||
| 224 | +/* ------------------------------------------------------------------ */ | ||
| 225 | +/* Node authentication */ | ||
| 226 | +/* ------------------------------------------------------------------ */ | ||
| 227 | + | ||
| 228 | +/* | ||
| 229 | + * The node API on :8150 is reachable from the LAN. Every request except | ||
| 230 | + * --meta discovery must prove it knows the node password. Accepted forms | ||
| 231 | + * match the rest of the node API: X-Bot-Password (what bot-web proxies | ||
| 232 | + * with), Authorization: Bearer, and ?pwd= (what the plugin iframe appends). | ||
| 233 | + * When BOT_PASSWORD is unset the plugin is a deliberate no-op, which is how | ||
| 234 | + * a developer runs it locally from a shell. | ||
| 235 | + */ | ||
| 236 | +static void require_node_auth(void) | ||
| 237 | +{ | ||
| 238 | + const char *np = getenv("BOT_PASSWORD"); | ||
| 239 | + const char *xp; | ||
| 240 | + const char *auth; | ||
| 241 | + char qpwd[256]; | ||
| 242 | + const char *qs; | ||
| 243 | + | ||
| 244 | + if (!np || !*np) return; | ||
| 245 | + | ||
| 246 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | ||
| 247 | + if (xp && strcmp(xp, np) == 0) return; | ||
| 248 | + | ||
| 249 | + auth = getenv("HTTP_AUTHORIZATION"); | ||
| 250 | + if (auth) { | ||
| 251 | + while (*auth == ' ') auth++; | ||
| 252 | + if (strncmp(auth, "Bearer ", 7) == 0) { | ||
| 253 | + auth += 7; | ||
| 254 | + while (*auth == ' ') auth++; | ||
| 255 | + if (strcmp(auth, np) == 0) return; | ||
| 256 | + } | ||
| 257 | + } | ||
| 258 | + | ||
| 259 | + qs = getenv("QUERY_STRING"); | ||
| 260 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) | ||
| 261 | + return; | ||
| 262 | + | ||
| 263 | + fputs("Status: 401 Unauthorized\r\n" | ||
| 264 | + "Content-Type: application/json; charset=utf-8\r\n" | ||
| 265 | + "Cache-Control: no-store\r\n" | ||
| 266 | + "X-Content-Type-Options: nosniff\r\n\r\n" | ||
| 267 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | ||
| 268 | + exit(0); | ||
| 269 | +} | ||
| 270 | + | ||
| 271 | +/* ------------------------------------------------------------------ */ | ||
| 272 | +/* Snapshot */ | ||
| 273 | +/* ------------------------------------------------------------------ */ | ||
| 274 | + | ||
| 275 | +typedef struct { | ||
| 276 | + int index; | ||
| 277 | + char uuid[MAX_UUID]; | ||
| 278 | + char name[MAX_NAME]; | ||
| 279 | + double util_gpu; | ||
| 280 | + double mem_used_mb; | ||
| 281 | + double mem_total_mb; | ||
| 282 | + double temp_c; | ||
| 283 | + double power_w; | ||
| 284 | + double power_limit_w; | ||
| 285 | + int has_temp; | ||
| 286 | + int has_power; | ||
| 287 | + int has_plimit; | ||
| 288 | +} gpu_t; | ||
| 289 | + | ||
| 290 | +typedef struct { | ||
| 291 | + char gpu_uuid[MAX_UUID]; | ||
| 292 | + long pid; | ||
| 293 | + char name[MAX_NAME]; | ||
| 294 | + double used_mb; | ||
| 295 | +} proc_t; | ||
| 296 | + | ||
| 297 | +typedef struct { | ||
| 298 | + gpu_t gpus[MAX_GPUS]; | ||
| 299 | + int ngpu; | ||
| 300 | + proc_t procs[MAX_PROCS]; | ||
| 301 | + int nproc; | ||
| 302 | + char driver[MAX_DRIVER]; | ||
| 303 | + char source[16]; /* nvidia / amd / apple / mock / none */ | ||
| 304 | + int available; | ||
| 305 | + int mocked; | ||
| 306 | + char note[192]; | ||
| 307 | +} snap_t; | ||
| 308 | + | ||
| 309 | +static void snap_init(snap_t *s) | ||
| 310 | +{ | ||
| 311 | + memset(s, 0, sizeof(*s)); | ||
| 312 | + copy_str(s->source, sizeof(s->source), "none"); | ||
| 313 | + copy_str(s->note, sizeof(s->note), "No local NVIDIA/AMD GPU detected"); | ||
| 314 | +} | ||
| 315 | + | ||
| 316 | +/* Run a fixed command and stream its stdout line by line. */ | ||
| 317 | +typedef void (*line_fn)(char *line, void *ctx); | ||
| 318 | + | ||
| 319 | +static int feed_file_lines(const char *path, line_fn fn, void *ctx); | ||
| 320 | + | ||
| 321 | +static int run_cmd_lines(const char *cmd, line_fn fn, void *ctx) | ||
| 322 | +{ | ||
| 323 | + FILE *fp; | ||
| 324 | + char buf[1024]; | ||
| 325 | + int any = 0; | ||
| 326 | + | ||
| 327 | + fp = popen(cmd, "r"); | ||
| 328 | + if (!fp) return 0; | ||
| 329 | + while (fgets(buf, (int)sizeof(buf), fp)) { | ||
| 330 | + size_t n = strlen(buf); | ||
| 331 | + while (n && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; | ||
| 332 | + if (!buf[0] || buf[0] == '#') continue; | ||
| 333 | + any = 1; | ||
| 334 | + fn(buf, ctx); | ||
| 335 | + } | ||
| 336 | + pclose(fp); | ||
| 337 | + return any; | ||
| 338 | +} | ||
| 339 | + | ||
| 340 | +/* ---- mock fixture ------------------------------------------------- */ | ||
| 341 | + | ||
| 342 | +/* | ||
| 343 | + * NVTOP_MOCK_CSV fixture format (one record per line, '#' comments allowed): | ||
| 344 | + * | ||
| 345 | + * GPU,<index>,<uuid>,<name>,<util%>,<mem_used_mb>,<mem_total_mb>,<temp_c>,<power_w>,<power_limit_w>,<driver> | ||
| 346 | + * APP,<gpu_uuid>,<pid>,<process name>,<used_mb> | ||
| 347 | + * | ||
| 348 | + * A field of "-" or "N/A" means "this counter is unavailable". Only the default | ||
| 349 | + * test fixtures use this path; production runs never set the variable. | ||
| 350 | + */ | ||
| 351 | +static void mock_line(char *line, void *ctx) | ||
| 352 | +{ | ||
| 353 | + snap_t *s = (snap_t *)ctx; | ||
| 354 | + char *f[12]; | ||
| 355 | + int n; | ||
| 356 | + | ||
| 357 | + if (line[0] == '#') return; | ||
| 358 | + n = split_csv(line, f, 12); | ||
| 359 | + if (n < 2) return; | ||
| 360 | + | ||
| 361 | + if (strcmp(trim(f[0]), "GPU") == 0 && n >= 11 && s->ngpu < MAX_GPUS) { | ||
| 362 | + gpu_t *g = &s->gpus[s->ngpu]; | ||
| 363 | + char *idx; | ||
| 364 | + memset(g, 0, sizeof(*g)); | ||
| 365 | + idx = trim(f[1]); | ||
| 366 | + g->index = atoi(idx); | ||
| 367 | + copy_str(g->uuid, sizeof(g->uuid), trim(f[2])); | ||
| 368 | + copy_str(g->name, sizeof(g->name), trim(f[3])); | ||
| 369 | + parse_num(trim(f[4]), &g->util_gpu); | ||
| 370 | + parse_num(trim(f[5]), &g->mem_used_mb); | ||
| 371 | + parse_num(trim(f[6]), &g->mem_total_mb); | ||
| 372 | + g->has_temp = parse_num(trim(f[7]), &g->temp_c); | ||
| 373 | + g->has_power = parse_num(trim(f[8]), &g->power_w); | ||
| 374 | + g->has_plimit = parse_num(trim(f[9]), &g->power_limit_w); | ||
| 375 | + if (!s->driver[0] && trim(f[10])[0] && strcmp(trim(f[10]), "-") != 0) | ||
| 376 | + copy_str(s->driver, sizeof(s->driver), trim(f[10])); | ||
| 377 | + s->ngpu++; | ||
| 378 | + } else if (strcmp(trim(f[0]), "APP") == 0 && n >= 5 && s->nproc < MAX_PROCS) { | ||
| 379 | + proc_t *p = &s->procs[s->nproc]; | ||
| 380 | + memset(p, 0, sizeof(*p)); | ||
| 381 | + copy_str(p->gpu_uuid, sizeof(p->gpu_uuid), trim(f[1])); | ||
| 382 | + p->pid = (long)atoi(trim(f[2])); | ||
| 383 | + copy_str(p->name, sizeof(p->name), trim(f[3])); | ||
| 384 | + parse_num(trim(f[4]), &p->used_mb); | ||
| 385 | + s->nproc++; | ||
| 386 | + } | ||
| 387 | +} | ||
| 388 | + | ||
| 389 | +static int load_mock(snap_t *s, const char *path) | ||
| 390 | +{ | ||
| 391 | + FILE *fp; | ||
| 392 | + char buf[1024]; | ||
| 393 | + int any = 0; | ||
| 394 | + | ||
| 395 | + fp = fopen(path, "r"); | ||
| 396 | + if (!fp) return 0; | ||
| 397 | + while (fgets(buf, (int)sizeof(buf), fp)) { | ||
| 398 | + size_t n = strlen(buf); | ||
| 399 | + while (n && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; | ||
| 400 | + if (!buf[0]) continue; | ||
| 401 | + any = 1; | ||
| 402 | + mock_line(buf, s); | ||
| 403 | + } | ||
| 404 | + fclose(fp); | ||
| 405 | + if (!any) return 0; | ||
| 406 | + s->mocked = 1; | ||
| 407 | + copy_str(s->source, sizeof(s->source), "mock"); | ||
| 408 | + s->available = s->ngpu > 0; | ||
| 409 | + if (s->available) s->note[0] = '\0'; | ||
| 410 | + return 1; | ||
| 411 | +} | ||
| 412 | + | ||
| 413 | +/* ---- NVIDIA ------------------------------------------------------- */ | ||
| 414 | + | ||
| 415 | +struct nv_ctx { snap_t *s; int stage; }; | ||
| 416 | +struct nv_mock_ctx { struct nv_ctx gpu; snap_t *s; }; | ||
| 417 | + | ||
| 418 | +/* | ||
| 419 | + * nvidia-smi --query-gpu=... --format=csv,noheader,nounits | ||
| 420 | + * index,uuid,name,utilization.gpu,memory.used,memory.total, | ||
| 421 | + * temperature.gpu,power.draw,power.limit,driver_version | ||
| 422 | + */ | ||
| 423 | +static void nv_gpu_line(char *line, void *ctx) | ||
| 424 | +{ | ||
| 425 | + struct nv_ctx *c = (struct nv_ctx *)ctx; | ||
| 426 | + snap_t *s = c->s; | ||
| 427 | + char *f[12]; | ||
| 428 | + int n = split_csv(line, f, 12); | ||
| 429 | + gpu_t *g; | ||
| 430 | + | ||
| 431 | + if (n < 10 || s->ngpu >= MAX_GPUS) return; | ||
| 432 | + g = &s->gpus[s->ngpu]; | ||
| 433 | + memset(g, 0, sizeof(*g)); | ||
| 434 | + g->index = atoi(trim(f[0])); | ||
| 435 | + copy_str(g->uuid, sizeof(g->uuid), trim(f[1])); | ||
| 436 | + copy_str(g->name, sizeof(g->name), trim(f[2])); | ||
| 437 | + parse_num(trim(f[3]), &g->util_gpu); | ||
| 438 | + parse_num(trim(f[4]), &g->mem_used_mb); | ||
| 439 | + parse_num(trim(f[5]), &g->mem_total_mb); | ||
| 440 | + g->has_temp = parse_num(trim(f[6]), &g->temp_c); | ||
| 441 | + g->has_power = parse_num(trim(f[7]), &g->power_w); | ||
| 442 | + g->has_plimit = parse_num(trim(f[8]), &g->power_limit_w); | ||
| 443 | + if (!s->driver[0]) copy_str(s->driver, sizeof(s->driver), trim(f[9])); | ||
| 444 | + s->ngpu++; | ||
| 445 | +} | ||
| 446 | + | ||
| 447 | +static void nv_proc_line(char *line, void *ctx) | ||
| 448 | +{ | ||
| 449 | + snap_t *s = (snap_t *)ctx; | ||
| 450 | + char *f[8]; | ||
| 451 | + int n = split_csv(line, f, 8); | ||
| 452 | + proc_t *p; | ||
| 453 | + | ||
| 454 | + if (n < 4 || s->nproc >= MAX_PROCS) return; | ||
| 455 | + p = &s->procs[s->nproc]; | ||
| 456 | + memset(p, 0, sizeof(*p)); | ||
| 457 | + copy_str(p->gpu_uuid, sizeof(p->gpu_uuid), trim(f[0])); | ||
| 458 | + p->pid = (long)atoi(trim(f[1])); | ||
| 459 | + copy_str(p->name, sizeof(p->name), trim(f[2])); | ||
| 460 | + parse_num(trim(f[3]), &p->used_mb); | ||
| 461 | + s->nproc++; | ||
| 462 | +} | ||
| 463 | + | ||
| 464 | +static int collect_nvidia(snap_t *s) | ||
| 465 | +{ | ||
| 466 | + struct nv_ctx c; | ||
| 467 | + int got; | ||
| 468 | + | ||
| 469 | + const char *mocksmi = getenv("NVTOP_MOCK_NVIDIA"); | ||
| 470 | + | ||
| 471 | + c.s = s; | ||
| 472 | + if (mocksmi && *mocksmi) s->mocked = 1; | ||
| 473 | + c.stage = 0; | ||
| 474 | + if (mocksmi && *mocksmi) { | ||
| 475 | + /* Fixture may interleave raw nvidia-smi GPU csv lines and "APP,..." | ||
| 476 | + * process lines; dispatch each line to the parser it belongs to. */ | ||
| 477 | + FILE *fp = fopen(mocksmi, "r"); | ||
| 478 | + char buf[1024]; | ||
| 479 | + got = 0; | ||
| 480 | + if (fp) { | ||
| 481 | + while (fgets(buf, (int)sizeof(buf), fp)) { | ||
| 482 | + size_t n = strlen(buf); | ||
| 483 | + char *ln; | ||
| 484 | + while (n && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; | ||
| 485 | + ln = trim(buf); | ||
| 486 | + if (!ln[0] || ln[0] == '#') continue; | ||
| 487 | + got = 1; | ||
| 488 | + /* Process lines are re-shaped into the csv,noheader layout that | ||
| 489 | + * nv_proc_line expects: uuid,pid,name,used_mb. */ | ||
| 490 | + if (strncmp(ln, "APP,", 4) == 0) | ||
| 491 | + nv_proc_line(ln + 4, (void *)s); | ||
| 492 | + else | ||
| 493 | + nv_gpu_line(ln, (void *)&c); | ||
| 494 | + } | ||
| 495 | + fclose(fp); | ||
| 496 | + } | ||
| 497 | + } else { | ||
| 498 | + got = run_cmd_lines( | ||
| 499 | + "nvidia-smi --query-gpu=index,uuid,name,utilization.gpu,memory.used," | ||
| 500 | + "memory.total,temperature.gpu,power.draw,power.limit,driver_version " | ||
| 501 | + "--format=csv,noheader,nounits" DEV_NULL, nv_gpu_line, &c); | ||
| 502 | + } | ||
| 503 | + if (!got || s->ngpu == 0) return 0; | ||
| 504 | + | ||
| 505 | + run_cmd_lines( | ||
| 506 | + "nvidia-smi --query-compute-apps=gpu_uuid,pid,process_name,used_memory " | ||
| 507 | + "--format=csv,noheader,nounits" DEV_NULL, nv_proc_line, s); | ||
| 508 | + | ||
| 509 | + copy_str(s->source, sizeof(s->source), "nvidia"); | ||
| 510 | + s->available = 1; | ||
| 511 | + s->note[0] = '\0'; | ||
| 512 | + return 1; | ||
| 513 | +} | ||
| 514 | + | ||
| 515 | +/* ---- AMD (rocm-smi) ----------------------------------------------- */ | ||
| 516 | + | ||
| 517 | +/* | ||
| 518 | + * rocm-smi prints one "GPU[n] : <key>: <value>" line per counter, which is | ||
| 519 | + * stable across the 5.x and 6.x releases. VRAM is reported in bytes. | ||
| 520 | + */ | ||
| 521 | +static void amd_line(char *line, void *ctx) | ||
| 522 | +{ | ||
| 523 | + snap_t *s = (snap_t *)ctx; | ||
| 524 | + char *lb, *key, *val, *rbr, *sep; | ||
| 525 | + int idx; | ||
| 526 | + gpu_t *g; | ||
| 527 | + | ||
| 528 | + if (strncmp(line, "GPU[", 4) != 0) return; | ||
| 529 | + idx = atoi(line + 4); | ||
| 530 | + if (idx < 0 || idx >= MAX_GPUS) return; | ||
| 531 | + lb = strchr(line, '['); | ||
| 532 | + rbr = lb ? strchr(lb, ']') : NULL; | ||
| 533 | + if (!rbr) return; | ||
| 534 | + /* "GPU[0] : GPU use (%): 87" -> key "GPU use (%)", value "87" */ | ||
| 535 | + key = trim(rbr + 1); | ||
| 536 | + if (*key == ':') key++; | ||
| 537 | + sep = strrchr(key, ':'); | ||
| 538 | + if (!sep) return; | ||
| 539 | + *sep = '\0'; | ||
| 540 | + val = trim(sep + 1); | ||
| 541 | + key = trim(key); | ||
| 542 | + if (!key[0] || !val[0]) return; | ||
| 543 | + | ||
| 544 | + while (s->ngpu <= idx) { | ||
| 545 | + int i = s->ngpu; | ||
| 546 | + memset(&s->gpus[i], 0, sizeof(s->gpus[i])); | ||
| 547 | + s->gpus[i].index = i; | ||
| 548 | + copy_str(s->gpus[i].name, sizeof(s->gpus[i].name), "AMD GPU"); | ||
| 549 | + s->ngpu++; | ||
| 550 | + } | ||
| 551 | + g = &s->gpus[idx]; | ||
| 552 | + | ||
| 553 | + if (strstr(key, "Card series") || strstr(key, "Card SKU")) { | ||
| 554 | + copy_str(g->name, sizeof(g->name), val); | ||
| 555 | + } else if (strstr(key, "GPU use (%)")) { | ||
| 556 | + parse_num(val, &g->util_gpu); | ||
| 557 | + } else if (strstr(key, "VRAM Total Memory (B)")) { | ||
| 558 | + double b = 0; | ||
| 559 | + if (parse_num(val, &b)) g->mem_total_mb = b / (1024.0 * 1024.0); | ||
| 560 | + } else if (strstr(key, "VRAM Total Used Memory (B)")) { | ||
| 561 | + double b = 0; | ||
| 562 | + if (parse_num(val, &b)) g->mem_used_mb = b / (1024.0 * 1024.0); | ||
| 563 | + } else if (strstr(key, "Temperature (Sensor edge)") || strstr(key, "Temperature (Sensor junction)")) { | ||
| 564 | + double v = 0; | ||
| 565 | + if (parse_num(val, &v) && !g->has_temp) { g->temp_c = v; g->has_temp = 1; } | ||
| 566 | + } else if (strstr(key, "Average Graphics Package Power") || strstr(key, "Current Socket Graphics Package Power")) { | ||
| 567 | + double v = 0; | ||
| 568 | + if (parse_num(val, &v) && !g->has_power) { g->power_w = v; g->has_power = 1; } | ||
| 569 | + } else if (strstr(key, "Max Graphics Package Power")) { | ||
| 570 | + double v = 0; | ||
| 571 | + if (parse_num(val, &v) && !g->has_plimit) { g->power_limit_w = v; g->has_plimit = 1; } | ||
| 572 | + } | ||
| 573 | +} | ||
| 574 | + | ||
| 575 | +/* Feed a rocm-smi text fixture through the real parser (offline tests). */ | ||
| 576 | +static int feed_file_lines(const char *path, line_fn fn, void *ctx) | ||
| 577 | +{ | ||
| 578 | + FILE *fp; | ||
| 579 | + char buf[1024]; | ||
| 580 | + int any = 0; | ||
| 581 | + | ||
| 582 | + fp = fopen(path, "r"); | ||
| 583 | + if (!fp) return 0; | ||
| 584 | + while (fgets(buf, (int)sizeof(buf), fp)) { | ||
| 585 | + size_t n = strlen(buf); | ||
| 586 | + while (n && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = '\0'; | ||
| 587 | + if (!buf[0] || buf[0] == '#') continue; | ||
| 588 | + any = 1; | ||
| 589 | + fn(buf, ctx); | ||
| 590 | + } | ||
| 591 | + fclose(fp); | ||
| 592 | + return any; | ||
| 593 | +} | ||
| 594 | + | ||
| 595 | +static int collect_amd(snap_t *s) | ||
| 596 | +{ | ||
| 597 | + const char *mockrocm = getenv("NVTOP_MOCK_ROCM"); | ||
| 598 | + int got; | ||
| 599 | + | ||
| 600 | + if (mockrocm && *mockrocm) { | ||
| 601 | + s->mocked = 1; | ||
| 602 | + got = feed_file_lines(mockrocm, amd_line, s); | ||
| 603 | + } | ||
| 604 | + else | ||
| 605 | + got = run_cmd_lines( | ||
| 606 | + "rocm-smi --showproductname --showuse --showmeminfo vram " | ||
| 607 | + "--showtemp --showpower" DEV_NULL, amd_line, s); | ||
| 608 | + | ||
| 609 | + if (!got || s->ngpu == 0) return 0; | ||
| 610 | + copy_str(s->source, sizeof(s->source), "amd"); | ||
| 611 | + s->available = 1; | ||
| 612 | + s->note[0] = '\0'; | ||
| 613 | + return 1; | ||
| 614 | +} | ||
| 615 | + | ||
| 616 | +/* ---- Apple Silicon (ioreg IOAccelerator) -------------------------- */ | ||
| 617 | + | ||
| 618 | +#if defined(__APPLE__) | ||
| 619 | +static void apple_line(char *line, void *ctx) | ||
| 620 | +{ | ||
| 621 | + snap_t *s = (snap_t *)ctx; | ||
| 622 | + gpu_t *g; | ||
| 623 | + | ||
| 624 | + if (s->ngpu == 0) { | ||
| 625 | + memset(&s->gpus[0], 0, sizeof(s->gpus[0])); | ||
| 626 | + copy_str(s->gpus[0].name, sizeof(s->gpus[0].name), "Apple GPU"); | ||
| 627 | + s->ngpu = 1; | ||
| 628 | + } | ||
| 629 | + g = &s->gpus[0]; | ||
| 630 | + | ||
| 631 | + if (strstr(line, "\"model\" =")) { | ||
| 632 | + const char *p = strchr(line, '<'); | ||
| 633 | + const char *q = p ? strchr(p, '>') : NULL; | ||
| 634 | + if (p && q && q > p + 1) { | ||
| 635 | + size_t n = (size_t)(q - p - 1); | ||
| 636 | + if (n >= sizeof(g->name)) n = sizeof(g->name) - 1; | ||
| 637 | + memcpy(g->name, p + 1, n); | ||
| 638 | + g->name[n] = '\0'; | ||
| 639 | + } | ||
| 640 | + } else if (strstr(line, "Device Utilization %")) { | ||
| 641 | + const char *p = strchr(line, '='); | ||
| 642 | + double v = 0; | ||
| 643 | + if (p && parse_num(p + 1, &v)) g->util_gpu = v; | ||
| 644 | + } else if (strstr(line, "In use system memory")) { | ||
| 645 | + const char *p = strchr(line, '='); | ||
| 646 | + double v = 0; | ||
| 647 | + if (p && parse_num(p + 1, &v)) g->mem_used_mb = v / (1024.0 * 1024.0); | ||
| 648 | + } | ||
| 649 | +} | ||
| 650 | + | ||
| 651 | +static int collect_apple(snap_t *s) | ||
| 652 | +{ | ||
| 653 | + int got = run_cmd_lines("ioreg -rc IOAccelerator -d 1" DEV_NULL, apple_line, s); | ||
| 654 | + if (!got || s->ngpu == 0) return 0; | ||
| 655 | + copy_str(s->source, sizeof(s->source), "apple"); | ||
| 656 | + s->available = 1; | ||
| 657 | + s->note[0] = '\0'; | ||
| 658 | + return 1; | ||
| 659 | +} | ||
| 660 | +#endif | ||
| 661 | + | ||
| 662 | +/* ---- orchestration ------------------------------------------------ */ | ||
| 663 | + | ||
| 664 | +static void snapshot(snap_t *s) | ||
| 665 | +{ | ||
| 666 | + const char *mock = getenv("NVTOP_MOCK_CSV"); | ||
| 667 | + | ||
| 668 | + snap_init(s); | ||
| 669 | + if (mock && *mock && load_mock(s, mock)) return; | ||
| 670 | + | ||
| 671 | + if (collect_nvidia(s)) return; | ||
| 672 | + if (collect_amd(s)) return; | ||
| 673 | +#if defined(__APPLE__) | ||
| 674 | + if (collect_apple(s)) return; | ||
| 675 | +#endif | ||
| 676 | + /* Nothing found: keep the clean CPU-only empty state. */ | ||
| 677 | + copy_str(s->source, sizeof(s->source), "none"); | ||
| 678 | + s->available = 0; | ||
| 679 | + copy_str(s->note, sizeof(s->note), "No local NVIDIA/AMD GPU detected"); | ||
| 680 | +} | ||
| 681 | + | ||
| 682 | +/* Attach "gpu_index" to each process by matching its UUID. */ | ||
| 683 | +static int gpu_index_for(snap_t *s, const char *uuid) | ||
| 684 | +{ | ||
| 685 | + int i; | ||
| 686 | + if (!uuid || !*uuid) return -1; | ||
| 687 | + for (i = 0; i < s->ngpu; i++) | ||
| 688 | + if (strcmp(s->gpus[i].uuid, uuid) == 0) return s->gpus[i].index; | ||
| 689 | + return -1; | ||
| 690 | +} | ||
| 691 | + | ||
| 692 | +/* ------------------------------------------------------------------ */ | ||
| 693 | +/* Modes */ | ||
| 694 | +/* ------------------------------------------------------------------ */ | ||
| 695 | + | ||
| 696 | +static int mode_meta(void) | ||
| 697 | +{ | ||
| 698 | + puts("{\"name\":\"nvtop\",\"desc\":\"Local GPUs\"}"); | ||
| 699 | + return 0; | ||
| 700 | +} | ||
| 701 | + | ||
| 702 | +static void json_header(void) | ||
| 703 | +{ | ||
| 704 | + /* Deliberately no Content-Length - the server owns framing. */ | ||
| 705 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | ||
| 706 | + "Cache-Control: no-store\r\n" | ||
| 707 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 708 | +} | ||
| 709 | + | ||
| 710 | +static void emit_gpu(const gpu_t *g) | ||
| 711 | +{ | ||
| 712 | + fputs("{\"index\":", stdout); | ||
| 713 | + printf("%d", g->index); | ||
| 714 | + fputs(",\"uuid\":", stdout); | ||
| 715 | + json_str(g->uuid); | ||
| 716 | + fputs(",\"name\":", stdout); | ||
| 717 | + json_str(g->name); | ||
| 718 | + printf(",\"util_gpu\":%.1f", g->util_gpu); | ||
| 719 | + printf(",\"mem_used_mb\":%.0f", g->mem_used_mb); | ||
| 720 | + printf(",\"mem_total_mb\":%.0f", g->mem_total_mb); | ||
| 721 | + fputs(",\"temp_c\":", stdout); | ||
| 722 | + if (g->has_temp) printf("%.0f", g->temp_c); else fputs("null", stdout); | ||
| 723 | + fputs(",\"power_w\":", stdout); | ||
| 724 | + if (g->has_power) printf("%.1f", g->power_w); else fputs("null", stdout); | ||
| 725 | + fputs(",\"power_limit_w\":", stdout); | ||
| 726 | + if (g->has_plimit) printf("%.1f", g->power_limit_w); else fputs("null", stdout); | ||
| 727 | + fputs("}", stdout); | ||
| 728 | +} | ||
| 729 | + | ||
| 730 | +static void emit_metrics(snap_t *s, const char *utc) | ||
| 731 | +{ | ||
| 732 | + int i; | ||
| 733 | + double mem_used = 0, mem_total = 0, util_sum = 0, power = 0; | ||
| 734 | + int power_n = 0; | ||
| 735 | + | ||
| 736 | + json_header(); | ||
| 737 | + fputs("{\"ok\":true,\"action\":\"metrics\"", stdout); | ||
| 738 | + fputs(",\"available\":", stdout); | ||
| 739 | + fputs(s->available ? "true" : "false", stdout); | ||
| 740 | + fputs(",\"source\":", stdout); | ||
| 741 | + json_str(s->source); | ||
| 742 | + fputs(",\"mocked\":", stdout); | ||
| 743 | + fputs(s->mocked ? "true" : "false", stdout); | ||
| 744 | + fputs(",\"driver\":", stdout); | ||
| 745 | + json_str(s->driver); | ||
| 746 | + fputs(",\"utc\":", stdout); | ||
| 747 | + json_str(utc); | ||
| 748 | + fputs(",\"count\":", stdout); | ||
| 749 | + printf("%d", s->ngpu); | ||
| 750 | + fputs(",\"process_count\":", stdout); | ||
| 751 | + printf("%d", s->nproc); | ||
| 752 | + | ||
| 753 | + for (i = 0; i < s->ngpu; i++) { | ||
| 754 | + mem_used += s->gpus[i].mem_used_mb; | ||
| 755 | + mem_total += s->gpus[i].mem_total_mb; | ||
| 756 | + util_sum += s->gpus[i].util_gpu; | ||
| 757 | + if (s->gpus[i].has_power) { power += s->gpus[i].power_w; power_n++; } | ||
| 758 | + } | ||
| 759 | + printf(",\"util_gpu_avg\":%.1f", s->ngpu ? util_sum / (double)s->ngpu : 0.0); | ||
| 760 | + printf(",\"mem_used_mb\":%.0f,\"mem_total_mb\":%.0f", mem_used, mem_total); | ||
| 761 | + fputs(",\"power_w\":", stdout); | ||
| 762 | + if (power_n) printf("%.1f", power); else fputs("null", stdout); | ||
| 763 | + | ||
| 764 | + fputs(",\"gpus\":[", stdout); | ||
| 765 | + for (i = 0; i < s->ngpu; i++) { | ||
| 766 | + if (i) putchar(','); | ||
| 767 | + emit_gpu(&s->gpus[i]); | ||
| 768 | + } | ||
| 769 | + fputs("],\"processes\":[", stdout); | ||
| 770 | + for (i = 0; i < s->nproc; i++) { | ||
| 771 | + const proc_t *p = &s->procs[i]; | ||
| 772 | + if (i) putchar(','); | ||
| 773 | + fputs("{\"gpu_uuid\":", stdout); | ||
| 774 | + json_str(p->gpu_uuid); | ||
| 775 | + fputs(",\"gpu_index\":", stdout); | ||
| 776 | + printf("%d", gpu_index_for(s, p->gpu_uuid)); | ||
| 777 | + fputs(",\"pid\":", stdout); | ||
| 778 | + printf("%ld", p->pid); | ||
| 779 | + fputs(",\"name\":", stdout); | ||
| 780 | + json_str(p->name); | ||
| 781 | + printf(",\"used_mb\":%.0f}", p->used_mb); | ||
| 782 | + } | ||
| 783 | + fputs("],\"message\":", stdout); | ||
| 784 | + json_str(s->note); | ||
| 785 | + fputs("}\n", stdout); | ||
| 786 | +} | ||
| 787 | + | ||
| 788 | +static int mode_json(const char *qs) | ||
| 789 | +{ | ||
| 790 | + char action[64]; | ||
| 791 | + char utc[40]; | ||
| 792 | + snap_t s; | ||
| 793 | + | ||
| 794 | + action[0] = '\0'; | ||
| 795 | + get_query_val(qs, "action", action, sizeof(action)); | ||
| 796 | + | ||
| 797 | + if (action[0] && strcmp(action, "metrics") != 0 && strcmp(action, "info") != 0) { | ||
| 798 | + json_header(); | ||
| 799 | + printf("{\"ok\":false,\"error\":\"unknown_action\"," | ||
| 800 | + "\"supported\":[\"metrics\",\"info\"],\"requested\":"); | ||
| 801 | + json_str(action); | ||
| 802 | + fputs("}\n", stdout); | ||
| 803 | + return 0; | ||
| 804 | + } | ||
| 805 | + if (!action[0]) copy_str(action, sizeof(action), "metrics"); | ||
| 806 | + | ||
| 807 | + utc_now(utc, sizeof(utc)); | ||
| 808 | + | ||
| 809 | + if (strcmp(action, "info") == 0) { | ||
| 810 | + char platform[64]; | ||
| 811 | + json_header(); | ||
| 812 | + fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\"," | ||
| 813 | + "\"version\":\"" PLUGIN_VER "\",\"platform\":", stdout); | ||
| 814 | +#if defined(_WIN32) | ||
| 815 | + copy_str(platform, sizeof(platform), "windows"); | ||
| 816 | +#elif defined(__APPLE__) | ||
| 817 | + copy_str(platform, sizeof(platform), "macos"); | ||
| 818 | +#else | ||
| 819 | + copy_str(platform, sizeof(platform), "linux"); | ||
| 820 | +#endif | ||
| 821 | + json_str(platform); | ||
| 822 | + fputs(",\"pid\":", stdout); | ||
| 823 | + printf("%ld", node_pid()); | ||
| 824 | + fputs(",\"utc\":", stdout); | ||
| 825 | + json_str(utc); | ||
| 826 | + fputs(",\"node_auth\":", stdout); | ||
| 827 | + { | ||
| 828 | + const char *np = getenv("BOT_PASSWORD"); | ||
| 829 | + fputs((np && *np) ? "true" : "false", stdout); | ||
| 830 | + } | ||
| 831 | + fputs(",\"supported\":[\"metrics\",\"info\"]," | ||
| 832 | + "\"probes\":[\"nvidia-smi\",\"rocm-smi\"]," | ||
| 833 | + "\"mock_hook\":\"NVTOP_MOCK_CSV\"," | ||
| 834 | + "\"max_gpus\":", stdout); | ||
| 835 | + printf("%d", MAX_GPUS); | ||
| 836 | + fputs(",\"zero_network\":true}\n", stdout); | ||
| 837 | + return 0; | ||
| 838 | + } | ||
| 839 | + | ||
| 840 | + snapshot(&s); | ||
| 841 | + emit_metrics(&s, utc); | ||
| 842 | + return 0; | ||
| 843 | +} | ||
| 844 | + | ||
| 845 | +static void mode_html(int embed) | ||
| 846 | +{ | ||
| 847 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | ||
| 848 | + "Cache-Control: no-store\r\n" | ||
| 849 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 850 | + | ||
| 851 | + fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>" | ||
| 852 | + "<meta name='viewport' content='width=device-width,initial-scale=1'>" | ||
| 853 | + "<title>nvtop</title><style>", stdout); | ||
| 854 | + | ||
| 855 | + fputs( | ||
| 856 | +":root{color-scheme:dark light;" | ||
| 857 | + "--bg:#0b0b0e;--surface:#141419;--surface2:#1c1c22;--text:#f5f5f7;" | ||
| 858 | + "--muted:#8e8e96;--line:rgba(255,255,255,.10);--accent:#0a84ff;" | ||
| 859 | + "--compute:#ff9f0a;--vram:#0a84ff;" | ||
| 860 | + "--ok:#30d158;--warn:#ffd60a;--danger:#ff453a;" | ||
| 861 | + "--mono:ui-monospace,SFMono-Regular,Menlo,monospace}" | ||
| 862 | +"html[data-theme=light]{--bg:#f2f2f6;--surface:#ffffff;--surface2:#f0f0f4;" | ||
| 863 | + "--text:#1c1c1e;--muted:#6b6b73;--line:rgba(0,0,0,.10)}" | ||
| 864 | +"*{box-sizing:border-box}" | ||
| 865 | +"body{margin:0;padding:16px;background:var(--bg);color:var(--text);" | ||
| 866 | + "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;" | ||
| 867 | + "font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}" | ||
| 868 | +".wrap{max-width:1180px;margin:0 auto;min-width:0}" | ||
| 869 | +".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}" | ||
| 870 | +".title{font-size:20px;font-weight:700;margin:0}" | ||
| 871 | +".sub{color:var(--muted);font-size:12px;font-family:var(--mono);overflow-wrap:anywhere}" | ||
| 872 | +".spacer{flex:1}" | ||
| 873 | +".pill{font-size:11px;font-weight:600;padding:2px 9px;border-radius:999px;" | ||
| 874 | + "background:var(--surface2);color:var(--muted);border:1px solid var(--line);" | ||
| 875 | + "white-space:nowrap}" | ||
| 876 | +".pill.live{color:var(--ok);border-color:rgba(48,209,88,.4)}" | ||
| 877 | +".pill.warn{color:var(--warn);border-color:rgba(255,214,10,.4)}" | ||
| 878 | +".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;" | ||
| 879 | + "padding:16px;margin-bottom:14px;min-width:0}" | ||
| 880 | +".card h2{margin:0 0 12px;font-size:12px;letter-spacing:.06em;" | ||
| 881 | + "text-transform:uppercase;color:var(--muted);font-weight:600}" | ||
| 882 | +".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:10px}" | ||
| 883 | +".kpi{background:var(--surface2);border:1px solid var(--line);border-radius:10px;" | ||
| 884 | + "padding:10px 12px;min-width:0}" | ||
| 885 | +".kpi .k{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}" | ||
| 886 | +".kpi .v{font-size:19px;font-weight:700;font-family:var(--mono);margin-top:2px;" | ||
| 887 | + "overflow:hidden;text-overflow:ellipsis;white-space:nowrap}" | ||
| 888 | +"button{background:var(--accent);color:#fff;border:0;border-radius:999px;" | ||
| 889 | + "padding:6px 13px;font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}" | ||
| 890 | +"button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}" | ||
| 891 | +"button:active{transform:scale(.98)}" | ||
| 892 | +".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}" | ||
| 893 | +".gpus{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:12px}" | ||
| 894 | +".gpu{background:var(--surface2);border:1px solid var(--line);border-radius:12px;" | ||
| 895 | + "padding:12px;min-width:0}" | ||
| 896 | +".gpu .h{display:flex;gap:8px;align-items:baseline;flex-wrap:wrap;margin-bottom:4px}" | ||
| 897 | +".gpu .idx{font-family:var(--mono);font-size:12px;font-weight:700;color:var(--compute)}" | ||
| 898 | +".gpu .nm{font-weight:700;font-size:13px;overflow-wrap:anywhere;min-width:0}" | ||
| 899 | +".gpu .uuid{color:var(--muted);font-size:10px;font-family:var(--mono);overflow-wrap:anywhere}" | ||
| 900 | +".chips{display:flex;gap:6px;flex-wrap:wrap;margin:8px 0 4px}" | ||
| 901 | +".chip{font-size:11px;font-family:var(--mono);padding:2px 8px;border-radius:999px;" | ||
| 902 | + "background:rgba(255,255,255,.06);border:1px solid var(--line);color:var(--muted);" | ||
| 903 | + "white-space:nowrap}" | ||
| 904 | +".chip.hot{color:var(--danger);border-color:rgba(255,69,58,.45)}" | ||
| 905 | +".chip.warm{color:var(--warn);border-color:rgba(255,214,10,.45)}" | ||
| 906 | +".legend{display:flex;gap:14px;flex-wrap:wrap;font-size:11px;color:var(--muted);" | ||
| 907 | + "font-family:var(--mono);margin-top:8px}" | ||
| 908 | +".dotc,.dotv{display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:5px}" | ||
| 909 | +".dotc{background:var(--compute)}.dotv{background:var(--vram)}" | ||
| 910 | +".spark{display:block;width:100%;height:52px;margin-top:6px}" | ||
| 911 | +".tblwrap{overflow-x:auto;-webkit-overflow-scrolling:touch}" | ||
| 912 | +"table{width:100%;border-collapse:collapse;font-size:13px}" | ||
| 913 | +"th,td{text-align:left;padding:7px 8px;border-bottom:1px solid var(--line)}" | ||
| 914 | +"th{color:var(--muted);font-size:11px;text-transform:uppercase;letter-spacing:.05em;" | ||
| 915 | + "font-weight:600}" | ||
| 916 | +"td.num,th.num{text-align:right;font-family:var(--mono)}" | ||
| 917 | +".muted{color:var(--muted)}" | ||
| 918 | +".hide{display:none}" | ||
| 919 | +".empty{text-align:center;padding:30px 12px}" | ||
| 920 | +".empty .big{font-size:16px;font-weight:700;margin-bottom:6px}" | ||
| 921 | +".empty .msg{color:var(--muted);font-size:13px;max-width:620px;margin:0 auto 10px}" | ||
| 922 | +"code{font-family:var(--mono);font-size:12px;background:rgba(255,255,255,.07);" | ||
| 923 | + "padding:1px 5px;border-radius:4px;overflow-wrap:anywhere}" | ||
| 924 | +"@media(max-width:640px){body{padding:12px}.hide-sm{display:none}}" | ||
| 925 | +"</style></head><body><div class='wrap'>", stdout); | ||
| 926 | + | ||
| 927 | + fputs("<div class='top'>" | ||
| 928 | + "<h1 class='title'>nvtop</h1>" | ||
| 929 | + "<span id='srcBadge' class='pill'>local</span>" | ||
| 930 | + "<span id='drvBadge' class='pill'>driver</span>" | ||
| 931 | + "<span class='spacer'></span>" | ||
| 932 | + "<span id='stamp' class='sub'></span>" | ||
| 933 | + "<button class='ghost' id='btnRefresh'>Refresh</button>" | ||
| 934 | + "</div>", stdout); | ||
| 935 | + | ||
| 936 | + fputs("<div class='card'><h2>Overview</h2><div class='grid'>" | ||
| 937 | + "<div class='kpi'><div class='k'>GPUs</div><div class='v' id='kGpus'>—</div></div>" | ||
| 938 | + "<div class='kpi'><div class='k'>Avg compute</div><div class='v' id='kUtil'>—</div></div>" | ||
| 939 | + "<div class='kpi'><div class='k'>VRAM used</div><div class='v' id='kMem'>—</div></div>" | ||
| 940 | + "<div class='kpi'><div class='k'>Power draw</div><div class='v' id='kPower'>—</div></div>" | ||
| 941 | + "<div class='kpi'><div class='k'>Compute procs</div><div class='v' id='kProcs'>—</div></div>" | ||
| 942 | + "</div></div>", stdout); | ||
| 943 | + | ||
| 944 | + fputs("<div class='card'><h2>GPUs</h2>" | ||
| 945 | + "<div id='gpuGrid' class='gpus'></div>" | ||
| 946 | + "<div id='emptyState' class='empty hide'>" | ||
| 947 | + "<div class='big'>No local NVIDIA/AMD GPU detected</div>" | ||
| 948 | + "<div class='msg'>This node answers via <code>nvidia-smi</code> and " | ||
| 949 | + "<code>rocm-smi</code>; neither reported a GPU, so there is nothing to " | ||
| 950 | + "chart. Apple Silicon nodes are probed through <code>ioreg</code>.</div>" | ||
| 951 | + "<div class='msg'>To monitor a <em>remote</em> GPU rig from this node, " | ||
| 952 | + "customize <code>src/plugin_nvtop.c</code>: replace the fixed " | ||
| 953 | + "<code>nvidia-smi</code> probe in <code>collect_nvidia()</code> with your " | ||
| 954 | + "own collection step, rebuild with <code>make</code> and the dashboard " | ||
| 955 | + "works unchanged.</div>" | ||
| 956 | + "</div>" | ||
| 957 | + "<div class='legend'><span><i class='dotc'></i>compute %</span>" | ||
| 958 | + "<span><i class='dotv'></i>VRAM</span>" | ||
| 959 | + "<span>rolling 60 samples</span></div>" | ||
| 960 | + "</div>", stdout); | ||
| 961 | + | ||
| 962 | + fputs("<div class='card'><h2>Compute processes</h2><div class='tblwrap'>" | ||
| 963 | + "<table><thead><tr><th class='num'>GPU</th><th class='num'>PID</th>" | ||
| 964 | + "<th>Process</th><th class='num'>VRAM</th></tr></thead>" | ||
| 965 | + "<tbody id='procRows'></tbody></table></div>" | ||
| 966 | + "<div id='procEmpty' class='muted hide'>No compute processes reported.</div>" | ||
| 967 | + "</div>", stdout); | ||
| 968 | + | ||
| 969 | + fputs("<div class='card'><h2>About this plugin</h2>" | ||
| 970 | + "<p class='muted' style='margin:0 0 8px'>Local node only. Probes " | ||
| 971 | + "<code>nvidia-smi</code> and <code>rocm-smi</code> on this machine and, on " | ||
| 972 | + "Apple Silicon, <code>ioreg</code>. Makes zero outbound network requests " | ||
| 973 | + "and opens no sockets.</p>" | ||
| 974 | + "<p class='muted' style='margin:0'>Every command is a compile-time " | ||
| 975 | + "constant; nothing from the query string is ever executed.</p></div>", | ||
| 976 | + stdout); | ||
| 977 | + | ||
| 978 | + if (!embed) | ||
| 979 | + fputs("<div class='sub' style='margin-bottom:14px'>Opened directly from the " | ||
| 980 | + "node API.</div>", stdout); | ||
| 981 | + | ||
| 982 | + fputs("<script>\n(function(){\n", stdout); | ||
| 983 | + | ||
| 984 | + fputs( | ||
| 985 | +" var q = new URLSearchParams(location.search);\n" | ||
| 986 | +" var HUB = q.get('plugin') || '';\n" | ||
| 987 | +" var node = q.get('node') || '';\n" | ||
| 988 | +" var sid = q.get('id') || '';\n" | ||
| 989 | +" var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n" | ||
| 990 | +" localStorage.getItem('bot_active_pwd') || '';\n" | ||
| 991 | +" var TIMER = null, BUSY = false, HIST = {}, N = 60;\n" | ||
| 992 | +"\n" | ||
| 993 | +" /* Two routes, and getting this wrong is the classic plugin bug:\n" | ||
| 994 | +" page served through the hub -> call the hub proxy back\n" | ||
| 995 | +" page opened directly on node -> the plugin IS the route */\n" | ||
| 996 | +" function base(action){\n" | ||
| 997 | +" if (HUB) return '/plugins?plugin=' + encodeURIComponent(HUB) +\n" | ||
| 998 | +" '&action=' + encodeURIComponent(action);\n" | ||
| 999 | +" return '/" PLUGIN_ID "?action=' + encodeURIComponent(action);\n" | ||
| 1000 | +" }\n" | ||
| 1001 | +" function withCtx(u){\n" | ||
| 1002 | +" if (node) u += '&node=' + encodeURIComponent(node);\n" | ||
| 1003 | +" if (sid) u += '&id=' + encodeURIComponent(sid);\n" | ||
| 1004 | +" if (pwd) u += '&pwd=' + encodeURIComponent(pwd);\n" | ||
| 1005 | +" return u;\n" | ||
| 1006 | +" }\n" | ||
| 1007 | +" function hdr(){ return pwd ? {'X-Bot-Password': pwd} : {}; }\n" | ||
| 1008 | +" function $(id){ return document.getElementById(id); }\n" | ||
| 1009 | +" function txt(id, v){ var e = $(id); if (e) e.textContent =\n" | ||
| 1010 | +" (v === undefined || v === null) ? '' : v; }\n" | ||
| 1011 | +" function mb(n){\n" | ||
| 1012 | +" if (n === null || n === undefined) return '\\u2014';\n" | ||
| 1013 | +" return n >= 1024 ? (n / 1024).toFixed(1) + ' GB' : Math.round(n) + ' MB';\n" | ||
| 1014 | +" }\n" | ||
| 1015 | +" function el(tag, c, t){\n" | ||
| 1016 | +" var e = document.createElement(tag);\n" | ||
| 1017 | +" if (c) e.className = c;\n" | ||
| 1018 | +" if (t !== undefined) e.textContent = t;\n" | ||
| 1019 | +" return e;\n" | ||
| 1020 | +" }\n" | ||
| 1021 | +"\n" | ||
| 1022 | +" /* Rolling sparkline: orange = compute %, blue = VRAM share. A polyline in\n" | ||
| 1023 | +" an SVG keeps it crisp at any width and needs no canvas resize logic. */\n" | ||
| 1024 | +" function spark(hist, colour){\n" | ||
| 1025 | +" var W = 100, H = 40, n = hist.length;\n" | ||
| 1026 | +" var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n" | ||
| 1027 | +" svg.setAttribute('class', 'spark');\n" | ||
| 1028 | +" svg.setAttribute('viewBox', '0 0 ' + W + ' ' + H);\n" | ||
| 1029 | +" svg.setAttribute('preserveAspectRatio', 'none');\n" | ||
| 1030 | +" var base = document.createElementNS('http://www.w3.org/2000/svg', 'line');\n" | ||
| 1031 | +" base.setAttribute('x1','0'); base.setAttribute('x2', String(W));\n" | ||
| 1032 | +" base.setAttribute('y1', String(H - 1)); base.setAttribute('y2', String(H - 1));\n" | ||
| 1033 | +" base.setAttribute('stroke', 'rgba(255,255,255,.14)');\n" | ||
| 1034 | +" base.setAttribute('stroke-width', '0.6');\n" | ||
| 1035 | +" svg.appendChild(base);\n" | ||
| 1036 | +" if (!n) return svg;\n" | ||
| 1037 | +" var pts = [];\n" | ||
| 1038 | +" for (var i = 0; i < n; i++){\n" | ||
| 1039 | +" var x = n === 1 ? W : (i * W) / (n - 1);\n" | ||
| 1040 | +" var v = Math.max(0, Math.min(100, hist[i]));\n" | ||
| 1041 | +" var y = H - 1 - (v / 100) * (H - 3);\n" | ||
| 1042 | +" pts.push(x.toFixed(2) + ',' + y.toFixed(2));\n" | ||
| 1043 | +" }\n" | ||
| 1044 | +" var poly = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');\n" | ||
| 1045 | +" poly.setAttribute('points', pts.join(' '));\n" | ||
| 1046 | +" poly.setAttribute('fill', 'none');\n" | ||
| 1047 | +" poly.setAttribute('stroke', colour);\n" | ||
| 1048 | +" poly.setAttribute('stroke-width', '1.4');\n" | ||
| 1049 | +" poly.setAttribute('stroke-linejoin', 'round');\n" | ||
| 1050 | +" poly.setAttribute('vector-effect', 'non-scaling-stroke');\n" | ||
| 1051 | +" svg.appendChild(poly);\n" | ||
| 1052 | +" return svg;\n" | ||
| 1053 | +" }\n" | ||
| 1054 | +"\n" | ||
| 1055 | +" function pushHist(key, util, memPct){\n" | ||
| 1056 | +" var h = HIST[key];\n" | ||
| 1057 | +" if (!h) h = HIST[key] = { u: [], m: [] };\n" | ||
| 1058 | +" h.u.push(util); h.m.push(memPct);\n" | ||
| 1059 | +" if (h.u.length > N) h.u.shift();\n" | ||
| 1060 | +" if (h.m.length > N) h.m.shift();\n" | ||
| 1061 | +" return h;\n" | ||
| 1062 | +" }\n" | ||
| 1063 | +"\n" | ||
| 1064 | +" function chip(text, cls){ return el('span', 'chip' + (cls ? ' ' + cls : ''), text); }\n" | ||
| 1065 | +"\n" | ||
| 1066 | +" function renderGpus(d){\n" | ||
| 1067 | +" var box = $('gpuGrid');\n" | ||
| 1068 | +" box.textContent = '';\n" | ||
| 1069 | +" var gpus = d.gpus || [];\n" | ||
| 1070 | +" gpus.forEach(function(g){\n" | ||
| 1071 | +" var memPct = g.mem_total_mb > 0 ? (g.mem_used_mb / g.mem_total_mb) * 100 : 0;\n" | ||
| 1072 | +" var h = pushHist(String(g.index), g.util_gpu, memPct);\n" | ||
| 1073 | +" var card = el('div', 'gpu');\n" | ||
| 1074 | +" var head = el('div', 'h');\n" | ||
| 1075 | +" head.appendChild(el('span', 'idx', 'GPU ' + g.index));\n" | ||
| 1076 | +" head.appendChild(el('span', 'nm', g.name));\n" | ||
| 1077 | +" card.appendChild(head);\n" | ||
| 1078 | +" card.appendChild(el('div', 'uuid', g.uuid || 'no uuid'));\n" | ||
| 1079 | +" var chips = el('div', 'chips');\n" | ||
| 1080 | +" chips.appendChild(chip(g.util_gpu.toFixed(0) + '% compute'));\n" | ||
| 1081 | +" chips.appendChild(chip(mb(g.mem_used_mb) + ' / ' + mb(g.mem_total_mb) + ' VRAM'));\n" | ||
| 1082 | +" if (g.temp_c !== null && g.temp_c !== undefined)\n" | ||
| 1083 | +" chips.appendChild(chip(Math.round(g.temp_c) + '\\u00b0C',\n" | ||
| 1084 | +" g.temp_c >= 85 ? 'hot' : (g.temp_c >= 70 ? 'warm' : '')));\n" | ||
| 1085 | +" if (g.power_w !== null && g.power_w !== undefined)\n" | ||
| 1086 | +" chips.appendChild(chip(Math.round(g.power_w) + ' W' +\n" | ||
| 1087 | +" (g.power_limit_w ? ' / ' + Math.round(g.power_limit_w) : '')));\n" | ||
| 1088 | +" card.appendChild(chips);\n" | ||
| 1089 | +" card.appendChild(spark(h.u, 'var(--compute)'));\n" | ||
| 1090 | +" card.appendChild(spark(h.m, 'var(--vram)'));\n" | ||
| 1091 | +" box.appendChild(card);\n" | ||
| 1092 | +" });\n" | ||
| 1093 | +" if (gpus.length) $('emptyState').classList.add('hide');\n" | ||
| 1094 | +" else $('emptyState').classList.remove('hide');\n" | ||
| 1095 | +" txt('kGpus', String(gpus.length));\n" | ||
| 1096 | +" txt('kUtil', gpus.length ? Number(d.util_gpu_avg).toFixed(0) + '%' : '\\u2014');\n" | ||
| 1097 | +" txt('kMem', gpus.length ? mb(d.mem_used_mb) + ' / ' + mb(d.mem_total_mb) : '\\u2014');\n" | ||
| 1098 | +" txt('kPower', (d.power_w === null || d.power_w === undefined)\n" | ||
| 1099 | +" ? '\\u2014' : Math.round(d.power_w) + ' W');\n" | ||
| 1100 | +" txt('kProcs', String((d.processes || []).length));\n" | ||
| 1101 | +" }\n" | ||
| 1102 | +"\n" | ||
| 1103 | +" function renderProcs(d){\n" | ||
| 1104 | +" var body = $('procRows');\n" | ||
| 1105 | +" body.textContent = '';\n" | ||
| 1106 | +" var procs = d.processes || [];\n" | ||
| 1107 | +" procs.forEach(function(p){\n" | ||
| 1108 | +" var tr = el('tr');\n" | ||
| 1109 | +" tr.appendChild(el('td', 'num', p.gpu_index >= 0 ? String(p.gpu_index) : '-'));\n" | ||
| 1110 | +" tr.appendChild(el('td', 'num', String(p.pid)));\n" | ||
| 1111 | +" tr.appendChild(el('td', 'nm', p.name));\n" | ||
| 1112 | +" tr.appendChild(el('td', 'num', mb(p.used_mb)));\n" | ||
| 1113 | +" body.appendChild(tr);\n" | ||
| 1114 | +" });\n" | ||
| 1115 | +" if (procs.length) $('procEmpty').classList.add('hide');\n" | ||
| 1116 | +" else $('procEmpty').classList.remove('hide');\n" | ||
| 1117 | +" }\n" | ||
| 1118 | +"\n" | ||
| 1119 | +" function paint(d){\n" | ||
| 1120 | +" txt('srcBadge', d.source || 'none');\n" | ||
| 1121 | +" var sb = $('srcBadge');\n" | ||
| 1122 | +" sb.className = 'pill' + (d.available ? ' live' : ' warn');\n" | ||
| 1123 | +" txt('drvBadge', d.driver ? ('driver ' + d.driver) : 'no driver');\n" | ||
| 1124 | +" txt('stamp', d.utc || '');\n" | ||
| 1125 | +" renderGpus(d);\n" | ||
| 1126 | +" renderProcs(d);\n" | ||
| 1127 | +" }\n" | ||
| 1128 | +"\n" | ||
| 1129 | +" function refresh(){\n" | ||
| 1130 | +" if (BUSY) return Promise.resolve();\n" | ||
| 1131 | +" BUSY = true;\n" | ||
| 1132 | +" return fetch(withCtx(base('metrics')), { headers: hdr(), cache: 'no-store' })\n" | ||
| 1133 | +" .then(function(r){ return r.json(); })\n" | ||
| 1134 | +" .then(function(d){ paint(d); })\n" | ||
| 1135 | +" .catch(function(){ txt('stamp', 'refresh failed'); })\n" | ||
| 1136 | +" .then(function(){ BUSY = false; });\n" | ||
| 1137 | +" }\n" | ||
| 1138 | +"\n" | ||
| 1139 | +" function tick(){ refresh().then(function(){\n" | ||
| 1140 | +" TIMER = setTimeout(tick, 2000);\n" | ||
| 1141 | +" }); }\n" | ||
| 1142 | +"\n" | ||
| 1143 | +" if (!HUB && !pwd && node && localStorage.getItem('bot_pwd_' + node))\n" | ||
| 1144 | +" pwd = localStorage.getItem('bot_pwd_' + node);\n" | ||
| 1145 | +" $('btnRefresh').addEventListener('click', function(){ refresh(); });\n" | ||
| 1146 | +" document.addEventListener('visibilitychange', function(){\n" | ||
| 1147 | +" if (document.hidden){ if (TIMER) { clearTimeout(TIMER); TIMER = null; } }\n" | ||
| 1148 | +" else if (!TIMER) tick();\n" | ||
| 1149 | +" });\n" | ||
| 1150 | +" tick();\n" | ||
| 1151 | +"})();\n" | ||
| 1152 | +"</script></div></body></html>\n", stdout); | ||
| 1153 | +} | ||
| 1154 | + | ||
| 1155 | +int main(int argc, char **argv) | ||
| 1156 | +{ | ||
| 1157 | + const char *qs; | ||
| 1158 | + int embed; | ||
| 1159 | + | ||
| 1160 | + if (argc > 1) { | ||
| 1161 | + if (strcmp(argv[1], "--meta") == 0) return mode_meta(); | ||
| 1162 | + if (strcmp(argv[1], "--version") == 0) { | ||
| 1163 | + puts(PLUGIN_VER); | ||
| 1164 | + return 0; | ||
| 1165 | + } | ||
| 1166 | + if (strcmp(argv[1], "--help") == 0) { | ||
| 1167 | + puts("usage: " PLUGIN_ID " [--meta|--version|--help]"); | ||
| 1168 | + puts(""); | ||
| 1169 | + puts("Runs as a CGI-style program under scorpiox-server."); | ||
| 1170 | + puts(" --meta print discovery metadata JSON and exit"); | ||
| 1171 | + puts(" --version print the plugin version and exit"); | ||
| 1172 | + puts(""); | ||
| 1173 | + puts("Query string actions:"); | ||
| 1174 | + puts(" (none) or action=metrics local GPU telemetry + compute procs"); | ||
| 1175 | + puts(" action=info plugin/platform capabilities"); | ||
| 1176 | + puts(" format=json same as an action, JSON output"); | ||
| 1177 | + puts(" (any other) HTML dashboard"); | ||
| 1178 | + puts(""); | ||
| 1179 | + puts("Environment:"); | ||
| 1180 | + puts(" NVTOP_MOCK_CSV=<path> read a CSV fixture instead of probing"); | ||
| 1181 | + return 0; | ||
| 1182 | + } | ||
| 1183 | + } | ||
| 1184 | + | ||
| 1185 | + if (getenv("SX_PLUGIN_META")) return mode_meta(); | ||
| 1186 | + | ||
| 1187 | + require_node_auth(); | ||
| 1188 | + | ||
| 1189 | + qs = getenv("QUERY_STRING"); | ||
| 1190 | + if (!qs) qs = ""; | ||
| 1191 | + | ||
| 1192 | + if (strstr(qs, "action=") || strstr(qs, "format=json")) | ||
| 1193 | + return mode_json(qs); | ||
| 1194 | + | ||
| 1195 | + embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL); | ||
| 1196 | + mode_html(embed); | ||
| 1197 | + return 0; | ||
| 1198 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..c3e7dcf | index 0000000..c3e7dcf | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/fixtures/mock-4gpu.csv | +++ b/tests/fixtures/mock-4gpu.csv | ||
| @@ -0,0 +1,12 @@ | @@ -0,0 +1,12 @@ | ||
| 1 | +# NVTOP_MOCK_CSV fixture format (invented by this plugin's test harness): | ||
| 2 | +# GPU,<index>,<uuid>,<name>,<util%>,<mem_used_mb>,<mem_total_mb>,<temp_c>,<power_w>,<power_limit_w>,<driver> | ||
| 3 | +# APP,<gpu_uuid>,<pid>,<process name>,<used_mb> | ||
| 4 | +# A "-" or "N/A" field means the counter is unavailable. | ||
| 5 | +GPU,0,GPU-11111111-aaaa-bbbb-cccc-000000000001,NVIDIA H100 80GB HBM3,91,74240,81920,74,431.5,700.0,550.54.14 | ||
| 6 | +GPU,1,GPU-11111111-aaaa-bbbb-cccc-000000000002,NVIDIA H100 80GB HBM3,0,2,81920,31,38.2,700.0,550.54.14 | ||
| 7 | +GPU,2,GPU-11111111-aaaa-bbbb-cccc-000000000003,NVIDIA H100 80GB HBM3,55,41000,81920,68,512.9,700.0,550.54.14 | ||
| 8 | +GPU,3,GPU-11111111-aaaa-bbbb-cccc-000000000004,NVIDIA H100 80GB HBM3,12,1024,81920,N/A,N/A,N/A,550.54.14 | ||
| 9 | +APP,GPU-11111111-aaaa-bbbb-cccc-000000000001,12001,python3,68000 | ||
| 10 | +APP,GPU-11111111-aaaa-bbbb-cccc-000000000001,12002,pt_main_thread,6000 | ||
| 11 | +APP,GPU-11111111-aaaa-bbbb-cccc-000000000003,12044,/usr/lib/xorg/Xorg,512 | ||
| 12 | +APP,GPU-11111111-aaaa-bbbb-cccc-000000000003,12077,ffmpeg,40 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..73384b6 | index 0000000..73384b6 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/fixtures/nvidia-4gpu.csv | +++ b/tests/fixtures/nvidia-4gpu.csv | ||
| @@ -0,0 +1,12 @@ | @@ -0,0 +1,12 @@ | ||
| 1 | +# nvidia-smi --query-gpu=index,uuid,name,utilization.gpu,memory.used,memory.total,temperature.gpu,power.draw,power.limit,driver_version --format=csv,noheader,nounits | ||
| 2 | +# Deterministic fixture: a 4-GPU training box - one busy, one idle, one at its | ||
| 3 | +# power cap, and one whose thermal / power counters are unsupported ("N/A"). | ||
| 4 | +# Lines starting with "APP," are the --query-compute-apps output. | ||
| 5 | +0,GPU-11111111-aaaa-bbbb-cccc-000000000001,NVIDIA H100 80GB HBM3,91,74240,81920,74,431.5,700.0,550.54.14 | ||
| 6 | +1,GPU-11111111-aaaa-bbbb-cccc-000000000002,NVIDIA H100 80GB HBM3,0,2,81920,31,38.2,700.0,550.54.14 | ||
| 7 | +2,GPU-11111111-aaaa-bbbb-cccc-000000000003,NVIDIA H100 80GB HBM3,55,41000,81920,68,512.9,700.0,550.54.14 | ||
| 8 | +3,GPU-11111111-aaaa-bbbb-cccc-000000000004,NVIDIA H100 80GB HBM3,12,1024,81920,N/A,N/A,N/A,550.54.14 | ||
| 9 | +APP,GPU-11111111-aaaa-bbbb-cccc-000000000001,12001,python3,68000 | ||
| 10 | +APP,GPU-11111111-aaaa-bbbb-cccc-000000000001,12002,pt_main_thread,6000 | ||
| 11 | +APP,GPU-11111111-aaaa-bbbb-cccc-000000000003,12044,/usr/lib/xorg/Xorg,512 | ||
| 12 | +APP,GPU-11111111-aaaa-bbbb-cccc-000000000003,12077,ffmpeg,40 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..2e018f3 | index 0000000..2e018f3 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/fixtures/nvidia-empty.csv | +++ b/tests/fixtures/nvidia-empty.csv | ||
| @@ -0,0 +1 @@ | @@ -0,0 +1 @@ | ||
| 1 | +# A probe that answered but reported nothing (e.g. driver loaded, no device). |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..64dc350 | index 0000000..64dc350 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/fixtures/rocm-1gpu.txt | +++ b/tests/fixtures/rocm-1gpu.txt | ||
| @@ -0,0 +1,8 @@ | @@ -0,0 +1,8 @@ | ||
| 1 | +# rocm-smi text fixture (5.x / 6.x "GPU[n] : key: value" shape) | ||
| 2 | +GPU[0] : Card series: AMD Radeon RX 7900 XTX | ||
| 3 | +GPU[0] : GPU use (%): 44 | ||
| 4 | +GPU[0] : VRAM Total Memory (B): 25753026560 | ||
| 5 | +GPU[0] : VRAM Total Used Memory (B): 2147483648 | ||
| 6 | +GPU[0] : Temperature (Sensor edge) (C): 58.0 | ||
| 7 | +GPU[0] : Average Graphics Package Power (W): 112.0 | ||
| 8 | +GPU[0] : Max Graphics Package Power (W): 355.0 |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..12c45ee | index 0000000..12c45ee | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/run.sh | +++ b/tests/run.sh | ||
| @@ -0,0 +1,386 @@ | @@ -0,0 +1,386 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# tests/run.sh - offline checks for plugin_nvtop across all 3 modes. | ||
| 3 | +# | ||
| 4 | +# Runs against ./plugin_nvtop (native build) on whatever machine it is executed | ||
| 5 | +# on, so the CPU-only assertions use this host's real state. Multi-GPU telemetry | ||
| 6 | +# is exercised deterministically through the NVTOP_MOCK_* fixtures, which is the | ||
| 7 | +# whole point of those hooks: a build box without a GPU must still be able to | ||
| 8 | +# prove the parsers are correct. | ||
| 9 | +# | ||
| 10 | +# If a musl static build, an aarch64 build or a Windows PE are present they are | ||
| 11 | +# checked too. The whole git history is finally audited for secrets and LAN IPs. | ||
| 12 | +# | ||
| 13 | +# Exit code 0 = everything passed. | ||
| 14 | + | ||
| 15 | +set -u | ||
| 16 | + | ||
| 17 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | ||
| 18 | +cd "$ROOT" || exit 1 | ||
| 19 | + | ||
| 20 | +BIN=./plugin_nvtop | ||
| 21 | +FIX=tests/fixtures | ||
| 22 | +PASS=0 | ||
| 23 | +FAIL=0 | ||
| 24 | + | ||
| 25 | +if [ -t 1 ]; then | ||
| 26 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | ||
| 27 | +else | ||
| 28 | + C_OK=; C_BAD=; C_B=; C_0= | ||
| 29 | +fi | ||
| 30 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | ||
| 31 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | ||
| 32 | + | ||
| 33 | +check() { # check <desc> <expected-substring> <actual> | ||
| 34 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | ||
| 35 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 300)" | ||
| 36 | + fi | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | ||
| 40 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | ||
| 41 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | ||
| 42 | + fi | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | ||
| 46 | + | ||
| 47 | +body() { printf '%s' "$1" | sed '1,/^\r$/d'; } | ||
| 48 | + | ||
| 49 | +py() { # py <desc> <python-script> <json-file> [extra args...] | ||
| 50 | + desc=$1; script=$2; file=$3; shift 3 | ||
| 51 | + if python3 -c "$script" "$file" "$@" 2>/dev/null; then pass "$desc"; else fail "$desc"; fi | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +TMP=$(mktemp -d 2>/dev/null || echo /tmp/nvtop_tests_$$) | ||
| 55 | +mkdir -p "$TMP" 2>/dev/null || true | ||
| 56 | + | ||
| 57 | +# ---------------------------------------------------------------- build | ||
| 58 | +section "build" | ||
| 59 | +if [ ! -x "$BIN" ]; then | ||
| 60 | + echo " building native binary..." | ||
| 61 | + cc -O2 -std=c99 -Wall -Wextra -o "$BIN" src/plugin_nvtop.c || { echo " build failed"; exit 1; } | ||
| 62 | +fi | ||
| 63 | +[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing" | ||
| 64 | + | ||
| 65 | +# ---------------------------------------------------------------- meta mode | ||
| 66 | +section "mode 1 --meta (must work without auth - discovery)" | ||
| 67 | +META=$("$BIN" --meta) | ||
| 68 | +check "meta emits name nvtop" '"name":"nvtop"' "$META" | ||
| 69 | +check "meta emits desc Local GPUs" '"desc":"Local GPUs"' "$META" | ||
| 70 | +METAENV=$(SX_PLUGIN_META=1 "$BIN") | ||
| 71 | +check "SX_PLUGIN_META=1 yields same meta" '"name":"nvtop"' "$METAENV" | ||
| 72 | +LEN=$(printf '%s' "$META" | wc -c | tr -d ' ') | ||
| 73 | +[ "$LEN" -lt 60 ] && pass "meta payload is compact ($LEN bytes)" || fail "meta payload too long ($LEN)" | ||
| 74 | +printf '%s' "$META" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \ | ||
| 75 | + && pass "meta is valid JSON" || fail "meta is not valid JSON" | ||
| 76 | +DESC=$(printf '%s' "$META" | sed 's/.*"desc":"\([^"]*\)".*/\1/') | ||
| 77 | +[ ${#DESC} -le 15 ] && pass "desc length ${#DESC} <= 15 chars" || fail "desc too long (${#DESC})" | ||
| 78 | +NAME=$(printf '%s' "$META" | sed 's/.*"name":"\([^"]*\)".*/\1/') | ||
| 79 | +[ "$(printf '%s' "$NAME" | wc -w | tr -d ' ')" -le 1 ] && pass "name is a single word" || fail "name has spaces" | ||
| 80 | +check "--version prints version" '1.0.0' "$("$BIN" --version)" | ||
| 81 | +check "--help is available" 'usage:' "$("$BIN" --help)" | ||
| 82 | +check "--help documents the mock hook" 'NVTOP_MOCK_CSV' "$("$BIN" --help)" | ||
| 83 | +META_AUTH=$(BOT_PASSWORD=secret "$BIN" --meta) | ||
| 84 | +check "meta still works when BOT_PASSWORD is set" '"name":"nvtop"' "$META_AUTH" | ||
| 85 | + | ||
| 86 | +# ---------------------------------------------------------------- auth | ||
| 87 | +section "node auth" | ||
| 88 | +AUTHNONE=$(BOT_PASSWORD=testpw QUERY_STRING='action=metrics' "$BIN") | ||
| 89 | +check "no credentials -> 401" 'Status: 401' "$AUTHNONE" | ||
| 90 | +check "401 body is json" 'invalid node password' "$AUTHNONE" | ||
| 91 | +AUTHH=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING='action=metrics' "$BIN") | ||
| 92 | +check "X-Bot-Password accepted" '"ok":true' "$(body "$AUTHH")" | ||
| 93 | +AUTHB=$(BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING='action=metrics' "$BIN") | ||
| 94 | +check "Bearer token accepted" '"ok":true' "$(body "$AUTHB")" | ||
| 95 | +AUTHQ=$(BOT_PASSWORD=testpw QUERY_STRING='action=metrics&pwd=testpw' "$BIN") | ||
| 96 | +check "?pwd= accepted" '"ok":true' "$(body "$AUTHQ")" | ||
| 97 | +AUTHBAD=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=wrong QUERY_STRING='action=metrics' "$BIN") | ||
| 98 | +check "wrong password -> 401" 'Status: 401' "$AUTHBAD" | ||
| 99 | +AUTHPAGE=$(BOT_PASSWORD=testpw QUERY_STRING='embed=1' "$BIN") | ||
| 100 | +check "html mode is protected too" 'Status: 401' "$AUTHPAGE" | ||
| 101 | + | ||
| 102 | +# ---------------------------------------------------------------- json header | ||
| 103 | +section "mode 2 json framing" | ||
| 104 | +J0=$(body "$(QUERY_STRING='action=metrics' "$BIN")") | ||
| 105 | +check "json mode reports an action" '"action":"metrics"' "$J0" | ||
| 106 | +check_not "json mode emits no Content-Length" 'Content-Length' "$J0" | ||
| 107 | +check "json mode is ok" '"ok":true' "$J0" | ||
| 108 | + | ||
| 109 | +# ---------------------------------------------------------------- cpu-only | ||
| 110 | +section "mode 2 CPU-only node (clean empty state)" | ||
| 111 | +CPU="$TMP/cpu.json" | ||
| 112 | +printf '%s' "$J0" > "$CPU" | ||
| 113 | +if printf '%s' "$J0" | grep -F -q '"available":false'; then | ||
| 114 | + pass "empty state reports available:false" | ||
| 115 | + check "empty state counts zero gpus" '"count":0' "$J0" | ||
| 116 | + check "empty state counts zero procs" '"process_count":0' "$J0" | ||
| 117 | + check "empty state explains itself" 'No local NVIDIA/AMD GPU detected' "$J0" | ||
| 118 | + check "empty state source is none" '"source":"none"' "$J0" | ||
| 119 | + check "empty state power is null" '"power_w":null' "$J0" | ||
| 120 | +else | ||
| 121 | + # A machine that really has a GPU (e.g. the .3 inference host) must report it. | ||
| 122 | + pass "this node has a GPU, so available:true (not the empty state)" | ||
| 123 | + python3 - "$CPU" <<'PY' && pass "live GPU rows are well formed" || fail "live GPU rows malformed" | ||
| 124 | +import json, sys | ||
| 125 | +d = json.load(open(sys.argv[1])) | ||
| 126 | +assert d["count"] >= 1 | ||
| 127 | +for g in d["gpus"]: | ||
| 128 | + assert isinstance(g["index"], int) | ||
| 129 | + assert g["mem_total_mb"] > 0 | ||
| 130 | + assert 0 <= g["util_gpu"] <= 100 | ||
| 131 | +PY | ||
| 132 | +fi | ||
| 133 | +py "empty-state payload is valid JSON" 'import json,sys; json.load(open(sys.argv[1]))' "$CPU" | ||
| 134 | +py "empty-state gpus is an empty array" 'import json,sys; d=json.load(open(sys.argv[1])); assert isinstance(d["gpus"], list); assert isinstance(d["processes"], list)' "$CPU" | ||
| 135 | + | ||
| 136 | +# ---------------------------------------------------------------- mock: 4 GPU | ||
| 137 | +section "mode 2 NVTOP_MOCK_CSV (4-GPU fixture, deterministic)" | ||
| 138 | +NVTOP_MOCK_CSV="$FIX/mock-4gpu.csv" QUERY_STRING='action=metrics' "$BIN" > "$TMP/raw-mock.txt" | ||
| 139 | +MOCK="$TMP/mock.json" | ||
| 140 | +body "$(cat "$TMP/raw-mock.txt")" > "$MOCK" | ||
| 141 | +J=$(cat "$MOCK") | ||
| 142 | +check "mock reports available:true" '"available":true' "$J" | ||
| 143 | +check "mock reports 4 gpus" '"count":4' "$J" | ||
| 144 | +check "mock reports 4 processes" '"process_count":4' "$J" | ||
| 145 | +check "mock source is mock" '"source":"mock"' "$J" | ||
| 146 | +check "mock is flagged as mocked" '"mocked":true' "$J" | ||
| 147 | +check "mock carries the driver" '"driver":"550.54.14"' "$J" | ||
| 148 | +check "mock carries the GPU name" 'NVIDIA H100 80GB HBM3' "$J" | ||
| 149 | +check "mock reports power" '"power_w":982.6' "$J" | ||
| 150 | +check "mock reports memory" '"mem_total_mb":327680' "$J" | ||
| 151 | +py "mock payload is valid JSON" 'import json,sys; json.load(open(sys.argv[1]))' "$MOCK" | ||
| 152 | +py "mock has exactly 4 well-formed GPU rows" \ | ||
| 153 | + 'import json,sys; d=json.load(open(sys.argv[1])); g=d["gpus"]; assert len(g)==4; [ (lambda x: (assert_kind(x)))(x) for x in [] ]; | ||
| 154 | +assert [x["index"] for x in g]==[0,1,2,3]; | ||
| 155 | +assert all(isinstance(x["util_gpu"],(int,float)) for x in g); | ||
| 156 | +assert all(x["mem_total_mb"]==81920 for x in g)' "$MOCK" | ||
| 157 | +py "mock per-GPU utilisation parsed" \ | ||
| 158 | + 'import json,sys; d=json.load(open(sys.argv[1])); u=[x["util_gpu"] for x in d["gpus"]]; assert u==[91.0,0.0,55.0,12.0], u' "$MOCK" | ||
| 159 | +py "mock unsupported temp/power become null" \ | ||
| 160 | + 'import json,sys; d=json.load(open(sys.argv[1])); g=d["gpus"][3]; | ||
| 161 | +assert g["temp_c"] is None and g["power_w"] is None and g["power_limit_w"] is None, g' "$MOCK" | ||
| 162 | +py "mock keeps a supported temp as a number" \ | ||
| 163 | + 'import json,sys; d=json.load(open(sys.argv[1])); assert d["gpus"][0]["temp_c"]==74, d["gpus"][0]' "$MOCK" | ||
| 164 | +py "mock averages compute across all GPUs" \ | ||
| 165 | + 'import json,sys; d=json.load(open(sys.argv[1])); assert abs(d["util_gpu_avg"]-39.5)<1e-6, d["util_gpu_avg"]' "$MOCK" | ||
| 166 | +py "mock power sums only the GPUs that report it" \ | ||
| 167 | + 'import json,sys; d=json.load(open(sys.argv[1])); assert abs(d["power_w"]-982.6)<1e-6, d["power_w"]' "$MOCK" | ||
| 168 | +py "mock maps every process back to its GPU index" \ | ||
| 169 | + 'import json,sys; d=json.load(open(sys.argv[1])); idx={p["pid"]:p["gpu_index"] for p in d["processes"]} | ||
| 170 | +assert idx[12001]==0 and idx[12002]==0 and idx[12044]==2 and idx[12077]==2, idx' "$MOCK" | ||
| 171 | +py "mock keeps process VRAM and names" \ | ||
| 172 | + 'import json,sys; d=json.load(open(sys.argv[1])); p=[x for x in d["processes"] if x["pid"]==12001][0] | ||
| 173 | +assert p["name"]=="python3" and p["used_mb"]==68000, p' "$MOCK" | ||
| 174 | +py "mock uuids survive round-trip" \ | ||
| 175 | + 'import json,sys; d=json.load(open(sys.argv[1])); | ||
| 176 | +assert d["gpus"][0]["uuid"]=="GPU-11111111-aaaa-bbbb-cccc-000000000001"' "$MOCK" | ||
| 177 | +py "mock message is empty when a GPU is present" \ | ||
| 178 | + 'import json,sys; d=json.load(open(sys.argv[1])); assert d["message"]=="", d["message"]' "$MOCK" | ||
| 179 | +py "index.json-style keys are all present" \ | ||
| 180 | + 'import json,sys; d=json.load(open(sys.argv[1])); | ||
| 181 | +for k in ["ok","available","driver","count","process_count","gpus","processes","source","utc"]: | ||
| 182 | + assert k in d, k' "$MOCK" | ||
| 183 | + | ||
| 184 | +# ---------------------------------------------------------------- mock: raw nvidia | ||
| 185 | +section "mode 2 raw nvidia-smi csv fixture (real query layout)" | ||
| 186 | +NVTOP_MOCK_NVIDIA="$FIX/nvidia-4gpu.csv" QUERY_STRING='action=metrics' "$BIN" > "$TMP/raw-nv.txt" | ||
| 187 | +NVM="$TMP/nvm.json" | ||
| 188 | +body "$(cat "$TMP/raw-nv.txt")" > "$NVM" | ||
| 189 | +NV=$(cat "$NVM") | ||
| 190 | +check "raw probe reports 4 gpus" '"count":4' "$NV" | ||
| 191 | +check "raw probe reports 4 procs" '"process_count":4' "$NV" | ||
| 192 | +check "raw probe source is nvidia" '"source":"nvidia"' "$NV" | ||
| 193 | +check "raw probe is flagged mocked" '"mocked":true' "$NV" | ||
| 194 | +check "raw probe picks up the driver" '"driver":"550.54.14' "$NV" | ||
| 195 | +py "raw probe parses the same numbers as the fixture" \ | ||
| 196 | + 'import json,sys; d=json.load(open(sys.argv[1])); assert [x["util_gpu"] for x in d["gpus"]]==[91.0,0.0,55.0,12.0]' "$NVM" | ||
| 197 | +py "raw probe tolerates N/A counters" \ | ||
| 198 | + 'import json,sys; d=json.load(open(sys.argv[1])); g=d["gpus"][3]; assert g["temp_c"] is None and g["power_w"] is None' "$NVM" | ||
| 199 | +py "raw probe splits APP lines from GPU lines" \ | ||
| 200 | + 'import json,sys; d=json.load(open(sys.argv[1])); assert d["processes"][0]["pid"]==12001' "$NVM" | ||
| 201 | + | ||
| 202 | +# An empty but successful probe must degrade to the clean empty state, not crash. | ||
| 203 | +NVTOP_MOCK_NVIDIA="$FIX/nvidia-empty.csv" QUERY_STRING='action=metrics' "$BIN" > "$TMP/raw-empty.txt" | ||
| 204 | +E=$(body "$(cat "$TMP/raw-empty.txt")") | ||
| 205 | +check "empty probe falls back to no-GPU state" '"available":false' "$E" | ||
| 206 | +check "empty probe explains itself" 'No local NVIDIA/AMD GPU detected' "$E" | ||
| 207 | + | ||
| 208 | +# ---------------------------------------------------------------- mock: rocm | ||
| 209 | +section "mode 2 rocm-smi text fixture (AMD path)" | ||
| 210 | +NVTOP_MOCK_ROCM="$FIX/rocm-1gpu.txt" QUERY_STRING='action=metrics' "$BIN" > "$TMP/raw-rocm.txt" | ||
| 211 | +RM="$TMP/rocm.json" | ||
| 212 | +body "$(cat "$TMP/raw-rocm.txt")" > "$RM" | ||
| 213 | +R=$(cat "$RM") | ||
| 214 | +check "rocm fixture reports one gpu" '"count":1' "$R" | ||
| 215 | +check "rocm fixture source is amd" '"source":"amd"' "$R" | ||
| 216 | +check "rocm fixture reads the product name" 'AMD Radeon RX 7900 XTX' "$R" | ||
| 217 | +py "rocm fixture converts VRAM bytes to MB" \ | ||
| 218 | + 'import json,sys; d=json.load(open(sys.argv[1])); g=d["gpus"][0] | ||
| 219 | +assert abs(g["mem_total_mb"]-24560)<2, g["mem_total_mb"] | ||
| 220 | +assert abs(g["mem_used_mb"]-2048)<1, g["mem_used_mb"]' "$RM" | ||
| 221 | +py "rocm fixture parses utilisation, temp and power" \ | ||
| 222 | + 'import json,sys; d=json.load(open(sys.argv[1])); g=d["gpus"][0] | ||
| 223 | +assert g["util_gpu"]==44.0 and g["temp_c"]==58 and g["power_w"]==112.0 and g["power_limit_w"]==355.0, g' "$RM" | ||
| 224 | + | ||
| 225 | +# ---------------------------------------------------------------- info | ||
| 226 | +section "mode 2 action=info" | ||
| 227 | +INFO=$(body "$(QUERY_STRING='action=info' "$BIN")") | ||
| 228 | +check "info names the plugin" '"plugin":"plugin_nvtop"' "$INFO" | ||
| 229 | +check "info reports the version" '"version":"1.0.0"' "$INFO" | ||
| 230 | +check "info lists the probes" 'nvidia-smi' "$INFO" | ||
| 231 | +check "info lists the mock hook" 'NVTOP_MOCK_CSV' "$INFO" | ||
| 232 | +check "info advertises zero_network" '"zero_network":true' "$INFO" | ||
| 233 | +check "info reports largest GPU count" '"max_gpus":32' "$INFO" | ||
| 234 | +INFOAUTH=$(BOT_PASSWORD=pw HTTP_X_BOT_PASSWORD=pw QUERY_STRING='action=info' "$BIN") | ||
| 235 | +check "info reflects node auth state" '"node_auth":true' "$INFOAUTH" | ||
| 236 | + | ||
| 237 | +# ---------------------------------------------------------------- unknown/misc | ||
| 238 | +section "mode 2 error handling" | ||
| 239 | +UNK=$(body "$(QUERY_STRING='action=destroy' "$BIN")") | ||
| 240 | +check "unknown action is rejected" '"ok":false' "$UNK" | ||
| 241 | +check "unknown action names itself" '"error":"unknown_action"' "$UNK" | ||
| 242 | +check "unknown action echoes input" '"requested":"destroy"' "$UNK" | ||
| 243 | +check "format=json aliases to metrics" '"action":"metrics"' "$(body "$(QUERY_STRING='format=json' "$BIN")")" | ||
| 244 | +BADAUTH=$(body "$(QUERY_STRING='action=metrics&pwd=x' BOT_PASSWORD=x "$BIN")") | ||
| 245 | +check "matching ?pwd still authorises" '"ok":true' "$BADAUTH" | ||
| 246 | + | ||
| 247 | +# ---------------------------------------------------------------- html | ||
| 248 | +section "mode 3 html dashboard" | ||
| 249 | +HTML=$("$BIN") | ||
| 250 | +check "html content type is set" 'Content-Type: text/html' "$HTML" | ||
| 251 | +check "html title is nvtop" "<title>nvtop</title>" "$HTML" | ||
| 252 | +check_not "html emits no Content-Length" 'Content-Length' "$HTML" | ||
| 253 | +check "html has the compute legend" 'compute %' "$HTML" | ||
| 254 | +check "html has the VRAM legend" 'VRAM' "$HTML" | ||
| 255 | +check "html explains the empty state" 'No local NVIDIA/AMD GPU detected' "$HTML" | ||
| 256 | +check "empty state explains remote customization" 'customize' "$HTML" | ||
| 257 | +check "empty state points at the source file" 'src/plugin_nvtop.c' "$HTML" | ||
| 258 | +check "html renders per-GPU cards" "id='gpuGrid'" "$HTML" | ||
| 259 | +check "html renders the process table" "id='procRows'" "$HTML" | ||
| 260 | +check "html wires the refresh button" "id='btnRefresh'" "$HTML" | ||
| 261 | +check "html builds rolling sparklines" 'spark' "$HTML" | ||
| 262 | +check "html polls every 2s" '2000' "$HTML" | ||
| 263 | +check "html routes via the hub proxy" "/plugins?plugin=" "$HTML" | ||
| 264 | +check "html routes directly on the node" '/plugin_nvtop?action=' "$HTML" | ||
| 265 | +check "html carries pwd on fetches" 'X-Bot-Password' "$HTML" | ||
| 266 | +check_not "html has no emoji-ish escapes" '\u26' "$HTML" | ||
| 267 | +HTML_EMBED=$(QUERY_STRING='embed=1' "$BIN") | ||
| 268 | +check "embed mode still renders" "id='gpuGrid'" "$HTML_EMBED" | ||
| 269 | +check_not "embed mode drops the direct-open note" 'Opened directly from the node API' "$HTML_EMBED" | ||
| 270 | +check "non-embed mode keeps the note" 'Opened directly from the node API' "$HTML" | ||
| 271 | +check_not "html has no remote hosts" 'ssh ' "$HTML" | ||
| 272 | + | ||
| 273 | +# ---------------------------------------------------------------- source scan | ||
| 274 | +section "source invariants" | ||
| 275 | +SRCCAT=$(cat src/plugin_nvtop.c) | ||
| 276 | +check "source probes nvidia-smi" 'nvidia-smi --query-gpu' "$SRCCAT" | ||
| 277 | +check "source probes compute apps" '--query-compute-apps' "$SRCCAT" | ||
| 278 | +check "source probes rocm-smi" 'rocm-smi' "$SRCCAT" | ||
| 279 | +check "source redacts stderr per platform" 'DEV_NULL' "$SRCCAT" | ||
| 280 | +check "source refuses Content-Length" 'no Content-Length' "$SRCCAT" | ||
| 281 | +check "source requires node auth" 'require_node_auth' "$SRCCAT" | ||
| 282 | +check "source honours embed=1" 'embed=true' "$SRCCAT" | ||
| 283 | +check "source documents the mock hook" 'NVTOP_MOCK_CSV' "$SRCCAT" | ||
| 284 | +check_not "source has no sockets" 'socket(' "$SRCCAT" | ||
| 285 | +check_not "source has no curl" 'curl ' "$SRCCAT" | ||
| 286 | +check_not "source has no wget" 'wget' "$SRCCAT" | ||
| 287 | +check_not "source has no ssh invocation" 'ssh ' "$SRCCAT" | ||
| 288 | +check_not "source has no sshpass" 'sshpass' "$SRCCAT" | ||
| 289 | +check_not "source has no system()" 'system(' "$SRCCAT" | ||
| 290 | +SNUM=$(grep -cE 'popen\(' src/plugin_nvtop.c) | ||
| 291 | +[ "$SNUM" -ge 1 ] && pass "source uses popen only for fixed probe commands ($SNUM call)" \ | ||
| 292 | + || fail "source does not use popen at all (expected for the probes)" | ||
| 293 | +# Every popen() argument must be a compile-time constant, never a query value. | ||
| 294 | +grep -n 'popen(' src/plugin_nvtop.c | grep -F 'cmd' >/dev/null \ | ||
| 295 | + && pass "popen is called with the const cmd string only" || fail "popen call shape changed - re-audit" | ||
| 296 | +check_not "query string never reaches a shell" 'qs, "r"' "$SRCCAT" | ||
| 297 | + | ||
| 298 | +# ---------------------------------------------------------------- optional targets | ||
| 299 | +section "optional cross builds" | ||
| 300 | +if [ -f plugin_nvtop.musl ]; then | ||
| 301 | + M=$(./plugin_nvtop.musl --meta) | ||
| 302 | + check "musl build --meta" '"name":"nvtop"' "$M" | ||
| 303 | + case $(head -c 4 plugin_nvtop.musl | od -An -tx1 | tr -d ' \n') in | ||
| 304 | + 7f454c46) pass "musl artifact is ELF" ;; | ||
| 305 | + *) fail "musl artifact is not ELF" ;; | ||
| 306 | + esac | ||
| 307 | +else | ||
| 308 | + echo " skip musl (not built)" | ||
| 309 | +fi | ||
| 310 | +if [ -f plugin_nvtop.arm64 ]; then | ||
| 311 | + case $(head -c 4 plugin_nvtop.arm64 | od -An -tx1 | tr -d ' \n') in | ||
| 312 | + 7f454c46) pass "arm64 artifact is ELF" ;; | ||
| 313 | + *) fail "arm64 artifact is not ELF" ;; | ||
| 314 | + esac | ||
| 315 | + EM=$(od -An -tx1 -j 18 -N 2 plugin_nvtop.arm64 | tr -d ' \n') | ||
| 316 | + [ "$EM" = "b700" ] && pass "arm64 artifact declares EM_AARCH64" \ | ||
| 317 | + || fail "arm64 artifact e_machine is $EM, expected b700" | ||
| 318 | +else | ||
| 319 | + echo " skip arm64 (not built)" | ||
| 320 | +fi | ||
| 321 | +if [ -f plugin_nvtop.exe ]; then | ||
| 322 | + MAGIC=$(head -c 2 plugin_nvtop.exe) | ||
| 323 | + [ "$MAGIC" = "MZ" ] && pass "windows artifact has MZ header" || fail "windows artifact missing MZ" | ||
| 324 | + SZ=$(wc -c < plugin_nvtop.exe | tr -d ' ') | ||
| 325 | + [ "$SZ" -gt 20000 ] && pass "windows artifact is not an error page ($SZ bytes)" \ | ||
| 326 | + || fail "windows artifact suspiciously small ($SZ bytes)" | ||
| 327 | +else | ||
| 328 | + echo " skip windows PE (not built)" | ||
| 329 | +fi | ||
| 330 | +for slice in arm64 x86_64; do | ||
| 331 | + f="plugin_nvtop.macos-$slice" | ||
| 332 | + if [ -f "$f" ]; then | ||
| 333 | + MFG=$(head -c 4 "$f" | od -An -tx1 | tr -d ' \n') | ||
| 334 | + case "$MFG" in | ||
| 335 | + cffaedfe|feedfacf|cefaedfe|feedface) pass "macos-$slice artifact is Mach-O" ;; | ||
| 336 | + *) fail "macos-$slice artifact is not Mach-O ($MFG)" ;; | ||
| 337 | + esac | ||
| 338 | + else | ||
| 339 | + echo " skip macos-$slice (not built)" | ||
| 340 | + fi | ||
| 341 | +done | ||
| 342 | + | ||
| 343 | +# ---------------------------------------------------------------- history audit | ||
| 344 | +section "git history secret & LAN audit" | ||
| 345 | +if git rev-parse --git-dir >/dev/null 2>&1; then | ||
| 346 | + ALL="$TMP/history.txt" | ||
| 347 | + # Bookkeeping lines of this audit are excluded so the detector cannot flag itself. | ||
| 348 | + git log -p --all 2>/dev/null \ | ||
| 349 | + | grep -v '^Author: ' \ | ||
| 350 | + | grep -vE 'audit "|HITS=|grep -E|scan "|P_ROOT=|P_WT=' \ | ||
| 351 | + > "$ALL" || : > "$ALL" | ||
| 352 | + | ||
| 353 | + audit() { # audit <label> <regex> | ||
| 354 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | ||
| 355 | + if [ -n "$H" ]; then | ||
| 356 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | ||
| 357 | + else | ||
| 358 | + pass "history clean: $1" | ||
| 359 | + fi | ||
| 360 | + } | ||
| 361 | + audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+' | ||
| 362 | + audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | ||
| 363 | + audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | ||
| 364 | + audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | ||
| 365 | + audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | ||
| 366 | + audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | ||
| 367 | + audit "bare host password" 'Xboxone0909|xboxone' | ||
| 368 | + PK="pico""bot"; WT=".work""trees" | ||
| 369 | + audit "fleet path" "/codebases/${PK}|${WT}/" | ||
| 370 | + rm -f "$ALL" | ||
| 371 | +else | ||
| 372 | + echo " skip history audit (not a git checkout)" | ||
| 373 | +fi | ||
| 374 | + | ||
| 375 | +rm -rf "$TMP" | ||
| 376 | + | ||
| 377 | +# ---------------------------------------------------------------- summary | ||
| 378 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | ||
| 379 | +printf ' passed: %d\n' "$PASS" | ||
| 380 | +printf ' failed: %d\n' "$FAIL" | ||
| 381 | +if [ "$FAIL" -ne 0 ]; then | ||
| 382 | + printf ' %sRESULT: FAIL%s\n' "$C_BAD" "$C_0" | ||
| 383 | + exit 1 | ||
| 384 | +fi | ||
| 385 | +printf ' %sRESULT: PASS%s\n' "$C_OK" "$C_0" | ||
| 386 | +exit 0 | ||
| 0 | 387 |