-
Notifications
You must be signed in to change notification settings - Fork 492
/
trafficcontroller.go
729 lines (588 loc) · 19 KB
/
trafficcontroller.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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
/*
* Copyright (c) 2017, The Easegress Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Package trafficcontroller implements the TrafficController.
package trafficcontroller
import (
"fmt"
"runtime/debug"
"sync"
"github.com/megaease/easegress/v2/pkg/cluster"
"github.com/megaease/easegress/v2/pkg/context"
"github.com/megaease/easegress/v2/pkg/logger"
"github.com/megaease/easegress/v2/pkg/supervisor"
"github.com/megaease/easegress/v2/pkg/util/easemonitor"
)
const (
// Category is the category of TrafficController.
Category = supervisor.CategorySystemController
// Kind is the kind of TrafficController.
Kind = "TrafficController"
)
type (
// TrafficController is a system controller to manage
// TrafficGate, Pipeline and their relationship.
TrafficController struct {
super *supervisor.Supervisor
superSpec *supervisor.Spec
spec *Spec
// Pointer aims to safely transform it to next generation.
mutex *sync.Mutex
namespaces map[string]*Namespace
}
// Namespace is the namespace
Namespace struct {
namespace string
// The scenario here satisfies the first common case:
// When the entry for a given key is only ever written once but read many times.
// Reference: https://golang.org/pkg/sync/#Map
// types of both: map[string]*supervisor.ObjectEntity
trafficGates sync.Map
pipelines sync.Map
}
// WalkFunc is the type of the function called for
// walking traffic gate and pipeline.
WalkFunc = supervisor.WalkFunc
// Spec describes TrafficController.
Spec struct{}
// Status is the status of namespaces
Status struct {
Namespaces []*NamespacesStatus `json:"namespaces"`
}
// NamespacesStatus is the universal status in one namespace.
NamespacesStatus struct {
Namespace string `json:"namespace"`
TrafficObjects []*TrafficObject `json:"trafficObjects"`
}
// TrafficObject is the traffic object.
TrafficObject struct {
Name string `json:"name"`
TrafficObjectStatus `json:",inline"`
}
// TrafficObjectStatus is the status of traffic object.
TrafficObjectStatus struct {
Spec interface{} `json:"spec"`
Status interface{} `json:"status"`
}
)
var _ easemonitor.Metricer = (*TrafficObjectStatus)(nil)
func init() {
supervisor.Register(&TrafficController{})
}
// ToMetrics implements easemonitor.Metricer.
func (s *TrafficObjectStatus) ToMetrics(service string) []*easemonitor.Metrics {
metricer, ok := s.Status.(easemonitor.Metricer)
if !ok {
return nil
}
return metricer.ToMetrics(service)
}
// TrafficNamespace returns the exported system namespace of the internal namespace of TrafficController.
func (ns *NamespacesStatus) TrafficNamespace() string {
return cluster.TrafficNamespace(ns.Namespace)
}
func newNamespace(namespace string) *Namespace {
return &Namespace{
namespace: namespace,
}
}
// GetHandler gets handler within the namespace
func (ns *Namespace) GetHandler(name string) (context.Handler, bool) {
entity, exists := ns.pipelines.Load(name)
if !exists {
return nil, false
}
handler := entity.(*supervisor.ObjectEntity).Instance().(context.Handler)
return handler, true
}
// Category returns the category of TrafficController.
func (tc *TrafficController) Category() supervisor.ObjectCategory {
return Category
}
// Kind return the kind of TrafficController.
func (tc *TrafficController) Kind() string {
return Kind
}
// DefaultSpec returns the default spec of TrafficController.
func (tc *TrafficController) DefaultSpec() interface{} {
return &Spec{}
}
// Init initializes TrafficController.
func (tc *TrafficController) Init(superSpec *supervisor.Spec) {
tc.superSpec, tc.spec, tc.super = superSpec, superSpec.ObjectSpec().(*Spec), superSpec.Super()
tc.mutex = &sync.Mutex{}
tc.namespaces = make(map[string]*Namespace)
tc.reload(nil)
}
// Inherit inherits previous generation of TrafficController.
func (tc *TrafficController) Inherit(superSpec *supervisor.Spec, previousGeneration supervisor.Object) {
tc.superSpec, tc.spec, tc.super = superSpec, superSpec.ObjectSpec().(*Spec), superSpec.Super()
tc.reload(previousGeneration.(*TrafficController))
}
func (tc *TrafficController) reload(previousGeneration *TrafficController) {
if previousGeneration != nil {
tc.mutex, tc.namespaces = previousGeneration.mutex, previousGeneration.namespaces
}
}
// CreateTrafficGateForSpec creates traffic gate with a spec
func (tc *TrafficController) CreateTrafficGateForSpec(namespace string, superSpec *supervisor.Spec) (
*supervisor.ObjectEntity, error,
) {
entity, err := tc.super.NewObjectEntityFromSpec(superSpec)
if err != nil {
return nil, err
}
return tc.CreateTrafficGate(namespace, entity)
}
// CreateTrafficGate creates traffic gate
func (tc *TrafficController) CreateTrafficGate(namespace string, entity *supervisor.ObjectEntity) (
*supervisor.ObjectEntity, error,
) {
if namespace == "" {
return nil, fmt.Errorf("empty namespace")
}
tc.mutex.Lock()
defer tc.mutex.Unlock()
space, exists := tc.namespaces[namespace]
if !exists {
space = newNamespace(namespace)
tc.namespaces[namespace] = space
logger.Infof("create namespace %s", namespace)
}
name := entity.Spec().Name()
entity.InitWithRecovery(space)
space.trafficGates.Store(name, entity)
logger.Infof("create traffic gate %s/%s", namespace, name)
return entity, nil
}
// UpdateTrafficGateForSpec updates traffic gate with a Spec
func (tc *TrafficController) UpdateTrafficGateForSpec(namespace string, superSpec *supervisor.Spec) (
*supervisor.ObjectEntity, error,
) {
entity, err := tc.super.NewObjectEntityFromSpec(superSpec)
if err != nil {
return nil, err
}
return tc.UpdateTrafficGate(namespace, entity)
}
// UpdateTrafficGate updates traffic gate
func (tc *TrafficController) UpdateTrafficGate(namespace string, entity *supervisor.ObjectEntity) (
*supervisor.ObjectEntity, error,
) {
tc.mutex.Lock()
defer tc.mutex.Unlock()
space, exists := tc.namespaces[namespace]
if !exists {
return nil, fmt.Errorf("namespace %s not found", namespace)
}
name := entity.Spec().Name()
previousEntity, exists := space.trafficGates.Load(name)
if !exists {
return nil, fmt.Errorf("traffic gate %s/%s not found", namespace, name)
}
entity.InheritWithRecovery(previousEntity.(*supervisor.ObjectEntity), space)
space.trafficGates.Store(name, entity)
logger.Infof("update traffic gate %s/%s", namespace, name)
return entity, nil
}
// ApplyTrafficGateForSpec applies traffic gate with a Spec
func (tc *TrafficController) ApplyTrafficGateForSpec(namespace string, superSpec *supervisor.Spec) (
*supervisor.ObjectEntity, error,
) {
entity, err := tc.super.NewObjectEntityFromSpec(superSpec)
if err != nil {
return nil, err
}
return tc.ApplyTrafficGate(namespace, entity)
}
// ApplyTrafficGate applies traffic gate
func (tc *TrafficController) ApplyTrafficGate(namespace string, entity *supervisor.ObjectEntity) (
*supervisor.ObjectEntity, error,
) {
if namespace == "" {
return nil, fmt.Errorf("empty namespace")
}
tc.mutex.Lock()
defer tc.mutex.Unlock()
space, exists := tc.namespaces[namespace]
if !exists {
space = newNamespace(namespace)
tc.namespaces[namespace] = space
logger.Infof("create namespace %s", namespace)
}
name := entity.Spec().Name()
previousEntity, exists := space.trafficGates.Load(name)
if !exists {
entity.InitWithRecovery(space)
space.trafficGates.Store(name, entity)
logger.Infof("create traffic gate %s/%s", namespace, name)
} else {
prev := previousEntity.(*supervisor.ObjectEntity)
if prev.Spec().Equals(entity.Spec()) {
logger.Infof("traffic gate %s/%s nothing change", namespace, name)
return prev, nil
}
entity.InheritWithRecovery(previousEntity.(*supervisor.ObjectEntity), space)
space.trafficGates.Store(name, entity)
logger.Infof("update traffic gate %s/%s", namespace, name)
}
return entity, nil
}
// DeleteTrafficGate deletes a traffic gate
func (tc *TrafficController) DeleteTrafficGate(namespace, name string) error {
tc.mutex.Lock()
defer tc.mutex.Unlock()
space, exists := tc.namespaces[namespace]
if !exists {
return fmt.Errorf("namespace %s not found", namespace)
}
entity, exists := space.trafficGates.LoadAndDelete(name)
if !exists {
return fmt.Errorf("traffic gate %s/%s not found", namespace, name)
}
entity.(*supervisor.ObjectEntity).CloseWithRecovery()
logger.Infof("delete traffic gate %s/%s", namespace, name)
tc._cleanSpace(namespace)
return nil
}
// GetTrafficGate gets a traffic gate by its namespace and name
func (tc *TrafficController) GetTrafficGate(namespace, name string) (*supervisor.ObjectEntity, bool) {
tc.mutex.Lock()
defer tc.mutex.Unlock()
space, exists := tc.namespaces[namespace]
if !exists {
return nil, false
}
entity, exists := space.trafficGates.Load(name)
if !exists {
return nil, false
}
return entity.(*supervisor.ObjectEntity), exists
}
// ListTrafficGates lists the traffic gates
func (tc *TrafficController) ListTrafficGates(namespace string) []*supervisor.ObjectEntity {
tc.mutex.Lock()
defer tc.mutex.Unlock()
space, exists := tc.namespaces[namespace]
if !exists {
return nil
}
entities := []*supervisor.ObjectEntity{}
space.trafficGates.Range(func(k, v interface{}) bool {
entities = append(entities, v.(*supervisor.ObjectEntity))
return true
})
return entities
}
// WalkTrafficGates walks traffic gates
func (tc *TrafficController) WalkTrafficGates(namespace string, walkFn WalkFunc) {
defer func() {
if err := recover(); err != nil {
logger.Errorf("WalkTrafficGates recover from err: %v, stack trace:\n%s\n",
err, debug.Stack())
}
}()
tc.mutex.Lock()
defer tc.mutex.Unlock()
space, exists := tc.namespaces[namespace]
if !exists {
return
}
space.trafficGates.Range(func(k, v interface{}) bool {
return walkFn(v.(*supervisor.ObjectEntity))
})
}
// WalkPipelines walks the pipelines
func (tc *TrafficController) WalkPipelines(namespace string, walkFn WalkFunc) {
defer func() {
if err := recover(); err != nil {
logger.Errorf("WalkPipelines recover from err: %v, stack trace:\n%s\n",
err, debug.Stack())
}
}()
tc.mutex.Lock()
defer tc.mutex.Unlock()
space, exists := tc.namespaces[namespace]
if !exists {
return
}
space.pipelines.Range(func(k, v interface{}) bool {
return walkFn(v.(*supervisor.ObjectEntity))
})
}
// CreatePipelineForSpec creates a pipeline by a spec
func (tc *TrafficController) CreatePipelineForSpec(namespace string, superSpec *supervisor.Spec) (
*supervisor.ObjectEntity, error,
) {
entity, err := tc.super.NewObjectEntityFromSpec(superSpec)
if err != nil {
return nil, err
}
return tc.CreatePipeline(namespace, entity)
}
// CreatePipeline creates a pipeline
func (tc *TrafficController) CreatePipeline(namespace string, entity *supervisor.ObjectEntity) (
*supervisor.ObjectEntity, error,
) {
if namespace == "" {
return nil, fmt.Errorf("empty namespace")
}
tc.mutex.Lock()
defer tc.mutex.Unlock()
space, exists := tc.namespaces[namespace]
if !exists {
space = newNamespace(namespace)
tc.namespaces[namespace] = space
logger.Infof("create namespace %s", namespace)
}
name := entity.Spec().Name()
entity.InitWithRecovery(space)
space.pipelines.Store(name, entity)
logger.Infof("create pipeline %s/%s", namespace, name)
return entity, nil
}
// UpdatePipelineForSpec updates the pipeline with a Spec
func (tc *TrafficController) UpdatePipelineForSpec(namespace string, superSpec *supervisor.Spec) (
*supervisor.ObjectEntity, error,
) {
entity, err := tc.super.NewObjectEntityFromSpec(superSpec)
if err != nil {
return nil, err
}
return tc.UpdatePipeline(namespace, entity)
}
// UpdatePipeline updates the pipeline
func (tc *TrafficController) UpdatePipeline(namespace string, entity *supervisor.ObjectEntity) (
*supervisor.ObjectEntity, error,
) {
tc.mutex.Lock()
defer tc.mutex.Unlock()
space, exists := tc.namespaces[namespace]
if !exists {
return nil, fmt.Errorf("namespace %s not found", namespace)
}
name := entity.Spec().Name()
previousEntity, exists := space.pipelines.Load(name)
if !exists {
return nil, fmt.Errorf("pipeline %s/%s not found", namespace, name)
}
entity.InheritWithRecovery(previousEntity.(*supervisor.ObjectEntity), space)
space.pipelines.Store(name, entity)
logger.Infof("update pipeline %s/%s", namespace, name)
return entity, nil
}
// ApplyPipelineForSpec applies the pipeline with a Spec
func (tc *TrafficController) ApplyPipelineForSpec(namespace string, superSpec *supervisor.Spec) (
*supervisor.ObjectEntity, error,
) {
entity, err := tc.super.NewObjectEntityFromSpec(superSpec)
if err != nil {
return nil, err
}
return tc.ApplyPipeline(namespace, entity)
}
// ApplyPipeline applies the pipeline
func (tc *TrafficController) ApplyPipeline(namespace string, entity *supervisor.ObjectEntity) (
*supervisor.ObjectEntity, error,
) {
if namespace == "" {
return nil, fmt.Errorf("empty namespace")
}
tc.mutex.Lock()
defer tc.mutex.Unlock()
space, exists := tc.namespaces[namespace]
if !exists {
space = newNamespace(namespace)
tc.namespaces[namespace] = space
logger.Infof("create namespace %s", namespace)
}
name := entity.Spec().Name()
previousEntity, exists := space.pipelines.Load(name)
if !exists {
entity.InitWithRecovery(space)
space.pipelines.Store(name, entity)
logger.Infof("create pipeline %s/%s", namespace, name)
} else {
prev := previousEntity.(*supervisor.ObjectEntity)
if prev.Spec().Equals(entity.Spec()) {
logger.Infof("pipeline %s/%s nothing change", namespace, name)
return prev, nil
}
entity.InheritWithRecovery(prev, space)
space.pipelines.Store(name, entity)
logger.Infof("update pipeline %s/%s", namespace, name)
}
return entity, nil
}
// DeletePipeline deletes the pipeline by its namespace and name
func (tc *TrafficController) DeletePipeline(namespace, name string) error {
tc.mutex.Lock()
defer tc.mutex.Unlock()
space, exists := tc.namespaces[namespace]
if !exists {
return fmt.Errorf("namespace %s not found", namespace)
}
entity, exists := space.pipelines.LoadAndDelete(name)
if !exists {
return fmt.Errorf("pipeline %s/%s not found", namespace, name)
}
entity.(*supervisor.ObjectEntity).CloseWithRecovery()
logger.Infof("delete pipeline %s/%s", namespace, name)
tc._cleanSpace(namespace)
return nil
}
// GetPipeline returns the pipeline by its namespace and name.
func (tc *TrafficController) GetPipeline(namespace, name string) (*supervisor.ObjectEntity, bool) {
tc.mutex.Lock()
defer tc.mutex.Unlock()
space, exists := tc.namespaces[namespace]
if !exists {
return nil, false
}
entity, exists := space.pipelines.Load(name)
if !exists {
return nil, false
}
return entity.(*supervisor.ObjectEntity), exists
}
// ListPipelines lists the pipelines
func (tc *TrafficController) ListPipelines(namespace string) []*supervisor.ObjectEntity {
tc.mutex.Lock()
defer tc.mutex.Unlock()
space, exists := tc.namespaces[namespace]
if !exists {
return nil
}
entities := []*supervisor.ObjectEntity{}
space.pipelines.Range(func(k, v interface{}) bool {
entities = append(entities, v.(*supervisor.ObjectEntity))
return true
})
return entities
}
// Clean all traffic gates and pipelines of one namespace.
func (tc *TrafficController) Clean(namespace string) error {
tc.mutex.Lock()
defer tc.mutex.Unlock()
space, exist := tc.namespaces[namespace]
if !exist {
return fmt.Errorf("namespace %s not found", namespace)
}
space.trafficGates.Range(func(k, v interface{}) bool {
v.(*supervisor.ObjectEntity).CloseWithRecovery()
logger.Infof("delete traffic gate %s/%s", namespace, k)
space.trafficGates.Delete(k)
return true
})
space.pipelines.Range(func(k, v interface{}) bool {
v.(*supervisor.ObjectEntity).CloseWithRecovery()
logger.Infof("delete pipeline %s/%s", namespace, k)
space.pipelines.Delete(k)
return true
})
tc._cleanSpace(namespace)
return nil
}
// _cleanSpace must be called after deleting traffic gate or Pipeline.
// It's caller's duty to keep concurrent safety.
func (tc *TrafficController) _cleanSpace(namespace string) {
space, exists := tc.namespaces[namespace]
if !exists {
logger.Errorf("BUG: namespace %s not found", namespace)
}
serverLen, pipelineLen := 0, 0
space.trafficGates.Range(func(k, v interface{}) bool {
serverLen++
return false
})
space.pipelines.Range(func(k, v interface{}) bool {
pipelineLen++
return false
})
if serverLen+pipelineLen == 0 {
delete(tc.namespaces, namespace)
logger.Infof("delete namespace %s", namespace)
}
}
// Status returns the status of TrafficController.
// It reports all traffic object spec and status.
func (tc *TrafficController) Status() *supervisor.Status {
tc.mutex.Lock()
defer tc.mutex.Unlock()
statuses := []*NamespacesStatus{}
for namespace, namespaceSpec := range tc.namespaces {
status := &NamespacesStatus{
Namespace: namespace,
}
recordStatus := func(key, value interface{}) bool {
k := key.(string)
v := value.(*supervisor.ObjectEntity)
trafficObject := &TrafficObject{
Name: k,
TrafficObjectStatus: TrafficObjectStatus{
Spec: v.Spec().ObjectSpec(),
Status: v.Instance().Status().ObjectStatus,
},
}
status.TrafficObjects = append(status.TrafficObjects, trafficObject)
return true
}
namespaceSpec.trafficGates.Range(recordStatus)
namespaceSpec.pipelines.Range(recordStatus)
statuses = append(statuses, status)
}
return &supervisor.Status{ObjectStatus: &Status{Namespaces: statuses}}
}
// Close closes TrafficController.
func (tc *TrafficController) Close() {
tc.mutex.Lock()
defer tc.mutex.Unlock()
for name, space := range tc.namespaces {
space.trafficGates.Range(func(k, v interface{}) bool {
entity := v.(*supervisor.ObjectEntity)
entity.CloseWithRecovery()
logger.Infof("delete traffic gate %s/%s", space.namespace, k)
return true
})
space.pipelines.Range(func(k, v interface{}) bool {
entity := v.(*supervisor.ObjectEntity)
entity.CloseWithRecovery()
logger.Infof("delete pipeline %s/%s", space.namespace, k)
return true
})
delete(tc.namespaces, name)
logger.Infof("delete namespace %s", name)
}
}
// ListAllNamespace lists pipelines and traffic gates in all namespaces.
func (tc *TrafficController) ListAllNamespace() map[string][]*supervisor.ObjectEntity {
tc.mutex.Lock()
defer tc.mutex.Unlock()
res := make(map[string][]*supervisor.ObjectEntity)
for namespace, space := range tc.namespaces {
entities := []*supervisor.ObjectEntity{}
space.pipelines.Range(func(k, v interface{}) bool {
entities = append(entities, v.(*supervisor.ObjectEntity))
return true
})
space.trafficGates.Range(func(k, v interface{}) bool {
entities = append(entities, v.(*supervisor.ObjectEntity))
return true
})
res[namespace] = entities
}
return res
}