-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathredisbetween.go
131 lines (111 loc) · 2.46 KB
/
redisbetween.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
package main
import (
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/DataDog/datadog-go/statsd"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/coinbase/redisbetween/config"
"github.com/coinbase/redisbetween/proxy"
)
func main() {
c := config.ParseFlags()
log := newLogger(c.Level, c.Pretty)
err := run(log, c)
if err != nil {
log.Panic("error", zap.Error(err))
}
}
func newLogger(level zapcore.Level, pretty bool) *zap.Logger {
var c zap.Config
if pretty {
c = zap.NewDevelopmentConfig()
c.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
} else {
c = zap.NewProductionConfig()
}
c.EncoderConfig.MessageKey = "message"
c.Level.SetLevel(level)
log, err := c.Build(zap.AddStacktrace(zap.FatalLevel))
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "Failed to initialize logger: %v\n", err)
os.Exit(1)
}
return log
}
func run(log *zap.Logger, cfg *config.Config) error {
proxies, err := proxies(cfg, log)
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")
return nil
}
func proxies(c *config.Config, log *zap.Logger) (proxies []*proxy.Proxy, err error) {
s, err := statsd.New(c.Statsd, statsd.WithNamespace("redisbetween"))
if err != nil {
return nil, err
}
for index := range c.Upstreams {
p, err := proxy.NewProxy(log, s, c, index)
if err != nil {
return nil, err
}
proxies = append(proxies, p)
}
return
}
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()
}
}
}()
}