From 64e9a97981b95631be1e41705c2aea9a545a7213 Mon Sep 17 00:00:00 2001 From: Akihiro Suda Date: Tue, 10 Mar 2020 00:54:12 +0900 Subject: [PATCH] cgroup2: fix conversion * TestConvertCPUSharesToCgroupV2Value(0) was returning 70369281052672, while the correct value is 0 * ConvertBlkIOToCgroupV2Value(0) was returning 32, while the correct value is 0 * ConvertBlkIOToCgroupV2Value(1000) was returning 4, while the correct value is 10000 Fix #2244 Follow-up to #2212 #2213 Signed-off-by: Akihiro Suda --- libcontainer/cgroups/utils.go | 8 +++++++- libcontainer/cgroups/utils_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/libcontainer/cgroups/utils.go b/libcontainer/cgroups/utils.go index 861716e82..704941cdf 100644 --- a/libcontainer/cgroups/utils.go +++ b/libcontainer/cgroups/utils.go @@ -592,7 +592,10 @@ func isEINVAL(err error) bool { // the formula for BlkIOWeight is y = (1 + (x - 10) * 9999 / 990) // convert linearly from [10-1000] to [1-10000] func ConvertBlkIOToCgroupV2Value(blkIoWeight uint16) uint64 { - return uint64(1 + (blkIoWeight-10)*9999/990) + if blkIoWeight == 0 { + return 0 + } + return uint64(1 + (uint64(blkIoWeight)-10)*9999/990) } // Since the OCI spec is designed for cgroup v1, in some cases @@ -601,5 +604,8 @@ func ConvertBlkIOToCgroupV2Value(blkIoWeight uint16) uint64 { // convert from [2-262144] to [1-10000] // 262144 comes from Linux kernel definition "#define MAX_SHARES (1UL << 18)" func ConvertCPUSharesToCgroupV2Value(cpuShares uint64) uint64 { + if cpuShares == 0 { + return 0 + } return (1 + ((cpuShares-2)*9999)/262142) } diff --git a/libcontainer/cgroups/utils_test.go b/libcontainer/cgroups/utils_test.go index 3214b9de0..3dfa6a0d4 100644 --- a/libcontainer/cgroups/utils_test.go +++ b/libcontainer/cgroups/utils_test.go @@ -457,3 +457,31 @@ func TestGetHugePageSizeImpl(t *testing.T) { } } } + +func TestConvertBlkIOToCgroupV2Value(t *testing.T) { + cases := map[uint16]uint64{ + 0: 0, + 10: 1, + 1000: 10000, + } + for i, expected := range cases { + got := ConvertBlkIOToCgroupV2Value(i) + if got != expected { + t.Errorf("expected ConvertBlkIOToCgroupV2Value(%d) to be %d, got %d", i, expected, got) + } + } +} + +func TestConvertCPUSharesToCgroupV2Value(t *testing.T) { + cases := map[uint64]uint64{ + 0: 0, + 2: 1, + 262144: 10000, + } + for i, expected := range cases { + got := ConvertCPUSharesToCgroupV2Value(i) + if got != expected { + t.Errorf("expected ConvertCPUSharesToCgroupV2Value(%d) to be %d, got %d", i, expected, got) + } + } +}