forked from intel/goresctrl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cgroupid.go
78 lines (65 loc) · 1.38 KB
/
cgroupid.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package cgroups
import (
"encoding/binary"
"fmt"
"os"
"path/filepath"
"sync"
"golang.org/x/sys/unix"
)
// CgroupID implements mapping kernel cgroup IDs to cgroupfs paths with transparent caching.
type CgroupID struct {
root string
cache map[uint64]string
sync.Mutex
}
// NewCgroupID creates a new CgroupID map/cache.
func NewCgroupID(root string) *CgroupID {
return &CgroupID{
root: root,
cache: make(map[uint64]string),
}
}
func getID(path string) uint64 {
h, _, err := unix.NameToHandleAt(unix.AT_FDCWD, path, 0)
if err != nil {
return 0
}
return binary.LittleEndian.Uint64(h.Bytes())
}
// Find finds the path for the given cgroup id.
func (cgid *CgroupID) Find(id uint64) (string, error) {
found := false
var p string
cgid.Lock()
defer cgid.Unlock()
if path, ok := cgid.cache[id]; ok {
return path, nil
}
err := fsi.Walk(cgid.root, func(path string, info os.FileInfo, err error) error {
if err != nil {
if os.IsNotExist(err) {
return nil
}
fmt.Printf("WalkFunc called with an error (path %q: %v\n)", path, err)
return err
}
if found {
return filepath.SkipDir
}
if info.IsDir() && id == getID(path) {
found = true
p = path
return filepath.SkipDir
}
return nil
})
if err != nil {
return "", err
} else if !found {
return "", fmt.Errorf("cgroupid %v not found", id)
} else {
cgid.cache[id] = p
return p, nil
}
}