sgpu 0.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sgpu-0.6.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 alex6095
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.
sgpu-0.6.0/PKG-INFO ADDED
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: sgpu
3
+ Version: 0.6.0
4
+ Summary: Simple GPU monitor for the SGVR H200 lab (MLXP) - kubectl-native dashboards, in-pod TUI, per-user usage stats
5
+ Author: alex6095
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/alex6095/sgpu
8
+ Project-URL: Repository, https://github.com/alex6095/sgpu
9
+ Keywords: gpu,kubernetes,monitoring,nvml,nvitop,h200
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: System :: Monitoring
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # SGPU
21
+
22
+ **SGVR GPU** / **S**imple **GPU** monitor for the lab's MLXP H200 nodes —
23
+ check the GPUs before you launch a pod.
24
+
25
+ - Every GPU process is attributed to its **pod and owner** (not just a PID).
26
+ - **In-pod TUI** (`kubectl exec -it`) — smooth like nvitop, scroll/sort/filter.
27
+ - **Usage stats 24/7**: per-owner GPU-hours, awards, GitHub-style activity
28
+ calendar, idle-allocation warnings (KST).
29
+ - Shared **storage (pv-01/pv-02) usage** at a glance.
30
+ - Monitor pod is read-only, always-on, and requests **no GPU**.
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ uvx sgpu # run without installing (uv)
36
+ pipx install sgpu # or pipx
37
+ pip install sgpu # or plain pip (WSL/Ubuntu: add --user --break-system-packages)
38
+ ```
39
+
40
+ Needs `kubectl` configured for the MLXP namespace
41
+ ([kubectl setup](#kubectl-setup-linuxwsl)).
42
+
43
+ ## Use
44
+
45
+ ```text
46
+ sgpu interactive TUI sgpu stats [days] usage report + awards
47
+ sgpu once one-shot dashboard sgpu apps processes + owners
48
+ sgpu watch [sec] dumb-terminal loop sgpu nvitop raw nvitop
49
+ sgpu pods|smi|gpustat|json|health|version|--help
50
+ ```
51
+
52
+ TUI keys: `j/k` scroll · `Tab` pane · `s` sort · `o` owner filter · `p` pause · `q` quit.
53
+ Options: `-n` namespace, `--pod`, `-r` refresh, `--no-color`. Env: `SGPU_NAMESPACE`, `SGPU_POD`.
54
+
55
+ ### Zero-install (kubectl only)
56
+
57
+ ```bash
58
+ kubectl exec -it -n p-sgvr-node-02 sangmin-gpu-monitor -- python3 /opt/gpu-monitor/tui.py
59
+ kubectl exec -n p-sgvr-node-02 sangmin-gpu-monitor -- curl -fsS http://127.0.0.1:8080/table
60
+ ```
61
+
62
+ Endpoints on `:8080`: `/table /apps /json /stats /pods /smi /topo /gpustat
63
+ /health /version /stats/files /stats/raw?date=` (`?color=1&cols=N&ascii=1`).
64
+
65
+ ## Stats
66
+
67
+ Sampled every 15 s around the clock into raw JSONL (full fidelity — future
68
+ tools can recompute anything), gzipped + rolled up daily, stored on the
69
+ shared volume at `pv-01/sangmin/sgpu`. Retention 365 d, capped at 2 GB.
70
+ `sgpu stats 30` shows the leaderboard, awards, daily activity calendar and
71
+ KST hour heatmap. Raw export: `/stats/raw?date=YYYYMMDD`.
72
+
73
+ > The monitor pod must stay running for stats to accumulate — it is designed
74
+ > to (tini init, `restartPolicy: Always`, no GPU held).
75
+
76
+ ## Deploy / operate
77
+
78
+ Image push works **from anywhere** via the registry's public endpoint
79
+ (`sgvr-registry.kr.ncr.ntruss.com`); the cluster pulls via the private
80
+ endpoint (`vnxb4cz3.kr.private-ncr.ntruss.com`, in-cluster only — preferred
81
+ per the MLXP guide). API key: NCP console → Access Management.
82
+
83
+ ```bash
84
+ docker login sgvr-registry.kr.ncr.ntruss.com
85
+ docker build -f docker/Dockerfile.gpu-monitor -t sgvr-registry.kr.ncr.ntruss.com/sangmin/gpu-monitor:TAG .
86
+ docker push sgvr-registry.kr.ncr.ntruss.com/sangmin/gpu-monitor:TAG
87
+
88
+ kubectl delete pod sangmin-gpu-monitor -n p-sgvr-node-02 --ignore-not-found
89
+ kubectl apply -f k8s/gpu-monitor.yaml # pods are immutable: delete + apply
90
+ kubectl wait --for=condition=Ready pod/sangmin-gpu-monitor -n p-sgvr-node-02 --timeout=180s
91
+ ```
92
+
93
+ Optional (enables the pod-allocation view + idle stats; kubelet syncs it in
94
+ within a minute, no restart):
95
+
96
+ ```bash
97
+ kubectl -n p-sgvr-node-02 create secret generic sgpu-kubeconfig --from-file=config=$HOME/.kube/config
98
+ ```
99
+
100
+ > Anyone with exec access to the monitor pod can read that token — fine
101
+ > inside a trusting lab namespace; use your least-privileged kubeconfig.
102
+
103
+ ## kubectl setup (Linux/WSL)
104
+
105
+ ```bash
106
+ mkdir -p ~/.local/bin ~/.kube
107
+ V=$(curl -fsSL https://dl.k8s.io/release/stable.txt)
108
+ curl -fsSL -o ~/.local/bin/kubectl "https://dl.k8s.io/release/${V}/bin/linux/amd64/kubectl" && chmod +x ~/.local/bin/kubectl
109
+ cp /path/to/sgvr-node-02-kubeconfig.yaml ~/.kube/config && chmod 600 ~/.kube/config
110
+ kubectl get pods -n p-sgvr-node-02 # connectivity test
111
+ ```
112
+
113
+ ## Development
114
+
115
+ ```bash
116
+ SGPU_MOCK=1 python3 tools/gpu-monitor/server.py # full pipeline, no GPU needed
117
+ SGPU_MOCK=1 python3 tools/gpu-monitor/tui.py
118
+ python3 -m unittest discover -s tests
119
+ ```
120
+
121
+ How it works: `sgpu` (thin Python client) → `kubectl exec` → monitor pod
122
+ (privileged, hostPID) where server.py renders everything; process→pod
123
+ attribution reads `/proc/<pid>/environ` (`HOSTNAME` = pod name), owner =
124
+ pod-name prefix. Known limits: pods overriding `spec.hostname` and MPS show
125
+ as `?`.
126
+
127
+ Troubleshooting: broken terminal after a dropped TUI → `reset` · frozen TUI
128
+ → rerun `sgpu` · garbled bars → Windows Terminal or `--no-color`.
sgpu-0.6.0/README.md ADDED
@@ -0,0 +1,109 @@
1
+ # SGPU
2
+
3
+ **SGVR GPU** / **S**imple **GPU** monitor for the lab's MLXP H200 nodes —
4
+ check the GPUs before you launch a pod.
5
+
6
+ - Every GPU process is attributed to its **pod and owner** (not just a PID).
7
+ - **In-pod TUI** (`kubectl exec -it`) — smooth like nvitop, scroll/sort/filter.
8
+ - **Usage stats 24/7**: per-owner GPU-hours, awards, GitHub-style activity
9
+ calendar, idle-allocation warnings (KST).
10
+ - Shared **storage (pv-01/pv-02) usage** at a glance.
11
+ - Monitor pod is read-only, always-on, and requests **no GPU**.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ uvx sgpu # run without installing (uv)
17
+ pipx install sgpu # or pipx
18
+ pip install sgpu # or plain pip (WSL/Ubuntu: add --user --break-system-packages)
19
+ ```
20
+
21
+ Needs `kubectl` configured for the MLXP namespace
22
+ ([kubectl setup](#kubectl-setup-linuxwsl)).
23
+
24
+ ## Use
25
+
26
+ ```text
27
+ sgpu interactive TUI sgpu stats [days] usage report + awards
28
+ sgpu once one-shot dashboard sgpu apps processes + owners
29
+ sgpu watch [sec] dumb-terminal loop sgpu nvitop raw nvitop
30
+ sgpu pods|smi|gpustat|json|health|version|--help
31
+ ```
32
+
33
+ TUI keys: `j/k` scroll · `Tab` pane · `s` sort · `o` owner filter · `p` pause · `q` quit.
34
+ Options: `-n` namespace, `--pod`, `-r` refresh, `--no-color`. Env: `SGPU_NAMESPACE`, `SGPU_POD`.
35
+
36
+ ### Zero-install (kubectl only)
37
+
38
+ ```bash
39
+ kubectl exec -it -n p-sgvr-node-02 sangmin-gpu-monitor -- python3 /opt/gpu-monitor/tui.py
40
+ kubectl exec -n p-sgvr-node-02 sangmin-gpu-monitor -- curl -fsS http://127.0.0.1:8080/table
41
+ ```
42
+
43
+ Endpoints on `:8080`: `/table /apps /json /stats /pods /smi /topo /gpustat
44
+ /health /version /stats/files /stats/raw?date=` (`?color=1&cols=N&ascii=1`).
45
+
46
+ ## Stats
47
+
48
+ Sampled every 15 s around the clock into raw JSONL (full fidelity — future
49
+ tools can recompute anything), gzipped + rolled up daily, stored on the
50
+ shared volume at `pv-01/sangmin/sgpu`. Retention 365 d, capped at 2 GB.
51
+ `sgpu stats 30` shows the leaderboard, awards, daily activity calendar and
52
+ KST hour heatmap. Raw export: `/stats/raw?date=YYYYMMDD`.
53
+
54
+ > The monitor pod must stay running for stats to accumulate — it is designed
55
+ > to (tini init, `restartPolicy: Always`, no GPU held).
56
+
57
+ ## Deploy / operate
58
+
59
+ Image push works **from anywhere** via the registry's public endpoint
60
+ (`sgvr-registry.kr.ncr.ntruss.com`); the cluster pulls via the private
61
+ endpoint (`vnxb4cz3.kr.private-ncr.ntruss.com`, in-cluster only — preferred
62
+ per the MLXP guide). API key: NCP console → Access Management.
63
+
64
+ ```bash
65
+ docker login sgvr-registry.kr.ncr.ntruss.com
66
+ docker build -f docker/Dockerfile.gpu-monitor -t sgvr-registry.kr.ncr.ntruss.com/sangmin/gpu-monitor:TAG .
67
+ docker push sgvr-registry.kr.ncr.ntruss.com/sangmin/gpu-monitor:TAG
68
+
69
+ kubectl delete pod sangmin-gpu-monitor -n p-sgvr-node-02 --ignore-not-found
70
+ kubectl apply -f k8s/gpu-monitor.yaml # pods are immutable: delete + apply
71
+ kubectl wait --for=condition=Ready pod/sangmin-gpu-monitor -n p-sgvr-node-02 --timeout=180s
72
+ ```
73
+
74
+ Optional (enables the pod-allocation view + idle stats; kubelet syncs it in
75
+ within a minute, no restart):
76
+
77
+ ```bash
78
+ kubectl -n p-sgvr-node-02 create secret generic sgpu-kubeconfig --from-file=config=$HOME/.kube/config
79
+ ```
80
+
81
+ > Anyone with exec access to the monitor pod can read that token — fine
82
+ > inside a trusting lab namespace; use your least-privileged kubeconfig.
83
+
84
+ ## kubectl setup (Linux/WSL)
85
+
86
+ ```bash
87
+ mkdir -p ~/.local/bin ~/.kube
88
+ V=$(curl -fsSL https://dl.k8s.io/release/stable.txt)
89
+ curl -fsSL -o ~/.local/bin/kubectl "https://dl.k8s.io/release/${V}/bin/linux/amd64/kubectl" && chmod +x ~/.local/bin/kubectl
90
+ cp /path/to/sgvr-node-02-kubeconfig.yaml ~/.kube/config && chmod 600 ~/.kube/config
91
+ kubectl get pods -n p-sgvr-node-02 # connectivity test
92
+ ```
93
+
94
+ ## Development
95
+
96
+ ```bash
97
+ SGPU_MOCK=1 python3 tools/gpu-monitor/server.py # full pipeline, no GPU needed
98
+ SGPU_MOCK=1 python3 tools/gpu-monitor/tui.py
99
+ python3 -m unittest discover -s tests
100
+ ```
101
+
102
+ How it works: `sgpu` (thin Python client) → `kubectl exec` → monitor pod
103
+ (privileged, hostPID) where server.py renders everything; process→pod
104
+ attribution reads `/proc/<pid>/environ` (`HOSTNAME` = pod name), owner =
105
+ pod-name prefix. Known limits: pods overriding `spec.hostname` and MPS show
106
+ as `?`.
107
+
108
+ Troubleshooting: broken terminal after a dropped TUI → `reset` · frozen TUI
109
+ → rerun `sgpu` · garbled bars → Windows Terminal or `--no-color`.
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "sgpu"
7
+ version = "0.6.0"
8
+ description = "Simple GPU monitor for the SGVR H200 lab (MLXP) - kubectl-native dashboards, in-pod TUI, per-user usage stats"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = "MIT"
12
+ authors = [{ name = "alex6095" }]
13
+ keywords = ["gpu", "kubernetes", "monitoring", "nvml", "nvitop", "h200"]
14
+ classifiers = [
15
+ "Environment :: Console",
16
+ "Intended Audience :: Science/Research",
17
+ "Operating System :: OS Independent",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: System :: Monitoring",
20
+ ]
21
+
22
+ [project.scripts]
23
+ sgpu = "sgpu.cli:main"
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/alex6095/sgpu"
27
+ Repository = "https://github.com/alex6095/sgpu"
28
+
29
+ [tool.setuptools]
30
+ packages = ["sgpu"]
sgpu-0.6.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """sgpu — simple GPU monitor client for the SGVR lab MLXP cluster."""
2
+
3
+ __version__ = "0.6.0"
@@ -0,0 +1,4 @@
1
+ from sgpu.cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
sgpu-0.6.0/sgpu/cli.py ADDED
@@ -0,0 +1,176 @@
1
+ """sgpu command-line client.
2
+
3
+ A thin cross-platform wrapper: all rendering happens inside the monitor pod,
4
+ this client only shells out to kubectl (fetch server-rendered text, or hand
5
+ the terminal to the in-pod TUI via `kubectl exec -it`).
6
+ """
7
+
8
+ import argparse
9
+ import os
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ import time
14
+
15
+ from sgpu import __version__
16
+
17
+ DEFAULT_NAMESPACE = os.environ.get("SGPU_NAMESPACE", "p-sgvr-node-02")
18
+ DEFAULT_POD = os.environ.get("SGPU_POD", "sangmin-gpu-monitor")
19
+ DEPLOY_URL = ("https://raw.githubusercontent.com/alex6095/sgpu/main/"
20
+ "k8s/gpu-monitor.yaml")
21
+
22
+ COMMANDS = ("top", "once", "watch", "apps", "stats", "nvitop", "pods",
23
+ "smi", "gpustat", "json", "health", "version")
24
+
25
+ EPILOG = """commands:
26
+ (none) | top interactive TUI (scroll, sort, owner filter)
27
+ once one-shot dashboard
28
+ watch [sec] simple refresh loop (for dumb terminals)
29
+ apps GPU process table with pod owners
30
+ stats [days] per-owner usage report (default 7 days)
31
+ nvitop raw nvitop TUI
32
+ pods | smi | gpustat | json | health | version
33
+ """
34
+
35
+
36
+ def _enable_ansi():
37
+ if os.name == "nt":
38
+ os.system("") # nudges conhost/Windows Terminal into VT mode
39
+ try:
40
+ sys.stdout.reconfigure(encoding="utf-8")
41
+ sys.stderr.reconfigure(encoding="utf-8")
42
+ except (AttributeError, OSError):
43
+ pass
44
+
45
+
46
+ def _hint_on_failure(args, stderr_text):
47
+ print("sgpu: cannot reach monitor pod '%s' in namespace '%s'"
48
+ % (args.pod, args.namespace), file=sys.stderr)
49
+ tail = [line for line in stderr_text.strip().splitlines()][-3:]
50
+ for line in tail:
51
+ print(line, file=sys.stderr)
52
+ lowered = stderr_text.lower()
53
+ if "notfound" in lowered or "not found" in lowered:
54
+ print("hint: the monitor pod is not running. Deploy it with:",
55
+ file=sys.stderr)
56
+ print(" kubectl apply -f " + DEPLOY_URL, file=sys.stderr)
57
+ elif "unauthorized" in lowered or "forbidden" in lowered \
58
+ or "credentials" in lowered:
59
+ print("hint: check your access: kubectl auth can-i get pods -n %s"
60
+ % args.namespace, file=sys.stderr)
61
+
62
+
63
+ def _fetch(args, path):
64
+ result = subprocess.run(
65
+ ["kubectl", "exec", "-n", args.namespace, args.pod, "--",
66
+ "curl", "-fsS", "http://127.0.0.1:8080" + path],
67
+ capture_output=True, text=True, encoding="utf-8", errors="replace")
68
+ if result.returncode != 0:
69
+ _hint_on_failure(args, result.stderr or result.stdout)
70
+ return None
71
+ return result.stdout
72
+
73
+
74
+ def _color_param(args):
75
+ use = (not args.no_color) and sys.stdout.isatty()
76
+ return "color=1" if use else "color=0"
77
+
78
+
79
+ def _cols_param():
80
+ cols = shutil.get_terminal_size(fallback=(120, 40)).columns
81
+ return "cols=%d" % max(40, cols)
82
+
83
+
84
+ def _print(text):
85
+ if text is not None:
86
+ sys.stdout.write(text)
87
+ if not text.endswith("\n"):
88
+ sys.stdout.write("\n")
89
+
90
+
91
+ def _interactive(args, pod_command):
92
+ if not (sys.stdout.isatty() and sys.stdin.isatty()):
93
+ _print(_fetch(args, "/table?color=0&" + _cols_param()))
94
+ return 0
95
+ return subprocess.call(
96
+ ["kubectl", "exec", "-it", "-n", args.namespace, args.pod, "--"]
97
+ + pod_command)
98
+
99
+
100
+ def _watch(args):
101
+ seconds = args.number if args.number else args.refresh
102
+ esc = "\x1b"
103
+ sys.stdout.write(esc + "[?1049h" + esc + "[?25l")
104
+ try:
105
+ while True:
106
+ frame = _fetch(args, "/table?%s&%s"
107
+ % (_color_param(args), _cols_param()))
108
+ if frame is None:
109
+ frame = "sgpu: fetch failed; retrying..."
110
+ sys.stdout.write(esc + "[H" + frame + "\n" + esc + "[0J")
111
+ sys.stdout.flush()
112
+ time.sleep(max(1, seconds))
113
+ except KeyboardInterrupt:
114
+ return 0
115
+ finally:
116
+ sys.stdout.write(esc + "[?25h" + esc + "[?1049l")
117
+ sys.stdout.flush()
118
+
119
+
120
+ def main(argv=None):
121
+ parser = argparse.ArgumentParser(
122
+ prog="sgpu",
123
+ description="Simple GPU monitor for the SGVR lab MLXP cluster.",
124
+ epilog=EPILOG,
125
+ formatter_class=argparse.RawDescriptionHelpFormatter)
126
+ parser.add_argument("command", nargs="?", default="top",
127
+ choices=COMMANDS, metavar="command")
128
+ parser.add_argument("number", nargs="?", type=int, default=0,
129
+ metavar="N",
130
+ help="days for stats, seconds for watch")
131
+ parser.add_argument("-n", "--namespace", default=DEFAULT_NAMESPACE)
132
+ parser.add_argument("--pod", default=DEFAULT_POD)
133
+ parser.add_argument("-r", "--refresh", type=int, default=2,
134
+ help="TUI/watch refresh interval (default 2)")
135
+ parser.add_argument("--no-color", action="store_true")
136
+ parser.add_argument("-V", "--version", action="version",
137
+ version="sgpu " + __version__)
138
+ args = parser.parse_args(argv)
139
+
140
+ if shutil.which("kubectl") is None:
141
+ print("sgpu: kubectl not found on PATH", file=sys.stderr)
142
+ print("hint: install kubectl and configure the MLXP kubeconfig "
143
+ "(see the sgpu README)", file=sys.stderr)
144
+ return 127
145
+
146
+ _enable_ansi()
147
+ query = "%s&%s" % (_color_param(args), _cols_param())
148
+
149
+ if args.command == "top":
150
+ return _interactive(args, ["python3", "/opt/gpu-monitor/tui.py",
151
+ str(args.refresh)])
152
+ if args.command == "nvitop":
153
+ return _interactive(args, ["nvitop"])
154
+ if args.command == "watch":
155
+ return _watch(args)
156
+
157
+ paths = {
158
+ "once": "/table?" + query,
159
+ "apps": "/apps?" + query,
160
+ "stats": "/stats?days=%d&%s" % (args.number or 7, query),
161
+ "pods": "/pods",
162
+ "smi": "/smi",
163
+ "gpustat": "/gpustat",
164
+ "json": "/json",
165
+ "health": "/health",
166
+ "version": "/version",
167
+ }
168
+ text = _fetch(args, paths[args.command])
169
+ if text is None:
170
+ return 1
171
+ _print(text)
172
+ return 0
173
+
174
+
175
+ if __name__ == "__main__":
176
+ sys.exit(main())
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: sgpu
3
+ Version: 0.6.0
4
+ Summary: Simple GPU monitor for the SGVR H200 lab (MLXP) - kubectl-native dashboards, in-pod TUI, per-user usage stats
5
+ Author: alex6095
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/alex6095/sgpu
8
+ Project-URL: Repository, https://github.com/alex6095/sgpu
9
+ Keywords: gpu,kubernetes,monitoring,nvml,nvitop,h200
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: System :: Monitoring
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # SGPU
21
+
22
+ **SGVR GPU** / **S**imple **GPU** monitor for the lab's MLXP H200 nodes —
23
+ check the GPUs before you launch a pod.
24
+
25
+ - Every GPU process is attributed to its **pod and owner** (not just a PID).
26
+ - **In-pod TUI** (`kubectl exec -it`) — smooth like nvitop, scroll/sort/filter.
27
+ - **Usage stats 24/7**: per-owner GPU-hours, awards, GitHub-style activity
28
+ calendar, idle-allocation warnings (KST).
29
+ - Shared **storage (pv-01/pv-02) usage** at a glance.
30
+ - Monitor pod is read-only, always-on, and requests **no GPU**.
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ uvx sgpu # run without installing (uv)
36
+ pipx install sgpu # or pipx
37
+ pip install sgpu # or plain pip (WSL/Ubuntu: add --user --break-system-packages)
38
+ ```
39
+
40
+ Needs `kubectl` configured for the MLXP namespace
41
+ ([kubectl setup](#kubectl-setup-linuxwsl)).
42
+
43
+ ## Use
44
+
45
+ ```text
46
+ sgpu interactive TUI sgpu stats [days] usage report + awards
47
+ sgpu once one-shot dashboard sgpu apps processes + owners
48
+ sgpu watch [sec] dumb-terminal loop sgpu nvitop raw nvitop
49
+ sgpu pods|smi|gpustat|json|health|version|--help
50
+ ```
51
+
52
+ TUI keys: `j/k` scroll · `Tab` pane · `s` sort · `o` owner filter · `p` pause · `q` quit.
53
+ Options: `-n` namespace, `--pod`, `-r` refresh, `--no-color`. Env: `SGPU_NAMESPACE`, `SGPU_POD`.
54
+
55
+ ### Zero-install (kubectl only)
56
+
57
+ ```bash
58
+ kubectl exec -it -n p-sgvr-node-02 sangmin-gpu-monitor -- python3 /opt/gpu-monitor/tui.py
59
+ kubectl exec -n p-sgvr-node-02 sangmin-gpu-monitor -- curl -fsS http://127.0.0.1:8080/table
60
+ ```
61
+
62
+ Endpoints on `:8080`: `/table /apps /json /stats /pods /smi /topo /gpustat
63
+ /health /version /stats/files /stats/raw?date=` (`?color=1&cols=N&ascii=1`).
64
+
65
+ ## Stats
66
+
67
+ Sampled every 15 s around the clock into raw JSONL (full fidelity — future
68
+ tools can recompute anything), gzipped + rolled up daily, stored on the
69
+ shared volume at `pv-01/sangmin/sgpu`. Retention 365 d, capped at 2 GB.
70
+ `sgpu stats 30` shows the leaderboard, awards, daily activity calendar and
71
+ KST hour heatmap. Raw export: `/stats/raw?date=YYYYMMDD`.
72
+
73
+ > The monitor pod must stay running for stats to accumulate — it is designed
74
+ > to (tini init, `restartPolicy: Always`, no GPU held).
75
+
76
+ ## Deploy / operate
77
+
78
+ Image push works **from anywhere** via the registry's public endpoint
79
+ (`sgvr-registry.kr.ncr.ntruss.com`); the cluster pulls via the private
80
+ endpoint (`vnxb4cz3.kr.private-ncr.ntruss.com`, in-cluster only — preferred
81
+ per the MLXP guide). API key: NCP console → Access Management.
82
+
83
+ ```bash
84
+ docker login sgvr-registry.kr.ncr.ntruss.com
85
+ docker build -f docker/Dockerfile.gpu-monitor -t sgvr-registry.kr.ncr.ntruss.com/sangmin/gpu-monitor:TAG .
86
+ docker push sgvr-registry.kr.ncr.ntruss.com/sangmin/gpu-monitor:TAG
87
+
88
+ kubectl delete pod sangmin-gpu-monitor -n p-sgvr-node-02 --ignore-not-found
89
+ kubectl apply -f k8s/gpu-monitor.yaml # pods are immutable: delete + apply
90
+ kubectl wait --for=condition=Ready pod/sangmin-gpu-monitor -n p-sgvr-node-02 --timeout=180s
91
+ ```
92
+
93
+ Optional (enables the pod-allocation view + idle stats; kubelet syncs it in
94
+ within a minute, no restart):
95
+
96
+ ```bash
97
+ kubectl -n p-sgvr-node-02 create secret generic sgpu-kubeconfig --from-file=config=$HOME/.kube/config
98
+ ```
99
+
100
+ > Anyone with exec access to the monitor pod can read that token — fine
101
+ > inside a trusting lab namespace; use your least-privileged kubeconfig.
102
+
103
+ ## kubectl setup (Linux/WSL)
104
+
105
+ ```bash
106
+ mkdir -p ~/.local/bin ~/.kube
107
+ V=$(curl -fsSL https://dl.k8s.io/release/stable.txt)
108
+ curl -fsSL -o ~/.local/bin/kubectl "https://dl.k8s.io/release/${V}/bin/linux/amd64/kubectl" && chmod +x ~/.local/bin/kubectl
109
+ cp /path/to/sgvr-node-02-kubeconfig.yaml ~/.kube/config && chmod 600 ~/.kube/config
110
+ kubectl get pods -n p-sgvr-node-02 # connectivity test
111
+ ```
112
+
113
+ ## Development
114
+
115
+ ```bash
116
+ SGPU_MOCK=1 python3 tools/gpu-monitor/server.py # full pipeline, no GPU needed
117
+ SGPU_MOCK=1 python3 tools/gpu-monitor/tui.py
118
+ python3 -m unittest discover -s tests
119
+ ```
120
+
121
+ How it works: `sgpu` (thin Python client) → `kubectl exec` → monitor pod
122
+ (privileged, hostPID) where server.py renders everything; process→pod
123
+ attribution reads `/proc/<pid>/environ` (`HOSTNAME` = pod name), owner =
124
+ pod-name prefix. Known limits: pods overriding `spec.hostname` and MPS show
125
+ as `?`.
126
+
127
+ Troubleshooting: broken terminal after a dropped TUI → `reset` · frozen TUI
128
+ → rerun `sgpu` · garbled bars → Windows Terminal or `--no-color`.
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ sgpu/__init__.py
5
+ sgpu/__main__.py
6
+ sgpu/cli.py
7
+ sgpu.egg-info/PKG-INFO
8
+ sgpu.egg-info/SOURCES.txt
9
+ sgpu.egg-info/dependency_links.txt
10
+ sgpu.egg-info/entry_points.txt
11
+ sgpu.egg-info/top_level.txt
12
+ tests/test_statsagg.py
13
+ tests/test_statsdb.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ sgpu = sgpu.cli:main
@@ -0,0 +1 @@
1
+ sgpu
@@ -0,0 +1,325 @@
1
+ """Unit tests for statsagg (aggregation math + rendering)."""
2
+
3
+ import gzip
4
+ import json
5
+ import os
6
+ import sys
7
+ import tempfile
8
+ import unittest
9
+ from datetime import datetime, timezone
10
+
11
+ # --- sys.path shim: make tools/gpu-monitor importable ---
12
+ _HERE = os.path.dirname(os.path.abspath(__file__))
13
+ _MOD_DIR = os.path.join(_HERE, "..", "tools", "gpu-monitor")
14
+ sys.path.insert(0, os.path.abspath(_MOD_DIR))
15
+
16
+ import statsagg # noqa: E402
17
+
18
+
19
+ def ts_at(base_epoch, offset_s):
20
+ dt = datetime.fromtimestamp(base_epoch + offset_s, tz=timezone.utc)
21
+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
22
+
23
+
24
+ def write_day(d, date_str, records, gzipped=False):
25
+ """Write a list of sample dicts as JSONL; return the path."""
26
+ name = "samples-%s.jsonl" % date_str
27
+ path = os.path.join(d, name)
28
+ text = "".join(json.dumps(r, separators=(",", ":")) + "\n" for r in records)
29
+ if gzipped:
30
+ path += ".gz"
31
+ with gzip.open(path, "wt", encoding="utf-8") as fh:
32
+ fh.write(text)
33
+ else:
34
+ with open(path, "w", encoding="utf-8") as fh:
35
+ fh.write(text)
36
+ return path
37
+
38
+
39
+ def sample(ts, gpus=None, procs=None, pods=None):
40
+ r = {"v": 1, "ts": ts, "node": "n1", "gpus": gpus or [], "procs": procs or []}
41
+ if pods is not None:
42
+ r["pods"] = pods
43
+ return r
44
+
45
+
46
+ def gpu(i, util=None, mem_total=143771, name="NVIDIA H200"):
47
+ return {"i": i, "util": util, "mem_total": mem_total, "name": name}
48
+
49
+
50
+ def proc(pid, gi, owner, mem=None, sm=None, pod=None):
51
+ return {"pid": pid, "gpu": gi, "owner": owner, "mem": mem, "sm": sm,
52
+ "pod": pod}
53
+
54
+
55
+ class TestDtGapRule(unittest.TestCase):
56
+ def test_gap_credit_bounded(self):
57
+ # 3 samples 15s apart, then a 2h gap, then 1 more.
58
+ base = 1751860000 # arbitrary epoch, aligned to a second
59
+ recs = [
60
+ sample(ts_at(base, 0), gpus=[gpu(0, 50)],
61
+ procs=[proc(1, 0, "a", sm=90)]),
62
+ sample(ts_at(base, 15), gpus=[gpu(0, 50)],
63
+ procs=[proc(1, 0, "a", sm=90)]),
64
+ sample(ts_at(base, 30), gpus=[gpu(0, 50)],
65
+ procs=[proc(1, 0, "a", sm=90)]),
66
+ sample(ts_at(base, 30 + 7200), gpus=[gpu(0, 50)],
67
+ procs=[proc(1, 0, "a", sm=90)]),
68
+ ]
69
+ with tempfile.TemporaryDirectory() as d:
70
+ path = write_day(d, "20260707", recs)
71
+ roll = statsagg.build_rollup(path)
72
+ self.assertEqual(roll["samples"], 4)
73
+ self.assertEqual(roll["interval_hint"], 15)
74
+ # dt: 15 (first) + 15 + 15 + min(7200, 30) = 75
75
+ self.assertAlmostEqual(roll["coverage_seconds"], 75.0, places=6)
76
+ # owner "a" active on 1 gpu each sample -> gpu_seconds == coverage
77
+ self.assertAlmostEqual(roll["owners"]["a"]["gpu_seconds"], 75.0,
78
+ places=6)
79
+
80
+
81
+ class TestSharedGpuUtil(unittest.TestCase):
82
+ def test_two_owners_share_one_gpu(self):
83
+ # One gpu, util 80, two owners each with a proc on it. Single sample.
84
+ base = 1751860000
85
+ recs = [
86
+ sample(ts_at(base, 0), gpus=[gpu(0, 80)],
87
+ procs=[proc(1, 0, "a"), proc(2, 0, "b")]),
88
+ ]
89
+ with tempfile.TemporaryDirectory() as d:
90
+ path = write_day(d, "20260707", recs)
91
+ roll = statsagg.build_rollup(path)
92
+ # First sample dt = interval_hint (fallback 15, no gaps).
93
+ dt = roll["interval_hint"]
94
+ a = roll["owners"]["a"]
95
+ b = roll["owners"]["b"]
96
+ # Both charged gpu_seconds for the shared gpu.
97
+ self.assertAlmostEqual(a["gpu_seconds"], 1 * dt, places=6)
98
+ self.assertAlmostEqual(b["gpu_seconds"], 1 * dt, places=6)
99
+ # Device util split by 2 sharers: 80*dt/2 each.
100
+ self.assertAlmostEqual(a["util_wsum"], 80 * dt / 2, places=6)
101
+ self.assertAlmostEqual(a["util_weight"], dt, places=6)
102
+ self.assertAlmostEqual(b["util_wsum"], 80 * dt / 2, places=6)
103
+
104
+
105
+ class TestIdleAllocation(unittest.TestCase):
106
+ def test_idle_when_pod_uses_fewer_gpus(self):
107
+ # Pod req=4 but procs only on 1 gpu -> idle 3*dt.
108
+ base = 1751860000
109
+ pods = [{"pod": "a-x", "owner": "a", "req": 4, "phase": "Running",
110
+ "start": ts_at(base, -3600)}]
111
+ recs = [
112
+ sample(ts_at(base, 0), gpus=[gpu(0, 50)],
113
+ procs=[proc(1, 0, "a", pod="a-x")], pods=pods),
114
+ ]
115
+ with tempfile.TemporaryDirectory() as d:
116
+ path = write_day(d, "20260707", recs)
117
+ roll = statsagg.build_rollup(path)
118
+ dt = roll["interval_hint"]
119
+ a = roll["owners"]["a"]
120
+ self.assertAlmostEqual(a["alloc_gpu_seconds"], 4 * dt, places=6)
121
+ self.assertAlmostEqual(a["idle_gpu_seconds"], 3 * dt, places=6)
122
+ self.assertAlmostEqual(roll["pods_coverage_seconds"], dt, places=6)
123
+
124
+
125
+ class TestKstBinning(unittest.TestCase):
126
+ def test_ts_2330_utc_maps_to_kst_hour_8(self):
127
+ # 23:30 UTC + 9h = 08:30 next day -> KST hour 8.
128
+ recs = [
129
+ sample("2026-07-07T23:30:00Z", gpus=[gpu(0, 50)],
130
+ procs=[proc(1, 0, "a")]),
131
+ ]
132
+ with tempfile.TemporaryDirectory() as d:
133
+ path = write_day(d, "20260707", recs)
134
+ roll = statsagg.build_rollup(path)
135
+ hist = roll["owners"]["a"]["hour_hist_kst"]
136
+ dt = roll["interval_hint"]
137
+ self.assertAlmostEqual(hist[8], 1 * dt, places=6)
138
+ for h in range(24):
139
+ if h != 8:
140
+ self.assertEqual(hist[h], 0.0)
141
+
142
+
143
+ class TestMergeEqualsConcat(unittest.TestCase):
144
+ def test_merge_two_days_equals_build_over_concat(self):
145
+ # The two groups are contiguous (group 2 starts exactly one interval
146
+ # after group 1's last sample) so that in the concatenated build the
147
+ # first sample of group 2 is credited dt = min(15, 2*15) = 15, matching
148
+ # the first-of-day credit it receives when group 2 is built alone. This
149
+ # is the condition under which merge(day1,day2) == build(day1+day2).
150
+ base = 1751860000 # some time
151
+ day1 = [
152
+ sample(ts_at(base, 0), gpus=[gpu(0, 60)],
153
+ procs=[proc(1, 0, "a", sm=70, mem=1000)]),
154
+ sample(ts_at(base, 15), gpus=[gpu(0, 60)],
155
+ procs=[proc(1, 0, "a", sm=70, mem=1000)]),
156
+ ]
157
+ base2 = base + 30 # 15s after day1's last sample -> contiguous
158
+ day2 = [
159
+ sample(ts_at(base2, 0), gpus=[gpu(1, 40)],
160
+ procs=[proc(2, 1, "a", sm=30, mem=500),
161
+ proc(3, 1, "b", sm=None, mem=200)]),
162
+ sample(ts_at(base2, 15), gpus=[gpu(1, 40)],
163
+ procs=[proc(2, 1, "a", sm=30, mem=500),
164
+ proc(3, 1, "b", sm=None, mem=200)]),
165
+ ]
166
+ with tempfile.TemporaryDirectory() as d:
167
+ p1 = write_day(d, "20260707", day1)
168
+ p2 = write_day(d, "20260708", day2)
169
+ r1 = statsagg.build_rollup(p1)
170
+ r2 = statsagg.build_rollup(p2)
171
+ merged = statsagg.merge_rollups([r1, r2])
172
+
173
+ # Build over the concatenation of both days (same interval hint 15).
174
+ pc = write_day(d, "20260709", day1 + day2)
175
+ concat = statsagg.build_rollup(pc)
176
+
177
+ self.assertAlmostEqual(merged["coverage_seconds"],
178
+ concat["coverage_seconds"], places=5)
179
+ for owner in ("a", "b"):
180
+ m = merged["owners"][owner]
181
+ c = concat["owners"][owner]
182
+ for key in ("gpu_seconds", "sm_wsum", "sm_weight", "util_wsum",
183
+ "util_weight", "mem_wsum", "mem_weight"):
184
+ self.assertAlmostEqual(m[key], c[key], places=5,
185
+ msg="%s.%s" % (owner, key))
186
+ self.assertEqual(m["mem_peak_mib"], c["mem_peak_mib"])
187
+ for h in range(24):
188
+ self.assertAlmostEqual(m["hour_hist_kst"][h],
189
+ c["hour_hist_kst"][h], places=5)
190
+
191
+
192
+ class TestMalformedLineSkipped(unittest.TestCase):
193
+ def test_truncated_trailing_line(self):
194
+ base = 1751860000
195
+ good = sample(ts_at(base, 0), gpus=[gpu(0, 50)],
196
+ procs=[proc(1, 0, "a")])
197
+ with tempfile.TemporaryDirectory() as d:
198
+ path = os.path.join(d, "samples-20260707.jsonl")
199
+ with open(path, "w", encoding="utf-8") as fh:
200
+ fh.write(json.dumps(good, separators=(",", ":")) + "\n")
201
+ fh.write('{"v":1,"ts":"2026-07-07T00:00:15Z","gpus":[{"i":0')
202
+ roll = statsagg.build_rollup(path)
203
+ # Only the one complete line counted.
204
+ self.assertEqual(roll["samples"], 1)
205
+
206
+
207
+ class TestGzipTransparent(unittest.TestCase):
208
+ def test_reads_gz(self):
209
+ base = 1751860000
210
+ recs = [sample(ts_at(base, 0), gpus=[gpu(0, 50)],
211
+ procs=[proc(1, 0, "a")])]
212
+ with tempfile.TemporaryDirectory() as d:
213
+ path = write_day(d, "20260707", recs, gzipped=True)
214
+ roll = statsagg.build_rollup(path)
215
+ self.assertEqual(roll["samples"], 1)
216
+
217
+
218
+ class TestCurrentIdle(unittest.TestCase):
219
+ def test_detects_running_pod_with_no_procs(self):
220
+ # Today's samples in the last 30 min: pod running, zero procs on it.
221
+ now = datetime(2026, 7, 7, 12, 0, 0, tzinfo=timezone.utc)
222
+ now_epoch = now.timestamp()
223
+ pods = [{"pod": "z-idle", "owner": "z", "req": 4, "phase": "Running",
224
+ "start": "2026-07-07T09:00:00Z"}]
225
+ recs = [
226
+ sample(ts_at(now_epoch, -600), gpus=[gpu(0, 0)], procs=[],
227
+ pods=pods),
228
+ sample(ts_at(now_epoch, -300), gpus=[gpu(0, 0)], procs=[],
229
+ pods=pods),
230
+ ]
231
+ with tempfile.TemporaryDirectory() as d:
232
+ write_day(d, "20260707", recs)
233
+ result = statsagg.query(d, days=1, now_fn=lambda: now)
234
+ idle = result["current_idle"]
235
+ self.assertEqual(len(idle), 1)
236
+ self.assertEqual(idle[0]["pod"], "z-idle")
237
+ self.assertEqual(idle[0]["owner"], "z")
238
+ self.assertEqual(idle[0]["req"], 4)
239
+ self.assertGreaterEqual(idle[0]["idle_minutes"], 9)
240
+
241
+ def test_pod_with_proc_not_idle(self):
242
+ now = datetime(2026, 7, 7, 12, 0, 0, tzinfo=timezone.utc)
243
+ now_epoch = now.timestamp()
244
+ pods = [{"pod": "z-busy", "owner": "z", "req": 4, "phase": "Running",
245
+ "start": "2026-07-07T09:00:00Z"}]
246
+ recs = [
247
+ sample(ts_at(now_epoch, -600), gpus=[gpu(0, 90)],
248
+ procs=[proc(1, 0, "z", pod="z-busy")], pods=pods),
249
+ ]
250
+ with tempfile.TemporaryDirectory() as d:
251
+ write_day(d, "20260707", recs)
252
+ result = statsagg.query(d, days=1, now_fn=lambda: now)
253
+ self.assertEqual(result["current_idle"], [])
254
+
255
+
256
+ class TestQueryAndRender(unittest.TestCase):
257
+ def test_query_empty_dir(self):
258
+ with tempfile.TemporaryDirectory() as d:
259
+ now = datetime(2026, 7, 7, 12, 0, 0, tzinfo=timezone.utc)
260
+ result = statsagg.query(d, days=7, now_fn=lambda: now)
261
+ self.assertEqual(result["merged"]["samples"], 0)
262
+ self.assertEqual(result["dates_covered"], [])
263
+ self.assertEqual(result["current_idle"], [])
264
+ text = statsagg.render_stats_text(result)
265
+ self.assertIn("no samples recorded yet", text)
266
+
267
+ def test_render_smoke_with_owners(self):
268
+ base = 1751860000
269
+ pods = [{"pod": "yoonki-x", "owner": "yoonki", "req": 4,
270
+ "phase": "Running", "start": ts_at(base, -3600)}]
271
+ recs = []
272
+ for i in range(400): # enough gpu-hours to trip LOW-UTIL
273
+ recs.append(sample(
274
+ ts_at(base, i * 15),
275
+ gpus=[gpu(0, 10)],
276
+ procs=[proc(1, 0, "yoonki", sm=10, mem=1000, pod="yoonki-x")],
277
+ pods=pods))
278
+ now = datetime.fromtimestamp(base + 400 * 15, tz=timezone.utc)
279
+ with tempfile.TemporaryDirectory() as d:
280
+ # Put it on "today" so query reads it as raw.
281
+ date_str = now.strftime("%Y%m%d")
282
+ write_day(d, date_str, recs)
283
+ result = statsagg.query(d, days=1, now_fn=lambda: now)
284
+ text = statsagg.render_stats_text(result, color=False)
285
+ self.assertIn("yoonki", text)
286
+ self.assertIn("SGPU usage report", text)
287
+ self.assertIn("KST", text)
288
+ # Color variant must not raise and must differ (ANSI codes present).
289
+ ctext = statsagg.render_stats_text(result, color=True)
290
+ self.assertIn("\x1b[", ctext)
291
+
292
+ def test_list_files(self):
293
+ with tempfile.TemporaryDirectory() as d:
294
+ write_day(d, "20260706", [sample("2026-07-06T00:00:00Z")])
295
+ with open(os.path.join(d, "rollup-20260706.json"), "w",
296
+ encoding="utf-8") as fh:
297
+ fh.write("{}")
298
+ with open(os.path.join(d, "ignore.txt"), "w",
299
+ encoding="utf-8") as fh:
300
+ fh.write("x")
301
+ files = statsagg.list_files(d)
302
+ names = [f["name"] for f in files]
303
+ self.assertIn("samples-20260706.jsonl", names)
304
+ self.assertIn("rollup-20260706.json", names)
305
+ self.assertNotIn("ignore.txt", names)
306
+ for f in files:
307
+ self.assertIn("size", f)
308
+ self.assertIn("mtime_iso", f)
309
+
310
+ def test_iter_raw_lines_missing_raises(self):
311
+ with tempfile.TemporaryDirectory() as d:
312
+ with self.assertRaises(FileNotFoundError):
313
+ list(statsagg.iter_raw_lines(d, "20990101"))
314
+
315
+ def test_iter_raw_lines_reads_gz(self):
316
+ with tempfile.TemporaryDirectory() as d:
317
+ write_day(d, "20260706", [sample("2026-07-06T00:00:00Z")],
318
+ gzipped=True)
319
+ lines = list(statsagg.iter_raw_lines(d, "20260706"))
320
+ self.assertEqual(len(lines), 1)
321
+ self.assertIn("2026-07-06T00:00:00Z", lines[0])
322
+
323
+
324
+ if __name__ == "__main__":
325
+ unittest.main()
@@ -0,0 +1,267 @@
1
+ """Unit tests for statsdb (sample recording + rotation)."""
2
+
3
+ import gzip
4
+ import json
5
+ import os
6
+ import sys
7
+ import tempfile
8
+ import unittest
9
+ from datetime import datetime, timezone
10
+
11
+ # --- sys.path shim: make tools/gpu-monitor importable ---
12
+ _HERE = os.path.dirname(os.path.abspath(__file__))
13
+ _MOD_DIR = os.path.join(_HERE, "..", "tools", "gpu-monitor")
14
+ sys.path.insert(0, os.path.abspath(_MOD_DIR))
15
+
16
+ import statsdb # noqa: E402
17
+ import statsagg # noqa: E402
18
+
19
+
20
+ def make_snapshot(ts="2026-07-07T04:12:30Z", with_pods=True, pods_ok=True):
21
+ snap = {
22
+ "schema": 2,
23
+ "source": "nvml",
24
+ "time_utc": ts,
25
+ "node": "h200-04-w-4b11",
26
+ "driver": "580.126.16",
27
+ "sgpu_version": "0.5.0",
28
+ "gpus": [{
29
+ "index": 0, "uuid": "GPU-abc", "name": "NVIDIA H200",
30
+ "util": 97, "mem_used_mib": 121004, "mem_total_mib": 143771,
31
+ "temp_c": 61, "power_w": 540.2, "power_limit_w": 700.0,
32
+ "owners": ["yoonki"],
33
+ }],
34
+ "procs": [{
35
+ "pid": 1234, "gpu_index": 0, "gpu_uuid": "GPU-abc",
36
+ "mem_mib": 40213, "owner": "yoonki", "pod": "yoonki-ume-xvrdr",
37
+ "pod_uid": None, "cmd": "x" * 200,
38
+ "started_utc": "2026-07-06T09:00:00Z", "sm_util": 85,
39
+ "attribution": "environ",
40
+ }],
41
+ "pods": {
42
+ "ok": pods_ok, "source": "kubeconfig", "error": None,
43
+ "rows": [{
44
+ "owner": "yoonki", "pod": "yoonki-ume-xvrdr", "node": "n",
45
+ "phase": "Running", "gpu": 4, "age": "19h7m",
46
+ "uid": "u", "start_iso": "2026-07-06T09:00:00Z", "active": 4,
47
+ }],
48
+ },
49
+ }
50
+ if not with_pods:
51
+ del snap["pods"]
52
+ return snap
53
+
54
+
55
+ class TestSnapshotToSample(unittest.TestCase):
56
+ def test_field_mapping(self):
57
+ s = statsdb.snapshot_to_sample(make_snapshot())
58
+ self.assertEqual(s["v"], 1)
59
+ self.assertEqual(s["ts"], "2026-07-07T04:12:30Z")
60
+ self.assertEqual(s["node"], "h200-04-w-4b11")
61
+ self.assertEqual(s["driver"], "580.126.16")
62
+ g = s["gpus"][0]
63
+ self.assertEqual(g["i"], 0)
64
+ self.assertEqual(g["uuid"], "GPU-abc")
65
+ self.assertEqual(g["util"], 97)
66
+ self.assertEqual(g["mem"], 121004)
67
+ self.assertEqual(g["mem_total"], 143771)
68
+ self.assertEqual(g["temp"], 61)
69
+ self.assertEqual(g["pw"], 540.2)
70
+ self.assertEqual(g["pw_lim"], 700.0)
71
+ p = s["procs"][0]
72
+ self.assertEqual(p["pid"], 1234)
73
+ self.assertEqual(p["gpu"], 0)
74
+ self.assertEqual(p["mem"], 40213)
75
+ self.assertEqual(p["owner"], "yoonki")
76
+ self.assertEqual(p["pod"], "yoonki-ume-xvrdr")
77
+ self.assertEqual(p["started"], "2026-07-06T09:00:00Z")
78
+ self.assertEqual(p["sm"], 85)
79
+
80
+ def test_cmd_truncation(self):
81
+ s = statsdb.snapshot_to_sample(make_snapshot())
82
+ self.assertEqual(len(s["procs"][0]["cmd"]), 120)
83
+
84
+ def test_none_passthrough(self):
85
+ snap = make_snapshot()
86
+ snap["gpus"][0]["util"] = None
87
+ snap["gpus"][0]["temp_c"] = None
88
+ snap["gpus"][0]["power_w"] = None
89
+ snap["procs"][0]["owner"] = None
90
+ snap["procs"][0]["sm_util"] = None
91
+ snap["procs"][0]["mem_mib"] = None
92
+ s = statsdb.snapshot_to_sample(snap)
93
+ self.assertIsNone(s["gpus"][0]["util"])
94
+ self.assertIsNone(s["gpus"][0]["temp"])
95
+ self.assertIsNone(s["gpus"][0]["pw"])
96
+ self.assertIsNone(s["procs"][0]["owner"])
97
+ self.assertIsNone(s["procs"][0]["sm"])
98
+ self.assertIsNone(s["procs"][0]["mem"])
99
+ # None survives a JSON round trip as null.
100
+ rt = json.loads(json.dumps(s))
101
+ self.assertIsNone(rt["procs"][0]["owner"])
102
+
103
+ def test_pods_key_present_when_ok(self):
104
+ s = statsdb.snapshot_to_sample(make_snapshot(pods_ok=True))
105
+ self.assertIn("pods", s)
106
+ self.assertEqual(s["pods"][0]["pod"], "yoonki-ume-xvrdr")
107
+ self.assertEqual(s["pods"][0]["req"], 4)
108
+ self.assertEqual(s["pods"][0]["phase"], "Running")
109
+
110
+ def test_pods_key_omitted_when_not_ok(self):
111
+ s = statsdb.snapshot_to_sample(make_snapshot(pods_ok=False))
112
+ self.assertNotIn("pods", s)
113
+
114
+ def test_pods_key_omitted_when_absent(self):
115
+ s = statsdb.snapshot_to_sample(make_snapshot(with_pods=False))
116
+ self.assertNotIn("pods", s)
117
+
118
+
119
+ class TestSampleOnce(unittest.TestCase):
120
+ def test_write_and_read_back(self):
121
+ with tempfile.TemporaryDirectory() as d:
122
+ fixed = datetime(2026, 7, 7, 4, 12, 30, tzinfo=timezone.utc)
123
+ calls = {"n": 0}
124
+
125
+ def collect(force=False):
126
+ calls["n"] += 1
127
+ self.assertTrue(force)
128
+ return make_snapshot()
129
+
130
+ path = statsdb._sample_once(collect, d, now_fn=lambda: fixed)
131
+ self.assertTrue(path.endswith("samples-20260707.jsonl"))
132
+ with open(path, "r", encoding="utf-8") as fh:
133
+ lines = fh.read().splitlines()
134
+ self.assertEqual(len(lines), 1)
135
+ rec = json.loads(lines[0])
136
+ self.assertEqual(rec["ts"], "2026-07-07T04:12:30Z")
137
+ self.assertEqual(calls["n"], 1)
138
+
139
+ def test_append_not_truncate(self):
140
+ with tempfile.TemporaryDirectory() as d:
141
+ fixed = datetime(2026, 7, 7, 4, 12, 30, tzinfo=timezone.utc)
142
+
143
+ def collect(force=False):
144
+ return make_snapshot()
145
+
146
+ statsdb._sample_once(collect, d, now_fn=lambda: fixed)
147
+ path = statsdb._sample_once(collect, d, now_fn=lambda: fixed)
148
+ with open(path, "r", encoding="utf-8") as fh:
149
+ lines = fh.read().splitlines()
150
+ self.assertEqual(len(lines), 2)
151
+
152
+
153
+ class TestRotation(unittest.TestCase):
154
+ def _write_raw_day(self, d, date_str, n=3):
155
+ path = os.path.join(d, "samples-%s.jsonl" % date_str)
156
+ with open(path, "w", encoding="utf-8") as fh:
157
+ for i in range(n):
158
+ ts = "%s-%s-%sT00:%02d:00Z" % (
159
+ date_str[:4], date_str[4:6], date_str[6:8], i)
160
+ rec = statsdb.snapshot_to_sample(make_snapshot(ts=ts))
161
+ fh.write(json.dumps(rec, separators=(",", ":")) + "\n")
162
+ return path
163
+
164
+ def test_rotate_gzips_and_rolls_up(self):
165
+ with tempfile.TemporaryDirectory() as d:
166
+ raw = self._write_raw_day(d, "20260706")
167
+ now = datetime(2026, 7, 7, 0, 0, 5, tzinfo=timezone.utc)
168
+ statsdb._rotate(d, "20260706", 365, 2048, now_fn=lambda: now)
169
+ gz = os.path.join(d, "samples-20260706.jsonl.gz")
170
+ self.assertTrue(os.path.isfile(gz))
171
+ self.assertFalse(os.path.isfile(raw))
172
+ rollup = os.path.join(d, "rollup-20260706.json")
173
+ self.assertTrue(os.path.isfile(rollup))
174
+ with open(rollup, "r", encoding="utf-8") as fh:
175
+ r = json.load(fh)
176
+ self.assertEqual(r["date"], "20260706")
177
+ self.assertEqual(r["samples"], 3)
178
+
179
+ def test_backfill_rotates_past_only(self):
180
+ with tempfile.TemporaryDirectory() as d:
181
+ self._write_raw_day(d, "20260705")
182
+ today_raw = self._write_raw_day(d, "20260707")
183
+ now = datetime(2026, 7, 7, 3, 0, 0, tzinfo=timezone.utc)
184
+ statsdb._backfill(d, 365, 2048, now_fn=lambda: now)
185
+ # Past day rotated.
186
+ self.assertTrue(os.path.isfile(
187
+ os.path.join(d, "samples-20260705.jsonl.gz")))
188
+ self.assertFalse(os.path.isfile(
189
+ os.path.join(d, "samples-20260705.jsonl")))
190
+ # Today untouched.
191
+ self.assertTrue(os.path.isfile(today_raw))
192
+ self.assertFalse(os.path.isfile(
193
+ os.path.join(d, "samples-20260707.jsonl.gz")))
194
+
195
+ def test_size_cap_deletes_oldest_first_never_today(self):
196
+ with tempfile.TemporaryDirectory() as d:
197
+ # Today's raw file must never be deleted.
198
+ today_raw = os.path.join(d, "samples-20260707.jsonl")
199
+ with open(today_raw, "w", encoding="utf-8") as fh:
200
+ fh.write("x\n")
201
+ # Fake old .gz files, 1 MiB each, three days.
202
+ payload = b"0" * (1024 * 1024)
203
+ for date_str in ("20260701", "20260702", "20260703"):
204
+ gz = os.path.join(d, "samples-%s.jsonl.gz" % date_str)
205
+ with gzip.open(gz, "wb") as fh:
206
+ fh.write(payload)
207
+ # gzip compresses zeros heavily; pad the on-disk file so the
208
+ # size cap actually triggers. Re-open as raw and append filler.
209
+ with open(gz, "ab") as fh:
210
+ fh.write(b"\x00" * (1024 * 1024))
211
+ now = datetime(2026, 7, 7, 5, 0, 0, tzinfo=timezone.utc)
212
+ # Cap of 2 MB with ~3 MB present -> delete oldest .gz first.
213
+ statsdb._enforce_size_cap(d, 2, now_fn=lambda: now)
214
+ self.assertFalse(os.path.isfile(
215
+ os.path.join(d, "samples-20260701.jsonl.gz")),
216
+ "oldest gz should be deleted first")
217
+ # today's raw untouched
218
+ self.assertTrue(os.path.isfile(today_raw))
219
+
220
+ def test_size_cap_never_deletes_today_even_if_over(self):
221
+ with tempfile.TemporaryDirectory() as d:
222
+ today_raw = os.path.join(d, "samples-20260707.jsonl")
223
+ with open(today_raw, "wb") as fh:
224
+ fh.write(b"0" * (3 * 1024 * 1024))
225
+ now = datetime(2026, 7, 7, 5, 0, 0, tzinfo=timezone.utc)
226
+ statsdb._enforce_size_cap(d, 1, now_fn=lambda: now)
227
+ self.assertTrue(os.path.isfile(today_raw))
228
+
229
+ def test_retention_deletes_old_gz(self):
230
+ with tempfile.TemporaryDirectory() as d:
231
+ old = os.path.join(d, "samples-20250101.jsonl.gz")
232
+ recent = os.path.join(d, "samples-20260706.jsonl.gz")
233
+ for p in (old, recent):
234
+ with gzip.open(p, "wb") as fh:
235
+ fh.write(b"{}\n")
236
+ now = datetime(2026, 7, 7, 0, 0, 0, tzinfo=timezone.utc)
237
+ statsdb._enforce_retention(d, 30, now_fn=lambda: now)
238
+ self.assertFalse(os.path.isfile(old))
239
+ self.assertTrue(os.path.isfile(recent))
240
+
241
+
242
+ class TestStatus(unittest.TestCase):
243
+ def test_status_before_start(self):
244
+ # status() must not blow up even if data_dir is None. We can't rely on
245
+ # module state here (other tests may have started a sampler), so we
246
+ # only assert the shape/keys.
247
+ st = statsdb.status()
248
+ for key in ("data_dir", "writable", "fallback", "files", "total_mb",
249
+ "sampling", "interval"):
250
+ self.assertIn(key, st)
251
+
252
+
253
+ @unittest.skipIf(os.name == "nt", "read-only dir simulation is POSIX-only")
254
+ class TestFallback(unittest.TestCase):
255
+ def test_unwritable_dir_falls_back(self):
256
+ with tempfile.TemporaryDirectory() as d:
257
+ # Use a file-as-dir: a regular file cannot host children.
258
+ bogus = os.path.join(d, "not-a-dir")
259
+ with open(bogus, "w", encoding="utf-8") as fh:
260
+ fh.write("i am a file")
261
+ resolved, fallback = statsdb._resolve_data_dir(bogus)
262
+ self.assertTrue(fallback)
263
+ self.assertNotEqual(resolved, bogus)
264
+
265
+
266
+ if __name__ == "__main__":
267
+ unittest.main()