-
Notifications
You must be signed in to change notification settings - Fork 28
/
cmdrunner.go
101 lines (82 loc) · 1.6 KB
/
cmdrunner.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
package main
import (
"os/exec"
"strings"
"syscall"
"time"
)
const startCmdDelay = time.Second
type cmdRunner struct {
restartNeeded chan bool
runEndNeeded chan bool
runEndFinished chan bool
}
var runCmdRunner cmdRunner
var serialCmdRunner cmdRunner
func (c *cmdRunner) kill(cmd *exec.Cmd) {
err := cmd.Process.Kill()
if err != nil {
_ = cmd.Process.Signal(syscall.SIGKILL)
}
}
func (c *cmdRunner) run(cmdLine string) {
var cmd *exec.Cmd
defer func() {
if cmd != nil {
c.kill(cmd)
}
c.runEndFinished <- true
}()
s := strings.Split(cmdLine, " ")
for {
select {
case <-c.runEndNeeded:
return
case <-time.After(startCmdDelay):
}
cmd = exec.Command(s[0], s[1:]...)
err := cmd.Start()
if err != nil {
log.Error("error starting ", cmd)
continue
}
log.Print("started: ", cmd)
finishedChan := make(chan error)
go func() {
finishedChan <- cmd.Wait()
}()
select {
case <-c.restartNeeded:
log.Debug("restarting ", cmd)
c.kill(cmd)
case err := <-finishedChan:
if err != nil {
log.Error(cmd, " error: ", err)
}
case <-c.runEndNeeded:
return
}
}
}
func (c *cmdRunner) startIfNeeded(cmdLine string) {
if c.runEndNeeded != nil || cmdLine == "" || cmdLine == "-" {
return
}
c.restartNeeded = make(chan bool)
c.runEndNeeded = make(chan bool)
c.runEndFinished = make(chan bool)
go c.run(cmdLine)
}
// func (c *cmdRunner) restart() {
// if c.restartNeeded == nil {
// return
// }
// c.restartNeeded <- true
// }
func (c *cmdRunner) stop() {
if c.runEndNeeded == nil {
return
}
c.runEndNeeded <- true
<-c.runEndFinished
}