Skip to content

Commit 4157503

Browse files
committed
cri: fix memory.memsw.limit_in_bytes: no such file or directory
Skip automatic `if swapLimit == 0 { s.Linux.Resources.Memory.Swap = &limit }` when the swap controller is missing. (default on Ubuntu 20.04) Fix issue 7828 (regression in PR 7783 "cri: make swapping disabled with memory limit") Signed-off-by: Akihiro Suda <[email protected]>
1 parent 544e31c commit 4157503

1 file changed

Lines changed: 33 additions & 1 deletion

File tree

pkg/cri/opts/spec_linux.go

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ import (
2929
"syscall"
3030

3131
"github.com/container-orchestrated-devices/container-device-interface/pkg/cdi"
32+
"github.com/containerd/cgroups/v3"
33+
"github.com/containerd/cgroups/v3/cgroup1"
3234
"github.com/containerd/containerd/containers"
3335
"github.com/containerd/containerd/log"
3436
"github.com/containerd/containerd/mount"
@@ -404,6 +406,36 @@ func WithSelinuxLabels(process, mount string) oci.SpecOpts {
404406
}
405407
}
406408

409+
var (
410+
swapControllerAvailability bool
411+
swapControllerAvailabilityOnce sync.Once
412+
)
413+
414+
func swapControllerAvailable() bool {
415+
swapControllerAvailabilityOnce.Do(func() {
416+
const warn = "Failed to detect the availability of the swap controller, assuming not available"
417+
p := "/sys/fs/cgroup/memory/memory.memsw.limit_in_bytes"
418+
if cgroups.Mode() == cgroups.Unified {
419+
// memory.swap.max does not exist in the cgroup root, so we check /sys/fs/cgroup/<SELF>/memory.swap.max
420+
_, unified, err := cgroup1.ParseCgroupFileUnified("/proc/self/cgroup")
421+
if err != nil {
422+
err = fmt.Errorf("failed to parse /proc/self/cgroup: %w", err)
423+
logrus.WithError(err).Warn(warn)
424+
return
425+
}
426+
p = filepath.Join("/sys/fs/cgroup", unified, "memory.swap.max")
427+
}
428+
if _, err := os.Stat(p); err != nil {
429+
if !errors.Is(err, os.ErrNotExist) {
430+
logrus.WithError(err).Warn(warn)
431+
}
432+
return
433+
}
434+
swapControllerAvailability = true
435+
})
436+
return swapControllerAvailability
437+
}
438+
407439
// WithResources sets the provided resource restrictions
408440
func WithResources(resources *runtime.LinuxContainerResources, tolerateMissingHugetlbController, disableHugetlbController bool) oci.SpecOpts {
409441
return func(ctx context.Context, client oci.Client, c *containers.Container, s *runtimespec.Spec) (err error) {
@@ -449,7 +481,7 @@ func WithResources(resources *runtime.LinuxContainerResources, tolerateMissingHu
449481
if limit != 0 {
450482
s.Linux.Resources.Memory.Limit = &limit
451483
// swap/memory limit should be equal to prevent container from swapping by default
452-
if swapLimit == 0 {
484+
if swapLimit == 0 && swapControllerAvailable() {
453485
s.Linux.Resources.Memory.Swap = &limit
454486
}
455487
}

0 commit comments

Comments
 (0)