Skip to content

Commit 65478b8

Browse files
committed
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 <[email protected]>
1 parent 1df7813 commit 65478b8

2 files changed

Lines changed: 21 additions & 2 deletions

File tree

v2/cpuv2_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,25 @@ func TestSystemdCgroupCpuController(t *testing.T) {
6868
checkFileContent(t, c.path, "cpu.weight", strconv.FormatUint(weight, 10))
6969
}
7070

71+
func TestSystemdCgroupCpuController_NilWeight(t *testing.T) {
72+
checkCgroupMode(t)
73+
group := "testingCpuNilWeight.slice"
74+
// nil weight defaults to 100
75+
var quota int64 = 10000
76+
var period uint64 = 8000
77+
cpuMax := NewCPUMax(&quota, &period)
78+
res := Resources{
79+
CPU: &CPU{
80+
Weight: nil,
81+
Max: cpuMax,
82+
},
83+
}
84+
_, err := NewSystemd("/", group, -1, &res)
85+
if err != nil {
86+
t.Fatal("failed to init new cgroup systemd manager: ", err)
87+
}
88+
}
89+
7190
func TestExtractQuotaAndPeriod(t *testing.T) {
7291
var (
7392
period uint64

v2/manager.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -734,12 +734,12 @@ func NewSystemd(slice, group string, pid int, resources *Resources) (*Manager, e
734734
properties = append(properties, newSystemdProperty("PIDs", []uint32{uint32(pid)}))
735735
}
736736

737-
if resources.Memory != nil && *resources.Memory.Max != 0 {
737+
if resources.Memory != nil && resources.Memory.Max != nil && *resources.Memory.Max != 0 {
738738
properties = append(properties,
739739
newSystemdProperty("MemoryMax", uint64(*resources.Memory.Max)))
740740
}
741741

742-
if resources.CPU != nil && *resources.CPU.Weight != 0 {
742+
if resources.CPU != nil && resources.CPU.Weight != nil && *resources.CPU.Weight != 0 {
743743
properties = append(properties,
744744
newSystemdProperty("CPUWeight", *resources.CPU.Weight))
745745
}

0 commit comments

Comments
 (0)