github.com/intel/goresctrl@v0.5.0/pkg/cgroups/cgroupid.go (about) 1 package cgroups 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 "sync" 8 ) 9 10 // CgroupID implements mapping kernel cgroup IDs to cgroupfs paths with transparent caching. 11 type CgroupID struct { 12 root string 13 cache map[uint64]string 14 sync.Mutex 15 } 16 17 // NewCgroupID creates a new CgroupID map/cache. 18 func NewCgroupID(root string) *CgroupID { 19 return &CgroupID{ 20 root: root, 21 cache: make(map[uint64]string), 22 } 23 } 24 25 // Find finds the path for the given cgroup id. 26 func (cgid *CgroupID) Find(id uint64) (string, error) { 27 found := false 28 var p string 29 30 cgid.Lock() 31 defer cgid.Unlock() 32 33 if path, ok := cgid.cache[id]; ok { 34 return path, nil 35 } 36 37 err := fsi.Walk(cgid.root, func(path string, info os.FileInfo, err error) error { 38 if err != nil { 39 if os.IsNotExist(err) { 40 return nil 41 } 42 return err 43 } 44 45 if found { 46 return filepath.SkipDir 47 } 48 49 if info.IsDir() && id == getID(path) { 50 found = true 51 p = path 52 return filepath.SkipDir 53 } 54 return nil 55 }) 56 57 if err != nil { 58 return "", err 59 } else if !found { 60 return "", fmt.Errorf("cgroupid %v not found", id) 61 } else { 62 cgid.cache[id] = p 63 return p, nil 64 } 65 }