-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloop.go
78 lines (68 loc) · 1.38 KB
/
loop.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
package loop
import (
"context"
"errors"
"os"
"os/signal"
"sync"
"time"
"github.com/sirupsen/logrus"
"github.com/shallowclouds/omil/icmp"
)
var (
ErrInterrupt = errors.New("signal interrupt")
restartInterval = time.Second
)
func Loop(ctx context.Context, monitors []*icmp.Monitor) (err error) {
var wg sync.WaitGroup
ctx, cancel := context.WithCancel(ctx)
defer cancel()
sigChan := make(chan os.Signal)
signal.Notify(sigChan, os.Interrupt)
go func() {
sig := <-sigChan
err = ErrInterrupt
logrus.Infof("Recv signal %s, exiting...", sig.String())
cancel()
}()
restart := true
var mu sync.RWMutex
go func() {
<-ctx.Done()
mu.Lock()
restart = false
mu.Unlock()
for _, monitor := range monitors {
logrus.Infof("stopping monitor %s", monitor.Name())
if err := monitor.Stop(); err != nil {
logrus.WithError(err).Error("failed to stop monitor")
}
}
}()
for _, monitor := range monitors {
wg.Add(1)
m := monitor
go func() {
for {
mu.RLock()
if !restart {
logrus.Infof("exiting monitor %s", m.Name())
wg.Done()
break
}
mu.RUnlock()
if err := m.Start(ctx); err != nil {
logrus.WithError(err).Error("failed to run monitor")
}
time.Sleep(restartInterval)
mu.RLock()
if restart {
logrus.Infof("restarting monitor %s", m.Name())
}
mu.RUnlock()
}
}()
}
wg.Wait()
return nil
}