2023-01-17 23:59:04 +03:00
|
|
|
package memlimit
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2023-08-28 09:59:08 +03:00
|
|
|
"fmt"
|
2024-04-22 11:59:30 +03:00
|
|
|
"log/slog"
|
2023-01-17 23:59:04 +03:00
|
|
|
"math"
|
|
|
|
"os"
|
|
|
|
"runtime/debug"
|
|
|
|
"strconv"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2024-04-22 11:59:30 +03:00
|
|
|
envGOMEMLIMIT = "GOMEMLIMIT"
|
|
|
|
envAUTOMEMLIMIT = "AUTOMEMLIMIT"
|
|
|
|
// Deprecated: use memlimit.WithLogger instead
|
2023-01-17 23:59:04 +03:00
|
|
|
envAUTOMEMLIMIT_DEBUG = "AUTOMEMLIMIT_DEBUG"
|
|
|
|
|
|
|
|
defaultAUTOMEMLIMIT = 0.9
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
// ErrNoLimit is returned when the memory limit is not set.
|
|
|
|
ErrNoLimit = errors.New("memory is not limited")
|
|
|
|
)
|
|
|
|
|
2023-08-28 09:59:08 +03:00
|
|
|
type config struct {
|
2024-04-22 11:59:30 +03:00
|
|
|
logger *slog.Logger
|
2023-08-28 09:59:08 +03:00
|
|
|
ratio float64
|
|
|
|
provider Provider
|
|
|
|
}
|
|
|
|
|
|
|
|
// Option is a function that configures the behavior of SetGoMemLimitWithOptions.
|
|
|
|
type Option func(cfg *config)
|
|
|
|
|
|
|
|
// WithRatio configures the ratio of the memory limit to set as GOMEMLIMIT.
|
2023-01-17 23:59:04 +03:00
|
|
|
//
|
2023-08-28 09:59:08 +03:00
|
|
|
// Default: 0.9
|
|
|
|
func WithRatio(ratio float64) Option {
|
|
|
|
return func(cfg *config) {
|
|
|
|
cfg.ratio = ratio
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-22 11:59:30 +03:00
|
|
|
// WithProvider configures the provider.
|
|
|
|
//
|
|
|
|
// Default: FromCgroup
|
|
|
|
func WithProvider(provider Provider) Option {
|
|
|
|
return func(cfg *config) {
|
|
|
|
cfg.provider = provider
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// WithLogger configures the logger.
|
|
|
|
// It automatically attaches the "package" attribute to the logs.
|
|
|
|
//
|
|
|
|
// Default: slog.New(noopLogger{})
|
|
|
|
func WithLogger(logger *slog.Logger) Option {
|
|
|
|
return func(cfg *config) {
|
|
|
|
cfg.logger = memlimitLogger(logger)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-28 09:59:08 +03:00
|
|
|
// WithEnv configures whether to use environment variables.
|
|
|
|
//
|
|
|
|
// Default: false
|
2024-01-22 12:35:23 +03:00
|
|
|
//
|
|
|
|
// Deprecated: currently this does nothing.
|
2023-08-28 09:59:08 +03:00
|
|
|
func WithEnv() Option {
|
2024-01-22 12:35:23 +03:00
|
|
|
return func(cfg *config) {}
|
2023-08-28 09:59:08 +03:00
|
|
|
}
|
|
|
|
|
2024-04-22 11:59:30 +03:00
|
|
|
func memlimitLogger(logger *slog.Logger) *slog.Logger {
|
|
|
|
if logger == nil {
|
|
|
|
return slog.New(noopLogger{})
|
2023-08-28 09:59:08 +03:00
|
|
|
}
|
2024-04-22 11:59:30 +03:00
|
|
|
return logger.With(slog.String("package", "github.com/KimMachineGun/automemlimit/memlimit"))
|
2023-08-28 09:59:08 +03:00
|
|
|
}
|
|
|
|
|
2024-01-22 12:35:23 +03:00
|
|
|
// SetGoMemLimitWithOpts sets GOMEMLIMIT with options and environment variables.
|
|
|
|
//
|
|
|
|
// You can configure how much memory of the cgroup's memory limit to set as GOMEMLIMIT
|
|
|
|
// through AUTOMEMLIMIT envrironment variable in the half-open range (0.0,1.0].
|
|
|
|
//
|
|
|
|
// If AUTOMEMLIMIT is not set, it defaults to 0.9. (10% is the headroom for memory sources the Go runtime is unaware of.)
|
|
|
|
// If GOMEMLIMIT is already set or AUTOMEMLIMIT=off, this function does nothing.
|
|
|
|
//
|
|
|
|
// If AUTOMEMLIMIT_EXPERIMENT is set, it enables experimental features.
|
|
|
|
// Please see the documentation of Experiments for more details.
|
2023-08-28 09:59:08 +03:00
|
|
|
//
|
|
|
|
// Options:
|
|
|
|
// - WithRatio
|
|
|
|
// - WithProvider
|
2024-04-22 11:59:30 +03:00
|
|
|
// - WithLogger
|
2023-08-28 09:59:08 +03:00
|
|
|
func SetGoMemLimitWithOpts(opts ...Option) (_ int64, _err error) {
|
2024-04-22 11:59:30 +03:00
|
|
|
// init config
|
2023-08-28 09:59:08 +03:00
|
|
|
cfg := &config{
|
2024-04-22 11:59:30 +03:00
|
|
|
logger: slog.New(noopLogger{}),
|
2023-08-28 09:59:08 +03:00
|
|
|
ratio: defaultAUTOMEMLIMIT,
|
|
|
|
provider: FromCgroup,
|
|
|
|
}
|
2024-04-22 11:59:30 +03:00
|
|
|
// TODO: remove this
|
|
|
|
if debug, ok := os.LookupEnv(envAUTOMEMLIMIT_DEBUG); ok {
|
|
|
|
defaultLogger := memlimitLogger(slog.Default())
|
|
|
|
defaultLogger.Warn("AUTOMEMLIMIT_DEBUG is deprecated, use memlimit.WithLogger instead")
|
|
|
|
if debug == "true" {
|
|
|
|
cfg.logger = defaultLogger
|
|
|
|
}
|
2023-08-28 09:59:08 +03:00
|
|
|
}
|
|
|
|
for _, opt := range opts {
|
|
|
|
opt(cfg)
|
|
|
|
}
|
2024-04-22 11:59:30 +03:00
|
|
|
|
|
|
|
// log error if any on return
|
2023-08-28 09:59:08 +03:00
|
|
|
defer func() {
|
|
|
|
if _err != nil {
|
2024-04-22 11:59:30 +03:00
|
|
|
cfg.logger.Error("failed to set GOMEMLIMIT", slog.Any("error", _err))
|
2023-08-28 09:59:08 +03:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2024-04-22 11:59:30 +03:00
|
|
|
// parse experiments
|
2024-01-22 12:35:23 +03:00
|
|
|
exps, err := parseExperiments()
|
|
|
|
if err != nil {
|
|
|
|
return 0, fmt.Errorf("failed to parse experiments: %w", err)
|
|
|
|
}
|
|
|
|
if exps.System {
|
2024-04-22 11:59:30 +03:00
|
|
|
cfg.logger.Info("system experiment is enabled: using system memory limit as a fallback")
|
2024-01-22 12:35:23 +03:00
|
|
|
cfg.provider = ApplyFallback(cfg.provider, FromSystem)
|
|
|
|
}
|
|
|
|
|
2024-04-22 11:59:30 +03:00
|
|
|
// capture the current GOMEMLIMIT for rollback in case of panic
|
2023-04-03 12:16:17 +03:00
|
|
|
snapshot := debug.SetMemoryLimit(-1)
|
|
|
|
defer func() {
|
2024-04-22 11:59:30 +03:00
|
|
|
panicErr := recover()
|
|
|
|
if panicErr != nil {
|
2023-08-28 09:59:08 +03:00
|
|
|
if _err != nil {
|
2024-04-22 11:59:30 +03:00
|
|
|
cfg.logger.Error("failed to set GOMEMLIMIT", slog.Any("error", _err))
|
2023-08-28 09:59:08 +03:00
|
|
|
}
|
2024-04-22 11:59:30 +03:00
|
|
|
_err = fmt.Errorf("panic during setting the Go's memory limit, rolling back to previous limit %d: %v",
|
|
|
|
snapshot, panicErr,
|
|
|
|
)
|
2023-04-03 12:16:17 +03:00
|
|
|
debug.SetMemoryLimit(snapshot)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2024-04-22 11:59:30 +03:00
|
|
|
// check if GOMEMLIMIT is already set
|
2023-01-17 23:59:04 +03:00
|
|
|
if val, ok := os.LookupEnv(envGOMEMLIMIT); ok {
|
2024-04-22 11:59:30 +03:00
|
|
|
cfg.logger.Info("GOMEMLIMIT is already set, skipping", slog.String(envGOMEMLIMIT, val))
|
2023-12-11 13:35:15 +03:00
|
|
|
return 0, nil
|
2023-01-17 23:59:04 +03:00
|
|
|
}
|
|
|
|
|
2024-04-22 11:59:30 +03:00
|
|
|
// parse AUTOMEMLIMIT
|
2023-08-28 09:59:08 +03:00
|
|
|
ratio := cfg.ratio
|
2023-01-17 23:59:04 +03:00
|
|
|
if val, ok := os.LookupEnv(envAUTOMEMLIMIT); ok {
|
|
|
|
if val == "off" {
|
2024-04-22 11:59:30 +03:00
|
|
|
cfg.logger.Info("AUTOMEMLIMIT is set to off, skipping")
|
2023-12-11 13:35:15 +03:00
|
|
|
return 0, nil
|
2023-01-17 23:59:04 +03:00
|
|
|
}
|
|
|
|
_ratio, err := strconv.ParseFloat(val, 64)
|
|
|
|
if err != nil {
|
2023-08-28 09:59:08 +03:00
|
|
|
return 0, fmt.Errorf("cannot parse AUTOMEMLIMIT: %s", val)
|
2023-01-17 23:59:04 +03:00
|
|
|
}
|
|
|
|
ratio = _ratio
|
|
|
|
}
|
|
|
|
|
2024-04-22 11:59:30 +03:00
|
|
|
// set GOMEMLIMIT
|
2023-12-11 13:35:15 +03:00
|
|
|
limit, err := setGoMemLimit(ApplyRatio(cfg.provider, ratio))
|
2023-01-17 23:59:04 +03:00
|
|
|
if err != nil {
|
2024-01-22 12:35:23 +03:00
|
|
|
if errors.Is(err, ErrNoLimit) {
|
2024-05-21 16:17:22 +03:00
|
|
|
cfg.logger.Info("memory is not limited, skipping")
|
2024-01-22 12:35:23 +03:00
|
|
|
return 0, nil
|
|
|
|
}
|
2023-08-28 09:59:08 +03:00
|
|
|
return 0, fmt.Errorf("failed to set GOMEMLIMIT: %w", err)
|
2023-01-17 23:59:04 +03:00
|
|
|
}
|
|
|
|
|
2024-04-22 11:59:30 +03:00
|
|
|
cfg.logger.Info("GOMEMLIMIT is updated", slog.Int64(envGOMEMLIMIT, limit))
|
2023-08-28 09:59:08 +03:00
|
|
|
|
|
|
|
return limit, nil
|
|
|
|
}
|
|
|
|
|
2024-04-22 11:59:30 +03:00
|
|
|
// SetGoMemLimitWithEnv sets GOMEMLIMIT with the value from the environment variables.
|
|
|
|
// Since WithEnv is deprecated, this function is equivalent to SetGoMemLimitWithOpts().
|
|
|
|
// Deprecated: use SetGoMemLimitWithOpts instead.
|
2023-08-28 09:59:08 +03:00
|
|
|
func SetGoMemLimitWithEnv() {
|
2024-01-22 12:35:23 +03:00
|
|
|
_, _ = SetGoMemLimitWithOpts()
|
2023-01-17 23:59:04 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// SetGoMemLimit sets GOMEMLIMIT with the value from the cgroup's memory limit and given ratio.
|
|
|
|
func SetGoMemLimit(ratio float64) (int64, error) {
|
2023-12-11 13:35:15 +03:00
|
|
|
return SetGoMemLimitWithOpts(WithRatio(ratio))
|
2023-01-17 23:59:04 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// SetGoMemLimitWithProvider sets GOMEMLIMIT with the value from the given provider and ratio.
|
|
|
|
func SetGoMemLimitWithProvider(provider Provider, ratio float64) (int64, error) {
|
2023-12-11 13:35:15 +03:00
|
|
|
return SetGoMemLimitWithOpts(WithProvider(provider), WithRatio(ratio))
|
|
|
|
}
|
|
|
|
|
|
|
|
func setGoMemLimit(provider Provider) (int64, error) {
|
2023-01-17 23:59:04 +03:00
|
|
|
limit, err := provider()
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
2023-12-11 13:35:15 +03:00
|
|
|
capped := cappedU64ToI64(limit)
|
|
|
|
debug.SetMemoryLimit(capped)
|
|
|
|
return capped, nil
|
2023-01-17 23:59:04 +03:00
|
|
|
}
|
|
|
|
|
2023-12-11 13:35:15 +03:00
|
|
|
func cappedU64ToI64(limit uint64) int64 {
|
|
|
|
if limit > math.MaxInt64 {
|
2023-01-17 23:59:04 +03:00
|
|
|
return math.MaxInt64
|
|
|
|
}
|
2023-12-11 13:35:15 +03:00
|
|
|
return int64(limit)
|
2023-01-17 23:59:04 +03:00
|
|
|
}
|