-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
224 lines (186 loc) · 6.72 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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package main
import (
"fmt"
"github.com/opentracing/opentracing-go"
"github.com/osstotalsoft/bifrost/gateway"
"github.com/osstotalsoft/bifrost/handler"
"github.com/osstotalsoft/bifrost/handler/nats"
"github.com/osstotalsoft/bifrost/handler/reverseproxy"
"github.com/osstotalsoft/bifrost/httputils"
"github.com/osstotalsoft/bifrost/log"
"github.com/osstotalsoft/bifrost/middleware"
"github.com/osstotalsoft/bifrost/middleware/auth"
"github.com/osstotalsoft/bifrost/middleware/cors"
r "github.com/osstotalsoft/bifrost/router"
"github.com/osstotalsoft/bifrost/servicediscovery/provider/kubernetes"
"github.com/osstotalsoft/bifrost/tracing"
"github.com/spf13/viper"
"github.com/uber/jaeger-client-go"
jaegercfg "github.com/uber/jaeger-client-go/config"
jaegerlog "github.com/uber/jaeger-client-go/log"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"io"
"net/http"
"os"
"os/signal"
"syscall"
)
func main() {
//https://github.com/golang/go/issues/16012
http.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost = 100
level, zlogger, _ := getZapLogger()
defer zlogger.Sync()
cfg := getConfig(zlogger)
changeLogLevel(level, cfg.LogLevel)
loggerFactory := tracing.SpanLoggerFactory(zlogger.With(zap.String("service", "api gateway")))
logger := loggerFactory(nil)
closer := setupJaeger(zlogger)
defer closer.Close()
provider := kubernetes.NewKubernetesServiceDiscoveryProvider(cfg.InCluster, cfg.OverrideServiceAddress, cfg.ServiceNamespacePrefixFilter, loggerFactory)
dynRouter := r.NewDynamicRouter(r.GorillaMuxRouteMatcher, loggerFactory)
//registry := in_memory_registry.NewInMemoryStore()
natsHandler, closeNatsConnection, err := nats.NewNatsPublisher(getNatsHandlerConfig(zlogger),
nats.TransformMessage(nats.NBBTransformMessage),
nats.BuildResponse(nats.NBBBuildResponse),
nats.Logger(logger),
)
if err != nil {
logger.Error("cannot connect to nats server", zap.Error(err))
}
defer closeNatsConnection()
gate := gateway.NewGateway(cfg, loggerFactory)
registerHandlerFunc := gateway.RegisterHandler(gate)
gateMiddlewareFunc := gateway.UseMiddleware(gate)
//gateMiddlewareFunc(ratelimit.RateLimitingFilterCode, ratelimit.RateLimiting(ratelimit.MaxRequestLimit))
gateMiddlewareFunc(cors.CORSFilterCode, middleware.Compose(tracing.MiddlewareSpanWrapper("CORS Filter"))(cors.CORSFilter(getCORSConfig(zlogger))))
gateMiddlewareFunc(auth.AuthorizationFilterCode, middleware.Compose(
tracing.MiddlewareSpanWrapper("Authorization Filter"),
)(auth.AuthorizationFilter(getIdentityServerConfig(zlogger))))
registerHandlerFunc(handler.EventPublisherHandlerType, handler.Compose(tracing.HandlerSpanWrapper("Nats Handler"))(natsHandler))
registerHandlerFunc(handler.ReverseProxyHandlerType, handler.Compose(
tracing.HandlerSpanWrapper("Reverse Proxy Handler"),
)(reverseproxy.NewReverseProxy(tracing.NewRoundTripperWithOpenTrancing(),
reverseproxy.AddUserIdToHeader,
reverseproxy.ClearCorsHeaders)))
addRouteFunc := r.AddRoute(dynRouter)
removeRouteFunc := r.RemoveRoute(dynRouter)
//configure and start ServiceDiscovery
kubernetes.Compose(
kubernetes.SubscribeOnAddService(gateway.AddService(gate)(addRouteFunc)),
kubernetes.SubscribeOnRemoveService(gateway.RemoveService(gate)(removeRouteFunc)),
kubernetes.SubscribeOnUpdateService(gateway.UpdateService(gate)(addRouteFunc, removeRouteFunc)),
kubernetes.Start,
)(provider)
defer kubernetes.Stop(provider)
go Shutdown(logger, gate)
err = gateway.ListenAndServe(gate, httputils.Compose(
httputils.RecoveryHandler(loggerFactory),
tracing.SpanWrapper,
)(r.GetHandler(dynRouter)))
if err != nil {
logger.Error("gateway cannot start", zap.Error(err))
}
}
//Shutdown gateway server and all subscriptions
func Shutdown(logger log.Logger, gate *gateway.Gateway) {
var signalsChannel = make(chan os.Signal, 1)
signal.Notify(signalsChannel, os.Interrupt, syscall.SIGTERM)
//wait for app closing
<-signalsChannel
logger.Info("Shutting down")
err := gateway.Shutdown(gate)
if err != nil {
logger.Error("error closing gateway", zap.Error(err))
}
}
func getZapLogger() (zap.AtomicLevel, *zap.Logger, error) {
cfg := zap.NewDevelopmentConfig()
cfg.Encoding = "json"
cfg.DisableCaller = true
l, e := cfg.Build()
return cfg.Level, l, e
}
func changeLogLevel(oldLevel zap.AtomicLevel, newLevel string) {
level := zapcore.InfoLevel
e := level.Set(newLevel)
if e == nil {
oldLevel.SetLevel(level)
}
return
}
func getConfig(logger *zap.Logger) *gateway.Config {
viper.SetConfigName("config")
viper.AddConfigPath(".")
viper.SetConfigType("json")
viper.AutomaticEnv()
//viper.WatchConfig()
err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
logger.Panic("unable to read configuration file", zap.Error(err))
}
var cfg = new(gateway.Config)
err = viper.Unmarshal(cfg)
if err != nil {
logger.Panic("unable to decode into struct", zap.Error(err))
}
logger.Info(fmt.Sprintf("using configuration: %v", viper.AllSettings()))
return cfg
}
func getNatsHandlerConfig(logger *zap.Logger) nats.Config {
var cfg = new(nats.Config)
err := viper.UnmarshalKey("handlers.event.nats", cfg)
if err != nil {
logger.Panic("unable to decode into NatsConfig", zap.Error(err))
}
return *cfg
}
func getIdentityServerConfig(logger *zap.Logger) auth.AuthorizationOptions {
var cfg = new(auth.AuthorizationOptions)
err := viper.UnmarshalKey("filters.auth", cfg)
if err != nil {
logger.Panic("unable to decode into AuthorizationOptions", zap.Error(err))
}
return *cfg
}
func getCORSConfig(logger *zap.Logger) cors.Options {
var cfg = new(cors.Options)
err := viper.UnmarshalKey("filters.cors", cfg)
if err != nil {
logger.Panic("unable to decode into cors.Options", zap.Error(err))
}
return *cfg
}
func setupJaeger(logger *zap.Logger) io.Closer {
var cfg = &struct {
Enabled bool `json:"enabled"`
Agent string `json:"agent"`
}{}
err := viper.UnmarshalKey("opentracing", cfg)
if err != nil {
logger.Panic("unable to decode into Jaeger Config", zap.Error(err))
}
jconfig := jaegercfg.Configuration{
Disabled: !cfg.Enabled,
ServiceName: "Bifrost API Gateway",
Sampler: &jaegercfg.SamplerConfig{
Type: jaeger.SamplerTypeConst,
Param: 1,
},
Reporter: &jaegercfg.ReporterConfig{
LogSpans: false,
LocalAgentHostPort: cfg.Agent,
},
}
jLogger := jaegerlog.StdLogger
//jMetricsFactory := jaegerprom.New() //metrics.NullFactory
//jaeger.NewMetrics(factory, map[string]string{"lib": "jaeger"})
// Initialize tracer with a logger and a metrics factory
tracer, closer, _ := jconfig.NewTracer(
jaegercfg.Logger(jLogger),
//jaegercfg.Metrics(jMetricsFactory),
)
// Set the singleton opentracing.Tracer with the Jaeger tracer.
opentracing.SetGlobalTracer(tracer)
return closer
}