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
|
package supervisor
import (
"fmt"
"os"
"os/exec"
"sync"
"time"
log "github.com/Sirupsen/logrus"
"github.com/kelseyhightower/envconfig"
)
// Config holds configuration for the circuit breaker of the respawn loop.
type Config struct {
// GITALY_SUPERVISOR_CRASH_THRESHOLD
CrashThreshold int `split_words:"true" default:"5"`
// GITALY_SUPERVISOR_CRASH_WAIT_TIME
CrashWaitTime time.Duration `split_words:"true" default:"1m"`
// GITALY_SUPERVISOR_CRASH_RESET_TIME
CrashResetTime time.Duration `split_words:"true" default:"1m"`
}
var config Config
func init() {
envconfig.MustProcess("gitaly_supervisor", &config)
}
// Process represents a running process.
type Process struct {
// Information to start the process
env []string
args []string
dir string
// Shutdown
done chan struct{}
stopOnce sync.Once
}
// New creates a new proces instance.
func New(env []string, args []string, dir string) (*Process, error) {
if len(args) < 1 {
return nil, fmt.Errorf("need at least one argument")
}
p := &Process{
env: env,
args: args,
dir: dir,
done: make(chan struct{}),
}
go watch(p)
return p, nil
}
func (p *Process) start() (*exec.Cmd, error) {
cmd := exec.Command(p.args[0], p.args[1:]...)
cmd.Env = p.env
cmd.Dir = p.dir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd, cmd.Start()
}
func watch(p *Process) {
// Count crashes to prevent a tight respawn loop. This is a 'circuit breaker'.
crashes := 0
logger := log.WithField("supervisor.args", p.args)
for {
if crashes >= config.CrashThreshold {
logger.Warn("opening circuit breaker")
select {
case <-p.done:
return
case <-time.After(config.CrashWaitTime):
logger.Warn("closing circuit breaker")
crashes = 0
}
}
cmd, err := p.start()
if err != nil {
crashes++
logger.WithError(err).Error("start failed")
continue
}
waitCh := make(chan struct{})
go func() {
logger.WithError(cmd.Wait()).Warn("exited")
close(waitCh)
}()
waitLoop:
for {
select {
case <-time.After(config.CrashResetTime):
crashes = 0
case <-waitCh:
crashes++
break waitLoop
case <-p.done:
if cmd.Process != nil {
cmd.Process.Kill()
}
return
}
}
}
}
// Stop terminates the process.
func (p *Process) Stop() {
if p == nil {
return
}
p.stopOnce.Do(func() {
close(p.done)
})
}
|