-
Notifications
You must be signed in to change notification settings - Fork 687
/
keepalive.go
146 lines (130 loc) · 2.28 KB
/
keepalive.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package tpu
import (
"bufio"
"io"
"log"
"os/exec"
"strings"
"syscall"
"time"
)
type Keeper struct {
Prefix string
Command string
Input string
Inspect string
Limit int
stop chan empty
done chan empty
}
func NewKeeper(prefix, command string) (k *Keeper) {
return &Keeper{
Prefix: prefix,
Command: command,
stop: make(chan empty),
done: make(chan empty),
}
}
func (k *Keeper) Stop() {
close(k.stop)
k.Wait()
}
func (k *Keeper) Wait() {
<-k.done
}
func (k *Keeper) log(line string, args ...interface{}) {
log.Printf(k.Prefix+": "+line, args...)
}
func (k *Keeper) Start() {
go func() {
count := 0
defer close(k.done)
for {
cmd := exec.Command("sh", "-c", k.Command)
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
}
k.log("%s", k.Command)
l := k.forwardOutput(cmd)
err := writeInput(cmd, k.Input)
if err != nil {
panic(err)
}
err = cmd.Start()
if err != nil {
panic(err)
}
died := make(chan empty)
go func() {
err = cmd.Wait()
if err != nil {
k.log("%s", err.Error())
}
died <- nil
}()
count += 1
select {
case <-died:
l.Wait()
if count < k.Limit || k.Limit == 0 {
k.log("%s restarting...", strings.Fields(k.Command)[0])
ShellLog(k.Inspect, func(line string) {
k.log("%s", line)
})
time.Sleep(time.Second)
} else {
return
}
case <-k.stop:
cmd.Process.Kill()
l.Wait()
return
}
}
}()
}
func (k *Keeper) forwardOutput(cmd *exec.Cmd) Latch {
pipe, err := cmd.StdoutPipe()
if err != nil {
panic(err)
}
l := NewLatch(2)
go k.reader(pipe, l)
pipe, err = cmd.StderrPipe()
if err != nil {
panic(err)
}
go k.reader(pipe, l)
return l
}
func writeInput(cmd *exec.Cmd, input string) error {
stdin, err := cmd.StdinPipe()
if err != nil {
return err
}
_, err = stdin.Write([]byte(input))
if err != nil {
return err
}
err = stdin.Close()
return err
}
func (k *Keeper) reader(pipe io.ReadCloser, l Latch) {
defer pipe.Close()
buf := bufio.NewReader(pipe)
for {
line, err := buf.ReadString('\n')
if err != nil {
if strings.TrimSpace(line) != "" {
k.log("%s", line)
}
if err != io.EOF {
k.log("%s", err.Error())
}
l.Notify()
return
} else {
k.log("%s", line)
}
}
}