-
-
Notifications
You must be signed in to change notification settings - Fork 165
/
file.go
90 lines (72 loc) · 2.03 KB
/
file.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
79
80
81
82
83
84
85
86
87
88
89
90
package cgroup
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/lxc/lxd/shared"
)
// NewFileReadWriter returns a CGroup instance using the filesystem as its backend.
func NewFileReadWriter(pid int, unifiedCapable bool) (*CGroup, error) {
// Setup the read/writer struct.
rw := fileReadWriter{}
// Locate the base path for each controller.
rw.paths = map[string]string{}
controllers, err := os.ReadFile(fmt.Sprintf("/proc/%d/cgroup", pid))
if err != nil {
return nil, err
}
for _, line := range strings.Split(string(controllers), "\n") {
// Skip empty lines.
line = strings.TrimSpace(line)
if line == "" {
continue
}
// Extract the fields.
fields := strings.Split(line, ":")
// Determine the mount path.
path := filepath.Join("/sys/fs/cgroup", fields[1], fields[2])
if fields[0] == "0" {
fields[1] = "unified"
if shared.PathExists("/sys/fs/cgroup/unified") {
path = filepath.Join("/sys/fs/cgroup", "unified", fields[2])
} else {
path = filepath.Join("/sys/fs/cgroup", fields[2])
}
if strings.HasSuffix(fields[2], "/init.scope") {
path = filepath.Dir(path)
}
}
// Add the controllers individually.
for _, ctrl := range strings.Split(fields[1], ",") {
rw.paths[ctrl] = path
}
}
cg, err := New(&rw)
if err != nil {
return nil, err
}
cg.UnifiedCapable = unifiedCapable
return cg, nil
}
type fileReadWriter struct {
paths map[string]string
}
func (rw *fileReadWriter) Get(version Backend, controller string, key string) (string, error) {
path := filepath.Join(rw.paths[controller], key)
if cgLayout == CgroupsUnified {
path = filepath.Join(rw.paths["unified"], key)
}
value, err := os.ReadFile(path)
if err != nil {
return "", err
}
return strings.TrimSpace(string(value)), nil
}
func (rw *fileReadWriter) Set(version Backend, controller string, key string, value string) error {
path := filepath.Join(rw.paths[controller], key)
if cgLayout == CgroupsUnified {
path = filepath.Join(rw.paths["unified"], key)
}
return os.WriteFile(path, []byte(value), 0600)
}