github.com/cilium/cilium@v1.16.2/pkg/cgroups/cgroups_linux.go (about) 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright Authors of Cilium 3 4 package cgroups 5 6 import ( 7 "fmt" 8 "os" 9 10 "github.com/vishvananda/netlink/nl" 11 "golang.org/x/sys/unix" 12 13 "github.com/cilium/cilium/pkg/mountinfo" 14 ) 15 16 // mountCgroup mounts the Cgroup v2 filesystem into the desired cgroupRoot directory. 17 func mountCgroup() error { 18 cgroupRootStat, err := os.Stat(cgroupRoot) 19 if err != nil { 20 if os.IsNotExist(err) { 21 if err := os.MkdirAll(cgroupRoot, 0755); err != nil { 22 return fmt.Errorf("Unable to create cgroup mount directory: %w", err) 23 } 24 } else { 25 return fmt.Errorf("Failed to stat the mount path %s: %w", cgroupRoot, err) 26 } 27 } else if !cgroupRootStat.IsDir() { 28 return fmt.Errorf("%s is a file which is not a directory", cgroupRoot) 29 } 30 31 if err := unix.Mount("none", cgroupRoot, "cgroup2", 0, ""); err != nil { 32 return fmt.Errorf("failed to mount %s: %w", cgroupRoot, err) 33 } 34 35 return nil 36 } 37 38 // checkOrMountCustomLocation tries to check or mount the cgroup filesystem in the 39 // given path. 40 func cgrpCheckOrMountLocation(cgroupRoot string) error { 41 setCgroupRoot(cgroupRoot) 42 43 // Check whether the custom location has a mount. 44 mounted, cgroupInstance, err := mountinfo.IsMountFS(mountinfo.FilesystemTypeCgroup2, cgroupRoot) 45 if err != nil { 46 return err 47 } 48 49 // If the custom location has no mount, let's mount there. 50 if !mounted { 51 return mountCgroup() 52 } else if !cgroupInstance { 53 return fmt.Errorf("Mount in the custom directory %s has a different filesystem than cgroup2", cgroupRoot) 54 } 55 56 return nil 57 } 58 59 func GetCgroupID(cgroupPath string) (uint64, error) { 60 handle, _, err := unix.NameToHandleAt(unix.AT_FDCWD, cgroupPath, 0) 61 if err != nil { 62 return 0, fmt.Errorf("NameToHandleAt failed: %w", err) 63 } 64 b := handle.Bytes()[:8] 65 cgID := nl.NativeEndian().Uint64(b) 66 67 return cgID, nil 68 }