Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `-<prefix>.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. #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
Expand Down
9 changes: 9 additions & 0 deletions docs/configuration/config-file-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,15 @@ resource_monitor:
# CLI flag: -resource-monitor.cpu-rate-interval
[cpu_rate_interval: <duration> | 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: <string> | default = "gomemlimit"]

api:
# Use GZIP compression for API responses. Some endpoints serve large YAML or
# JSON blobs which can benefit from compression.
Expand Down
2 changes: 2 additions & 0 deletions docs/configuration/v1-guarantees.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`)
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -249,6 +250,7 @@ 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/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
Expand Down Expand Up @@ -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=
Expand Down
18 changes: 18 additions & 0 deletions pkg/configs/resource_monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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 {
Expand All @@ -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
}
45 changes: 45 additions & 0 deletions pkg/configs/resource_monitor_test.go
Original file line number Diff line number Diff line change
@@ -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)
})
}
}
5 changes: 3 additions & 2 deletions pkg/cortex/modules.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"maps"
"net/http"
"runtime"
"runtime/debug"

"github.com/go-kit/log/level"
"github.com/opentracing-contrib/go-stdlib/nethttp"
Expand All @@ -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"
Expand Down Expand Up @@ -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)
}
Expand Down
50 changes: 50 additions & 0 deletions pkg/util/resource/memory_limit.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package resource

import (
"runtime/debug"

"github.com/KimMachineGun/automemlimit/memlimit"
"github.com/go-kit/log"
"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

// 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 {
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", "type", heapLimitTypeContainer, "err", err)
return 0
}

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)
}
98 changes: 98 additions & 0 deletions pkg/util/resource/memory_limit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package resource

import (
"bytes"
"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())
}

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)
}
}
6 changes: 6 additions & 0 deletions schemas/cortex-config-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
21 changes: 21 additions & 0 deletions vendor/github.com/KimMachineGun/automemlimit/LICENSE

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading