Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Align the Go memory limit with the enclosing cgroup limit

rcourtmanfed7179c92b3
diff --git a/pkg/server/memlimit.go b/pkg/server/memlimit.go
new file mode 100644
index 0000000000..2e04dfbf54
--- /dev/null
+++ b/pkg/server/memlimit.go
@@ -0,0 +1,142 @@
+package server
+
+import (
+ "math"
+ "os"
+ "path/filepath"
+ "runtime/debug"
+ "strconv"
+ "strings"
+
+ "github.com/rs/zerolog/log"
+)
+
+const (
+ cgroupV2Root = "/sys/fs/cgroup"
+ // cgroupV1NoLimit is the value cgroup v1 reports when no memory limit is
+ // set (PAGE_SIZE-rounded max int64).
+ cgroupV1NoLimit = int64(9223372036854771712)
+ // memoryLimitHeadroomPercent is how much of the cgroup limit the Go
+ // runtime may use. The remainder absorbs non-heap memory the GC cannot
+ // control: goroutine stacks, mmap'd files, and CGO allocations.
+ memoryLimitHeadroomPercent = 90
+ // minimumUsableMemoryLimit guards against nonsense cgroup values; below
+ // this a soft limit would just make the GC thrash.
+ minimumUsableMemoryLimit = int64(64 << 20)
+)
+
+// applyRuntimeMemoryLimit aligns the Go GC with the enclosing cgroup memory
+// limit so a capped service (systemd MemoryMax, docker --memory, Kubernetes
+// limits) tightens garbage collection as it approaches the cap instead of
+// growing until the kernel OOM-kills it. Without this the GC paces itself
+// purely off GOGC and is blind to the limit. Best effort: any failure leaves
+// the runtime untouched.
+func applyRuntimeMemoryLimit() {
+ if v := strings.TrimSpace(os.Getenv("GOMEMLIMIT")); v != "" {
+ // The runtime already honors the explicit operator setting.
+ log.Debug().Str("GOMEMLIMIT", v).Msg("runtime memory limit set from environment")
+ return
+ }
+
+ limit, ok := readCgroupMemoryLimit()
+ if !ok {
+ log.Debug().Msg("no cgroup memory limit detected; leaving GC defaults")
+ return
+ }
+
+ soft := limit / 100 * memoryLimitHeadroomPercent
+ if soft < minimumUsableMemoryLimit {
+ log.Warn().Int64("cgroupLimitBytes", limit).Msg("cgroup memory limit too small for a GC soft limit; leaving GC defaults")
+ return
+ }
+
+ debug.SetMemoryLimit(soft)
+ log.Info().
+ Int64("cgroupLimitBytes", limit).
+ Int64("goMemLimitBytes", soft).
+ Msg("aligned Go memory limit with cgroup memory limit")
+}
+
+func readCgroupMemoryLimit() (int64, bool) {
+ if limit, ok := readCgroupV2MemoryLimit(cgroupV2Root, "/proc/self/cgroup"); ok {
+ return limit, true
+ }
+ return readCgroupV1MemoryLimit("/sys/fs/cgroup/memory/memory.limit_in_bytes")
+}
+
+// readCgroupV2MemoryLimit resolves the process's own cgroup from
+// procSelfCgroup and walks from that directory up to the cgroup root, taking
+// the smallest memory.max on the path. The limit may sit on any ancestor
+// (systemd applies MemoryMax to the service cgroup; container runtimes to the
+// container root).
+func readCgroupV2MemoryLimit(root, procSelfCgroup string) (int64, bool) {
+ data, err := os.ReadFile(procSelfCgroup)
+ if err != nil {
+ return 0, false
+ }
+ rel := cgroupV2PathFrom(string(data))
+ if rel == "" {
+ return 0, false
+ }
+
+ lowest := int64(math.MaxInt64)
+ dir := filepath.Join(root, rel)
+ for {
+ if raw, err := os.ReadFile(filepath.Join(dir, "memory.max")); err == nil {
+ if v, ok := parseCgroupMemoryValue(string(raw)); ok && v < lowest {
+ lowest = v
+ }
+ }
+ if dir == root {
+ break
+ }
+ parent := filepath.Dir(dir)
+ if parent == dir {
+ break
+ }
+ dir = parent
+ }
+
+ if lowest == math.MaxInt64 {
+ return 0, false
+ }
+ return lowest, true
+}
+
+// cgroupV2PathFrom extracts the unified-hierarchy path from /proc/self/cgroup
+// content ("0::/system.slice/pulse.service" -> "system.slice/pulse.service").
+func cgroupV2PathFrom(content string) string {
+ for _, line := range strings.Split(content, "\n") {
+ if !strings.HasPrefix(line, "0::") {
+ continue
+ }
+ return strings.TrimPrefix(strings.TrimSpace(strings.TrimPrefix(line, "0::")), "/")
+ }
+ return ""
+}
+
+func readCgroupV1MemoryLimit(limitFile string) (int64, bool) {
+ raw, err := os.ReadFile(limitFile)
+ if err != nil {
+ return 0, false
+ }
+ v, ok := parseCgroupMemoryValue(string(raw))
+ if !ok || v >= cgroupV1NoLimit {
+ return 0, false
+ }
+ return v, true
+}
+
+// parseCgroupMemoryValue parses a cgroup memory file value. "max" (v2's
+// explicit no-limit marker) and non-numeric content report no limit.
+func parseCgroupMemoryValue(raw string) (int64, bool) {
+ s := strings.TrimSpace(raw)
+ if s == "" || s == "max" {
+ return 0, false
+ }
+ v, err := strconv.ParseInt(s, 10, 64)
+ if err != nil || v <= 0 {
+ return 0, false
+ }
+ return v, true
+}
diff --git a/pkg/server/memlimit_test.go b/pkg/server/memlimit_test.go
new file mode 100644
index 0000000000..5019530038
--- /dev/null
+++ b/pkg/server/memlimit_test.go
@@ -0,0 +1,127 @@
+package server
+
+import (
+ "os"
+ "path/filepath"
+ "strconv"
+ "testing"
+)
+
+func TestParseCgroupMemoryValue(t *testing.T) {
+ cases := []struct {
+ name string
+ raw string
+ want int64
+ ok bool
+ }{
+ {"plain number", "838860800\n", 838860800, true},
+ {"max marker", "max\n", 0, false},
+ {"empty", "", 0, false},
+ {"whitespace", " \n", 0, false},
+ {"garbage", "not-a-number", 0, false},
+ {"zero", "0", 0, false},
+ {"negative", "-5", 0, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got, ok := parseCgroupMemoryValue(tc.raw)
+ if ok != tc.ok || got != tc.want {
+ t.Fatalf("parseCgroupMemoryValue(%q) = (%d, %v), want (%d, %v)", tc.raw, got, ok, tc.want, tc.ok)
+ }
+ })
+ }
+}
+
+func TestCgroupV2PathFrom(t *testing.T) {
+ cases := []struct {
+ name string
+ content string
+ want string
+ }{
+ {"systemd service", "0::/system.slice/pulse.service\n", "system.slice/pulse.service"},
+ {"container root", "0::/\n", ""},
+ {"hybrid picks unified line", "12:memory:/legacy\n0::/system.slice/pulse.service\n", "system.slice/pulse.service"},
+ {"v1 only", "12:memory:/legacy\n", ""},
+ {"empty", "", ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := cgroupV2PathFrom(tc.content); got != tc.want {
+ t.Fatalf("cgroupV2PathFrom(%q) = %q, want %q", tc.content, got, tc.want)
+ }
+ })
+ }
+}
+
+func writeCgroupFixture(t *testing.T, path, content string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestReadCgroupV2MemoryLimitWalksAncestors(t *testing.T) {
+ root := t.TempDir()
+ proc := filepath.Join(root, "proc-self-cgroup")
+ writeCgroupFixture(t, proc, "0::/system.slice/pulse.service\n")
+
+ // Limit set on the service, "max" at the root: service limit wins.
+ writeCgroupFixture(t, filepath.Join(root, "system.slice/pulse.service/memory.max"), "838860800\n")
+ writeCgroupFixture(t, filepath.Join(root, "system.slice/memory.max"), "max\n")
+ writeCgroupFixture(t, filepath.Join(root, "memory.max"), "max\n")
+
+ got, ok := readCgroupV2MemoryLimit(root, proc)
+ if !ok || got != 838860800 {
+ t.Fatalf("got (%d, %v), want (838860800, true)", got, ok)
+ }
+}
+
+func TestReadCgroupV2MemoryLimitTakesSmallestOnPath(t *testing.T) {
+ root := t.TempDir()
+ proc := filepath.Join(root, "proc-self-cgroup")
+ writeCgroupFixture(t, proc, "0::/a/b\n")
+
+ // Ancestor holds the tighter limit.
+ writeCgroupFixture(t, filepath.Join(root, "a/b/memory.max"), "2147483648\n")
+ writeCgroupFixture(t, filepath.Join(root, "a/memory.max"), "1073741824\n")
+
+ got, ok := readCgroupV2MemoryLimit(root, proc)
+ if !ok || got != 1073741824 {
+ t.Fatalf("got (%d, %v), want (1073741824, true)", got, ok)
+ }
+}
+
+func TestReadCgroupV2MemoryLimitNoLimitAnywhere(t *testing.T) {
+ root := t.TempDir()
+ proc := filepath.Join(root, "proc-self-cgroup")
+ writeCgroupFixture(t, proc, "0::/a\n")
+ writeCgroupFixture(t, filepath.Join(root, "a/memory.max"), "max\n")
+ writeCgroupFixture(t, filepath.Join(root, "memory.max"), "max\n")
+
+ if got, ok := readCgroupV2MemoryLimit(root, proc); ok {
+ t.Fatalf("expected no limit, got %d", got)
+ }
+}
+
+func TestReadCgroupV1MemoryLimit(t *testing.T) {
+ dir := t.TempDir()
+ limitFile := filepath.Join(dir, "memory.limit_in_bytes")
+
+ writeCgroupFixture(t, limitFile, "536870912\n")
+ if got, ok := readCgroupV1MemoryLimit(limitFile); !ok || got != 536870912 {
+ t.Fatalf("got (%d, %v), want (536870912, true)", got, ok)
+ }
+
+ // The v1 no-limit sentinel reports no limit.
+ writeCgroupFixture(t, limitFile, strconv.FormatInt(cgroupV1NoLimit, 10)+"\n")
+ if got, ok := readCgroupV1MemoryLimit(limitFile); ok {
+ t.Fatalf("expected sentinel to mean no limit, got %d", got)
+ }
+
+ if _, ok := readCgroupV1MemoryLimit(filepath.Join(dir, "missing")); ok {
+ t.Fatal("expected missing file to mean no limit")
+ }
+}
diff --git a/pkg/server/server.go b/pkg/server/server.go
index 4807353878..b8348e1494 100644
--- a/pkg/server/server.go
+++ b/pkg/server/server.go
@@ -149,6 +149,8 @@ func Run(ctx context.Context, version string) error {
})
defer logging.Shutdown()
+ applyRuntimeMemoryLimit()
+
if err := api.ValidateTrustedProxyCIDRsFromEnv(); err != nil {
return err
}