-
Notifications
You must be signed in to change notification settings - Fork 25
/
reaper_linux.go
105 lines (97 loc) · 2.31 KB
/
reaper_linux.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
104
105
package proc
import (
"bufio"
"io/ioutil"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"k8s.io/klog/v2"
)
// parseProcForZombies parses the current procfs mounted at /proc
// to find proccess in the zombie state.
func parseProcForZombies() ([]int, error) {
files, err := ioutil.ReadDir("/proc")
if err != nil {
return nil, err
}
var zombies []int
for _, file := range files {
processID, err := strconv.Atoi(file.Name())
if err != nil {
break
}
stateFilePath := filepath.Join("/proc", file.Name(), "status")
fd, err := os.Open(stateFilePath)
if err != nil {
klog.V(4).Infof("Failed to open %q: %v", stateFilePath, err)
continue
}
defer fd.Close()
fs := bufio.NewScanner(fd)
for fs.Scan() {
line := fs.Text()
if strings.HasPrefix(line, "State:") {
if strings.Contains(line, "zombie") {
zombies = append(zombies, processID)
}
break
}
}
}
return zombies, nil
}
// StartPeriodicReaper starts a goroutine to reap processes periodically if called
// from a pid 1 process.
// The zombie processes are reaped at the beginning of next cycle, so os.Exec calls
// have an oppurtunity to reap their children within `period` seconds.
func StartPeriodicReaper(period int64) {
if os.Getpid() == 1 {
klog.V(4).Infof("Launching periodic reaper")
go func() {
var zs []int
var err error
for {
for _, z := range zs {
if _, err := syscall.Wait4(z, nil, syscall.WNOHANG, nil); err != nil {
klog.V(4).Infof("Zombie reap error: %v", err)
}
}
klog.V(4).Infof("Reaped: %v", zs)
zs, err = parseProcForZombies()
if err != nil {
klog.V(4).Infof(err.Error())
continue
}
time.Sleep(time.Duration(period) * time.Second)
}
}()
}
}
// StartReaper starts a goroutine to reap processes if called from a process
// that has pid 1.
func StartReaper() {
if os.Getpid() == 1 {
klog.V(4).Infof("Launching reaper")
go func() {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGCHLD)
for {
// Wait for a child to terminate
sig := <-sigs
klog.V(4).Infof("Signal received: %v", sig)
for {
// Reap processes
cpid, _ := syscall.Wait4(-1, nil, syscall.WNOHANG, nil)
if cpid < 1 {
break
}
klog.V(4).Infof("Reaped process with pid %d", cpid)
}
}
}()
}
}