forked from krakend/krakend-ce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
executor.go
393 lines (337 loc) · 13.4 KB
/
executor.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package krakend
import (
"context"
"io"
"net/http"
"os"
"time"
"github.com/gin-gonic/gin"
"github.com/go-contrib/uuid"
"golang.org/x/sync/errgroup"
krakendbf "github.com/krakendio/bloomfilter/v2/krakend"
asyncamqp "github.com/krakendio/krakend-amqp/v2/async"
cel "github.com/krakendio/krakend-cel/v2"
cmd "github.com/krakendio/krakend-cobra/v2"
cors "github.com/krakendio/krakend-cors/v2/gin"
gelf "github.com/krakendio/krakend-gelf/v2"
gologging "github.com/krakendio/krakend-gologging/v2"
influxdb "github.com/krakendio/krakend-influx/v2"
jose "github.com/krakendio/krakend-jose/v2"
logstash "github.com/krakendio/krakend-logstash/v2"
metrics "github.com/krakendio/krakend-metrics/v2/gin"
opencensus "github.com/krakendio/krakend-opencensus/v2"
_ "github.com/krakendio/krakend-opencensus/v2/exporter/datadog"
_ "github.com/krakendio/krakend-opencensus/v2/exporter/influxdb"
_ "github.com/krakendio/krakend-opencensus/v2/exporter/jaeger"
_ "github.com/krakendio/krakend-opencensus/v2/exporter/ocagent"
_ "github.com/krakendio/krakend-opencensus/v2/exporter/prometheus"
_ "github.com/krakendio/krakend-opencensus/v2/exporter/stackdriver"
_ "github.com/krakendio/krakend-opencensus/v2/exporter/xray"
_ "github.com/krakendio/krakend-opencensus/v2/exporter/zipkin"
pubsub "github.com/krakendio/krakend-pubsub/v2"
"github.com/krakendio/krakend-usage/client"
"github.com/luraproject/lura/v2/async"
"github.com/luraproject/lura/v2/config"
"github.com/luraproject/lura/v2/core"
"github.com/luraproject/lura/v2/logging"
"github.com/luraproject/lura/v2/proxy"
router "github.com/luraproject/lura/v2/router/gin"
serverhttp "github.com/luraproject/lura/v2/transport/http/server"
server "github.com/luraproject/lura/v2/transport/http/server/plugin"
)
// NewExecutor returns an executor for the cmd package. The executor initalizes the entire gateway by
// registering the components and composing a RouterFactory wrapping all the middlewares.
func NewExecutor(ctx context.Context) cmd.Executor {
eb := new(ExecutorBuilder)
return eb.NewCmdExecutor(ctx)
}
// PluginLoader defines the interface for the collaborator responsible of starting the plugin loaders
type PluginLoader interface {
Load(folder, pattern string, logger logging.Logger)
}
// SubscriberFactoriesRegister registers all the required subscriber factories from the available service
// discover components and adapters and returns a service register function.
// The service register function will register the service by the given name and port to all the available
// service discover clients
type SubscriberFactoriesRegister interface {
Register(context.Context, config.ServiceConfig, logging.Logger) func(string, int)
}
// TokenRejecterFactory returns a jose.ChainedRejecterFactory containing all the required jose.RejecterFactory.
// It also should setup and manage any service related to the management of the revocation process, if required.
type TokenRejecterFactory interface {
NewTokenRejecter(context.Context, config.ServiceConfig, logging.Logger, func(string, int)) (jose.ChainedRejecterFactory, error)
}
// MetricsAndTracesRegister registers the defined observability components and returns a metrics collector,
// if required.
type MetricsAndTracesRegister interface {
Register(context.Context, config.ServiceConfig, logging.Logger) *metrics.Metrics
}
// EngineFactory returns a gin engine, ready to be passed to the KrakenD RouterFactory
type EngineFactory interface {
NewEngine(config.ServiceConfig, router.EngineOptions) *gin.Engine
}
// ProxyFactory returns a KrakenD proxy factory, ready to be passed to the KrakenD RouterFactory
type ProxyFactory interface {
NewProxyFactory(logging.Logger, proxy.BackendFactory, *metrics.Metrics) proxy.Factory
}
// BackendFactory returns a KrakenD backend factory, ready to be passed to the KrakenD proxy factory
type BackendFactory interface {
NewBackendFactory(context.Context, logging.Logger, *metrics.Metrics) proxy.BackendFactory
}
// HandlerFactory returns a KrakenD router handler factory, ready to be passed to the KrakenD RouterFactory
type HandlerFactory interface {
NewHandlerFactory(logging.Logger, *metrics.Metrics, jose.RejecterFactory) router.HandlerFactory
}
// LoggerFactory returns a KrakenD Logger factory, ready to be passed to the KrakenD RouterFactory
type LoggerFactory interface {
NewLogger(config.ServiceConfig) (logging.Logger, io.Writer, error)
}
// RunServer defines the interface of a function used by the KrakenD router to start the service
type RunServer func(context.Context, config.ServiceConfig, http.Handler) error
// RunServerFactory returns a RunServer with several wraps around the injected one
type RunServerFactory interface {
NewRunServer(logging.Logger, router.RunServerFunc) RunServer
}
// AgentStarter defines a type that starts a set of agents
type AgentStarter interface {
Start(
context.Context,
[]*config.AsyncAgent,
logging.Logger,
chan<- string,
proxy.Factory,
) func() error
}
// ExecutorBuilder is a composable builder. Every injected property is used by the NewCmdExecutor method.
type ExecutorBuilder struct {
LoggerFactory LoggerFactory
PluginLoader PluginLoader
SubscriberFactoriesRegister SubscriberFactoriesRegister
TokenRejecterFactory TokenRejecterFactory
MetricsAndTracesRegister MetricsAndTracesRegister
EngineFactory EngineFactory
ProxyFactory ProxyFactory
BackendFactory BackendFactory
HandlerFactory HandlerFactory
RunServerFactory RunServerFactory
AgentStarterFactory AgentStarter
Middlewares []gin.HandlerFunc
}
// NewCmdExecutor returns an executor for the cmd package. The executor initializes the entire gateway by
// delegating most of the tasks to the injected collaborators. They register the components and
// compose a RouterFactory wrapping all the middlewares.
// Every nil collaborator is replaced by the default one offered by this package.
func (e *ExecutorBuilder) NewCmdExecutor(ctx context.Context) cmd.Executor {
e.checkCollaborators()
return func(cfg config.ServiceConfig) {
cfg.Normalize()
logger, gelfWriter, gelfErr := e.LoggerFactory.NewLogger(cfg)
if gelfErr != nil {
return
}
startReporter(ctx, logger, cfg)
if cfg.Plugin != nil {
e.PluginLoader.Load(cfg.Plugin.Folder, cfg.Plugin.Pattern, logger)
}
metricCollector := e.MetricsAndTracesRegister.Register(ctx, cfg, logger)
tokenRejecterFactory, err := e.TokenRejecterFactory.NewTokenRejecter(
ctx,
cfg,
logger,
e.SubscriberFactoriesRegister.Register(ctx, cfg, logger),
)
if err != nil && err != krakendbf.ErrNoConfig {
logger.Warning("[SERVICE: Bloomfilter]", err.Error())
}
pf := e.ProxyFactory.NewProxyFactory(
logger,
e.BackendFactory.NewBackendFactory(ctx, logger, metricCollector),
metricCollector,
)
agentPing := make(chan string, len(cfg.AsyncAgents))
// setup the krakend router
routerFactory := router.NewFactory(router.Config{
Engine: e.EngineFactory.NewEngine(cfg, router.EngineOptions{
Logger: logger,
Writer: gelfWriter,
Health: (<-chan string)(agentPing),
}),
ProxyFactory: pf,
Middlewares: e.Middlewares,
Logger: logger,
HandlerFactory: e.HandlerFactory.NewHandlerFactory(logger, metricCollector, tokenRejecterFactory),
RunServer: router.RunServerFunc(e.RunServerFactory.NewRunServer(logger, serverhttp.RunServer)),
})
// start the engines
logger.Info("Starting the KrakenD instance")
if len(cfg.AsyncAgents) == 0 {
routerFactory.NewWithContext(ctx).Run(cfg)
return
}
// start the async agents in the same error group as the router
g, gctx := errgroup.WithContext(ctx)
gctx, closeGroupCtx := context.WithCancel(gctx)
if cfg.SequentialStart {
waitAgents := e.AgentStarterFactory.Start(gctx, cfg.AsyncAgents, logger, (chan<- string)(agentPing), pf)
g.Go(waitAgents)
} else {
g.Go(func() error {
return e.AgentStarterFactory.Start(gctx, cfg.AsyncAgents, logger, (chan<- string)(agentPing), pf)()
})
}
g.Go(func() error {
logger.Info("[SERVICE: Gin] Building the router")
routerFactory.NewWithContext(ctx).Run(cfg)
closeGroupCtx()
return nil
})
g.Wait()
}
}
func (e *ExecutorBuilder) checkCollaborators() {
if e.PluginLoader == nil {
e.PluginLoader = new(pluginLoader)
}
if e.SubscriberFactoriesRegister == nil {
e.SubscriberFactoriesRegister = new(registerSubscriberFactories)
}
if e.TokenRejecterFactory == nil {
e.TokenRejecterFactory = new(BloomFilterJWT)
}
if e.MetricsAndTracesRegister == nil {
e.MetricsAndTracesRegister = new(MetricsAndTraces)
}
if e.EngineFactory == nil {
e.EngineFactory = new(engineFactory)
}
if e.ProxyFactory == nil {
e.ProxyFactory = new(proxyFactory)
}
if e.BackendFactory == nil {
e.BackendFactory = new(backendFactory)
}
if e.HandlerFactory == nil {
e.HandlerFactory = new(handlerFactory)
}
if e.LoggerFactory == nil {
e.LoggerFactory = new(LoggerBuilder)
}
if e.RunServerFactory == nil {
e.RunServerFactory = new(DefaultRunServerFactory)
}
if e.AgentStarterFactory == nil {
e.AgentStarterFactory = async.AgentStarter([]async.Factory{asyncamqp.StartAgent})
}
}
// DefaultRunServerFactory creates the default RunServer by wrapping the injected RunServer
// with the plugin loader and the CORS module
type DefaultRunServerFactory struct{}
func (*DefaultRunServerFactory) NewRunServer(l logging.Logger, next router.RunServerFunc) RunServer {
return RunServer(server.New(
l,
server.RunServer(cors.NewRunServer(cors.NewRunServerWithLogger(cors.RunServer(next), l))),
))
}
// LoggerBuilder is the default BuilderFactory implementation.
type LoggerBuilder struct{}
// NewLogger sets up the logging components as defined at the configuration.
func (LoggerBuilder) NewLogger(cfg config.ServiceConfig) (logging.Logger, io.Writer, error) {
var writers []io.Writer
gelfWriter, gelfErr := gelf.NewWriter(cfg.ExtraConfig)
if gelfErr == nil {
writers = append(writers, gelfWriterWrapper{gelfWriter})
gologging.SetFormatterSelector(func(w io.Writer) string {
switch w.(type) {
case gelfWriterWrapper:
return "%{message}"
default:
return gologging.DefaultPattern
}
})
}
logger, gologgingErr := logstash.NewLogger(cfg.ExtraConfig)
if gologgingErr != nil {
logger, gologgingErr = gologging.NewLogger(cfg.ExtraConfig, writers...)
if gologgingErr != nil {
var err error
logger, err = logging.NewLogger("DEBUG", os.Stdout, "KRAKEND")
if err != nil {
return logger, gelfWriter, err
}
logger.Error("[SERVICE: Logging] Unable to create the logger:", gologgingErr.Error())
}
}
if gelfErr != nil && gelfErr != gelf.ErrWrongConfig {
logger.Error("[SERVICE: Logging][GELF] Unable to create the writer:", gelfErr.Error())
}
return logger, gelfWriter, nil
}
// BloomFilterJWT is the default TokenRejecterFactory implementation.
type BloomFilterJWT struct{}
// NewTokenRejecter registers the bloomfilter component and links it to a token rejecter. Then it returns a chained
// rejecter factory with the created token rejecter and other based on the CEL component.
func (BloomFilterJWT) NewTokenRejecter(ctx context.Context, cfg config.ServiceConfig, l logging.Logger, reg func(n string, p int)) (jose.ChainedRejecterFactory, error) {
rejecter, err := krakendbf.Register(ctx, "krakend-bf", cfg, l, reg)
return jose.ChainedRejecterFactory([]jose.RejecterFactory{
jose.RejecterFactoryFunc(func(_ logging.Logger, _ *config.EndpointConfig) jose.Rejecter {
return jose.RejecterFunc(rejecter.RejectToken)
}),
jose.RejecterFactoryFunc(func(l logging.Logger, cfg *config.EndpointConfig) jose.Rejecter {
if r := cel.NewRejecter(l, cfg); r != nil {
return r
}
return jose.FixedRejecter(false)
}),
}), err
}
// MetricsAndTraces is the default implementation of the MetricsAndTracesRegister interface.
type MetricsAndTraces struct{}
// Register registers the metrics, influx and opencensus packages as required by the given configuration.
func (MetricsAndTraces) Register(ctx context.Context, cfg config.ServiceConfig, l logging.Logger) *metrics.Metrics {
metricCollector := metrics.New(ctx, cfg.ExtraConfig, l)
if err := influxdb.New(ctx, cfg.ExtraConfig, metricCollector, l); err != nil {
if err != influxdb.ErrNoConfig {
l.Warning("[SERVICE: InfluxDB]", err.Error())
}
} else {
l.Debug("[SERVICE: InfluxDB] Service correctly registered")
}
if err := opencensus.Register(ctx, cfg, append(opencensus.DefaultViews, pubsub.OpenCensusViews...)...); err != nil {
if err != opencensus.ErrNoConfig {
l.Warning("[SERVICE: OpenCensus]", err.Error())
}
} else {
l.Debug("[SERVICE: OpenCensus] Service correctly registered")
}
return metricCollector
}
const (
usageDisable = "USAGE_DISABLE"
usageDelay = 5 * time.Second
)
func startReporter(ctx context.Context, logger logging.Logger, cfg config.ServiceConfig) {
logPrefix := "[SERVICE: Telemetry]"
if os.Getenv(usageDisable) == "1" {
return
}
clusterID, err := cfg.Hash()
if err != nil {
logger.Debug(logPrefix, "Unable to create the Cluster ID hash:", err.Error())
return
}
go func() {
time.Sleep(usageDelay)
serverID := uuid.NewV4().String()
logger.Debug(logPrefix, "Registering usage stats for Cluster ID", clusterID)
if err := client.StartReporter(ctx, client.Options{
ClusterID: clusterID,
ServerID: serverID,
Version: core.KrakendVersion,
}); err != nil {
logger.Debug(logPrefix, "Unable to create the usage report client:", err.Error())
}
}()
}
type gelfWriterWrapper struct {
io.Writer
}