Skip to content

Commit

Permalink
feat(memlimit): handle ErrNoLimit as math.MaxInt64 during refresh
Browse files Browse the repository at this point in the history
  • Loading branch information
KimMachineGun committed Dec 8, 2024
1 parent 0506e2d commit dd7ecc6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
2 changes: 1 addition & 1 deletion examples/dynamic/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func FileProvider(path string) memlimit.Provider {

b = bytes.TrimSpace(b)
if len(b) == 0 {
return memlimit.ApplyFallback(memlimit.FromCgroup, memlimit.FromSystem)()
return 0, memlimit.ErrNoLimit
}

return strconv.ParseUint(string(b), 10, 64)
Expand Down
17 changes: 14 additions & 3 deletions memlimit/memlimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,7 @@ func WithLogger(logger *slog.Logger) Option {
// If a refresh interval is greater than 0, automemlimit periodically fetches
// the memory limit from the provider and reapplies it if it has changed.
// If the provider returns an error, it logs the error and continues.
// Since ErrNoLimit is also considered as an error (but not logged),
// you should return math.MaxInt64 if you want to unset the limit.
// ErrNoLimit is treated as math.MaxInt64.
//
// Default: 0 (no refresh)
func WithRefreshInterval(refresh time.Duration) Option {
Expand Down Expand Up @@ -208,14 +207,16 @@ func refresh(provider Provider, logger *slog.Logger, refresh time.Duration) {
return
}

provider = noErrNoLimitProvider(provider)

t := time.NewTicker(refresh)
for range t.C {
err := func() (_err error) {
snapshot := debug.SetMemoryLimit(-1)
defer rollbackOnPanic(logger, snapshot, &_err)

_, err := updateGoMemLimit(uint64(snapshot), provider, logger)
if err != nil && !errors.Is(err, ErrNoLimit) {
if err != nil {
return err
}

Expand Down Expand Up @@ -259,6 +260,16 @@ func SetGoMemLimitWithProvider(provider Provider, ratio float64) (int64, error)
return SetGoMemLimitWithOpts(WithProvider(provider), WithRatio(ratio))
}

func noErrNoLimitProvider(provider Provider) Provider {
return func() (uint64, error) {
limit, err := provider()
if errors.Is(err, ErrNoLimit) {
return math.MaxInt64, nil
}
return limit, err
}
}

func capProvider(provider Provider) Provider {
return func() (uint64, error) {
limit, err := provider()
Expand Down

0 comments on commit dd7ecc6

Please sign in to comment.