From a70f354680b47b283dd2782d26d5afa6b1f98684 Mon Sep 17 00:00:00 2001 From: lifubang Date: Fri, 1 May 2020 22:44:59 +0800 Subject: [PATCH] let runc disable swap in cgroup v2 In cgroup v2, when memory and memorySwap set to the same value which is greater than zero, runc should write zero in `memory.swap.max` to disable swap. Signed-off-by: lifubang --- libcontainer/cgroups/fs2/memory.go | 11 +++++++---- libcontainer/cgroups/systemd/v2.go | 12 ++++++------ libcontainer/cgroups/utils.go | 2 +- 3 files changed, 14 insertions(+), 11 deletions(-) diff --git a/libcontainer/cgroups/fs2/memory.go b/libcontainer/cgroups/fs2/memory.go index 681bedd1..1cda30cc 100644 --- a/libcontainer/cgroups/fs2/memory.go +++ b/libcontainer/cgroups/fs2/memory.go @@ -45,10 +45,13 @@ func setMemory(dirPath string, cgroup *configs.Cgroup) error { if err != nil { return err } - if val := numToStr(swap); val != "" { - if err := fscommon.WriteFile(dirPath, "memory.swap.max", val); err != nil { - return err - } + swapStr := numToStr(swap) + if swapStr == "" && swap == 0 && cgroup.Resources.MemorySwap > 0 { + // memory and memorySwap set to the same value -- disable swap + swapStr = "0" + } + if err := fscommon.WriteFile(dirPath, "memory.swap.max", swapStr); err != nil { + return err } if val := numToStr(cgroup.Resources.Memory); val != "" { diff --git a/libcontainer/cgroups/systemd/v2.go b/libcontainer/cgroups/systemd/v2.go index 77f7696e..282d629f 100644 --- a/libcontainer/cgroups/systemd/v2.go +++ b/libcontainer/cgroups/systemd/v2.go @@ -39,12 +39,12 @@ func genV2ResourcesProperties(c *configs.Cgroup) ([]systemdDbus.Property, error) properties = append(properties, newProp("MemoryMax", uint64(c.Resources.Memory))) } - - swap, err := cgroups.ConvertMemorySwapToCgroupV2Value(c.Resources.MemorySwap, c.Resources.Memory) - if err != nil { - return nil, err - } - if swap > 0 { + // swap is set + if c.Resources.MemorySwap != 0 { + swap, err := cgroups.ConvertMemorySwapToCgroupV2Value(c.Resources.MemorySwap, c.Resources.Memory) + if err != nil { + return nil, err + } properties = append(properties, newProp("MemorySwapMax", uint64(swap))) } diff --git a/libcontainer/cgroups/utils.go b/libcontainer/cgroups/utils.go index f1e11160..8cdd6b7e 100644 --- a/libcontainer/cgroups/utils.go +++ b/libcontainer/cgroups/utils.go @@ -639,7 +639,7 @@ func ConvertMemorySwapToCgroupV2Value(memorySwap, memory int64) (int64, error) { return 0, fmt.Errorf("invalid memory value: %d", memory) } if memorySwap < memory { - return 0, errors.New("memory+swap limit should be > memory limit") + return 0, errors.New("memory+swap limit should be >= memory limit") } return memorySwap - memory, nil