-
Notifications
You must be signed in to change notification settings - Fork 48
/
mongobetween.go
87 lines (73 loc) · 1.43 KB
/
mongobetween.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
package main
import (
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
"go.uber.org/zap"
"github.com/coinbase/mongobetween/config"
)
func main() {
c := config.ParseFlags()
run(c)
}
func run(config *config.Config) {
proxies, err := config.Proxies(config.Logger())
log := config.Logger()
if err != nil {
log.Fatal("Startup error", zap.Error(err))
}
var wg sync.WaitGroup
defer func() {
wg.Wait()
}()
for _, p := range proxies {
p := p
wg.Add(1)
go func() {
err := p.Run()
if err != nil {
log.Error("Error", zap.Error(err))
}
wg.Done()
}()
}
shutdown := func() {
for _, p := range proxies {
p.Shutdown()
}
}
kill := func() {
for _, p := range proxies {
p.Kill()
}
}
shutdownOnSignal(log, shutdown, kill)
log.Info("Running")
}
func shutdownOnSignal(log *zap.Logger, shutdownFunc func(), killFunc func()) {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
shutdownAttempted := false
for sig := range c {
log.Info("Signal", zap.String("signal", sig.String()))
if !shutdownAttempted {
log.Info("Shutting down")
go shutdownFunc()
shutdownAttempted = true
if sig == os.Interrupt {
time.AfterFunc(1*time.Second, func() {
fmt.Println("Ctrl-C again to kill incoming connections")
})
}
} else if sig == os.Interrupt {
log.Warn("Terminating")
_ = log.Sync() // #nosec
killFunc()
}
}
}()
}