-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcgroup.go
103 lines (98 loc) · 2.74 KB
/
cgroup.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
91
92
93
94
95
96
97
98
99
100
101
102
103
package lctn
import (
"bufio"
"bytes"
"fmt"
"github.com/golang/glog"
"io/ioutil"
"os"
"path"
"path/filepath"
"strconv"
)
type CgroupInfo struct {
CgroupRoot string
CgroupSubSystems []string
}
func FindCgroupInfo() (*CgroupInfo, error) {
mounts, err := ioutil.ReadFile("/proc/self/mounts")
if err != nil {
return nil, fmt.Errorf("failed to read /proc/self/mountinfo: %v", err)
}
var (
device, mountpoint, fileSystemType string
cgInfo CgroupInfo
)
sc := bufio.NewScanner(bytes.NewReader(mounts))
for sc.Scan() {
line := sc.Text()
if n, err := fmt.Sscanf(line, "%s %s %s", &device, &mountpoint, &fileSystemType); n == 3 && err == nil {
if fileSystemType == "cgroup" {
if path.Base(mountpoint) == "systemd" {
continue
}
cgInfo.CgroupRoot = path.Dir(mountpoint)
cgInfo.CgroupSubSystems = append(cgInfo.CgroupSubSystems, path.Base(mountpoint))
}
}
}
if cgInfo.CgroupRoot == "" {
return nil, fmt.Errorf("failed to find cgroup root path")
}
return &cgInfo, nil
}
func EnsureCgroup(path string, cgInfo *CgroupInfo) error {
pidBytes := []byte(strconv.Itoa(os.Getpid()))
if path != "" {
for _, sub := range cgInfo.CgroupSubSystems {
if sub == "cpuset" {
dir := filepath.Join(cgInfo.CgroupRoot, sub, path)
if err := os.MkdirAll(dir, 0644); err != nil {
glog.Warning(err)
break
}
cpusetCpus, err := ioutil.ReadFile(filepath.Join(cgInfo.CgroupRoot, "cpuset", "cpuset.cpus"))
if err != nil {
glog.Warning(err)
break
}
cpusetMems, err := ioutil.ReadFile(filepath.Join(cgInfo.CgroupRoot, "cpuset", "cpuset.mems"))
if err != nil {
glog.Warning(err)
break
}
if err := ioutil.WriteFile(filepath.Join(dir, "cpuset.cpus"), cpusetCpus, 0); err != nil {
glog.Warning(err)
}
if err := ioutil.WriteFile(filepath.Join(dir, "cpuset.mems"), cpusetMems, 0); err != nil {
glog.Warning(err)
}
break
}
}
}
for _, sub := range cgInfo.CgroupSubSystems {
dir := filepath.Join(cgInfo.CgroupRoot, sub, path)
if err := os.MkdirAll(dir, 0600); err != nil {
continue
}
if err := ioutil.WriteFile(filepath.Join(cgInfo.CgroupRoot, sub, path, "cgroup.procs"), pidBytes, 0); err != nil {
glog.Warning(err)
}
}
return nil
}
func RemoveCgroup(path string, cgInfo *CgroupInfo) {
if path != "" {
pidBytes := []byte(strconv.Itoa(os.Getpid()))
for _, sub := range cgInfo.CgroupSubSystems {
// move pid to root, or we'll get "device or resource busy" on removeDir
if err := ioutil.WriteFile(filepath.Join(cgInfo.CgroupRoot, sub, "cgroup.procs"), pidBytes, 0); err != nil {
glog.Warning(err)
}
if err := os.RemoveAll(filepath.Join(cgInfo.CgroupRoot, sub, path)); err != nil {
glog.Warning(err)
}
}
}
}