-
Notifications
You must be signed in to change notification settings - Fork 0
/
d.go
133 lines (117 loc) · 2.27 KB
/
d.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
package main
import (
"fmt"
"io"
"log"
"os"
"os/exec"
"syscall"
"time"
)
var MIMIMUM_AGE = 2.0
type God struct {
cmd *exec.Cmd
name string
args []string
started time.Time
stopping bool
exited bool
}
func NewGod(name string, args []string) *God {
d := new(God)
d.name = name
d.args = args
return d
}
func (d *God) Start(done chan bool) {
log.Printf("Start command '%s' ...", d.name)
cmd := exec.Command(d.name, d.args...)
stdout, err := cmd.StdoutPipe()
if err != nil {
panic(err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
panic(err)
}
go io.Copy(os.Stdout, stdout)
go io.Copy(os.Stderr, stderr)
err = cmd.Start()
if err != nil {
panic(err)
}
d.cmd = cmd
d.started = time.Now()
d.exited = false
go d.Watch(done)
}
func (d *God) Watch(done chan bool) {
if d.cmd == nil {
panic("You must call Start first")
}
log.Printf("Waiting for command '%s' to finish...", d.name)
if done != nil {
done <- true
}
err := d.cmd.Wait()
d.exited = true
if err == nil {
log.Printf("Command '%s' terminate without error", d.name)
return
}
if d.stopping {
log.Printf("Stopping. Command '%s' exited with %v", d.name, err)
return
}
log.Printf("Command '%s' finished with error: %v", d.name, err)
if time.Now().Sub(d.started).Seconds() < MIMIMUM_AGE {
log.Printf("Program '%s' restart too fast. No restart!", d.name)
return
}
d.Restart(nil)
}
func (d *God) Restart(done chan bool) {
log.Printf("Restart program %s", d.name)
d.Stop()
d.Start(done)
}
func (d *God) Stop() {
if d.cmd == nil {
panic("You must call Start first")
}
if d.Exited() {
return
}
d.stopping = true
d.Signal(syscall.SIGTERM)
d.waitExited(60 * time.Second)
// if not exited with SIGTERM we force with SIGKILL
if !d.Exited() {
d.Signal(syscall.SIGKILL)
d.waitExited(120 * time.Second)
}
d.stopping = false
}
func (d *God) Exited() bool {
return d.cmd.ProcessState != nil && d.exited
}
func (d *God) Signal(s os.Signal) error {
if d.cmd == nil {
return fmt.Errorf("You must call Start first")
}
return d.cmd.Process.Signal(s)
}
func (d *God) waitExited(maxSecs time.Duration) {
ticker := time.Tick(maxSecs)
for {
select {
case <-ticker:
return
default:
if d.Exited() {
return
}
time.Sleep(30 * time.Millisecond)
}
}
}