From 2cb732230235093a34aa84ec01f6dd7fa520eec0 Mon Sep 17 00:00:00 2001 From: Cameron Sparr Date: Wed, 16 Feb 2022 14:35:36 -0800 Subject: [PATCH] Fix panic in NewSystemd on nil values NewSystemd previously panicked if it was given a nil resource value for resources.Memory.Max or resources.CPU.Weight (if resources.CPU or resources.Memory is non-nil) This also checks the value of Max and Weight before dereferencing them. Signed-off-by: Cameron Sparr --- v2/cpuv2_test.go | 20 ++++++++++++++++++++ v2/manager.go | 4 ++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/v2/cpuv2_test.go b/v2/cpuv2_test.go index 4f75f7c4..eb8b6646 100644 --- a/v2/cpuv2_test.go +++ b/v2/cpuv2_test.go @@ -68,6 +68,26 @@ func TestSystemdCgroupCpuController(t *testing.T) { checkFileContent(t, c.path, "cpu.weight", strconv.FormatUint(weight, 10)) } +func TestSystemdCgroupCpuController_NilWeight(t *testing.T) { + checkCgroupMode(t) + group := "testingCpuNilWeight.slice" + // nil weight defaults to 100 + var quota int64 = 10000 + var period uint64 = 8000 + cpuMax := NewCPUMax("a, &period) + res := Resources{ + CPU: &CPU{ + Weight: nil, + Max: cpuMax, + }, + } + c, err := NewSystemd("/", group, -1, &res) + if err != nil { + t.Fatal("failed to init new cgroup systemd manager: ", err) + } + defer c.DeleteSystemd() +} + func TestExtractQuotaAndPeriod(t *testing.T) { var ( period uint64 diff --git a/v2/manager.go b/v2/manager.go index afed14c6..f5466785 100644 --- a/v2/manager.go +++ b/v2/manager.go @@ -734,12 +734,12 @@ func NewSystemd(slice, group string, pid int, resources *Resources) (*Manager, e properties = append(properties, newSystemdProperty("PIDs", []uint32{uint32(pid)})) } - if resources.Memory != nil && *resources.Memory.Max != 0 { + if resources.Memory != nil && resources.Memory.Max != nil && *resources.Memory.Max != 0 { properties = append(properties, newSystemdProperty("MemoryMax", uint64(*resources.Memory.Max))) } - if resources.CPU != nil && *resources.CPU.Weight != 0 { + if resources.CPU != nil && resources.CPU.Weight != nil && *resources.CPU.Weight != 0 { properties = append(properties, newSystemdProperty("CPUWeight", *resources.CPU.Weight)) }