forked from movio/bramble
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
84 lines (66 loc) · 2.05 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
package bramble
import (
"context"
"flag"
"net/http"
"os"
"os/signal"
"sync"
"time"
log "github.com/sirupsen/logrus"
)
// Main runs the gateway. This function is exported so that it can be reused
// when building Bramble with custom plugins.
func Main() {
var configFiles arrayFlags
flag.Var(&configFiles, "config", "Config file (can appear multiple times)")
flag.Var(&configFiles, "conf", "deprecated, use -config instead")
flag.Parse()
log.SetFormatter(&log.JSONFormatter{TimestampFormat: time.RFC3339Nano})
cfg, err := GetConfig(configFiles)
if err != nil {
log.WithError(err).Fatal("failed to get config")
}
go cfg.Watch()
err = cfg.Init()
if err != nil {
log.WithError(err).Fatal("failed to configure")
}
log.WithField("config", cfg).Debug("configuration")
gtw := NewGateway(cfg.executableSchema, cfg.plugins)
RegisterMetrics()
go gtw.UpdateSchemas(cfg.PollIntervalDuration)
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
var wg sync.WaitGroup
wg.Add(3)
go runHandler(ctx, &wg, "metrics", cfg.MetricAddress(), NewMetricsHandler())
go runHandler(ctx, &wg, "private", cfg.PrivateAddress(), gtw.PrivateRouter())
go runHandler(ctx, &wg, "public", cfg.GatewayAddress(), gtw.Router(cfg))
wg.Wait()
}
func runHandler(ctx context.Context, wg *sync.WaitGroup, name, addr string, handler http.Handler) {
srv := &http.Server{
Addr: addr,
Handler: handler,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
}
go func() {
log.WithField("addr", addr).Infof("serving %s handler", name)
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.WithError(err).Fatal("server terminated unexpectedly")
}
}()
<-ctx.Done()
timeoutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
log.Infof("shutting down %s handler", name)
err := srv.Shutdown(timeoutCtx)
if err != nil {
log.WithError(err).Error("error shutting down server")
}
log.Infof("shut down %s handler", name)
wg.Done()
}