forked from zalando/skipper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
datasource.go
540 lines (456 loc) · 12.1 KB
/
datasource.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
package routing
import (
"fmt"
"net/url"
"sort"
"time"
"github.com/zalando/skipper/eskip"
"github.com/zalando/skipper/filters"
"github.com/zalando/skipper/logging"
"github.com/zalando/skipper/predicates"
)
type incomingType uint
const (
incomingReset incomingType = iota
incomingUpdate
)
// legacy, non-tree predicate names:
const (
hostRegexpName = "Host"
pathRegexpName = "PathRegexp"
methodName = "Method"
headerName = "Header"
headerRegexpName = "HeaderRegexp"
)
func (it incomingType) String() string {
switch it {
case incomingReset:
return "reset"
case incomingUpdate:
return "update"
default:
return "unknown"
}
}
type routeDefs map[string]*eskip.Route
type incomingData struct {
typ incomingType
client DataClient
upsertedRoutes []*eskip.Route
deletedIds []string
}
func (d *incomingData) log(l logging.Logger, suppress bool) {
if suppress {
l.Infof("route settings, %v, upsert count: %v", d.typ, len(d.upsertedRoutes))
l.Infof("route settings, %v, delete count: %v", d.typ, len(d.deletedIds))
return
}
for _, r := range d.upsertedRoutes {
l.Infof("route settings, %v, route: %v: %v", d.typ, r.Id, r)
}
for _, id := range d.deletedIds {
l.Infof("route settings, %v, deleted id: %v", d.typ, id)
}
}
// continuously receives route definitions from a data client on the the output channel.
// The function does not return unless quit is closed. When started, it request for the
// whole current set of routes, and continues polling for the subsequent updates. When a
// communication error occurs, it re-requests the whole valid set, and continues polling.
// Currently, the routes with the same id coming from different sources are merged in an
// undeterministic way, but this may change in the future.
func receiveFromClient(c DataClient, o Options, out chan<- *incomingData, quit <-chan struct{}) {
initial := true
for {
var (
routes []*eskip.Route
deletedIDs []string
err error
)
to := o.PollTimeout
if initial {
routes, err = c.LoadAll()
} else {
routes, deletedIDs, err = c.LoadUpdate()
}
switch {
case err != nil && initial:
o.Log.Error("error while receiveing initial data;", err)
case err != nil:
o.Log.Error("error while receiving update;", err)
initial = true
to = 0
case initial || len(routes) > 0 || len(deletedIDs) > 0:
var incoming *incomingData
if initial {
incoming = &incomingData{incomingReset, c, routes, nil}
} else {
incoming = &incomingData{incomingUpdate, c, routes, deletedIDs}
}
initial = false
select {
case out <- incoming:
case <-quit:
return
}
}
select {
case <-time.After(to):
case <-quit:
return
}
}
}
// applies incoming route definitions to key/route map, where
// the keys are the route ids.
func applyIncoming(defs routeDefs, d *incomingData) routeDefs {
if d.typ == incomingReset || defs == nil {
defs = make(routeDefs)
}
if d.typ == incomingUpdate {
for _, id := range d.deletedIds {
delete(defs, id)
}
}
if d.typ == incomingReset || d.typ == incomingUpdate {
for _, def := range d.upsertedRoutes {
defs[def.Id] = def
}
}
return defs
}
// merges the route definitions from multiple data clients by route id
func mergeDefs(defsByClient map[DataClient]routeDefs) []*eskip.Route {
mergeByID := make(routeDefs)
for _, defs := range defsByClient {
for id, def := range defs {
mergeByID[id] = def
}
}
var all []*eskip.Route
for _, def := range mergeByID {
all = append(all, def)
}
return all
}
// receives the initial set of the route definitiosn and their
// updates from multiple data clients, merges them by route id
// and sends the merged route definitions to the output channel.
//
// The active set of routes from last successful update are used until the
// next successful update.
func receiveRouteDefs(o Options, quit <-chan struct{}) <-chan []*eskip.Route {
in := make(chan *incomingData)
out := make(chan []*eskip.Route)
defsByClient := make(map[DataClient]routeDefs)
for _, c := range o.DataClients {
go receiveFromClient(c, o, in, quit)
}
go func() {
for {
var incoming *incomingData
select {
case incoming = <-in:
case <-quit:
return
}
incoming.log(o.Log, o.SuppressLogs)
c := incoming.client
defsByClient[c] = applyIncoming(defsByClient[c], incoming)
select {
case out <- mergeDefs(defsByClient):
case <-quit:
return
}
}
}()
return out
}
// splits the backend address of a route definition into separate
// scheme and host variables.
func splitBackend(r *eskip.Route) (string, string, error) {
if r.Shunt || r.BackendType == eskip.ShuntBackend || r.BackendType == eskip.LoopBackend {
return "", "", nil
}
bu, err := url.ParseRequestURI(r.Backend)
if err != nil {
return "", "", err
}
return bu.Scheme, bu.Host, nil
}
// creates a filter instance based on its definition and its
// specification in the filter registry.
func createFilter(fr filters.Registry, def *eskip.Filter) (filters.Filter, error) {
spec, ok := fr[def.Name]
if !ok {
return nil, fmt.Errorf("filter not found: '%s'", def.Name)
}
return spec.CreateFilter(def.Args)
}
// creates filter instances based on their definition
// and the filter registry.
func createFilters(fr filters.Registry, defs []*eskip.Filter) ([]*RouteFilter, error) {
var fs []*RouteFilter
for i, def := range defs {
f, err := createFilter(fr, def)
if err != nil {
return nil, err
}
fs = append(fs, &RouteFilter{f, def.Name, i})
}
return fs, nil
}
// check if a predicate is a distinguished, path tree predicate
func isTreePredicate(name string) bool {
switch name {
case PathSubtreeName:
return true
case PathName:
return true
default:
return false
}
}
func getFreeStringArgs(count int, p *eskip.Predicate) ([]string, error) {
if len(p.Args) != count {
return nil, fmt.Errorf(
"invalid length of predicate args in %s, %d instead of %d",
p.Name,
len(p.Args),
count,
)
}
var a []string
for i := range p.Args {
s, ok := p.Args[i].(string)
if !ok {
return nil, fmt.Errorf("expected argument of type string, %s", p.Name)
}
a = append(a, s)
}
return a, nil
}
func mergeLegacyNonTreePredicates(r *eskip.Route) error {
var rest []*eskip.Predicate
for _, p := range r.Predicates {
if isTreePredicate(p.Name) {
rest = append(rest, p)
continue
}
switch p.Name {
case hostRegexpName:
a, err := getFreeStringArgs(1, p)
if err != nil {
return err
}
r.HostRegexps = append(r.HostRegexps, a[0])
case pathRegexpName:
a, err := getFreeStringArgs(1, p)
if err != nil {
return err
}
r.PathRegexps = append(r.PathRegexps, a[0])
case methodName:
a, err := getFreeStringArgs(1, p)
if err != nil {
return err
}
r.Method = a[0]
case headerName:
a, err := getFreeStringArgs(2, p)
if err != nil {
return err
}
if r.Headers == nil {
r.Headers = make(map[string]string)
}
r.Headers[a[0]] = a[1]
case headerRegexpName:
a, err := getFreeStringArgs(2, p)
if err != nil {
return err
}
if r.HeaderRegexps == nil {
r.HeaderRegexps = make(map[string][]string)
}
r.HeaderRegexps[a[0]] = append(r.HeaderRegexps[a[0]], a[1])
default:
rest = append(rest, p)
}
}
r.Predicates = rest
return nil
}
// initialize predicate instances from their spec with the concrete arguments
func processPredicates(cpm map[string]PredicateSpec, defs []*eskip.Predicate) ([]Predicate, error) {
cps := make([]Predicate, 0, len(defs))
for _, def := range defs {
if isTreePredicate(def.Name) {
continue
}
spec, ok := cpm[def.Name]
if !ok {
return nil, fmt.Errorf("predicate not found: '%s'", def.Name)
}
cp, err := spec.Create(def.Args)
if err != nil {
return nil, err
}
cps = append(cps, cp)
}
return cps, nil
}
// returns the subtree path if it is a valid definition
func processPathOrSubTree(p *eskip.Predicate) (string, error) {
if len(p.Args) != 1 {
return "", predicates.ErrInvalidPredicateParameters
}
if s, ok := p.Args[0].(string); ok {
return s, nil
}
return "", predicates.ErrInvalidPredicateParameters
}
func validTreePredicates(predicates []*eskip.Predicate) bool {
var has bool
for _, p := range predicates {
switch p.Name {
case PathName, PathSubtreeName:
if has {
return false
}
has = true
}
}
return true
}
// processes path tree relevant predicates
func processTreePredicates(r *Route, predicates []*eskip.Predicate) error {
// backwards compatibility
if r.Path != "" {
predicates = append(predicates, &eskip.Predicate{Name: PathName, Args: []interface{}{r.Path}})
}
if !validTreePredicates(predicates) {
return fmt.Errorf("multiple tree predicates (Path, PathSubtree) in the route: %s", r.Id)
}
for _, p := range predicates {
switch p.Name {
case PathName:
path, err := processPathOrSubTree(p)
if err != nil {
return err
}
r.path = path
case PathSubtreeName:
pst, err := processPathOrSubTree(p)
if err != nil {
return err
}
r.pathSubtree = pst
}
}
return nil
}
// processes a route definition for the routing table
func processRouteDef(cpm map[string]PredicateSpec, fr filters.Registry, def *eskip.Route) (*Route, error) {
scheme, host, err := splitBackend(def)
if err != nil {
return nil, err
}
fs, err := createFilters(fr, def.Filters)
if err != nil {
return nil, err
}
if err := mergeLegacyNonTreePredicates(def); err != nil {
return nil, err
}
cps, err := processPredicates(cpm, def.Predicates)
if err != nil {
return nil, err
}
r := &Route{Route: *def, Scheme: scheme, Host: host, Predicates: cps, Filters: fs}
if err := processTreePredicates(r, def.Predicates); err != nil {
return nil, err
}
return r, nil
}
// convert a slice of predicate specs to a map keyed by their names
func mapPredicates(cps []PredicateSpec) map[string]PredicateSpec {
cpm := make(map[string]PredicateSpec)
for _, cp := range cps {
cpm[cp.Name()] = cp
}
return cpm
}
// processes a set of route definitions for the routing table
func processRouteDefs(o Options, fr filters.Registry, defs []*eskip.Route) (routes []*Route, invalidDefs []*eskip.Route) {
cpm := mapPredicates(o.Predicates)
for _, def := range defs {
route, err := processRouteDef(cpm, fr, def)
if err == nil {
routes = append(routes, route)
} else {
invalidDefs = append(invalidDefs, def)
o.Log.Errorf("failed to process route (%v): %v", def.Id, err)
}
}
return
}
type routeTable struct {
m *matcher
validRoutes []*eskip.Route
invalidRoutes []*eskip.Route
created time.Time
}
// receives the next version of the routing table on the output channel,
// when an update is received on one of the data clients.
func receiveRouteMatcher(o Options, out chan<- *routeTable, quit <-chan struct{}) {
updates := receiveRouteDefs(o, quit)
var (
rt *routeTable
outRelay chan<- *routeTable
updatesRelay <-chan []*eskip.Route
)
updatesRelay = updates
for {
select {
case defs := <-updatesRelay:
o.Log.Info("route settings received")
routes, invalidRoutes := processRouteDefs(o, o.FilterRegistry, defs)
// TODO: consider if the fallbacks logic should be a post processor
routes = applyFallbackGroups(routes)
for i := range o.PostProcessors {
routes = o.PostProcessors[i].Do(routes)
}
m, errs := newMatcher(routes, o.MatchingOptions)
invalidRouteIds := make(map[string]struct{})
validRoutes := []*eskip.Route{}
for _, err := range errs {
o.Log.Error(err)
invalidRouteIds[err.ID] = struct{}{}
}
for _, r := range routes {
if _, found := invalidRouteIds[r.Id]; found {
invalidRoutes = append(invalidRoutes, &r.Route)
} else {
validRoutes = append(validRoutes, &r.Route)
}
}
sort.SliceStable(validRoutes, func(i, j int) bool {
return validRoutes[i].Id < validRoutes[j].Id
})
rt = &routeTable{
m: m,
validRoutes: validRoutes,
invalidRoutes: invalidRoutes,
created: time.Now().UTC(),
}
updatesRelay = nil
outRelay = out
case outRelay <- rt:
rt = nil
updatesRelay = updates
outRelay = nil
case <-quit:
return
}
}
}