From 7c439cc6f617eb234bbc1754ab0b21041a9be87e Mon Sep 17 00:00:00 2001 From: Boris Popovschi Date: Wed, 15 Jan 2020 18:33:15 +0200 Subject: [PATCH] Added conversion for cpu.weight v2 Signed-off-by: Boris Popovschi --- libcontainer/cgroups/utils.go | 9 +++++++++ libcontainer/specconv/spec_linux.go | 5 +++++ update.go | 4 ++++ 3 files changed, 18 insertions(+) diff --git a/libcontainer/cgroups/utils.go b/libcontainer/cgroups/utils.go index dbcc58f5..279b2e38 100644 --- a/libcontainer/cgroups/utils.go +++ b/libcontainer/cgroups/utils.go @@ -586,3 +586,12 @@ func isEINVAL(err error) bool { return false } } + +// Since the OCI spec is designed for cgroup v1, in some cases +// there is need to convert from the cgroup v1 configuration to cgroup v2 +// the formula for cpuShares is y = (1 + ((x - 2) * 9999) / 262142) +// convert from [2-262144] to [1-10000] +// 262144 comes from Linux kernel definition "#define MAX_SHARES (1UL << 18)" +func ConvertCPUSharesToCgroupV2Value(cpuShares uint64) uint64 { + return (1 + ((cpuShares-2)*9999)/262142) +} diff --git a/libcontainer/specconv/spec_linux.go b/libcontainer/specconv/spec_linux.go index d9e73c46..0084e7cd 100644 --- a/libcontainer/specconv/spec_linux.go +++ b/libcontainer/specconv/spec_linux.go @@ -11,6 +11,8 @@ import ( "strings" "time" + "github.com/opencontainers/runc/libcontainer/cgroups" + "github.com/opencontainers/runc/libcontainer/configs" "github.com/opencontainers/runc/libcontainer/seccomp" libcontainerUtils "github.com/opencontainers/runc/libcontainer/utils" @@ -405,6 +407,9 @@ func CreateCgroupConfig(opts *CreateOpts) (*configs.Cgroup, error) { if r.CPU != nil { if r.CPU.Shares != nil { c.Resources.CpuShares = *r.CPU.Shares + + //CpuWeight is used for cgroupv2 and should be converted + c.Resources.CpuWeight = cgroups.ConvertCPUSharesToCgroupV2Value(c.Resources.CpuShares) } if r.CPU.Quota != nil { c.Resources.CpuQuota = *r.CPU.Quota diff --git a/update.go b/update.go index 05dc4b51..84306b29 100644 --- a/update.go +++ b/update.go @@ -8,6 +8,8 @@ import ( "os" "strconv" + "github.com/opencontainers/runc/libcontainer/cgroups" + "github.com/docker/go-units" "github.com/opencontainers/runc/libcontainer/configs" "github.com/opencontainers/runc/libcontainer/intelrdt" @@ -253,6 +255,8 @@ other options are ignored. config.Cgroups.Resources.CpuPeriod = *r.CPU.Period config.Cgroups.Resources.CpuQuota = *r.CPU.Quota config.Cgroups.Resources.CpuShares = *r.CPU.Shares + //CpuWeight is used for cgroupv2 and should be converted + config.Cgroups.Resources.CpuWeight = cgroups.ConvertCPUSharesToCgroupV2Value(*r.CPU.Shares) config.Cgroups.Resources.CpuRtPeriod = *r.CPU.RealtimePeriod config.Cgroups.Resources.CpuRtRuntime = *r.CPU.RealtimeRuntime config.Cgroups.Resources.CpusetCpus = r.CPU.Cpus