Fix MaxCPU and MaxMemory semantics

If a limit of 0 (or negative) is given for both cpu and memory, then
no limiting will be triggered. If any value between 1 and 100 (inclusive)
is given, then limiting will be triggered when that limit is reached.

I.e. giving a limit of 100 doesn't not mean unlimited.
This commit is contained in:
Ingo Oppermann
2023-07-12 11:53:39 +02:00
parent 519f39b217
commit 51d8b30e8f
2 changed files with 42 additions and 25 deletions

View File

@@ -54,6 +54,12 @@ type Config struct {
}
func New(config Config) (Resources, error) {
isUnlimited := false
if config.MaxCPU <= 0 && config.MaxMemory <= 0 {
isUnlimited = true
}
if config.MaxCPU <= 0 {
config.MaxCPU = 100
}
@@ -69,13 +75,10 @@ func New(config Config) (Resources, error) {
r := &resources{
maxCPU: config.MaxCPU,
psutil: config.PSUtil,
isUnlimited: isUnlimited,
logger: config.Logger,
}
if config.MaxCPU == 100 && config.MaxMemory == 100 {
r.isUnlimited = true
}
if r.logger == nil {
r.logger = log.New("")
}
@@ -167,33 +170,37 @@ func (r *resources) observe(ctx context.Context, interval time.Duration) {
doCPULimit := false
if !r.isUnlimited {
if !r.isCPULimiting {
if cpuload > r.maxCPU {
if cpuload >= r.maxCPU {
r.logger.Debug().WithField("cpu", cpuload).Log("CPU limit reached")
doCPULimit = true
}
} else {
doCPULimit = true
if cpuload <= r.maxCPU {
if cpuload < r.maxCPU {
r.logger.Debug().WithField("cpu", cpuload).Log("CPU limit released")
doCPULimit = false
}
}
}
doMemoryLimit := false
if !r.isUnlimited {
if !r.isMemoryLimiting {
if vmstat.Used > r.maxMemory {
if vmstat.Used >= r.maxMemory {
r.logger.Debug().WithField("memory", vmstat.Used).Log("Memory limit reached")
doMemoryLimit = true
}
} else {
doMemoryLimit = true
if vmstat.Used <= r.maxMemory {
if vmstat.Used < r.maxMemory {
r.logger.Debug().WithField("memory", vmstat.Used).Log("Memory limit released")
doMemoryLimit = false
}
}
}
r.lock.Lock()
if r.isCPULimiting != doCPULimit {

View File

@@ -177,6 +177,16 @@ func TestHasLimits(t *testing.T) {
require.True(t, r.HasLimits())
r, err = New(Config{
MaxCPU: 100,
MaxMemory: 100,
PSUtil: &util{},
Logger: nil,
})
require.NoError(t, err)
require.True(t, r.HasLimits())
r, err = New(Config{
MaxCPU: 0,
MaxMemory: 0,