-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
121 lines (102 loc) · 2.32 KB
/
main.go
File metadata and controls
121 lines (102 loc) · 2.32 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package main
import (
"encoding/csv"
"flag"
"fmt"
"github.com/containerd/cgroups"
"github.com/opencontainers/runtime-spec/specs-go"
"io"
"os"
"os/exec"
"strconv"
"strings"
)
func main() {
var (
cpu = flag.Int("cpu", 30, "cpu limit(%)")
memory = flag.Int64("memory", 512*1024*1024, "memory limit(bytes)")
pids = flag.String("pids", "", "pids(comma separate)")
group = flag.String("group", "grcon", "cgroups path")
user = flag.String("user", "", "exec username")
command = flag.String("command", "", "exec command")
)
flag.Parse()
if len(*command) == 0 && len(*pids) == 0 {
fmt.Println("command or pids not found: --command or --pids")
os.Exit(1)
}
if len(*command) > 0 && len(*pids) > 0 {
fmt.Println("don't use both --command and --pids")
os.Exit(1)
}
if len(*user) > 0 && len(*pids) > 0 {
fmt.Println("don't use both --user and --pids")
os.Exit(1)
}
if len(*user) == 0 && len(*pids) == 0 {
fmt.Println("user not found: --user")
os.Exit(1)
}
quota := int64(*cpu) * 1000
limit := int64(*memory)
control, err := cgroups.New(cgroups.V1, cgroups.StaticPath(fmt.Sprintf("/%s", *group)), &specs.LinuxResources{
CPU: &specs.LinuxCPU{
Quota: "a,
},
Memory: &specs.LinuxMemory{
Limit: &limit,
},
})
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer control.Delete()
if len(*pids) > 0 {
r := csv.NewReader(strings.NewReader(*pids))
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
fmt.Println(err)
os.Exit(1)
}
for i := 0; i < len(record); i++ {
pid, err := strconv.Atoi(record[i])
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if err := control.Add(cgroups.Process{Pid: pid}); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
}
} else {
if err := control.Add(cgroups.Process{Pid: os.Getpid()}); err != nil {
fmt.Println(err)
os.Exit(1)
}
cmd := exec.Command("sh", "-c", fmt.Sprintf("sudo -u %s %s", *user, *command))
stdout, err := cmd.StdoutPipe()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
stderr, err := cmd.StderrPipe()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if err = cmd.Start(); err != nil {
fmt.Println(err)
os.Exit(1)
}
defer cmd.Wait()
go io.Copy(os.Stdout, stdout)
go io.Copy(os.Stderr, stderr)
}
}