/
watchdog.go
86 lines (71 loc) · 1.82 KB
/
watchdog.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
package common
import (
"flag"
"fmt"
"os"
"os/exec"
"syscall"
"time"
)
// https://medium.com/@vCabbage/go-timeout-commands-with-os-exec-commandcontext-ba0c861ed738
type ErrWatchdog struct {
Pid int
Start time.Time
Cmd *exec.Cmd
}
var (
flagTimeout *int
)
func init() {
flagTimeout = flag.Int("watchdog.timeout", 0, "watchdog timeout")
}
func (e *ErrWatchdog) Error() string {
return fmt.Sprintf("watchdog killed process pid: %d cmd: %s after: %v", e.Cmd.Process.Pid, CmdToString(e.Cmd), time.Since(e.Start))
}
func Watchdog(cmd *exec.Cmd, timeout time.Duration) error {
if MillisecondToDuration(*flagTimeout) > timeout {
timeout = MillisecondToDuration(*flagTimeout)
}
doneCh := make(chan error)
start := time.Now()
err := cmd.Start()
if err != nil {
return err
}
Debug("Watchdog observe process pid: %d timeout: %v cmd: %s ...", cmd.Process.Pid, timeout, CmdToString(cmd))
go func() {
doneCh <- cmd.Wait()
}()
select {
case <-time.After(timeout):
Debug("Watchdog: process killed! pid: %d timeout: %v cmd: %s time: %s", cmd.Process.Pid, timeout, CmdToString(cmd), time.Since(start))
Error(cmd.Process.Kill())
return &ErrWatchdog{cmd.Process.Pid, start, cmd}
case err = <-doneCh:
exitcode := 0
if err != nil {
if exitError, ok := err.(*exec.ExitError); ok {
exitcode = exitError.ExitCode()
} else {
exitcode = -1
}
}
exitstate := ""
switch exitcode {
case 0:
exitstate = "successfull"
default:
exitstate = "failed"
}
Debug("Watchdog: process %s! pid: %d exitcode: %d timeout: %v cmd: %s time: %s", exitstate, cmd.Process.Pid, exitcode, timeout, CmdToString(cmd), time.Since(start))
return err
}
}
func StillAlive(pid int) bool {
process, err := os.FindProcess(pid)
if err != nil {
return false
} else {
return process.Signal(syscall.Signal(0)) != nil
}
}