...
1
2
3
4
5
6
7
8
9
10
11
12
13
14 package router
15
16 import (
17 "reflect"
18
19 "github.com/go-logr/logr"
20 "github.com/pkg/errors"
21 "k8s.io/apimachinery/pkg/runtime"
22 ctrl "sigs.k8s.io/controller-runtime"
23
24 "github.com/chaos-mesh/chaos-mesh/pkg/config"
25 "github.com/chaos-mesh/chaos-mesh/pkg/router/endpoint"
26 )
27
28 type routeEntry struct {
29 Name string
30 Object runtime.Object
31 Endpoints []routeEndpoint
32 }
33
34 func newEntry(name string, obj runtime.Object) *routeEntry {
35 return &routeEntry{
36 Name: name,
37 Object: obj,
38 Endpoints: []routeEndpoint{},
39 }
40 }
41
42 type routeEndpoint struct {
43 RouteFunc func(runtime.Object) bool
44 NewEndpoint endpoint.NewEndpoint
45 }
46
47 var routeTable map[reflect.Type]*routeEntry
48
49 var log logr.Logger
50
51
52 func Register(name string, obj runtime.Object, routeFunc func(runtime.Object) bool, newEndpoint endpoint.NewEndpoint) {
53 typ := reflect.TypeOf(obj)
54 _, ok := routeTable[typ]
55 if !ok {
56 routeTable[typ] = newEntry(name, obj)
57 }
58
59 entry := routeTable[typ]
60 if entry.Name != name {
61 err := errors.Errorf("different names for one type of resource")
62 log.Error(err, "different names for one type of resource", "name", name, "existingName", entry.Name)
63 }
64
65 entry.Endpoints = append(entry.Endpoints, routeEndpoint{
66 RouteFunc: routeFunc,
67 NewEndpoint: newEndpoint,
68 })
69 }
70
71
72 func SetupWithManagerAndConfigs(mgr ctrl.Manager, cfg *config.ChaosControllerConfig) error {
73 for typ, end := range routeTable {
74 log.Info("setup reconciler with manager", "type", typ, "endpoint", end.Name)
75 reconciler := NewReconciler(end.Name, end.Object, mgr, end.Endpoints, cfg.ClusterScoped, cfg.TargetNamespace)
76 err := reconciler.SetupWithManager(mgr)
77 if err != nil {
78 log.Error(err, "fail to setup reconciler with manager")
79
80 return err
81 }
82
83 if err := ctrl.NewWebhookManagedBy(mgr).
84 For(end.Object).
85 Complete(); err != nil {
86 log.Error(err, "fail to setup webhook")
87 return err
88 }
89 }
90
91 return nil
92 }
93
94 func init() {
95 routeTable = make(map[reflect.Type]*routeEntry)
96 log = ctrl.Log.WithName("router")
97 }
98