From 8e6ae5fe16fe1193771e8a14f79bf2f51e92b9f5 Mon Sep 17 00:00:00 2001 From: Michael Crosby Date: Thu, 7 Nov 2019 11:26:07 -0500 Subject: [PATCH] Add ToResources func for spec to v2.Resources Signed-off-by: Michael Crosby --- v2/cpu.go | 14 ++++++++++++++ v2/utils.go | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/v2/cpu.go b/v2/cpu.go index 1203354c..cf939d50 100644 --- a/v2/cpu.go +++ b/v2/cpu.go @@ -19,6 +19,8 @@ package v2 type CPU struct { Weight *uint64 Max *uint64 + Cpus string + Mems string } func (r *CPU) Values() (o []Value) { @@ -34,5 +36,17 @@ func (r *CPU) Values() (o []Value) { value: *r.Max, }) } + if r.Cpus != "" { + o = append(o, Value{ + filename: "cpuset.cpus", + value: r.Cpus, + }) + } + if r.Mems != "" { + o = append(o, Value{ + filename: "cpuset.mems", + value: r.Mems, + }) + } return o } diff --git a/v2/utils.go b/v2/utils.go index ebb5335b..076b5328 100644 --- a/v2/utils.go +++ b/v2/utils.go @@ -26,6 +26,7 @@ import ( "strings" "time" + "github.com/opencontainers/runtime-spec/specs-go" "github.com/pkg/errors" ) @@ -153,3 +154,43 @@ func parseCgroupFromReader(r io.Reader) (string, error) { } return "", fmt.Errorf("cgroup path not found") } + +// ToResources converts the oci LinuxResources struct into a +// v2 Resources type for use with this package. +// +// converting cgroups configuration from v1 to v2 +// ref: https://github.com/containers/crun/blob/master/crun.1.md#cgroup-v2 +func ToResources(spec *specs.LinuxResources) *Resources { + var resources Resources + if cpu := spec.CPU; cpu != nil { + resources.CPU = &CPU{ + Cpus: cpu.Cpus, + Mems: cpu.Mems, + } + if shares := cpu.Shares; shares != nil { + convertedWeight := (1 + ((*shares-2)*9999)/262142) + resources.CPU.Weight = &convertedWeight + } + if period := cpu.Period; period != nil { + resources.CPU.Max = period + } + } + if mem := spec.Memory; mem != nil { + resources.Memory = &Memory{} + if swap := mem.Swap; swap != nil { + resources.Memory.Swap = swap + } + if l := mem.Limit; l != nil { + resources.Memory.Max = l + } + if h := mem.Reservation; h != nil { + resources.Memory.High = h + } + } + if pids := spec.Pids; pids != nil { + resources.Pids = &Pids{ + Max: pids.Limit, + } + } + return &resources +}