From 17183a8a56098476fa31cb4b3bf6a55c5cd4958d Mon Sep 17 00:00:00 2001 From: Ahmed Hassan Date: Mon, 30 Nov 2026 22:34:36 +0000 Subject: [PATCH 1/4] Resource monitor: divide heap utilization by the container memory limit The resource monitor divides heap objects by GOMEMLIMIT, so a heap rejection threshold is a fraction of the GC's own target. When GOMEMLIMIT drives the GC, the heap goal is (GOMEMLIMIT - non-heap) x 0.97, about 0.93 of GOMEMLIMIT, and heap objects climb to it before every collection. A 0.9 threshold therefore rejects queries before each GC cycle can free its garbage, and the threshold cannot be moved above the GC goal without also moving the GC goal, because both scale with GOMEMLIMIT. Add -resource-monitor.heap-limit with two values: - gomemlimit (default): divide by GOMEMLIMIT, as today. - container: divide by the container memory limit, read from cgroups with github.com/KimMachineGun/automemlimit (memlimit.FromCgroup), which handles cgroup v1, v2 and nested hierarchies. With container, heap_utilization thresholds are a fraction of pod memory, so GOMEMLIMIT (where the GC runs) and the rejection threshold can be set independently, e.g. GC goal < threshold < pod limit. If the container memory limit cannot be read, the monitor logs a warning and reports a heap utilization of 0, so heap-based rejection and eviction stay off rather than acting on the wrong limit, and the pod still starts. CPU-based limits are unaffected. Signed-off-by: Ahmed Hassan --- CHANGELOG.md | 1 + docs/configuration/config-file-reference.md | 9 + docs/configuration/v1-guarantees.md | 2 + go.mod | 2 + go.sum | 4 + pkg/configs/resource_monitor.go | 18 + pkg/configs/resource_monitor_test.go | 45 ++ pkg/cortex/modules.go | 5 +- pkg/util/resource/memory_limit.go | 39 ++ pkg/util/resource/memory_limit_test.go | 81 +++ schemas/cortex-config-schema.json | 6 + .../KimMachineGun/automemlimit/LICENSE | 21 + .../automemlimit/memlimit/cgroups.go | 658 ++++++++++++++++++ .../automemlimit/memlimit/cgroups_linux.go | 8 + .../memlimit/cgroups_unsupported.go | 9 + .../automemlimit/memlimit/logger.go | 22 + .../automemlimit/memlimit/memlimit.go | 215 ++++++ .../automemlimit/memlimit/provider.go | 47 ++ .../automemlimit/memlimit/system.go | 14 + vendor/github.com/pbnjay/memory/LICENSE | 29 + vendor/github.com/pbnjay/memory/README.md | 41 ++ vendor/github.com/pbnjay/memory/doc.go | 24 + vendor/github.com/pbnjay/memory/memory_bsd.go | 19 + .../github.com/pbnjay/memory/memory_darwin.go | 49 ++ .../github.com/pbnjay/memory/memory_linux.go | 29 + .../pbnjay/memory/memory_windows.go | 60 ++ vendor/github.com/pbnjay/memory/memsysctl.go | 21 + vendor/github.com/pbnjay/memory/stub.go | 10 + vendor/modules.txt | 6 + 29 files changed, 1492 insertions(+), 2 deletions(-) create mode 100644 pkg/configs/resource_monitor_test.go create mode 100644 pkg/util/resource/memory_limit.go create mode 100644 pkg/util/resource/memory_limit_test.go create mode 100644 vendor/github.com/KimMachineGun/automemlimit/LICENSE create mode 100644 vendor/github.com/KimMachineGun/automemlimit/memlimit/cgroups.go create mode 100644 vendor/github.com/KimMachineGun/automemlimit/memlimit/cgroups_linux.go create mode 100644 vendor/github.com/KimMachineGun/automemlimit/memlimit/cgroups_unsupported.go create mode 100644 vendor/github.com/KimMachineGun/automemlimit/memlimit/logger.go create mode 100644 vendor/github.com/KimMachineGun/automemlimit/memlimit/memlimit.go create mode 100644 vendor/github.com/KimMachineGun/automemlimit/memlimit/provider.go create mode 100644 vendor/github.com/KimMachineGun/automemlimit/memlimit/system.go create mode 100644 vendor/github.com/pbnjay/memory/LICENSE create mode 100644 vendor/github.com/pbnjay/memory/README.md create mode 100644 vendor/github.com/pbnjay/memory/doc.go create mode 100644 vendor/github.com/pbnjay/memory/memory_bsd.go create mode 100644 vendor/github.com/pbnjay/memory/memory_darwin.go create mode 100644 vendor/github.com/pbnjay/memory/memory_linux.go create mode 100644 vendor/github.com/pbnjay/memory/memory_windows.go create mode 100644 vendor/github.com/pbnjay/memory/memsysctl.go create mode 100644 vendor/github.com/pbnjay/memory/stub.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 789baf7f420..ecd6959c3f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ * [FEATURE] Ruler: Add experimental support for federated rule groups. A rule group listing tenants in its `source_tenants` field is evaluated against those tenants while the resulting series and alerts are written to the tenant owning the rule group. Enabled with `-ruler.enable-federated-rules` (requires `-tenant-federation.enabled`), and restricted to selected tenants with `-ruler.allowed-federated-tenants` and `-ruler.disallowed-federated-tenants`. #7828 * [FEATURE] Distributor: Add experimental OTLP metrics ingestion over gRPC (`opentelemetry.proto.collector.metrics.v1.MetricsService/Export`) on the gRPC server port. Enable it with `-distributor.otlp.grpc-enabled`. The tenant is read from the `X-Scope-OrgID` gRPC metadata, and the request size is limited by `-server.grpc-max-recv-msg-size-bytes`. #7873 * [FEATURE] Storage: Add support for Alibaba Cloud OSS as a backend for blocks, ruler, and alertmanager storage. Configured via `-.oss.*` flags with `backend: oss`. #7907 +* [ENHANCEMENT] Resource monitor: Add experimental `-resource-monitor.heap-limit` to choose what heap utilization is divided by: `gomemlimit` (default, unchanged behaviour) or `container`, the container memory limit read from cgroups. With `container`, heap-based rejection and eviction thresholds are a fraction of the container memory limit instead of GOMEMLIMIT. If the container memory limit cannot be read, a warning is logged and heap-based rejection and eviction are disabled. * [ENHANCEMENT] Compactor: Add `-compactor.block-ranges-compaction-delay` to configure the compaction group graceful period per `-compactor.block-ranges` entry, matched by position. A larger block range can now be held back until its sub-ranges have settled, instead of every range sharing one period derived from `-compactor.cleanup-interval`. Leaving it empty, and any range without an entry, keeps the current behaviour of twice `-compactor.cleanup-interval`. The delay is a lower bound: groups only become eligible on a compaction run, so the effective wait can be up to `-compactor.compaction-interval` longer. Only used by the partitioning compaction strategy. #7916 * [ENHANCEMENT] Compactor: Add `-compactor.compaction-drain-timeout`. When set, a compaction that is already running when shutdown is requested is allowed to finish, for up to this duration, instead of being cancelled. The compactor stops planning new compaction groups and stops picking up further tenants as soon as shutdown is requested. Defaults to 0, which cancels the running compaction immediately and discards the work it has done so far. #7973 * [ENHANCEMENT] Ring: Add the `cortex_ring_member_zonal_ownership_percent{name, member, zone}` metric, reporting the fraction of its own zone's token space owned by each ring member. With zone-aware replication a write is routed within a single zone, so the existing `cortex_ring_member_ownership_percent`, which is computed over the merged token list of all zones, does not reflect the hash range a member actually serves. Reported when ring detailed metrics and zone awareness are both enabled. #7910 diff --git a/docs/configuration/config-file-reference.md b/docs/configuration/config-file-reference.md index a2e30348c26..9880386b68a 100644 --- a/docs/configuration/config-file-reference.md +++ b/docs/configuration/config-file-reference.md @@ -89,6 +89,15 @@ resource_monitor: # CLI flag: -resource-monitor.cpu-rate-interval [cpu_rate_interval: | default = 1m] + # The memory limit that heap utilization is divided by. Supported values are + # gomemlimit (the Go soft memory limit, GOMEMLIMIT) and container (the + # container memory limit read from cgroups). With container, heap utilization + # thresholds are a fraction of the container memory limit, independent of + # GOMEMLIMIT. If the container memory limit cannot be read, a warning is + # logged and heap-based rejection and eviction are disabled. + # CLI flag: -resource-monitor.heap-limit + [heap_limit: | default = "gomemlimit"] + api: # Use GZIP compression for API responses. Some endpoints serve large YAML or # JSON blobs which can benefit from compression. diff --git a/docs/configuration/v1-guarantees.md b/docs/configuration/v1-guarantees.md index 4556590fe76..a55c3c0a5d1 100644 --- a/docs/configuration/v1-guarantees.md +++ b/docs/configuration/v1-guarantees.md @@ -119,6 +119,8 @@ Currently experimental features are: - `-ingester.query-protection.rejection` - `-store-gateway.query-protection.rejection` - `-querier.query-protection.rejection` +- Resource monitor: heap utilization denominator + - `-resource-monitor.heap-limit` (string) - Distributor/Ingester: Stream push connection - Enable stream push connection between distributor and ingester by setting `-distributor.use-stream-push=true` on Distributor. - Enable stream push authentication on Distributor/Ingester. (`-distributor.sign-write-requests-keys`) diff --git a/go.mod b/go.mod index d83334c10ba..ca6f6da2e83 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/cortexproject/cortex go 1.27.0 require ( + github.com/KimMachineGun/automemlimit v1.0.2 github.com/Masterminds/squirrel v1.5.4 github.com/RoaringBitmap/roaring/v2 v2.30.0 github.com/VictoriaMetrics/fastcache v1.13.3 @@ -251,6 +252,7 @@ require ( github.com/parquet-go/jsonlite v1.0.0 // indirect github.com/philhofer/fwd v1.2.0 // indirect github.com/pierrec/lz4/v4 v4.1.26 // indirect + github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect diff --git a/go.sum b/go.sum index 9fa1cfe86fa..4079ad30606 100644 --- a/go.sum +++ b/go.sum @@ -118,6 +118,8 @@ github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapp github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0/go.mod h1:cSgYe11MCNYunTnRXrKiR/tHc0eoKjICUuWpNZoVCOo= github.com/HdrHistogram/hdrhistogram-go v1.1.2 h1:5IcZpTvzydCQeHzK4Ef/D5rrSqwxob0t8PQPMybUNFM= github.com/HdrHistogram/hdrhistogram-go v1.1.2/go.mod h1:yDgFjdqOqDEKOvasDdhWNXYg9BVp4O+o5f6V/ehm6Oo= +github.com/KimMachineGun/automemlimit v1.0.2 h1:DkORkhuzrwT2/b35xz8zLd7cJ6Hu2ESRGBY8HKUFIYk= +github.com/KimMachineGun/automemlimit v1.0.2/go.mod h1:n+BSXxQWDFS1DKh67Rqo0lgTsowsg6x65ak5uyngML0= github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM= github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= @@ -849,6 +851,8 @@ github.com/parquet-go/parquet-go v0.30.1/go.mod h1:navtkAYr2LGoJVp141oXPlO/sxLva github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= +github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 h1:onHthvaw9LFnH4t2DcNVpwGmV9E1BkGknEliJkfwQj0= +github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58/go.mod h1:DXv8WO4yhMYhSNPKjeNKa5WY9YCIEBRbNzFFPJbWO6Y= github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o= github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/pelletier/go-toml/v2 v2.0.5/go.mod h1:OMHamSCAODeSsVrwwvcJOaoN0LIUIaFVNZzmWyNfXas= diff --git a/pkg/configs/resource_monitor.go b/pkg/configs/resource_monitor.go index 4d5fc06346a..90b5b9501fd 100644 --- a/pkg/configs/resource_monitor.go +++ b/pkg/configs/resource_monitor.go @@ -9,10 +9,18 @@ import ( "github.com/cortexproject/cortex/pkg/util/resource" ) +const ( + // HeapLimitGOMEMLIMIT divides heap usage by the Go soft memory limit (GOMEMLIMIT). + HeapLimitGOMEMLIMIT = "gomemlimit" + // HeapLimitContainer divides heap usage by the container memory limit read from cgroups. + HeapLimitContainer = "container" +) + type ResourceMonitor struct { Resources flagext.StringSliceCSV `yaml:"resources"` Interval time.Duration `yaml:"interval"` CPURateInterval time.Duration `yaml:"cpu_rate_interval"` + HeapLimit string `yaml:"heap_limit"` } func (cfg *ResourceMonitor) RegisterFlags(f *flag.FlagSet) { @@ -23,6 +31,9 @@ func (cfg *ResourceMonitor) RegisterFlags(f *flag.FlagSet) { "that are close estimates. Empty string to disable.") f.DurationVar(&cfg.Interval, "resource-monitor.interval", 100*time.Millisecond, "Update interval of resource monitor. Must be greater than 0.") f.DurationVar(&cfg.CPURateInterval, "resource-monitor.cpu-rate-interval", time.Minute, "Interval to calculate average CPU rate. Must be greater than resource monitor interval.") + f.StringVar(&cfg.HeapLimit, "resource-monitor.heap-limit", HeapLimitGOMEMLIMIT, "The memory limit that heap utilization is divided by. "+ + "Supported values are gomemlimit (the Go soft memory limit, GOMEMLIMIT) and container (the container memory limit read from cgroups). "+ + "With container, heap utilization thresholds are a fraction of the container memory limit, independent of GOMEMLIMIT. If the container memory limit cannot be read, a warning is logged and heap-based rejection and eviction are disabled.") } func (cfg *ResourceMonitor) Validate() error { @@ -44,5 +55,12 @@ func (cfg *ResourceMonitor) Validate() error { return fmt.Errorf("resource monitor cpu rate interval cannot be smaller than resource monitor interval") } + switch cfg.HeapLimit { + // An empty value keeps configs built in code without RegisterFlags on the GOMEMLIMIT behaviour. + case "", HeapLimitGOMEMLIMIT, HeapLimitContainer: + default: + return fmt.Errorf("unsupported resource monitor heap limit: %q (supported: %s, %s)", cfg.HeapLimit, HeapLimitGOMEMLIMIT, HeapLimitContainer) + } + return nil } diff --git a/pkg/configs/resource_monitor_test.go b/pkg/configs/resource_monitor_test.go new file mode 100644 index 00000000000..7b66366113d --- /dev/null +++ b/pkg/configs/resource_monitor_test.go @@ -0,0 +1,45 @@ +package configs + +import ( + "flag" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestResourceMonitor_HeapLimit(t *testing.T) { + tests := map[string]struct { + heapLimit string + expectedErr string + }{ + "default is gomemlimit": {heapLimit: ""}, + "gomemlimit": {heapLimit: HeapLimitGOMEMLIMIT}, + "container": {heapLimit: HeapLimitContainer}, + "unsupported": {heapLimit: "pod", expectedErr: "unsupported resource monitor heap limit"}, + } + + t.Run("unset in a config built without flags", func(t *testing.T) { + cfg := ResourceMonitor{Interval: time.Second, CPURateInterval: time.Minute} + require.NoError(t, cfg.Validate()) + }) + + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + cfg := ResourceMonitor{} + fs := flag.NewFlagSet("", flag.PanicOnError) + cfg.RegisterFlags(fs) + require.Equal(t, HeapLimitGOMEMLIMIT, cfg.HeapLimit) + if tc.heapLimit != "" { + require.NoError(t, fs.Set("resource-monitor.heap-limit", tc.heapLimit)) + } + + err := cfg.Validate() + if tc.expectedErr != "" { + require.ErrorContains(t, err, tc.expectedErr) + return + } + require.NoError(t, err) + }) + } +} diff --git a/pkg/cortex/modules.go b/pkg/cortex/modules.go index d787a6b2429..d667671cff2 100644 --- a/pkg/cortex/modules.go +++ b/pkg/cortex/modules.go @@ -8,7 +8,6 @@ import ( "maps" "net/http" "runtime" - "runtime/debug" "github.com/go-kit/log/level" "github.com/opentracing-contrib/go-stdlib/nethttp" @@ -33,6 +32,7 @@ import ( "github.com/cortexproject/cortex/pkg/alertmanager/alertstore" "github.com/cortexproject/cortex/pkg/api" "github.com/cortexproject/cortex/pkg/compactor" + "github.com/cortexproject/cortex/pkg/configs" configAPI "github.com/cortexproject/cortex/pkg/configs/api" "github.com/cortexproject/cortex/pkg/configs/db" "github.com/cortexproject/cortex/pkg/distributor" @@ -936,7 +936,8 @@ func (t *Cortex) initResourceMonitor() (services.Service, error) { case resource.CPU: containerLimits[resource.Type(res)] = float64(runtime.GOMAXPROCS(0)) case resource.Heap: - containerLimits[resource.Type(res)] = float64(debug.SetMemoryLimit(-1)) + useContainerLimit := t.Cfg.ResourceMonitor.HeapLimit == configs.HeapLimitContainer + containerLimits[resource.Type(res)] = resource.HeapLimit(useContainerLimit, util_log.Logger) default: return nil, fmt.Errorf("unknown resource type: %s", res) } diff --git a/pkg/util/resource/memory_limit.go b/pkg/util/resource/memory_limit.go new file mode 100644 index 00000000000..3ac568df976 --- /dev/null +++ b/pkg/util/resource/memory_limit.go @@ -0,0 +1,39 @@ +package resource + +import ( + "runtime/debug" + + "github.com/KimMachineGun/automemlimit/memlimit" + "github.com/go-kit/log" + "github.com/go-kit/log/level" +) + +// containerMemoryLimit reads the memory limit of the container the process runs in from cgroups. +// It is a variable so tests can replace it. +var containerMemoryLimit = memlimit.FromCgroup + +// goMemoryLimit returns the Go soft memory limit (GOMEMLIMIT) without changing it. +// It is a variable so tests can replace it. +var goMemoryLimit = func() int64 { return debug.SetMemoryLimit(-1) } + +// HeapLimit returns the bytes that heap usage is divided by to get heap utilization. +// +// By default it is the Go soft memory limit (GOMEMLIMIT). With useContainerLimit it is the +// container memory limit read from cgroups. If that limit cannot be read, for example because +// the container has no memory limit, HeapLimit logs a warning and returns 0. The monitor then +// reports a heap utilization of 0, so heap-based rejection and eviction never trigger, and the +// process still starts. +func HeapLimit(useContainerLimit bool, logger log.Logger) float64 { + if !useContainerLimit { + return float64(goMemoryLimit()) + } + + limit, err := containerMemoryLimit() + if err != nil || limit == 0 { + level.Warn(logger).Log("msg", "resource monitor could not read the container memory limit, heap-based rejection and eviction are disabled", "err", err) + return 0 + } + + level.Info(logger).Log("msg", "resource monitor divides heap usage by the container memory limit", "container_memory_limit_bytes", limit) + return float64(limit) +} diff --git a/pkg/util/resource/memory_limit_test.go b/pkg/util/resource/memory_limit_test.go new file mode 100644 index 00000000000..3f857c72c3c --- /dev/null +++ b/pkg/util/resource/memory_limit_test.go @@ -0,0 +1,81 @@ +package resource + +import ( + "errors" + "testing" + + "github.com/KimMachineGun/automemlimit/memlimit" + "github.com/go-kit/log" + "github.com/stretchr/testify/require" +) + +func TestHeapLimit(t *testing.T) { + const ( + goLimitBytes = int64(50 << 30) + containerLimitBytes = uint64(60_000_000_000) + ) + + tests := map[string]struct { + useContainerLimit bool + containerLimit uint64 + containerErr error + expected float64 + }{ + "gomemlimit by default": { + useContainerLimit: false, + containerLimit: containerLimitBytes, + expected: float64(goLimitBytes), + }, + "container limit": { + useContainerLimit: true, + containerLimit: containerLimitBytes, + expected: float64(containerLimitBytes), + }, + "container without a memory limit disables heap utilization": { + useContainerLimit: true, + containerErr: memlimit.ErrNoLimit, + expected: 0, + }, + "process not in a cgroup disables heap utilization": { + useContainerLimit: true, + containerErr: memlimit.ErrNoCgroup, + expected: 0, + }, + "unreadable cgroup disables heap utilization": { + useContainerLimit: true, + containerErr: errors.New("permission denied"), + expected: 0, + }, + "zero container limit disables heap utilization": { + useContainerLimit: true, + containerLimit: 0, + expected: 0, + }, + } + + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + origContainer, origGo := containerMemoryLimit, goMemoryLimit + t.Cleanup(func() { containerMemoryLimit, goMemoryLimit = origContainer, origGo }) + + containerMemoryLimit = func() (uint64, error) { return tc.containerLimit, tc.containerErr } + goMemoryLimit = func() int64 { return goLimitBytes } + + require.Equal(t, tc.expected, HeapLimit(tc.useContainerLimit, log.NewNopLogger())) + }) + } +} + +// A heap limit of 0 is what HeapLimit returns when the container limit is missing. The monitor +// must then report 0 heap utilization, so no heap threshold can trigger. +func TestMonitor_ZeroHeapLimitReportsNoUtilization(t *testing.T) { + const heapBytes = float64(40 << 30) + + m := &Monitor{containerLimit: map[Type]float64{Heap: 0}, utilization: map[Type]float64{}} + m.storeHeapUtilization(heapBytes) + require.Equal(t, float64(0), m.GetHeapUtilization()) + + m.containerLimit[Heap] = heapBytes * 2 + m.storeHeapUtilization(heapBytes) + require.Equal(t, 0.5, m.GetHeapUtilization()) +} diff --git a/schemas/cortex-config-schema.json b/schemas/cortex-config-schema.json index 1d1df6aa453..40f9b6920ab 100644 --- a/schemas/cortex-config-schema.json +++ b/schemas/cortex-config-schema.json @@ -10192,6 +10192,12 @@ "x-cli-flag": "resource-monitor.cpu-rate-interval", "x-format": "duration" }, + "heap_limit": { + "default": "gomemlimit", + "description": "The memory limit that heap utilization is divided by. Supported values are gomemlimit (the Go soft memory limit, GOMEMLIMIT) and container (the container memory limit read from cgroups). With container, heap utilization thresholds are a fraction of the container memory limit, independent of GOMEMLIMIT. If the container memory limit cannot be read, a warning is logged and heap-based rejection and eviction are disabled.", + "type": "string", + "x-cli-flag": "resource-monitor.heap-limit" + }, "interval": { "default": "100ms", "description": "Update interval of resource monitor. Must be greater than 0.", diff --git a/vendor/github.com/KimMachineGun/automemlimit/LICENSE b/vendor/github.com/KimMachineGun/automemlimit/LICENSE new file mode 100644 index 00000000000..1f5b8f6b30d --- /dev/null +++ b/vendor/github.com/KimMachineGun/automemlimit/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Geon Kim + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/KimMachineGun/automemlimit/memlimit/cgroups.go b/vendor/github.com/KimMachineGun/automemlimit/memlimit/cgroups.go new file mode 100644 index 00000000000..0b8c7d4532d --- /dev/null +++ b/vendor/github.com/KimMachineGun/automemlimit/memlimit/cgroups.go @@ -0,0 +1,658 @@ +package memlimit + +import ( + "bufio" + "errors" + "fmt" + "io" + "math" + "os" + "path/filepath" + "slices" + "strconv" + "strings" +) + +const ( + procSelfMountInfoPath = "/proc/self/mountinfo" + procSelfCgroupPath = "/proc/self/cgroup" +) + +var ( + // ErrNoCgroup is returned when the process is not assigned to a cgroup. + ErrNoCgroup = errors.New("process is not in cgroup") + // ErrCgroupsNotSupported is returned when the system does not support cgroups. + ErrCgroupsNotSupported = errors.New("cgroups is not supported on this system") +) + +func fromCgroup(mountInfoPath, cgroupPath string) (uint64, error) { + mf, err := os.Open(mountInfoPath) + if err != nil { + return 0, fmt.Errorf("failed to open %s: %w", mountInfoPath, err) + } + defer mf.Close() + + mis, err := parseMountInfo(mf) + if err != nil { + return 0, fmt.Errorf("failed to parse mountinfo: %w", err) + } + + cf, err := os.Open(cgroupPath) + if err != nil { + return 0, fmt.Errorf("failed to open %s: %w", cgroupPath, err) + } + defer cf.Close() + + chs, err := parseCgroupFile(cf) + if err != nil { + return 0, fmt.Errorf("failed to parse cgroup file: %w", err) + } + + controller, err := selectMemoryController(chs, mis) + if err != nil { + return 0, err + } + if controller.isV2 { + return getMemoryLimitV2FromControllerPath(controller.path, mis) + } + + return getMemoryLimitV1FromControllerPath(controller.path, mis) +} + +type memoryController struct { + path string + isV2 bool +} + +// selectMemoryController selects v1 when both v1 and v2 are available. +func selectMemoryController(chs []cgroupHierarchy, mis []mountInfo) (memoryController, error) { + var ( + v1Path string + v2Path string + hasV1Entry bool + hasV2Entry bool + hasV1Mount bool + hasV2Mount bool + ) + + for _, ch := range chs { + if !hasV1Entry && ch.HierarchyID != "0" && slices.Contains(strings.Split(ch.ControllerList, ","), "memory") { + v1Path = ch.CgroupPath + hasV1Entry = true + } else if !hasV2Entry && ch.HierarchyID == "0" && ch.ControllerList == "" { + v2Path = ch.CgroupPath + hasV2Entry = true + } + } + + for _, mi := range mis { + if !hasV1Mount && mi.FilesystemType == "cgroup" && slices.Contains(strings.Split(mi.SuperOptions, ","), "memory") { + hasV1Mount = true + } else if !hasV2Mount && mi.FilesystemType == "cgroup2" { + // cgroup v2 uses a unified hierarchy, so the filesystem type is sufficient + hasV2Mount = true + } + } + + switch { + case hasV1Entry: + if !hasV1Mount { + return memoryController{}, errors.New("memory controller found in /proc/self/cgroup but no cgroup v1 memory mount found") + } + return memoryController{path: v1Path}, nil + case hasV2Entry: + if !hasV2Mount { + return memoryController{}, errors.New("cgroup v2 hierarchy found in /proc/self/cgroup but no cgroup2 mount found") + } + return memoryController{path: v2Path, isV2: true}, nil + default: + return memoryController{}, ErrNoCgroup + } +} + +// readMemoryLimitV2FromPath reads a memory limit from a cgroup v2 memory.max file. +// It returns [ErrNoLimit] for "max" and preserves [os.ErrNotExist] for a missing file. +func readMemoryLimitV2FromPath(path string) (uint64, error) { + b, err := os.ReadFile(path) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return 0, err + } + return 0, fmt.Errorf("failed to read memory.max: %w", err) + } + + slimit := strings.TrimSpace(string(b)) + if slimit == "max" { + return 0, ErrNoLimit + } + + limit, err := strconv.ParseUint(slimit, 10, 64) + if err != nil { + return 0, fmt.Errorf("failed to parse memory.max value: %w", err) + } + + return limit, nil +} + +// walkCgroupV2Hierarchy returns the smallest limit between cgroupPath and mountPoint. +// It skips missing and unlimited values, returning [ErrNoLimit] if no concrete limit remains. +func walkCgroupV2Hierarchy(cgroupPath, mountPoint string) (uint64, error) { + var ( + found = false + minLimit uint64 = math.MaxUint64 + ) + for currentPath := cgroupPath; ; { + limit, err := readMemoryLimitV2FromPath(filepath.Join(currentPath, "memory.max")) + if err == nil { + found = true + minLimit = min(minLimit, limit) + } else if !errors.Is(err, os.ErrNotExist) && !errors.Is(err, ErrNoLimit) { + return 0, err + } + if currentPath == mountPoint { + break + } + + parent := filepath.Dir(currentPath) + if parent == currentPath { + break + } + currentPath = parent + } + if !found { + return 0, ErrNoLimit + } + + return minLimit, nil +} + +// getMemoryLimitV2FromControllerPath prefers mounts rooted closest to the cgroup hierarchy root. +func getMemoryLimitV2FromControllerPath(relPath string, mis []mountInfo) (uint64, error) { + rootClosestMounts, err := getRootClosestMountCandidates( + relPath, + mis, + func(mi mountInfo) bool { + return mi.FilesystemType == "cgroup2" + }, + ) + if err != nil { + return 0, err + } + + limit, found, err := getMemoryLimitFromMountCandidates( + rootClosestMounts, + func(mi mountInfo) (uint64, bool, error) { + cgroupPath, err := resolveCgroupPath(mi.MountPoint, mi.Root, relPath) + if err != nil { + return 0, false, err + } + + stat, err := os.Stat(cgroupPath) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return 0, false, nil + } + return 0, false, err + } + if !stat.IsDir() { + return 0, false, fmt.Errorf("cgroup v2 path %s is not a directory", cgroupPath) + } + + limit, err := walkCgroupV2Hierarchy(cgroupPath, mi.MountPoint) + if err != nil { + return 0, false, err + } + + return limit, true, nil + }, + ) + if err != nil { + return 0, err + } else if found { + return limit, nil + } + + return 0, errors.New("no usable cgroup v2 memory mount found") +} + +// getMemoryLimitV1FromControllerPath prefers mounts rooted closest to the cgroup hierarchy root. +func getMemoryLimitV1FromControllerPath(relPath string, mis []mountInfo) (uint64, error) { + rootClosestMounts, err := getRootClosestMountCandidates( + relPath, + mis, + func(mi mountInfo) bool { + return mi.FilesystemType == "cgroup" && slices.Contains(strings.Split(mi.SuperOptions, ","), "memory") + }, + ) + if err != nil { + return 0, err + } + + limit, found, err := getMemoryLimitFromMountCandidates( + rootClosestMounts, + func(mi mountInfo) (uint64, bool, error) { + cgroupPath, err := resolveCgroupPath(mi.MountPoint, mi.Root, relPath) + if err != nil { + return 0, false, err + } + + return readMemoryLimitV1FromPath(cgroupPath) + }, + ) + if err != nil { + return 0, err + } else if found { + return limit, nil + } + + return 0, errors.New("no usable cgroup v1 memory mount found") +} + +func getRootClosestMountCandidates( + relPath string, + mis []mountInfo, + isCandidate func(mi mountInfo) bool, +) ([]mountInfo, error) { + var ( + rootClosestMounts []mountInfo + maxDepth = -1 + ) + for _, mi := range mis { + if !isCandidate(mi) { + continue + } + + cgroupPath, err := resolveCgroupPath(mi.MountPoint, mi.Root, relPath) + if err != nil { + return nil, err + } else if cgroupPath == "" { + continue + } + if _, err := os.Stat(cgroupPath); errors.Is(err, os.ErrNotExist) { + continue + } + + rel, err := filepath.Rel(mi.MountPoint, cgroupPath) + if err != nil { + return nil, err + } + + depth := 0 + if rel != "." { + depth = strings.Count(rel, string(filepath.Separator)) + 1 + } + + switch { + case depth > maxDepth: + rootClosestMounts = []mountInfo{mi} + maxDepth = depth + case depth == maxDepth: + rootClosestMounts = append(rootClosestMounts, mi) + } + } + + return rootClosestMounts, nil +} + +// getLimit may return found=false to skip a candidate or [ErrNoLimit] for no usable limit. +// Permission errors are returned only if no candidate returns a limit or [ErrNoLimit]. +// Other errors and conflicting concrete limits are returned. +func getMemoryLimitFromMountCandidates( + mis []mountInfo, + getLimit func(mi mountInfo) (uint64, bool, error), +) (uint64, bool, error) { + var ( + firstErr, permissionErr, conflictErr error + sawNoLimit, limitFound bool + firstLimit uint64 + ) + for _, mi := range mis { + limit, found, err := getLimit(mi) + if err != nil { + if errors.Is(err, ErrNoLimit) { + sawNoLimit = true + } else if errors.Is(err, os.ErrPermission) { + if permissionErr == nil { + permissionErr = err + } + } else if firstErr == nil { + firstErr = err + } + continue + } else if !found { + continue + } + + if !limitFound { + limitFound = true + firstLimit = limit + } else if limit != firstLimit && conflictErr == nil { + conflictErr = fmt.Errorf("conflicting memory limits from cgroup mount candidates: %d and %d", firstLimit, limit) + } + } + if firstErr != nil { + return 0, false, firstErr + } + if conflictErr != nil { + return 0, false, conflictErr + } + + if limitFound { + return firstLimit, true, nil + } + if sawNoLimit { + return 0, false, ErrNoLimit + } + if permissionErr != nil { + return 0, false, permissionErr + } + + return 0, false, nil +} + +// cgroup v1 uses the kernel's maximum page counter value to represent no limit +func isCgroupV1NoLimit(limit uint64) bool { + pageSize := uint64(os.Getpagesize()) + if limit >= math.MaxInt64/pageSize*pageSize { + return true + } + + // strconv.IntSize reflects the Go binary width, not the kernel bitness + if strconv.IntSize == 32 { + return limit == math.MaxInt32*pageSize + } + + return false +} + +// readMemoryLimitV1FromPath reads the effective memory limit from a cgroup v1 directory. +// It returns [ErrNoLimit] for a no-limit sentinel. +// The bool reports whether a limit value was found. +func readMemoryLimitV1FromPath(cgroupPath string) (uint64, bool, error) { + // use math.MaxUint64 as a neutral fallback so memory.limit_in_bytes determines the result + hml, hmlFound, err := readHierarchicalMemoryLimit(filepath.Join(cgroupPath, "memory.stat")) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return 0, false, fmt.Errorf("failed to read hierarchical_memory_limit: %w", err) + } else if !hmlFound { + hml = math.MaxUint64 + } + + var libFound bool + lib, err := readMemoryLimitInBytes(filepath.Join(cgroupPath, "memory.limit_in_bytes")) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return 0, false, err + } else if errors.Is(err, os.ErrNotExist) { + lib = math.MaxUint64 + } else { + libFound = true + } + + if !hmlFound && !libFound { + return 0, false, nil + } + + limit := min(hml, lib) + if isCgroupV1NoLimit(limit) { + return 0, true, ErrNoLimit + } + + return limit, true, nil +} + +// readHierarchicalMemoryLimit returns false if memory.stat has no hierarchical_memory_limit field. +func readHierarchicalMemoryLimit(path string) (uint64, bool, error) { + file, err := os.Open(path) + if err != nil { + return 0, false, err + } + defer file.Close() + + scanner := bufio.NewScanner(file) + for scanner.Scan() { + line := scanner.Text() + + fields := strings.Fields(line) + if len(fields) == 0 || fields[0] != "hierarchical_memory_limit" { + continue + } + if len(fields) < 2 { + return 0, false, fmt.Errorf("failed to parse memory.stat %q: not enough fields", line) + } else if len(fields) > 2 { + return 0, false, fmt.Errorf("failed to parse memory.stat %q: too many fields for hierarchical_memory_limit", line) + } + + limit, err := strconv.ParseUint(fields[1], 10, 64) + if err != nil { + return 0, false, fmt.Errorf("failed to parse hierarchical_memory_limit value: %w", err) + } + + return limit, true, nil + } + if err := scanner.Err(); err != nil { + return 0, false, err + } + + return 0, false, nil +} + +func readMemoryLimitInBytes(path string) (uint64, error) { + b, err := os.ReadFile(path) + if err != nil { + return 0, fmt.Errorf("failed to read memory.limit_in_bytes: %w", err) + } + + limit, err := strconv.ParseUint(strings.TrimSpace(string(b)), 10, 64) + if err != nil { + return 0, fmt.Errorf("failed to parse memory.limit_in_bytes value: %w", err) + } + + return limit, nil +} + +// https://www.man7.org/linux/man-pages/man5/proc_pid_mountinfo.5.html +// 731 771 0:59 /sysrq-trigger /proc/sysrq-trigger ro,nosuid,nodev,noexec,relatime - proc proc rw +// +// 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue +// (1)(2)(3) (4) (5) (6) (7) (8) (9) (10) (11) +// +// (1) mount ID: a unique ID for the mount (may be reused after umount(2)). +// (2) parent ID: the ID of the parent mount (or of self for the root of this mount namespace's mount tree). +// (3) major:minor: the value of st_dev for files on this filesystem (see stat(2)). +// (4) root: the pathname of the directory in the filesystem which forms the root of this mount. +// (5) mount point: the pathname of the mount point relative to the process's root directory. +// (6) mount options: per-mount options (see mount(2)). +// (7) optional fields: zero or more fields of the form "tag[:value]"; see below. +// (8) separator: the end of the optional fields is marked by a single hyphen. +// (9) filesystem type: the filesystem type in the form "type[.subtype]". +// (10) mount source: filesystem-specific information or "none". +// (11) super options: per-superblock options (see mount(2)). +type mountInfo struct { + Root string + MountPoint string + FilesystemType string + SuperOptions string +} + +func parseMountInfoLine(line string) (mountInfo, error) { + if line == "" { + return mountInfo{}, errors.New("empty line") + } + + fieldss := strings.SplitN(line, " - ", 2) + if len(fieldss) != 2 { + return mountInfo{}, fmt.Errorf("invalid separator") + } + + fields1 := strings.SplitN(fieldss[0], " ", 7) + if len(fields1) < 6 { + return mountInfo{}, fmt.Errorf("not enough fields before separator: %v", fields1) + } else if len(fields1) == 6 { + fields1 = append(fields1, "") + } + + fields2 := strings.SplitN(fieldss[1], " ", 3) + if len(fields2) < 3 { + return mountInfo{}, fmt.Errorf("not enough fields after separator: %v", fields2) + } + + return mountInfo{ + Root: unescapeMountInfoPath(fields1[3]), + MountPoint: unescapeMountInfoPath(fields1[4]), + FilesystemType: fields2[0], + SuperOptions: fields2[2], + }, nil +} + +// unescapeMountInfoPath decodes path escapes written to /proc//mountinfo. +// https://github.com/torvalds/linux/blob/master/fs/proc_namespace.c +func unescapeMountInfoPath(path string) string { + if strings.IndexByte(path, '\\') == -1 { + return path + } + + var b strings.Builder + b.Grow(len(path)) + for i := 0; i < len(path); i++ { + if path[i] == '\\' && i+3 < len(path) { + switch path[i : i+4] { + case `\040`: + b.WriteByte(' ') + i += 3 + continue + case `\011`: + b.WriteByte('\t') + i += 3 + continue + case `\012`: + b.WriteByte('\n') + i += 3 + continue + case `\134`: + b.WriteByte('\\') + i += 3 + continue + } + } + + b.WriteByte(path[i]) + } + + return b.String() +} + +func parseMountInfo(r io.Reader) ([]mountInfo, error) { + var ( + s = bufio.NewScanner(r) + mis []mountInfo + ) + for s.Scan() { + line := s.Text() + + mi, err := parseMountInfoLine(line) + if err != nil { + return nil, fmt.Errorf("failed to parse mountinfo file %q: %w", line, err) + } + + mis = append(mis, mi) + } + if err := s.Err(); err != nil { + return nil, err + } + + return mis, nil +} + +// https://www.man7.org/linux/man-pages/man7/cgroups.7.html +// +// 5:cpuacct,cpu,cpuset:/daemons +// (1) (2) (3) +// +// (1) hierarchy ID: +// +// cgroups version 1 hierarchies, this field +// contains a unique hierarchy ID number that can be +// matched to a hierarchy ID in /proc/cgroups. For the +// cgroups version 2 hierarchy, this field contains the +// value 0. +// +// (2) controller list: +// +// For cgroups version 1 hierarchies, this field +// contains a comma-separated list of the controllers +// bound to the hierarchy. For the cgroups version 2 +// hierarchy, this field is empty. +// +// (3) cgroup path: +// +// This field contains the pathname of the control group +// in the hierarchy to which the process belongs. This +// pathname is relative to the mount point of the +// hierarchy. +type cgroupHierarchy struct { + HierarchyID string + ControllerList string + CgroupPath string +} + +func parseCgroupHierarchyLine(line string) (cgroupHierarchy, error) { + if line == "" { + return cgroupHierarchy{}, errors.New("empty line") + } + + fields := strings.SplitN(line, ":", 3) + if len(fields) < 3 { + return cgroupHierarchy{}, fmt.Errorf("not enough fields: %v", fields) + } + + return cgroupHierarchy{ + HierarchyID: fields[0], + ControllerList: fields[1], + CgroupPath: fields[2], + }, nil +} + +func parseCgroupFile(r io.Reader) ([]cgroupHierarchy, error) { + var ( + s = bufio.NewScanner(r) + chs []cgroupHierarchy + ) + for s.Scan() { + line := s.Text() + + ch, err := parseCgroupHierarchyLine(line) + if err != nil { + return nil, fmt.Errorf("failed to parse cgroup file %q: %w", line, err) + } + + chs = append(chs, ch) + } + if err := s.Err(); err != nil { + return nil, err + } + + return chs, nil +} + +// resolveCgroupPath maps cgroupRelPath from root into mountPoint. +// It returns an empty path when cgroupRelPath lies outside root. +func resolveCgroupPath(mountPoint, root, cgroupRelPath string) (string, error) { + if !strings.HasPrefix(root, "/") || !strings.HasPrefix(cgroupRelPath, "/") { + return "", errors.New("cgroup root and path must be absolute") + } + + if root == cgroupRelPath { + return mountPoint, nil + } + + prefix := root + if root != "/" { + prefix += "/" + } + + rel, ok := strings.CutPrefix(cgroupRelPath, prefix) + if !ok || !filepath.IsLocal(rel) { + return "", nil + } + + return filepath.Join(mountPoint, rel), nil +} diff --git a/vendor/github.com/KimMachineGun/automemlimit/memlimit/cgroups_linux.go b/vendor/github.com/KimMachineGun/automemlimit/memlimit/cgroups_linux.go new file mode 100644 index 00000000000..575f0a9e8c1 --- /dev/null +++ b/vendor/github.com/KimMachineGun/automemlimit/memlimit/cgroups_linux.go @@ -0,0 +1,8 @@ +//go:build linux + +package memlimit + +// FromCgroup returns the memory limit for the current process's cgroup. +func FromCgroup() (uint64, error) { + return fromCgroup(procSelfMountInfoPath, procSelfCgroupPath) +} diff --git a/vendor/github.com/KimMachineGun/automemlimit/memlimit/cgroups_unsupported.go b/vendor/github.com/KimMachineGun/automemlimit/memlimit/cgroups_unsupported.go new file mode 100644 index 00000000000..f96f7dadea3 --- /dev/null +++ b/vendor/github.com/KimMachineGun/automemlimit/memlimit/cgroups_unsupported.go @@ -0,0 +1,9 @@ +//go:build !linux + +package memlimit + +// FromCgroup returns the memory limit for the current process's cgroup. +// On non-Linux platforms, it always returns [ErrCgroupsNotSupported]. +func FromCgroup() (uint64, error) { + return 0, ErrCgroupsNotSupported +} diff --git a/vendor/github.com/KimMachineGun/automemlimit/memlimit/logger.go b/vendor/github.com/KimMachineGun/automemlimit/memlimit/logger.go new file mode 100644 index 00000000000..8f683043343 --- /dev/null +++ b/vendor/github.com/KimMachineGun/automemlimit/memlimit/logger.go @@ -0,0 +1,22 @@ +package memlimit + +import ( + "context" + "log/slog" +) + +var _ slog.Handler = discardHandler{} + +type discardHandler struct{} + +func (discardHandler) Enabled(context.Context, slog.Level) bool { return false } +func (discardHandler) Handle(context.Context, slog.Record) error { return nil } +func (dh discardHandler) WithAttrs([]slog.Attr) slog.Handler { return dh } +func (dh discardHandler) WithGroup(string) slog.Handler { return dh } + +func memlimitLogger(logger *slog.Logger) *slog.Logger { + if logger == nil { + return slog.New(discardHandler{}) + } + return logger.With(slog.String("package", "github.com/KimMachineGun/automemlimit/memlimit")) +} diff --git a/vendor/github.com/KimMachineGun/automemlimit/memlimit/memlimit.go b/vendor/github.com/KimMachineGun/automemlimit/memlimit/memlimit.go new file mode 100644 index 00000000000..9119c635d55 --- /dev/null +++ b/vendor/github.com/KimMachineGun/automemlimit/memlimit/memlimit.go @@ -0,0 +1,215 @@ +// Package memlimit configures GOMEMLIMIT from a memory limit provider. +package memlimit + +import ( + "context" + "errors" + "fmt" + "log/slog" + "math" + "os" + "runtime/debug" + "strconv" + "time" +) + +const ( + envGOMEMLIMIT = "GOMEMLIMIT" + envAUTOMEMLIMIT = "AUTOMEMLIMIT" + + defaultAUTOMEMLIMIT = 0.9 +) + +// ErrNoLimit indicates that a [Provider] reports no memory limit. +// [Set] handles it as success by setting GOMEMLIMIT to [math.MaxInt64]. +var ErrNoLimit = errors.New("memory is not limited") + +type config struct { + logger *slog.Logger + ratio float64 + minLimit int64 + provider Provider + refresh time.Duration + refreshCtx context.Context +} + +// Option configures the behavior of [Set]. +type Option func(cfg *config) + +// WithRatio configures the fraction of the memory limit used for GOMEMLIMIT. +// The ratio must be in (0.0, 1.0]. +// +// Default: 0.9 +func WithRatio(ratio float64) Option { + return func(cfg *config) { + cfg.ratio = ratio + } +} + +// WithMin configures the minimum GOMEMLIMIT after applying the ratio. +// A non-positive value disables the minimum. +// +// Default: 0 (no minimum) +func WithMin(minLimit int64) Option { + return func(cfg *config) { + cfg.minLimit = minLimit + } +} + +// WithProvider configures the provider used by [Set]. +// +// Default: [FromCgroup] +func WithProvider(provider Provider) Option { + return func(cfg *config) { + cfg.provider = provider + } +} + +// WithLogger configures the logger. +// It adds the "package" attribute to every log record. +// +// Default: logging disabled +func WithLogger(logger *slog.Logger) Option { + return func(cfg *config) { + cfg.logger = memlimitLogger(logger) + } +} + +// WithRefreshInterval configures [Set] to periodically refresh GOMEMLIMIT. +// +// Set starts a refresh goroutine after the initial provider call +// when refresh is positive and ctx is non-nil. +// The goroutine starts even if the initial call returns an error. +// Canceling ctx stops the refresh loop but does not interrupt an active provider call. +// Provider errors other than [ErrNoLimit] are reported to the configured logger +// and do not stop later refreshes. +// +// Default: 0 (no refresh) +func WithRefreshInterval(ctx context.Context, refresh time.Duration) Option { + return func(cfg *config) { + cfg.refresh = refresh + cfg.refreshCtx = ctx + } +} + +// Set sets GOMEMLIMIT using the configured provider. +// +// By default, Set uses 90% of the limit reported by [FromCgroup]. +// AUTOMEMLIMIT overrides the configured ratio with a value in (0.0, 1.0]. +// Setting it to "off" disables Set. +// +// If GOMEMLIMIT is set to a non-empty value or AUTOMEMLIMIT is set to "off", +// Set returns the current GOMEMLIMIT without calling the provider or starting a refresh goroutine. +// +// Set returns the resulting GOMEMLIMIT on success. +// On error, it returns the previous GOMEMLIMIT and the error. +// It handles [ErrNoLimit] as success by setting GOMEMLIMIT to [math.MaxInt64]. +func Set(opts ...Option) (_limit int64, _err error) { + cfg := &config{ + logger: slog.New(discardHandler{}), + ratio: defaultAUTOMEMLIMIT, + provider: FromCgroup, + } + for _, opt := range opts { + opt(cfg) + } + + defer func() { + if _err != nil { + cfg.logger.Error("failed to set GOMEMLIMIT", slog.Any("error", _err)) + } + }() + + snapshot := debug.SetMemoryLimit(-1) + + if val := os.Getenv(envGOMEMLIMIT); val != "" { + cfg.logger.Info("GOMEMLIMIT is already set, skipping", slog.String(envGOMEMLIMIT, val)) + return snapshot, nil + } + + ratio := cfg.ratio + if val, ok := os.LookupEnv(envAUTOMEMLIMIT); ok { + if val == "off" { + cfg.logger.Info("AUTOMEMLIMIT is off, skipping") + return snapshot, nil + } + + r, err := strconv.ParseFloat(val, 64) + if err != nil { + return snapshot, fmt.Errorf("cannot parse AUTOMEMLIMIT: %s", val) + } + ratio = r + } + if math.IsNaN(ratio) || ratio <= 0 || ratio > 1 { + return snapshot, fmt.Errorf( + "failed to set GOMEMLIMIT: invalid ratio: %f, ratio should be in the range (0.0,1.0]", + ratio, + ) + } + + provider := boundedProvider(ApplyRatio(cfg.provider, ratio), cfg.minLimit) + limit, err := updateGoMemLimit(provider, cfg.logger) + if cfg.refresh > 0 && cfg.refreshCtx != nil { + go refresh(cfg.refreshCtx, provider, cfg.logger, cfg.refresh) + } + if err != nil { + return snapshot, fmt.Errorf("failed to set GOMEMLIMIT: %w", err) + } + + return int64(limit), nil +} + +func updateGoMemLimit(provider Provider, logger *slog.Logger) (uint64, error) { + newLimit, err := provider() + if err != nil { + if errors.Is(err, ErrNoLimit) { + return updateGoMemLimit(Limit(math.MaxInt64), logger) + } + return 0, err + } + + previous := debug.SetMemoryLimit(int64(newLimit)) + if newLimit == uint64(previous) { + logger.Debug("GOMEMLIMIT is unchanged", slog.Uint64(envGOMEMLIMIT, newLimit)) + return newLimit, nil + } + + logger.Info("GOMEMLIMIT is updated", slog.Uint64(envGOMEMLIMIT, newLimit), slog.Uint64("previous", uint64(previous))) + + return newLimit, nil +} + +func refresh(ctx context.Context, provider Provider, logger *slog.Logger, refresh time.Duration) { + if refresh == 0 { + return + } + + ticker := time.NewTicker(refresh) + defer ticker.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + _, err := updateGoMemLimit(provider, logger) + if err != nil { + logger.Error("failed to refresh GOMEMLIMIT", slog.Any("error", err)) + } + } + } +} + +func boundedProvider(provider Provider, minLimit int64) Provider { + return func() (uint64, error) { + limit, err := provider() + if err != nil { + return 0, err + } else if limit > math.MaxInt64 { + return math.MaxInt64, nil + } else if minLimit > 0 && limit < uint64(minLimit) { + return uint64(minLimit), nil + } + return limit, nil + } +} diff --git a/vendor/github.com/KimMachineGun/automemlimit/memlimit/provider.go b/vendor/github.com/KimMachineGun/automemlimit/memlimit/provider.go new file mode 100644 index 00000000000..70c730d1728 --- /dev/null +++ b/vendor/github.com/KimMachineGun/automemlimit/memlimit/provider.go @@ -0,0 +1,47 @@ +package memlimit + +import ( + "fmt" + "math" +) + +// Provider returns a memory limit in bytes. +// It should return [ErrNoLimit] when the source reports no limit. +type Provider func() (uint64, error) + +// Limit returns a [Provider] that always returns limit. +func Limit(limit uint64) Provider { + return func() (uint64, error) { + return limit, nil + } +} + +// ApplyRatio wraps provider and applies ratio to its result. +// The ratio must be in (0.0, 1.0]. +func ApplyRatio(provider Provider, ratio float64) Provider { + if ratio == 1 { + return provider + } + return func() (uint64, error) { + if math.IsNaN(ratio) || ratio <= 0 || ratio > 1 { + return 0, fmt.Errorf("invalid ratio: %f, ratio should be in the range (0.0,1.0]", ratio) + } + limit, err := provider() + if err != nil { + return 0, err + } + return uint64(float64(limit) * ratio), nil + } +} + +// ApplyFallback returns a [Provider] that calls fallback when provider returns an error, +// including [ErrNoLimit]. +func ApplyFallback(provider Provider, fallback Provider) Provider { + return func() (uint64, error) { + limit, err := provider() + if err != nil { + return fallback() + } + return limit, nil + } +} diff --git a/vendor/github.com/KimMachineGun/automemlimit/memlimit/system.go b/vendor/github.com/KimMachineGun/automemlimit/memlimit/system.go new file mode 100644 index 00000000000..9901fe816dd --- /dev/null +++ b/vendor/github.com/KimMachineGun/automemlimit/memlimit/system.go @@ -0,0 +1,14 @@ +package memlimit + +import ( + "github.com/pbnjay/memory" +) + +// FromSystem returns the total system memory. +func FromSystem() (uint64, error) { + limit := memory.TotalMemory() + if limit == 0 { + return 0, ErrNoLimit + } + return limit, nil +} diff --git a/vendor/github.com/pbnjay/memory/LICENSE b/vendor/github.com/pbnjay/memory/LICENSE new file mode 100644 index 00000000000..63ca4a6d249 --- /dev/null +++ b/vendor/github.com/pbnjay/memory/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2017, Jeremy Jay +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pbnjay/memory/README.md b/vendor/github.com/pbnjay/memory/README.md new file mode 100644 index 00000000000..e98f261a0f3 --- /dev/null +++ b/vendor/github.com/pbnjay/memory/README.md @@ -0,0 +1,41 @@ +# memory + +Package `memory` provides two methods reporting total physical system memory +accessible to the kernel, and free memory available to the running application. + +This package has no external dependency besides the standard library and default operating system tools. + +Documentation: +[![GoDoc](https://godoc.org/github.com/pbnjay/memory?status.svg)](https://godoc.org/github.com/pbnjay/memory) + +This is useful for dynamic code to minimize thrashing and other contention, similar to the stdlib `runtime.NumCPU` +See some history of the proposal at https://github.com/golang/go/issues/21816 + + +## Example + +```go +fmt.Printf("Total system memory: %d\n", memory.TotalMemory()) +fmt.Printf("Free memory: %d\n", memory.FreeMemory()) +``` + + +## Testing + +Tested/working on: + - macOS 10.12.6 (16G29), 10.15.7 (19H2) + - Windows 10 1511 (10586.1045) + - Linux RHEL (3.10.0-327.3.1.el7.x86_64) + - Raspberry Pi 3 (ARMv8) on Raspbian, ODROID-C1+ (ARMv7) on Ubuntu, C.H.I.P + (ARMv7). + - Amazon Linux 2 aarch64 (m6a.large, 4.14.203-156.332.amzn2.aarch64) + +Tested on virtual machines: + - Windows 7 SP1 386 + - Debian stretch 386 + - NetBSD 7.1 amd64 + 386 + - OpenBSD 6.1 amd64 + 386 + - FreeBSD 11.1 amd64 + 386 + - DragonFly BSD 4.8.1 amd64 + +If you have access to untested systems please test and report success/bugs. diff --git a/vendor/github.com/pbnjay/memory/doc.go b/vendor/github.com/pbnjay/memory/doc.go new file mode 100644 index 00000000000..4e4f984c0f2 --- /dev/null +++ b/vendor/github.com/pbnjay/memory/doc.go @@ -0,0 +1,24 @@ +// Package memory provides a single method reporting total system memory +// accessible to the kernel. +package memory + +// TotalMemory returns the total accessible system memory in bytes. +// +// The total accessible memory is installed physical memory size minus reserved +// areas for the kernel and hardware, if such reservations are reported by +// the operating system. +// +// If accessible memory size could not be determined, then 0 is returned. +func TotalMemory() uint64 { + return sysTotalMemory() +} + +// FreeMemory returns the total free system memory in bytes. +// +// The total free memory is installed physical memory size minus reserved +// areas for other applications running on the same system. +// +// If free memory size could not be determined, then 0 is returned. +func FreeMemory() uint64 { + return sysFreeMemory() +} diff --git a/vendor/github.com/pbnjay/memory/memory_bsd.go b/vendor/github.com/pbnjay/memory/memory_bsd.go new file mode 100644 index 00000000000..49d808a9e72 --- /dev/null +++ b/vendor/github.com/pbnjay/memory/memory_bsd.go @@ -0,0 +1,19 @@ +// +build freebsd openbsd dragonfly netbsd + +package memory + +func sysTotalMemory() uint64 { + s, err := sysctlUint64("hw.physmem") + if err != nil { + return 0 + } + return s +} + +func sysFreeMemory() uint64 { + s, err := sysctlUint64("hw.usermem") + if err != nil { + return 0 + } + return s +} diff --git a/vendor/github.com/pbnjay/memory/memory_darwin.go b/vendor/github.com/pbnjay/memory/memory_darwin.go new file mode 100644 index 00000000000..a3f45769904 --- /dev/null +++ b/vendor/github.com/pbnjay/memory/memory_darwin.go @@ -0,0 +1,49 @@ +// +build darwin + +package memory + +import ( + "os/exec" + "regexp" + "strconv" +) + +func sysTotalMemory() uint64 { + s, err := sysctlUint64("hw.memsize") + if err != nil { + return 0 + } + return s +} + +func sysFreeMemory() uint64 { + cmd := exec.Command("vm_stat") + outBytes, err := cmd.Output() + if err != nil { + return 0 + } + + rePageSize := regexp.MustCompile("page size of ([0-9]*) bytes") + reFreePages := regexp.MustCompile("Pages free: *([0-9]*)\\.") + + // default: page size of 4096 bytes + matches := rePageSize.FindSubmatchIndex(outBytes) + pageSize := uint64(4096) + if len(matches) == 4 { + pageSize, err = strconv.ParseUint(string(outBytes[matches[2]:matches[3]]), 10, 64) + if err != nil { + return 0 + } + } + + // ex: Pages free: 1126961. + matches = reFreePages.FindSubmatchIndex(outBytes) + freePages := uint64(0) + if len(matches) == 4 { + freePages, err = strconv.ParseUint(string(outBytes[matches[2]:matches[3]]), 10, 64) + if err != nil { + return 0 + } + } + return freePages * pageSize +} diff --git a/vendor/github.com/pbnjay/memory/memory_linux.go b/vendor/github.com/pbnjay/memory/memory_linux.go new file mode 100644 index 00000000000..3d07711ce54 --- /dev/null +++ b/vendor/github.com/pbnjay/memory/memory_linux.go @@ -0,0 +1,29 @@ +// +build linux + +package memory + +import "syscall" + +func sysTotalMemory() uint64 { + in := &syscall.Sysinfo_t{} + err := syscall.Sysinfo(in) + if err != nil { + return 0 + } + // If this is a 32-bit system, then these fields are + // uint32 instead of uint64. + // So we always convert to uint64 to match signature. + return uint64(in.Totalram) * uint64(in.Unit) +} + +func sysFreeMemory() uint64 { + in := &syscall.Sysinfo_t{} + err := syscall.Sysinfo(in) + if err != nil { + return 0 + } + // If this is a 32-bit system, then these fields are + // uint32 instead of uint64. + // So we always convert to uint64 to match signature. + return uint64(in.Freeram) * uint64(in.Unit) +} diff --git a/vendor/github.com/pbnjay/memory/memory_windows.go b/vendor/github.com/pbnjay/memory/memory_windows.go new file mode 100644 index 00000000000..c8500cc6f3b --- /dev/null +++ b/vendor/github.com/pbnjay/memory/memory_windows.go @@ -0,0 +1,60 @@ +// +build windows + +package memory + +import ( + "syscall" + "unsafe" +) + +// omitting a few fields for brevity... +// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx +type memStatusEx struct { + dwLength uint32 + dwMemoryLoad uint32 + ullTotalPhys uint64 + ullAvailPhys uint64 + unused [5]uint64 +} + +func sysTotalMemory() uint64 { + kernel32, err := syscall.LoadDLL("kernel32.dll") + if err != nil { + return 0 + } + // GetPhysicallyInstalledSystemMemory is simpler, but broken on + // older versions of windows (and uses this under the hood anyway). + globalMemoryStatusEx, err := kernel32.FindProc("GlobalMemoryStatusEx") + if err != nil { + return 0 + } + msx := &memStatusEx{ + dwLength: 64, + } + r, _, _ := globalMemoryStatusEx.Call(uintptr(unsafe.Pointer(msx))) + if r == 0 { + return 0 + } + return msx.ullTotalPhys +} + +func sysFreeMemory() uint64 { + kernel32, err := syscall.LoadDLL("kernel32.dll") + if err != nil { + return 0 + } + // GetPhysicallyInstalledSystemMemory is simpler, but broken on + // older versions of windows (and uses this under the hood anyway). + globalMemoryStatusEx, err := kernel32.FindProc("GlobalMemoryStatusEx") + if err != nil { + return 0 + } + msx := &memStatusEx{ + dwLength: 64, + } + r, _, _ := globalMemoryStatusEx.Call(uintptr(unsafe.Pointer(msx))) + if r == 0 { + return 0 + } + return msx.ullAvailPhys +} diff --git a/vendor/github.com/pbnjay/memory/memsysctl.go b/vendor/github.com/pbnjay/memory/memsysctl.go new file mode 100644 index 00000000000..438d9eff8e6 --- /dev/null +++ b/vendor/github.com/pbnjay/memory/memsysctl.go @@ -0,0 +1,21 @@ +// +build darwin freebsd openbsd dragonfly netbsd + +package memory + +import ( + "syscall" + "unsafe" +) + +func sysctlUint64(name string) (uint64, error) { + s, err := syscall.Sysctl(name) + if err != nil { + return 0, err + } + // hack because the string conversion above drops a \0 + b := []byte(s) + if len(b) < 8 { + b = append(b, 0) + } + return *(*uint64)(unsafe.Pointer(&b[0])), nil +} diff --git a/vendor/github.com/pbnjay/memory/stub.go b/vendor/github.com/pbnjay/memory/stub.go new file mode 100644 index 00000000000..f29473ba083 --- /dev/null +++ b/vendor/github.com/pbnjay/memory/stub.go @@ -0,0 +1,10 @@ +// +build !linux,!darwin,!windows,!freebsd,!dragonfly,!netbsd,!openbsd + +package memory + +func sysTotalMemory() uint64 { + return 0 +} +func sysFreeMemory() uint64 { + return 0 +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 4883454b2bc..c0d344da5fe 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -137,6 +137,9 @@ github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric # github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0 ## explicit; go 1.23.0 github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping +# github.com/KimMachineGun/automemlimit v1.0.2 +## explicit; go 1.21.0 +github.com/KimMachineGun/automemlimit/memlimit # github.com/Masterminds/squirrel v1.5.4 ## explicit; go 1.14 github.com/Masterminds/squirrel @@ -1014,6 +1017,9 @@ github.com/pierrec/lz4/v4/internal/lz4block github.com/pierrec/lz4/v4/internal/lz4errors github.com/pierrec/lz4/v4/internal/lz4stream github.com/pierrec/lz4/v4/internal/xxh32 +# github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 +## explicit; go 1.16 +github.com/pbnjay/memory # github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c ## explicit; go 1.14 github.com/pkg/browser From 8610a4aee52e4e38c988eadffd10584084a893cc Mon Sep 17 00:00:00 2001 From: Ahmed Hassan Date: Fri, 4 Dec 2026 17:24:03 +0000 Subject: [PATCH 2/4] Add PR number to CHANGELOG entry Signed-off-by: Ahmed Hassan --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ecd6959c3f1..6d4f909027d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ * [FEATURE] Ruler: Add experimental support for federated rule groups. A rule group listing tenants in its `source_tenants` field is evaluated against those tenants while the resulting series and alerts are written to the tenant owning the rule group. Enabled with `-ruler.enable-federated-rules` (requires `-tenant-federation.enabled`), and restricted to selected tenants with `-ruler.allowed-federated-tenants` and `-ruler.disallowed-federated-tenants`. #7828 * [FEATURE] Distributor: Add experimental OTLP metrics ingestion over gRPC (`opentelemetry.proto.collector.metrics.v1.MetricsService/Export`) on the gRPC server port. Enable it with `-distributor.otlp.grpc-enabled`. The tenant is read from the `X-Scope-OrgID` gRPC metadata, and the request size is limited by `-server.grpc-max-recv-msg-size-bytes`. #7873 * [FEATURE] Storage: Add support for Alibaba Cloud OSS as a backend for blocks, ruler, and alertmanager storage. Configured via `-.oss.*` flags with `backend: oss`. #7907 -* [ENHANCEMENT] Resource monitor: Add experimental `-resource-monitor.heap-limit` to choose what heap utilization is divided by: `gomemlimit` (default, unchanged behaviour) or `container`, the container memory limit read from cgroups. With `container`, heap-based rejection and eviction thresholds are a fraction of the container memory limit instead of GOMEMLIMIT. If the container memory limit cannot be read, a warning is logged and heap-based rejection and eviction are disabled. +* [ENHANCEMENT] Resource monitor: Add experimental `-resource-monitor.heap-limit` to choose what heap utilization is divided by: `gomemlimit` (default, unchanged behaviour) or `container`, the container memory limit read from cgroups. With `container`, heap-based rejection and eviction thresholds are a fraction of the container memory limit instead of GOMEMLIMIT. If the container memory limit cannot be read, a warning is logged and heap-based rejection and eviction are disabled. #7991 * [ENHANCEMENT] Compactor: Add `-compactor.block-ranges-compaction-delay` to configure the compaction group graceful period per `-compactor.block-ranges` entry, matched by position. A larger block range can now be held back until its sub-ranges have settled, instead of every range sharing one period derived from `-compactor.cleanup-interval`. Leaving it empty, and any range without an entry, keeps the current behaviour of twice `-compactor.cleanup-interval`. The delay is a lower bound: groups only become eligible on a compaction run, so the effective wait can be up to `-compactor.compaction-interval` longer. Only used by the partitioning compaction strategy. #7916 * [ENHANCEMENT] Compactor: Add `-compactor.compaction-drain-timeout`. When set, a compaction that is already running when shutdown is requested is allowed to finish, for up to this duration, instead of being cancelled. The compactor stops planning new compaction groups and stops picking up further tenants as soon as shutdown is requested. Defaults to 0, which cancels the running compaction immediately and discards the work it has done so far. #7973 * [ENHANCEMENT] Ring: Add the `cortex_ring_member_zonal_ownership_percent{name, member, zone}` metric, reporting the fraction of its own zone's token space owned by each ring member. With zone-aware replication a write is routed within a single zone, so the existing `cortex_ring_member_ownership_percent`, which is computed over the merged token list of all zones, does not reflect the hash range a member actually serves. Reported when ring detailed metrics and zone awareness are both enabled. #7910 From 4252d80d2fd8d0fb7c54e726da57a31639d364b7 Mon Sep 17 00:00:00 2001 From: Ahmed Hassan Date: Fri, 4 Dec 2026 18:13:38 +0000 Subject: [PATCH 3/4] Resource monitor: log the heap limit type and bytes for both modes Signed-off-by: Ahmed Hassan --- pkg/util/resource/memory_limit.go | 17 ++++++++++++++--- pkg/util/resource/memory_limit_test.go | 17 +++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/pkg/util/resource/memory_limit.go b/pkg/util/resource/memory_limit.go index 3ac568df976..8d393f198fa 100644 --- a/pkg/util/resource/memory_limit.go +++ b/pkg/util/resource/memory_limit.go @@ -8,6 +8,11 @@ import ( "github.com/go-kit/log/level" ) +const ( + heapLimitTypeGOMEMLIMIT = "gomemlimit" + heapLimitTypeContainer = "container" +) + // containerMemoryLimit reads the memory limit of the container the process runs in from cgroups. // It is a variable so tests can replace it. var containerMemoryLimit = memlimit.FromCgroup @@ -25,15 +30,21 @@ var goMemoryLimit = func() int64 { return debug.SetMemoryLimit(-1) } // process still starts. func HeapLimit(useContainerLimit bool, logger log.Logger) float64 { if !useContainerLimit { - return float64(goMemoryLimit()) + limit := goMemoryLimit() + logHeapLimit(logger, heapLimitTypeGOMEMLIMIT, uint64(limit)) + return float64(limit) } limit, err := containerMemoryLimit() if err != nil || limit == 0 { - level.Warn(logger).Log("msg", "resource monitor could not read the container memory limit, heap-based rejection and eviction are disabled", "err", err) + level.Warn(logger).Log("msg", "resource monitor could not read the container memory limit, heap-based rejection and eviction are disabled", "type", heapLimitTypeContainer, "err", err) return 0 } - level.Info(logger).Log("msg", "resource monitor divides heap usage by the container memory limit", "container_memory_limit_bytes", limit) + logHeapLimit(logger, heapLimitTypeContainer, limit) return float64(limit) } + +func logHeapLimit(logger log.Logger, limitType string, bytes uint64) { + level.Info(logger).Log("msg", "resource monitor heap limit", "type", limitType, "bytes", bytes) +} diff --git a/pkg/util/resource/memory_limit_test.go b/pkg/util/resource/memory_limit_test.go index 3f857c72c3c..a0827b69d77 100644 --- a/pkg/util/resource/memory_limit_test.go +++ b/pkg/util/resource/memory_limit_test.go @@ -1,6 +1,7 @@ package resource import ( + "bytes" "errors" "testing" @@ -79,3 +80,19 @@ func TestMonitor_ZeroHeapLimitReportsNoUtilization(t *testing.T) { m.storeHeapUtilization(heapBytes) require.Equal(t, 0.5, m.GetHeapUtilization()) } + +func TestHeapLimit_LogsTypeAndBytes(t *testing.T) { + origContainer, origGo := containerMemoryLimit, goMemoryLimit + t.Cleanup(func() { containerMemoryLimit, goMemoryLimit = origContainer, origGo }) + goMemoryLimit = func() int64 { return 1000 } + containerMemoryLimit = func() (uint64, error) { return 2000, nil } + + for useContainerLimit, expected := range map[bool]string{ + false: "type=gomemlimit bytes=1000", + true: "type=container bytes=2000", + } { + var buf bytes.Buffer + HeapLimit(useContainerLimit, log.NewLogfmtLogger(&buf)) + require.Contains(t, buf.String(), `msg="resource monitor heap limit" `+expected) + } +} From 0f6d15ff5479df679d7ff3e69e4f7589aad14b74 Mon Sep 17 00:00:00 2001 From: Ahmed Hassan Date: Fri, 4 Dec 2026 18:34:52 +0000 Subject: [PATCH 4/4] Sort the pbnjay/memory entries in go.mod and vendor/modules.txt Signed-off-by: Ahmed Hassan --- go.mod | 2 +- vendor/modules.txt | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index ca6f6da2e83..0a71c7ce33b 100644 --- a/go.mod +++ b/go.mod @@ -250,9 +250,9 @@ require ( github.com/oracle/oci-go-sdk/v65 v65.93.1 // indirect github.com/parquet-go/bitpack v1.0.0 // indirect github.com/parquet-go/jsonlite v1.0.0 // indirect + github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect github.com/philhofer/fwd v1.2.0 // indirect github.com/pierrec/lz4/v4 v4.1.26 // indirect - github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect diff --git a/vendor/modules.txt b/vendor/modules.txt index c0d344da5fe..623a6e7a9df 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1007,6 +1007,9 @@ github.com/parquet-go/parquet-go/internal/memory github.com/parquet-go/parquet-go/internal/unsafecast github.com/parquet-go/parquet-go/sparse github.com/parquet-go/parquet-go/variant +# github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 +## explicit; go 1.16 +github.com/pbnjay/memory # github.com/philhofer/fwd v1.2.0 ## explicit; go 1.20 github.com/philhofer/fwd @@ -1017,9 +1020,6 @@ github.com/pierrec/lz4/v4/internal/lz4block github.com/pierrec/lz4/v4/internal/lz4errors github.com/pierrec/lz4/v4/internal/lz4stream github.com/pierrec/lz4/v4/internal/xxh32 -# github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 -## explicit; go 1.16 -github.com/pbnjay/memory # github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c ## explicit; go 1.14 github.com/pkg/browser