/
supervisor.go
171 lines (135 loc) · 3.04 KB
/
supervisor.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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package supervisor
import (
"context"
"fmt"
"os"
"os/exec"
"os/signal"
"syscall"
"time"
"github.com/fly-examples/postgres-ha/pkg/server"
"github.com/google/shlex"
"golang.org/x/sync/errgroup"
)
type processError struct {
process *process
}
func (pe *processError) Error() string {
return fmt.Sprintf("process %s failed", pe.process.name)
}
type Supervisor struct {
name string
output *multiOutput
procs []*process
stop chan struct{}
timeout time.Duration
}
func New(name string, timeout time.Duration) *Supervisor {
return &Supervisor{
timeout: 5 * time.Second,
name: name,
output: &multiOutput{},
}
}
var colors = []int{2, 3, 4, 5, 6, 42, 130, 103, 129, 108}
func (h *Supervisor) AddProcess(name string, command string, opts ...Opt) {
proc := &process{
name: name,
color: colors[len(h.procs)%len(colors)],
output: h.output,
stopSignal: syscall.SIGINT,
env: os.Environ(),
}
parsedCmd, err := shlex.Split(command)
fatalOnErr(err)
proc.f = func() *exec.Cmd {
cmd := exec.Command(parsedCmd[0], parsedCmd[1:]...)
cmd.SysProcAttr = &syscall.SysProcAttr{}
cmd.Env = proc.env
cmd.Dir = proc.dir
return cmd
}
for _, opt := range opts {
opt(proc)
}
proc.output.Connect(proc)
h.procs = append(h.procs, proc)
}
func (h *Supervisor) runProcess(ctx context.Context, proc *process) error {
restarts := 0
for {
proc.Run()
// supervisor is stopping, exit
if ctx.Err() != nil {
return nil
}
// process is done, exit
if !proc.restart {
proc.writeLine([]byte("done"))
return nil
}
// process restart limit reached, crash supervisor
if proc.maxRestarts > 0 && restarts >= proc.maxRestarts {
proc.writeLine([]byte("restart attempts exhausted, crashing"))
return &processError{proc}
}
restarts++
proc.writeLine([]byte(fmt.Sprintf("restarting in %s [attempt %d]", proc.restartDelay, restarts)))
select {
case <-time.After(proc.restartDelay):
case <-ctx.Done():
return nil
}
}
}
func (h *Supervisor) waitForTimeoutOrInterrupt() {
select {
case <-time.After(h.timeout):
case <-h.stop:
}
}
func (h *Supervisor) waitForExit(ctx context.Context) {
<-ctx.Done()
fmt.Println("supervisor stopping")
for _, proc := range h.procs {
go proc.Interrupt()
}
h.waitForTimeoutOrInterrupt()
for _, proc := range h.procs {
go proc.Kill()
}
}
func (h *Supervisor) StartHttpListener() {
go server.StartHttpServer()
}
func (h *Supervisor) Run() error {
h.stop = make(chan struct{})
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
go func() {
<-h.stop
cancel()
}()
eg, egCtx := errgroup.WithContext(ctx)
for _, proc := range h.procs {
p := proc
eg.Go(func() error {
return h.runProcess(egCtx, p)
})
}
go h.waitForExit(egCtx)
return eg.Wait()
}
func (h *Supervisor) Stop() {
h.stop <- struct{}{}
}
func (h *Supervisor) StopOnSignal(sigs ...os.Signal) {
sigch := make(chan os.Signal)
signal.Notify(sigch, sigs...)
go func() {
for sig := range sigch {
fmt.Printf("Got %s, stopping\n", sig)
h.Stop()
}
}()
}