Documentation
¶
Overview ¶
Package cgroup probes Linux control-group resource limits and container identity for the current process: cgroup v1/v2 CPU and memory limit detection, Docker-vs-LXC distinction, container-ID lookup, a TTL cache for limit detection, and a ZFS ARC helper for memory accounting.
All probes degrade gracefully on non-Linux hosts: the cgroup and procfs files simply fail to open and the functions report "not in a cgroup" / zero values.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( // IsDockerContainer reports whether the current process is running inside a // Docker container (as opposed to an LXC container, a VM, or bare metal). // // The distinction matters for host resource stats: in Docker the cgroup // limits (--cpus / --memory) are artificial constraints set by the operator // and should NOT be used as the host resource totals shown in a dashboard. // In LXC, by contrast, the cgroup limits represent the real hardware budget // assigned to the container — gopsutil reads the host's /proc values which are // higher, so the cgroup limits must be applied to show correct figures. // // Detection: Docker always creates /.dockerenv inside every container it // starts. LXC does not. We fall back to a /proc/self/cgroup pattern check // as a secondary signal. IsDockerContainer = sync.OnceValue(func() bool { if _, err := os.Stat("/.dockerenv"); err == nil { return true } data, err := os.ReadFile("/proc/self/cgroup") if err != nil { return false } return cgroupV1ContainerPattern.Match(data) || cgroupV2ContainerPattern.Match(data) }) // CurrentContainerID detects the current container ID using multiple detection methods. // It tries cgroup, mountinfo, and hostname in that order. CurrentContainerID = sync.OnceValues(func() (string, error) { if id, err := func() (string, error) { data, err := os.ReadFile("/proc/self/cgroup") if err != nil { return "", err } if matches := cgroupV1ContainerPattern.FindStringSubmatch(string(data)); len(matches) >= 2 { return matches[1], nil } if matches := cgroupV2ContainerPattern.FindStringSubmatch(string(data)); len(matches) >= 2 { return matches[1], nil } return "", errors.New("no container ID found in cgroup") }(); err == nil { slog.DebugContext(context.Background(), "CurrentContainerID: found via cgroup", "containerId", id) return id, nil } if id, err := func() (string, error) { data, err := os.ReadFile("/proc/self/mountinfo") if err != nil { return "", err } for line := range strings.SplitSeq(string(data), "\n") { _, after, ok := strings.Cut(line, "/docker/containers/") if id, _, _ := strings.Cut(after, "/"); ok && len(id) >= 12 { return id[:min(len(id), 64)], nil } } return "", errors.New("no container ID found in mountinfo") }(); err == nil { slog.DebugContext(context.Background(), "CurrentContainerID: found via mountinfo", "containerId", id) return id, nil } if id, err := func() (string, error) { hostname, err := os.Hostname() if err != nil { return "", err } if len(hostname) == 12 || len(hostname) == 64 { for _, c := range hostname { if (c < '0' || c > '9') && (c < 'a' || c > 'f') { return "", errors.New("hostname doesn't match container ID pattern") } } return hostname, nil } return "", errors.New("hostname doesn't match expected container ID length") }(); err == nil { slog.DebugContext(context.Background(), "CurrentContainerID: found via hostname", "containerId", id) return id, nil } return "", errors.New("no container ID found via cgroup, mountinfo, or hostname") }) )
Functions ¶
func DockerHostRoot ¶
DockerHostRoot finds the guest root for a Docker process in a shared cgroup v2 namespace. The caller must also verify host cgroup mode with the Docker daemon.
func MemoryUsage ¶
MemoryUsage reads cgroup v2 memory usage excluding file cache, in bytes.
func ZFSARCReclaimable ¶
func ZFSARCReclaimable() uint64
ZFSARCReclaimable returns the number of bytes of ZFS ARC (Adaptive Replacement Cache) that the kernel counts as used memory but that can be reclaimed under memory pressure.
The kernel accounts ZFS ARC as used and excludes it from /proc/meminfo's MemAvailable, so gopsutil's Used (= Total - MemAvailable) counts the whole ARC as used. Tools like btop/htop instead treat ARC as reclaimable cache. We subtract the reclaimable portion so dashboards do not over-report usage on ZFS hosts.
The arcstats file only exists when the ZFS kernel module is loaded, so the open fails cheaply on non-ZFS systems (including macOS dev machines) and this returns 0 there.
Types ¶
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache memoizes the result of cgroup limit detection for a configurable TTL. A single in-flight refresh is shared across concurrent callers, so a stampede of samplers never duplicates the work. The zero Cache is usable and runs DetectLimits on every Get.
type CacheConfig ¶
type CacheConfig struct {
// Detector replaces DetectLimits, e.g. in tests that simulate failures. Nil uses DetectLimits.
Detector func() (*Limits, error)
// TTL is how long a detection result is reused. Zero or negative disables caching.
TTL time.Duration
}
CacheConfig configures a Cache. The zero value detects on every call with DetectLimits.
type Limits ¶
type Limits struct {
MemoryLimit int64
MemoryUsage int64
CPUQuota int64
CPUPeriod int64
CPUCount int
}
Limits holds the detected cgroup resource limits. Fields are -1 when the corresponding limit is absent or unrestricted.
func DetectLimits ¶
DetectLimits detects the cgroup (v1 or v2) CPU and memory limits applied to the current process. It returns an error when the process is not running under a cgroup with explicit limits.