forked from draganm/event-buffer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
187 lines (163 loc) · 4.6 KB
/
main.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
package main
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/draganm/bolted"
"github.com/draganm/bolted/embedded"
"github.com/draganm/event-buffer/server"
"github.com/go-logr/logr"
"github.com/go-logr/zapr"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/urfave/cli/v2"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"golang.org/x/sync/errgroup"
)
func main() {
logger, _ := zap.Config{
Encoding: "json",
Level: zap.NewAtomicLevelAt(zapcore.DebugLevel),
OutputPaths: []string{"stdout"},
EncoderConfig: zapcore.EncoderConfig{
MessageKey: "message",
LevelKey: "level",
EncodeLevel: zapcore.CapitalLevelEncoder,
TimeKey: "time",
EncodeTime: zapcore.ISO8601TimeEncoder,
CallerKey: "caller",
EncodeCaller: zapcore.ShortCallerEncoder,
},
}.Build()
defer logger.Sync()
app := &cli.App{
Flags: []cli.Flag{
&cli.StringFlag{
Name: "addr",
Value: ":5566",
EnvVars: []string{"ADDR"},
},
&cli.StringFlag{
Name: "metrics-addr",
Value: ":3000",
EnvVars: []string{"METRICS_ADDR"},
},
&cli.StringFlag{
Name: "internal-addr",
Value: ":5000",
EnvVars: []string{"INTERNAL_ADDR"},
},
&cli.StringFlag{
Name: "state-file",
Value: "state",
EnvVars: []string{"STATE_FILE"},
},
&cli.DurationFlag{
Name: "retention-period",
EnvVars: []string{"RETENTION_PERIOD"},
Value: 2 * time.Hour,
},
&cli.DurationFlag{
Name: "prune-frequency",
EnvVars: []string{"PRUNE_FREQUENCY"},
Value: 5 * time.Minute,
},
},
Action: func(c *cli.Context) error {
log := zapr.NewLogger(logger)
defer log.Info("server exiting")
eg, ctx := errgroup.WithContext(context.Background())
db, err := embedded.Open(c.String("state-file"), 0700, embedded.Options{})
if err != nil {
return fmt.Errorf("could not open state: %w", err)
}
srv, err := server.New(log, db)
if err != nil {
return fmt.Errorf("could not start server: %w", err)
}
err = srv.Prune(time.Now().Add(-c.Duration("retention-period")))
if err != nil {
return fmt.Errorf("could not prune stale events: %w", err)
}
eg.Go(func() error {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
select {
case sig := <-sigChan:
log.Info("received signal", "signal", sig.String())
return fmt.Errorf("received signal %s", sig.String())
case <-ctx.Done():
return nil
}
})
// run API server
eg.Go(runHttp(ctx, log, c.String("addr"), "api", srv))
// run metrics server
metricsRouter := mux.NewRouter()
metricsRouter.Methods("GET").Path("/metrics").Handler(promhttp.Handler())
eg.Go(runHttp(ctx, log, c.String("metrics-addr"), "metrics", metricsRouter))
// run internal api
internalRouter := mux.NewRouter()
internalRouter.Methods("GET").Path("/dump").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/binary")
err := bolted.SugaredRead(db, func(tx bolted.SugaredReadTx) error {
tx.Dump(w)
return nil
})
if err != nil {
http.Error(w, fmt.Errorf("could not write dump: %w", err).Error(), http.StatusInternalServerError)
return
}
})
eg.Go(runHttp(ctx, log, c.String("internal-addr"), "internal", internalRouter))
// run the pruner
eg.Go(func() error {
ticker := time.NewTicker(c.Duration("prune-frequency"))
for {
select {
case <-ctx.Done():
return nil
case <-ticker.C:
err = srv.Prune(time.Now().Add(-c.Duration("retention-period")))
if err != nil {
log.Error(err, "prune failed")
}
}
}
})
return eg.Wait()
},
}
app.RunAndExitOnError()
}
func runHttp(ctx context.Context, log logr.Logger, addr, name string, handler http.Handler) func() error {
return func() error {
l, err := net.Listen("tcp", addr)
if err != nil {
return fmt.Errorf("could not listen for %s requests: %w", name, err)
}
s := &http.Server{
Handler: handler,
}
go func() {
<-ctx.Done()
shutdownContext, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
log.Info(fmt.Sprintf("graceful shutdown of the %s server", name))
err := s.Shutdown(shutdownContext)
if errors.Is(err, context.DeadlineExceeded) {
log.Info(fmt.Sprintf("%s server did not shut down gracefully, forcing close", name))
s.Close()
}
}()
log.Info(fmt.Sprintf("%s server started", name), "addr", l.Addr().String())
return s.Serve(l)
}
}