You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
sys: cpu and memory (cgroup v2 in a constrained container)
* test cgroup v2 manually
- `docker run --rm --cpus=1.5 --memory=512m ...`
* add README section
* add TestMain to `sys.Init()` only once
------
* part four, prev. commit: 3fb3aeb
Signed-off-by: Alex Aizman <alex.aizman@gmail.com>
-[Example: testing `sys` package inside a constrained container](#example-testing-sys-package-inside-a-constrained-container)
25
26
-[Current limitations and future plans](#current-limitations-and-future-plans)
26
27
-[cgroup v1 deprecation](#cgroup-v1-deprecation)
27
28
-[Hardcoded thresholds](#hardcoded-thresholds)
@@ -171,7 +172,86 @@ The package follows these rules:
171
172
- for CPU: preserve a usable percentage whenever possible
172
173
- for memory: prefer host stats over failing when container-specific files cannot be read
173
174
174
-
This makes the package resilient across bare-metal, VMs, containers, and mixed environments, at the cost of occasionally returning an approximation instead of a strict container-scoped answer.
175
+
## Example: testing `sys` package inside a constrained container
176
+
177
+
A simple way to validate container-aware CPU and memory reporting is to compare the same test run on the host and inside a Docker container with explicit CPU and memory limits.
sys_test.go:79: Either swap is off or failed to read its stats
235
+
--- PASS: TestMemoryStats (0.00s)
236
+
=== RUN TestProcAndMaxLoad
237
+
sys_test.go:110: First call: load=0, extreme=false
238
+
...
239
+
sys_test.go:133: Second call: load=15, extreme=false
240
+
sys_test.go:145: Process CPU usage: 14.82%
241
+
--- PASS: TestProcAndMaxLoad (5.70s)
242
+
```
243
+
244
+
The comparison illustrates several points:
245
+
246
+
* On the host, `TestMemoryStats` reports host-scale memory totals.
247
+
* Inside the container, the same test reports memory bounded by the cgroup limit (`--memory=512m`) rather than the host's physical RAM.
248
+
*`TestNumCPU` and `TestMaxProcs` exercise init-time CPU detection and container-aware CPU count.
249
+
*`TestProcAndMaxLoad` burns CPU in-process and verifies that `MaxLoad2()` reports non-zero utilization on a subsequent sample.
250
+
* Swap may report as zero or be unavailable inside short-lived containers; this is not unusual.
251
+
252
+
To further confirm container-scoped memory accounting, rerun the container example with a different limit (for example, `--memory=4G`). `TestMemoryStats` should then report a total close to 4 GiB instead of 512 MiB.
253
+
254
+
> The container example above assumes cgroup v2 - the default on modern Linux distributions and container runtimes.
0 commit comments