This repository has been archived by the owner on Jan 3, 2024. It is now read-only.
forked from rainycape/governator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
376 lines (343 loc) · 7.44 KB
/
service.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package main
import (
"fmt"
"math"
"os"
"os/exec"
"reflect"
"strings"
"sync"
"syscall"
"time"
"gnd.la/log"
)
var (
// avoids starting multiple services
// at the same time, to enforce resource limits
startLock sync.Mutex
)
type State uint8
const (
StateStopped State = iota
StateStopping
StateStarted
StateStarting
StateBackoff
StateFailed
)
func (s State) isRunState() bool {
return s == StateStarted || s == StateStarting
}
func (s State) canStop() bool {
return s.isRunState() || s == StateBackoff
}
const (
minTime = time.Second
maxRetries = 10
)
type Service struct {
mu sync.Mutex // protects access to the fields
st sync.Mutex // prevents start/stop from running concurrently
Config *Config
Cmd *exec.Cmd
State State
Started time.Time
Restarts int
Err error
stopCh chan error
errCh chan error
retries int
startTimer *time.Timer
nextStart time.Time
monitor *Monitor
startedTimer *time.Timer
}
func newService(cfg *Config) *Service {
return &Service{Config: cfg, stopCh: make(chan error)}
}
func (s *Service) Name() string {
return s.Config.ServiceName()
}
func (s *Service) sendErr(ch *chan<- error, err error) {
if err != nil && s.State != StateStopping {
s.errorf("%v", err)
}
s.Err = err
if ch != nil && *ch != nil {
select {
case *ch <- err:
*ch = nil
default:
}
}
if s.errCh != nil {
select {
case s.errCh <- err:
default:
}
}
}
func (s *Service) Start() error {
s.st.Lock()
defer s.st.Unlock()
if s.State.isRunState() {
return nil
}
if s.Config.Log != nil {
if err := s.Config.Log.Open(); err != nil {
return err
}
}
if err := s.startService(); err != nil {
return err
}
if err := s.startWatchdog(); err != nil {
s.errorf("error starting watchdog %s: %s", s.Name(), err)
}
return nil
}
func (s *Service) startIn(d time.Duration) {
s.stopTimer()
s.startTimer = time.AfterFunc(d, func() {
s.Run(nil)
})
s.nextStart = time.Now().Add(d)
}
func (s *Service) started(ch *chan<- error) {
s.State = StateStarted
s.stopTimer()
s.sendErr(ch, nil)
s.retries = 0
}
func (s *Service) startFailed(ch *chan<- error, err error) {
s.sendErr(ch, err)
if s.retries < maxRetries-1 {
s.State = StateBackoff
duration := time.Second * time.Duration(math.Pow(2, float64(s.retries)))
s.startIn(duration)
s.retries++
s.infof("will retry in %s", duration)
} else {
s.State = StateFailed
s.Cmd = nil
s.errorf("maximum retries reached")
}
}
func (s *Service) untilNextRestart() time.Duration {
return s.nextStart.Sub(time.Now())
}
func (s *Service) Run(ch chan<- error) {
s.mu.Lock()
defer s.mu.Unlock()
s.State = StateStarted
if s.State != StateStarted {
s.sendErr(&ch, nil)
return
}
cmd, err := s.Config.Cmd()
if err != nil {
s.State = StateFailed
s.sendErr(&ch, fmt.Errorf("could not initialize service: %s", err))
return
}
s.Cmd = cmd
s.Started = time.Now()
s.infof("starting")
if err != nil {
s.errorf("error setting service limits: %s", err)
}
s.startedTimer = time.AfterFunc(minTime, func() {
s.afterStarted(&ch)
})
startLock.Lock()
limits, err := SetLimits(s.Config)
serr := s.monitor.Start(s.Cmd, s.Config.Log, s.exited(&ch))
if err := RestoreLimits(limits); err != nil {
s.errorf("error restoring limits: %s", err)
}
startLock.Unlock()
if serr != nil {
s.errorf("failed to start: %s", serr)
s.startFailed(&ch, serr)
return
}
}
func (s *Service) afterStarted(ch *chan<- error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.startedTimer == nil {
return
}
s.startedTimer = nil
// Clear any potentially stored errors
s.started(ch)
s.infof("started")
}
func (s *Service) exited(ch *chan<- error) func(error) {
return func(err error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.startedTimer != nil {
// Consider failure, no mintime has passed
s.startedTimer.Stop()
s.startedTimer = nil
since := time.Since(s.Started)
s.startFailed(ch, fmt.Errorf("exited too fast (%s)", since))
return
}
if s.State != StateStarted {
s.Cmd = nil
s.sendErr(ch, err)
s.stopCh <- nil
return
}
s.Restarts++
if err != nil {
s.infof("exited with error %s - restarting", err)
} else {
s.infof("exited without error - restarting")
}
// Spawn a goroutine so this function ends and
// the lock is released before Run() is executed
// again.
go s.Run(*ch)
}
}
func (s *Service) Stop() error {
s.st.Lock()
defer s.st.Unlock()
s.stopWatchdog()
if err := s.stopService(); err != nil {
s.startWatchdog()
return err
}
return nil
}
func (s *Service) startWatchdog() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.Config.Watchdog != nil {
interval := s.Config.WatchdogInterval
if interval < 0 {
interval = defaultWatchdogInterval
}
return s.Config.Watchdog.Start(s, interval)
}
return nil
}
func (s *Service) stopWatchdog() {
s.mu.Lock()
defer s.mu.Unlock()
if s.Config.Watchdog != nil {
s.Config.Watchdog.Stop()
}
}
func (s *Service) stopTimerLocking() {
s.mu.Lock()
defer s.mu.Unlock()
s.stopTimer()
}
func (s *Service) stopTimer() {
if s.startTimer != nil {
s.startTimer.Stop()
s.startTimer = nil
s.nextStart = time.Time{}
}
}
func (s *Service) startService() error {
ch := make(chan error)
s.stopTimerLocking()
go s.Run(ch)
err := <-ch
close(ch)
return err
}
func (s *Service) stopService() error {
s.stopTimer()
s.mu.Lock()
if !s.State.isRunState() {
if s.State.canStop() {
s.infof("stopped")
}
s.State = StateStopped
s.mu.Unlock()
return nil
}
prevState := s.State
s.State = StateStopping
s.infof("stopping")
p := s.Cmd.Process
s.mu.Unlock()
if s != nil {
stopped := isStoppedErr(p.Signal(os.Signal(syscall.SIGTERM)))
if !stopped {
select {
case <-s.stopCh:
stopped = true
case <-time.After(10 * time.Second):
stopped = isStoppedErr(p.Kill())
}
if !stopped {
select {
case <-s.stopCh:
case <-time.After(2 * time.Second):
// sending signal 0 checks that the process is
// alive and we're allowed to send the signal
// without actually sending anything
if isStoppedErr(p.Signal(syscall.Signal(0))) {
break
}
s.mu.Lock()
s.State = prevState
s.mu.Unlock()
err := fmt.Errorf("could not stop, probably stuck")
s.errorf("%v", err)
return err
}
}
}
}
s.mu.Lock()
s.State = StateStopped
s.Restarts = 0
s.mu.Unlock()
if s.Config.Log != nil {
s.Config.Log.Close()
}
s.infof("stopped")
return nil
}
func (s *Service) log(level log.LLevel, prefix string, format string, args ...interface{}) {
msg := fmt.Sprintf(format, args...)
log.Logf(level, "[%s] %s", s.Name(), msg)
if s.Config.Log != nil {
s.Config.Log.WriteString(prefix, msg)
}
}
func (s *Service) errorf(format string, args ...interface{}) {
s.log(log.LError, "error", format, args...)
}
func (s *Service) infof(format string, args ...interface{}) {
s.log(log.LInfo, "info", format, args...)
}
func (s *Service) debugf(format string, args ...interface{}) {
s.log(log.LDebug, "debug", format, args...)
}
func (s *Service) updateConfig(cfg *Config) {
if reflect.DeepEqual(s.Config, cfg) {
// there were changes to the file which don't affect the conf
return
}
log.Debugf("changed service %s's configuration", s.Name())
start := false
if s.State == StateStarted {
start = s.Stop() == nil
}
s.Config = cfg
if start {
s.Start()
}
}
func isStoppedErr(err error) bool {
return err != nil && strings.Contains(err.Error(), "process already finished")
}