-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
102 lines (80 loc) · 1.91 KB
/
main.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
package main
import (
"os"
ps "github.com/mitchellh/go-ps"
log "github.com/sirupsen/logrus"
)
// CommitString is the commit used to build the server
var CommitString string
var exceptByParent = map[string]struct{}{
"screen": {},
"tmux: server": {},
"tmux": {},
}
var exceptByName = map[string]struct{}{
"okteto-remote": {},
"syncthing": {},
}
func shouldKill(p ps.Process) bool {
if p.Pid() == 1 {
log.Info("not killing root process of the container")
return false
}
if p.Pid() == os.Getppid() {
log.Info("not killing parent process")
return false
}
if p.Pid() == os.Getpid() {
log.Info("not killing yourself")
return false
}
if _, ok := exceptByName[p.Executable()]; ok {
log.Infof("not killing, excluded by name %s", p.Executable())
return false
}
if isChildrenOfExceptByParent(p) {
return false
}
return true
}
func isChildrenOfExceptByParent(p ps.Process) bool {
if p.Pid() == 1 {
return false
}
if _, ok := exceptByParent[p.Executable()]; ok {
log.Infof("not killing, children of %s", p.Executable())
return true
}
parent, err := ps.FindProcess(p.PPid())
if err != nil {
log.Errorf("fail to find process %d : %s", p.PPid(), err)
return false
}
if parent == nil {
return false
}
return isChildrenOfExceptByParent(parent)
}
func main() {
log.Infof("clean service started sha=%s pid=%d ppid=%d", CommitString, os.Getpid(), os.Getppid())
processes, err := ps.Processes()
if err != nil {
log.Errorf("fail to list processes: %s", processes)
os.Exit(1)
}
for _, p := range processes {
log.Infof("checking process %s", p.Executable())
if !shouldKill(p) {
continue
}
pr, err := os.FindProcess(p.Pid())
if err != nil {
log.Errorf("fail to find process %d : %s", p.Pid(), err)
continue
}
if err := pr.Kill(); err != nil {
log.Errorf("fail to kill process %d : %s", p.Pid(), err)
}
}
log.Infof("clean service finished")
}