From 8057cd72c39cf04b0b8ffcb46935d3b053e25984 Mon Sep 17 00:00:00 2001 From: Julio Montes Date: Mon, 9 Dec 2019 16:41:12 +0000 Subject: [PATCH] virtcontainers: add function to identify systemd cgroup path Add function to identify if the given cgroup path is a systemd cgroup path. We need to parse the cgroup path to know which cgroup manager we have to use, since some container engines do not use `--systemd-cgroup` runtime option. Signed-off-by: Julio Montes --- virtcontainers/cgroups.go | 11 +++++++++++ virtcontainers/cgroups_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/virtcontainers/cgroups.go b/virtcontainers/cgroups.go index 588613ae0a..ba82fba740 100644 --- a/virtcontainers/cgroups.go +++ b/virtcontainers/cgroups.go @@ -11,6 +11,7 @@ import ( "fmt" "os" "path/filepath" + "regexp" "strings" "github.com/containerd/cgroups" @@ -182,3 +183,13 @@ func renameCgroupPath(path string) (string, error) { return filepath.Join(cgroupPathDir, cgroupPathName), nil } + +func isSystemdCgroup(cgroupPath string) bool { + // systemd cgroup path: slice:prefix:name + re := regexp.MustCompile(`([[:alnum:]]|\.)+:([[:alnum:]]|\.)+:([[:alnum:]]|\.)+`) + found := re.FindStringIndex(cgroupPath) + + // if found string is equal to cgroupPath then + // it's a correct systemd cgroup path. + return found != nil && cgroupPath[found[0]:found[1]] == cgroupPath +} diff --git a/virtcontainers/cgroups_test.go b/virtcontainers/cgroups_test.go index 6fb73c4845..2f744ffbcc 100644 --- a/virtcontainers/cgroups_test.go +++ b/virtcontainers/cgroups_test.go @@ -197,3 +197,30 @@ func TestUpdateCgroups(t *testing.T) { err = s.cgroupsDelete() assert.NoError(err) } + +func TestIsSystemdCgroup(t *testing.T) { + assert := assert.New(t) + + tests := []struct { + path string + expected bool + }{ + {"slice:kata:afhts2e5d4g5s", true}, + {"slice.system:kata:afhts2e5d4g5s", true}, + {"/kata/afhts2e5d4g5s", false}, + {"a:b:c:d", false}, + {":::", false}, + {"", false}, + {":", false}, + {"::", false}, + {":::", false}, + {"a:b", false}, + {"a:b:", false}, + {":a:b", false}, + {"@:@:@", false}, + } + + for _, t := range tests { + assert.Equal(t.expected, isSystemdCgroup(t.path), "invalid systemd cgroup path: %v", t.path) + } +}