github.com/rkt/rkt@v1.30.1-0.20200224141603-171c416fac02/common/cgroup/v2/cgroup.go (about) 1 // Copyright 2016 The rkt Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 //+build linux 16 17 package v2 18 19 import ( 20 "bufio" 21 "errors" 22 "fmt" 23 "os" 24 "strings" 25 26 "github.com/hashicorp/errwrap" 27 ) 28 29 // GetEnabledControllers returns a list of enabled cgroup controllers 30 func GetEnabledControllers() ([]string, error) { 31 controllersFile, err := os.Open("/sys/fs/cgroup/cgroup.controllers") 32 if err != nil { 33 return nil, err 34 } 35 defer controllersFile.Close() 36 37 sc := bufio.NewScanner(controllersFile) 38 39 sc.Scan() 40 if err := sc.Err(); err != nil { 41 return nil, err 42 } 43 44 return strings.Split(sc.Text(), " "), nil 45 } 46 47 func parseProcCgroupInfo(procCgroupInfoPath string) (string, error) { 48 cg, err := os.Open(procCgroupInfoPath) 49 if err != nil { 50 return "", errwrap.Wrap(errors.New("error opening /proc/self/cgroup"), err) 51 } 52 defer cg.Close() 53 54 s := bufio.NewScanner(cg) 55 s.Scan() 56 parts := strings.SplitN(s.Text(), ":", 3) 57 if len(parts) < 3 { 58 return "", fmt.Errorf("error parsing /proc/self/cgroup") 59 } 60 61 return parts[2], nil 62 } 63 64 // GetOwnCgroupPath returns the cgroup path of this process 65 func GetOwnCgroupPath() (string, error) { 66 return parseProcCgroupInfo("/proc/self/cgroup") 67 } 68 69 // GetCgroupPathByPid returns the cgroup path of the process 70 func GetCgroupPathByPid(pid int) (string, error) { 71 return parseProcCgroupInfo(fmt.Sprintf("/proc/%d/cgroup", pid)) 72 }