Skip to content

Commit

Permalink
cgroupv2: fix setting MemorySwap
Browse files Browse the repository at this point in the history
The resources.MemorySwap field from OCI is memory+swap, while cgroupv2
has a separate swap limit, so subtract memory from the limit (and make
sure values are set and sane).

Make sure to set MemorySwapMax for systemd, too. Since systemd does not
have MemorySwapMax for cgroupv1, it is only needed for v2 driver.

Signed-off-by: Kir Kolyshkin <[email protected]>
  • Loading branch information
kolyshkin committed Apr 7, 2020
1 parent d3fdacb commit 7a9a692
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
7 changes: 6 additions & 1 deletion libcontainer/cgroups/fs2/memory.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,16 @@ func numToStr(value int64) (ret string) {
}

func setMemory(dirPath string, cgroup *configs.Cgroup) error {
if val := numToStr(cgroup.Resources.MemorySwap); val != "" {
swap, err := cgroups.ConvertMemorySwapToCgroupV2Value(cgroup.Resources.MemorySwap, cgroup.Resources.Memory)
if err != nil {
return err
}
if val := numToStr(swap); val != "" {
if err := fscommon.WriteFile(dirPath, "memory.swap.max", val); err != nil {
return err
}
}

if val := numToStr(cgroup.Resources.Memory); val != "" {
if err := fscommon.WriteFile(dirPath, "memory.max", val); err != nil {
return err
Expand Down
9 changes: 9 additions & 0 deletions libcontainer/cgroups/systemd/unified_hierarchy.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,15 @@ func (m *UnifiedManager) Apply(pid int) error {
newProp("MemoryMax", uint64(c.Resources.Memory)))
}

swap, err := cgroups.ConvertMemorySwapToCgroupV2Value(c.Resources.MemorySwap, c.Resources.Memory)
if err != nil {
return err
}
if swap > 0 {
properties = append(properties,
newProp("MemorySwapMax", uint64(swap)))
}

if c.Resources.CpuWeight != 0 {
properties = append(properties,
newProp("CPUWeight", c.Resources.CpuWeight))
Expand Down
19 changes: 19 additions & 0 deletions libcontainer/cgroups/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -623,3 +623,22 @@ func ConvertCPUQuotaCPUPeriodToCgroupV2Value(quota int64, period uint64) string
}
return fmt.Sprintf("%d %d", quota, period)
}

// ConvertMemorySwapToCgroupV2Value converts MemorySwap value for cgroup v2
// drivers. Since Resources.MemorySwap is define as memory+swap combined,
// while in cgroup v2 swap is a separate value, a conversion is needed.
func ConvertMemorySwapToCgroupV2Value(memorySwap, memory int64) (int64, error) {
if memorySwap <= 0 {
return memorySwap, nil
}

if memory <= 0 {
return 0, errors.New("unable to set swap limit without memory limit")

}
if memory > memorySwap {
return 0, errors.New("memory+swap limit should be > memory limit")
}

return memorySwap - memory, nil
}

0 comments on commit 7a9a692

Please sign in to comment.