diff --git a/backend/app/plugins/serverkit-gpu/__init__.py b/backend/app/plugins/serverkit-gpu/__init__.py new file mode 100644 index 00000000..8234c5c7 --- /dev/null +++ b/backend/app/plugins/serverkit-gpu/__init__.py @@ -0,0 +1 @@ +"""ServerKit GPU Monitor extension backend package.""" diff --git a/backend/app/plugins/serverkit-gpu/gpu.py b/backend/app/plugins/serverkit-gpu/gpu.py new file mode 100644 index 00000000..9b88e12d --- /dev/null +++ b/backend/app/plugins/serverkit-gpu/gpu.py @@ -0,0 +1,20 @@ +"""GPU Monitor API endpoints (serverkit-gpu extension). + +Mounted under ``/api/v1/gpu`` via the manifest's ``entry_point`` + ``url_prefix`` +(the same prefix the core route used, so the frontend is unchanged — decision D9). +Thin routing layer over :class:`GpuService`; read-only metrics, JWT-protected. +""" +from flask import Blueprint, jsonify +from flask_jwt_extended import jwt_required + +from .gpu_service import GpuService + +gpu_bp = Blueprint('gpu', __name__) + + +@gpu_bp.route('/', methods=['GET']) +@jwt_required() +def gpu_info(): + """Per-GPU stats (utilization, VRAM, temperature, power, fan, driver) plus + the GPU compute processes, with best-effort container resolution.""" + return jsonify(GpuService.info()) diff --git a/backend/app/plugins/serverkit-gpu/gpu_service.py b/backend/app/plugins/serverkit-gpu/gpu_service.py new file mode 100644 index 00000000..342417d3 --- /dev/null +++ b/backend/app/plugins/serverkit-gpu/gpu_service.py @@ -0,0 +1,130 @@ +"""NVIDIA GPU monitoring (serverkit-gpu extension). + +Moved out of core as the first CORE_SLIM slice (plan 32 #7). Shells out to +``nvidia-smi`` (like the rest of the service layer) and degrades gracefully to +"no GPUs" when it isn't present, so the panel stays happy on GPU-less hosts. +""" +import logging +import re +import subprocess + +logger = logging.getLogger(__name__) + +# (key, caster) in the same order as GPU_QUERY below. +GPU_FIELDS = [ + ('index', int), + ('name', str), + ('utilization_gpu', float), # % + ('memory_used', float), # MiB + ('memory_total', float), # MiB + ('temperature', float), # C + ('power_draw', float), # W + ('power_limit', float), # W + ('fan_speed', float), # % + ('driver_version', str), +] +GPU_QUERY = ('index,name,utilization.gpu,memory.used,memory.total,' + 'temperature.gpu,power.draw,power.limit,fan.speed,driver_version') + +_NA = ('', '[N/A]', 'N/A', '[Not Supported]', '[Unknown Error]') + + +class GpuService: + + @staticmethod + def _run(args, timeout=10): + return subprocess.run(['nvidia-smi', *args], capture_output=True, text=True, timeout=timeout) + + @staticmethod + def _coerce(value, caster): + v = value.strip() + if v in _NA: + return None + try: + return caster(v) + except (ValueError, TypeError): + return v if caster is str else None + + @classmethod + def available(cls): + try: + return cls._run(['--query-gpu=index', '--format=csv,noheader']).returncode == 0 + except Exception: + return False + + @classmethod + def list_gpus(cls): + try: + result = cls._run([f'--query-gpu={GPU_QUERY}', '--format=csv,noheader,nounits']) + if result.returncode != 0: + return [] + except Exception: + return [] + + gpus = [] + for line in result.stdout.strip().splitlines(): + if not line.strip(): + continue + parts = [p.strip() for p in line.split(',')] + if len(parts) < len(GPU_FIELDS): + continue + gpu = {key: cls._coerce(raw, caster) + for (key, caster), raw in zip(GPU_FIELDS, parts)} + if gpu.get('memory_total'): + gpu['memory_percent'] = round(100.0 * (gpu.get('memory_used') or 0) / gpu['memory_total'], 1) + gpus.append(gpu) + return gpus + + @classmethod + def _container_for_pid(cls, pid): + """Best-effort: resolve a host PID to a Docker container name via its + cgroup. Returns None when it can't be determined (or off Linux).""" + if not pid: + return None + try: + with open(f'/proc/{pid}/cgroup', 'r') as fh: + match = re.search(r'docker[-/]([0-9a-f]{64})', fh.read()) + if not match: + return None + cid = match.group(1)[:12] + out = subprocess.run(['docker', 'inspect', '-f', '{{.Name}}', cid], + capture_output=True, text=True, timeout=5) + return out.stdout.strip().lstrip('/') if out.returncode == 0 else cid + except Exception: + return None + + @classmethod + def processes(cls): + try: + result = cls._run(['--query-compute-apps=gpu_uuid,pid,process_name,used_memory', + '--format=csv,noheader,nounits']) + if result.returncode != 0: + return [] + except Exception: + return [] + + procs = [] + for line in result.stdout.strip().splitlines(): + if not line.strip(): + continue + parts = [p.strip() for p in line.split(',')] + if len(parts) < 4: + continue + pid = cls._coerce(parts[1], int) + procs.append({ + 'gpu_uuid': parts[0], + 'pid': pid, + 'process_name': parts[2], + 'used_memory': cls._coerce(parts[3], float), + 'container': cls._container_for_pid(pid), + }) + return procs + + @classmethod + def info(cls): + gpus = cls.list_gpus() + return { + 'available': bool(gpus), + 'gpus': gpus, + 'processes': cls.processes() if gpus else [], + } diff --git a/backend/app/plugins/serverkit-gpu/plugin.json b/backend/app/plugins/serverkit-gpu/plugin.json new file mode 100644 index 00000000..f18b30f4 --- /dev/null +++ b/backend/app/plugins/serverkit-gpu/plugin.json @@ -0,0 +1,47 @@ +{ + "name": "serverkit-gpu", + "display_name": "GPU Monitor", + "version": "1.0.0", + "description": "Live NVIDIA GPU metrics covering utilization, memory, temperature, power and fan, for servers with a GPU.", + "author": "ServerKit", + "license": "MIT", + "category": "monitoring", + "homepage": "https://github.com/jhd3197/ServerKit", + "permissions": [ + "shell" + ], + "min_panel_version": "1.7.0", + "sdk_version": "^1.0.0", + "entry_point": "gpu:gpu_bp", + "url_prefix": "/api/v1/gpu", + "icon": "", + "contributions": { + "nav": [ + { + "id": "gpu", + "label": "GPU Monitor", + "route": "/gpu", + "category": "system", + "requiresCondition": "gpuAvailable", + "icon": "" + } + ], + "routes": [ + { + "path": "gpu", + "component": "GpuMonitorPage" + } + ], + "page_titles": { + "/gpu": "GPU Monitor" + }, + "command_palette": [ + { + "label": "GPU Monitor", + "path": "/gpu", + "category": "Pages", + "keywords": "nvidia cuda metrics gpu" + } + ] + } +} \ No newline at end of file diff --git a/frontend/src/plugins/serverkit-cloud-provision/plugin.json b/frontend/src/plugins/serverkit-cloud-provision/plugin.json index b06582e8..9d72c3c8 100644 --- a/frontend/src/plugins/serverkit-cloud-provision/plugin.json +++ b/frontend/src/plugins/serverkit-cloud-provision/plugin.json @@ -40,4 +40,4 @@ } ] } -} +} \ No newline at end of file diff --git a/frontend/src/plugins/serverkit-ftp/plugin.json b/frontend/src/plugins/serverkit-ftp/plugin.json index b7c5354d..57208093 100644 --- a/frontend/src/plugins/serverkit-ftp/plugin.json +++ b/frontend/src/plugins/serverkit-ftp/plugin.json @@ -45,4 +45,4 @@ } ] } -} +} \ No newline at end of file diff --git a/frontend/src/plugins/serverkit-gpu/plugin.json b/frontend/src/plugins/serverkit-gpu/plugin.json index dc25ccbb..f18b30f4 100644 --- a/frontend/src/plugins/serverkit-gpu/plugin.json +++ b/frontend/src/plugins/serverkit-gpu/plugin.json @@ -44,4 +44,4 @@ } ] } -} +} \ No newline at end of file diff --git a/frontend/src/plugins/serverkit-remote-access/plugin.json b/frontend/src/plugins/serverkit-remote-access/plugin.json index 901b4a42..689a42b6 100644 --- a/frontend/src/plugins/serverkit-remote-access/plugin.json +++ b/frontend/src/plugins/serverkit-remote-access/plugin.json @@ -40,4 +40,4 @@ } ] } -} +} \ No newline at end of file diff --git a/frontend/src/plugins/serverkit-status/plugin.json b/frontend/src/plugins/serverkit-status/plugin.json index 7d514dc3..03137964 100644 --- a/frontend/src/plugins/serverkit-status/plugin.json +++ b/frontend/src/plugins/serverkit-status/plugin.json @@ -37,4 +37,4 @@ } ] } -} +} \ No newline at end of file diff --git a/frontend/src/plugins/serverkit-workflows/plugin.json b/frontend/src/plugins/serverkit-workflows/plugin.json index e0d3ef56..e7caec2c 100644 --- a/frontend/src/plugins/serverkit-workflows/plugin.json +++ b/frontend/src/plugins/serverkit-workflows/plugin.json @@ -41,4 +41,4 @@ } ] } -} +} \ No newline at end of file