This repository has been archived by the owner on Jul 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
controller.go
1514 lines (1388 loc) · 50.6 KB
/
controller.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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2019 IBM Corporation
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 main
import (
"encoding/json"
"fmt"
"os"
"runtime"
"strings"
"sync"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
k8sruntime "k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/discovery"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
)
/* kAppNav Status Controller
client-go Cluster Watcher queue channel
+----------+ +-------------+
kind1 ->| kind 1 |-> +rate limiting| --> handler 1 --> batchStore
store+controller | | |queue | ^ ^ |
+----------+ +-------------+ | | |
kind2 | kind 2 |-> |rate limiting| ------- | V
store +controller | | +queue | | batch
+----------+ +-------------+ | processor
| ... | | ... | --> handler 2 +
+ ---------+ +-------------+
The kAppNav Status controller is designed to
- watch over multiple kinds of resources
- watch over kinds defined by custom resource definitions that
- may not be declared yet
- may be deleted
The main entry point to create the kappnav status controller is
the NewClusterWathcer method. By default, resource change events are first
queed, and then processed by handlers. There are three bulit-in handers:
- CRDHandler: to process custom resource definitions as they come and go
- ApplicationHandler to process kappnav application status changes
- default handler: to process non-application resources that can have
kappnav status.
The client-go library is used to create a Kubernetes controller and cache
for each kind. A callback handler is registered with client-go library to
receive resource add/delete/modify events for each resource.
The handler for each resource calulates the minimum resources that are
affected by a resource change, and then places the information into
a batchStore. A separate thread fetches the affected resources from
the batchStore to recalculate status in batches. Examples of change:
- when a resource is changed, status needs to be recalulated on
all the ancestor resources before change, and after change
- when an application is changed, status needs to be recalculated
all the ancestor resources, and for the application itself.
After calculating minimum affected resources, the handlers place the
resources on a channel to be sent to the batch store. A batch processor
calls the bathStore to get resources to be processed in batches. The
batchStore will
- block until there are resources to be processed
- batch up resources for up to a cofigured duration before deliverig them to
to reduce resource usage.
The batch processor calculates the application and resource status, and
updates the kubernetes server if the status has changed. If there is an
error, resources that still exist are placed back into the bathStore
to be processed again in the later.
*/
const (
retryLimit = 5 // number of times to retry if the handlers encounter error
DEPLOYMENT = "Deployment"
STATEFULSET = "StatefulSet"
APPLICATION = "Application"
KAppNav = "KAppNav"
KappnavUIService = "kappnav-ui-service"
CustomResourceDefinition = "CustomResourceDefinition"
OpenShiftWebConsoleConfig = "OpenShiftWebConsoleConfig"
OpenShiftWebConsole = "openshift-web-console"
V1 = "v1"
CONFIGMAPS = "configmaps"
APIVERSION = "apiVersion"
KIND = "kind"
ANNOTATIONS = "annotations"
MATCHEXPRESSIONS = "matchExpressions"
KEY = "key"
PLURAL = "plural"
OPERATOR = "operator"
SCOPE = "scope"
NAMESPACED = "Namespaced"
VALUES = "values"
GROUP = "group"
METADATA = "metadata"
MATCHLABELS = "matchLabels"
NAME = "name"
NAMES = "names"
NAMESPACE = "namespace"
LABELS = "labels"
SPEC = "spec"
VERSION = "version"
SELECTOR = "selector"
COMPONENTKINDS = "componentKinds"
statusUnknown = "status-unknown"
appStatusPrecedence = "app-status-precedence"
appNamespaces = "app-namespaces"
kappnavStatusValue = "kappnav.status.value"
kappnavStatusFlyover = "kappnav.status.flyover"
kappnavStatusFlyoverNls = "kappnav.status.flyover.nls"
defaultkAppNavNamespace = "kappnav"
kappnavConfig = "kappnav-config"
kappnavComponentNamespaces = "kappnav.component.namespaces" // annotation for additional namespaces for application components
)
// coreKindToGVR map is for backward compatibility with initial releases
// of KAppNav where specifying kind was enough. It maps a kind string
// to the default GVR for the kind.
var (
coreKindToGVR map[string]schema.GroupVersionResource
coreServiceGVR = schema.GroupVersionResource{
Group: "",
Version: "v1",
Resource: "services",
}
coreDeploymentGVR = schema.GroupVersionResource{
Group: "apps",
Version: "v1",
Resource: "deployments",
}
corePodGVR = schema.GroupVersionResource{
Group: "",
Version: "v1",
Resource: "pods",
}
coreConfigMapGVR = schema.GroupVersionResource{
Group: "",
Version: "v1",
Resource: "configmaps",
}
coreSecretGVR = schema.GroupVersionResource{
Group: "",
Version: "v1",
Resource: "secrets",
}
coreVolumeGVR = schema.GroupVersionResource{
Group: "",
Version: "v1",
Resource: "volumes",
}
coreRouteGVR = schema.GroupVersionResource{
Group: "route.openshift.io",
Version: "v1",
Resource: "routes",
}
coreCustomResourceDefinitionGVR = schema.GroupVersionResource{
Group: "apiextensions.k8s.io",
Version: "v1beta1",
Resource: "customresourcedefinitions",
}
coreV1CustomResourceDefinitionGVR = schema.GroupVersionResource{
Group: "apiextensions.k8s.io",
Version: "v1",
Resource: "customresourcedefinitions",
}
coreApplicationGVR = schema.GroupVersionResource{
Group: "app.k8s.io",
Version: "v1beta1",
Resource: "applications",
}
coreStatefulSetGVR = schema.GroupVersionResource{
Group: "apps",
Version: "v1",
Resource: "statefulsets",
}
coreIngressGVR = schema.GroupVersionResource{
Group: "extensions",
Version: "v1beta1",
Resource: "ingresses",
}
coreJobGVR = schema.GroupVersionResource{
Group: "batch",
Version: "v1",
Resource: "jobs",
}
coreServiceAccountGVR = schema.GroupVersionResource{
Group: "",
Version: "v1",
Resource: "serviceaccounts",
}
coreClusterRoleGVR = schema.GroupVersionResource{
Group: "rbac.authorization.k8s.io",
Version: "v1",
Resource: "clusterroles",
}
coreClusterRoleBindingGVR = schema.GroupVersionResource{
Group: "rbac.authorization.k8s.io",
Version: "v1",
Resource: "clusterrolebindings",
}
coreRoleGVR = schema.GroupVersionResource{
Group: "rbac.authorization.k8s.io",
Version: "v1",
Resource: "roles",
}
coreRoleBindingGVR = schema.GroupVersionResource{
Group: "rbac.authorization.k8s.io",
Version: "v1",
Resource: "rolebindings",
}
coreStorageClassGVR = schema.GroupVersionResource{
Group: "storage.k8s.io",
Version: "v1",
Resource: "storageclasses",
}
coreEndpointGVR = schema.GroupVersionResource{
Group: "",
Version: "v1",
Resource: "endpoints",
}
corePersistentVolumeClaimGVR = schema.GroupVersionResource{
Group: "",
Version: "v1",
Resource: "persistentvolumeclaims",
}
coreNodeGVR = schema.GroupVersionResource{
Group: "",
Version: "v1",
Resource: "nodes",
}
coreKappNavGVR = schema.GroupVersionResource{
Group: "kappnav.operator.kappnav.io",
Version: "v1",
Resource: "kappnavs",
}
coreClusterServiceVersionGVR = schema.GroupVersionResource{
Group: "operators.coreos.com",
Version: "v1alpha1",
Resource: "clusterserviceversions",
}
)
func init() {
if logger.IsEnabled(LogTypeInfo) {
logger.Log(CallerName(), LogTypeInfo, "init")
}
coreKindToGVR = make(map[string]schema.GroupVersionResource)
coreKindToGVR["Service"] = coreServiceGVR
coreKindToGVR["Deployment"] = coreDeploymentGVR
coreKindToGVR["Pod"] = corePodGVR
coreKindToGVR["Route"] = coreRouteGVR
coreKindToGVR["ConfigMap"] = coreConfigMapGVR
coreKindToGVR["Secret"] = coreSecretGVR
coreKindToGVR["Volume"] = coreVolumeGVR
coreKindToGVR["PersistentVolumeClaim"] = corePersistentVolumeClaimGVR
coreKindToGVR["CustomResourceDefinition"] = coreCustomResourceDefinitionGVR
coreKindToGVR["Application"] = coreApplicationGVR
coreKindToGVR["StatefulSet"] = coreStatefulSetGVR
coreKindToGVR["Ingress"] = coreIngressGVR
coreKindToGVR["Job"] = coreJobGVR
coreKindToGVR["ServiceAccount"] = coreServiceAccountGVR
coreKindToGVR["ClusterRole"] = coreClusterRoleGVR
coreKindToGVR["ClusterRoleBinding"] = coreClusterRoleBindingGVR
coreKindToGVR["Role"] = coreRoleGVR
coreKindToGVR["RoleBinding"] = coreRoleBindingGVR
coreKindToGVR["StorageClass"] = coreStorageClassGVR
coreKindToGVR["Endpoint"] = coreEndpointGVR
coreKindToGVR["Node"] = coreNodeGVR
coreKindToGVR["Kappnav"] = coreKappNavGVR
}
func logStack(msg string) {
buf := make([]byte, 4096)
len := runtime.Stack(buf, false)
if logger.IsEnabled(LogTypeInfo) {
logger.Log(CallerName(), LogTypeInfo, fmt.Sprintf("BEGIN STACK %s\n%s\nEND STACK\n", msg, buf[:len]))
}
}
// ControllerPlugin contains dependencies to the controller that can be mocked by unit test
type ControllerPlugin struct {
dynamicClient dynamic.Interface
discoveryClient discovery.DiscoveryInterface
batchDuration time.Duration
statusFunc calculateComponentStatusFunc
}
// ClusterWatcher watches all resources for one Kube cluster
type ClusterWatcher struct {
plugin *ControllerPlugin
handlerMgr *HandlerManager
nsFilter *namespaceFilter
resourceMap map[schema.GroupVersionResource]*ResourceWatcher // all resources being watched
gvrsToWatch map[schema.GroupVersionResource]bool // set of gvrs to watch for resources
apiVersionKindToGVR sync.Map
groupKindToGVR sync.Map
csvOwners sync.Map // map from a GVR to the CSVs that own the GVR's CRD
csvMutex sync.Mutex
statusPrecedence []string // array of status precedence
unknownStatus string // value of unkown status
namespaces map[string]string
resourceChannel *resourceChannel // channel to send application updates
mutex sync.Mutex
}
// OwnedCRDInfo contains info about a CRD that is
// owned by at least one ClusterServiceVersion (CSV).
// It contains the gvr and name of the CRD resource
// a set of GVRs/names of the CSVs that own the CRD
type OwnedCRDInfo struct {
// crdGVR schema.GroupVersionResource // GVR of the CRD
crdName string // name of the CRD
csvs map[CSVInfo]CSVInfo // set of CSVs that own the CRD
}
// CSVInfo contains the gvr and name of a CSV resource
type CSVInfo struct {
csvGVR schema.GroupVersionResource
csvName string
}
// NewClusterWatcher creates a new ClusterWatcher
func NewClusterWatcher(controllerPlugin *ControllerPlugin) (*ClusterWatcher, error) {
var resController = &ClusterWatcher{}
resController.plugin = controllerPlugin
resController.handlerMgr = newHandlerManager()
resController.nsFilter = newNamespaceFilter()
resController.gvrsToWatch = make(map[schema.GroupVersionResource]bool, 50)
resController.resourceMap = make(map[schema.GroupVersionResource]*ResourceWatcher, 50)
var err error
resController.statusPrecedence, resController.unknownStatus, resController.namespaces, err =
fetchDataFromConfigMap(controllerPlugin.dynamicClient)
if err != nil {
return nil, err
}
// init list of all resources
err = resController.initResourceMap()
if err != nil {
return nil, err
}
// start batchStore to unprocessed resource changes
resController.resourceChannel = newResourceChannel()
batchStore := newBatchStore(resController, controllerPlugin.batchDuration)
go batchStore.run()
// start watch CRD
gvr, ok := resController.getWatchGVR(coreCustomResourceDefinitionGVR)
if !ok {
if logger.IsEnabled(LogTypeExit) {
logger.Log(CallerName(), LogTypeExit, fmt.Sprintf("Error getting GVR: %s, returning nil", coreCustomResourceDefinitionGVR))
}
return nil, nil
}
err = resController.AddToWatch(gvr)
if err != nil {
if logger.IsEnabled(LogTypeExit) {
logger.Log(CallerName(), LogTypeExit, fmt.Sprintf("Error adding GVR: %s to watch, returning nil", coreCustomResourceDefinitionGVR))
}
return nil, err
}
if logger.IsEnabled(LogTypeExit) {
logger.Log(CallerName(), LogTypeExit, "Exit success")
}
return resController, nil
}
func getkAppNavNamespace() string {
ns := os.Getenv("KAPPNAV_CONFIG_NAMESPACE")
if ns == "" {
ns = defaultkAppNavNamespace
}
return ns
}
// fetchDataFromConfigMap gets status precedence, unknown status, and application namespaces from ConfigMap Kubernetes
func fetchDataFromConfigMap(dynInterf dynamic.Interface) ([]string, string, map[string]string, error) {
gvr := schema.GroupVersionResource{
Group: "",
Version: V1,
Resource: CONFIGMAPS,
}
var intfNoNS = dynInterf.Resource(gvr)
var intf dynamic.ResourceInterface
intf = intfNoNS.Namespace(getkAppNavNamespace())
// fetch the current resource
var unstructuredObj *unstructured.Unstructured
var err error
unstructuredObj, err = intf.Get(kappnavConfig, metav1.GetOptions{})
if err != nil {
return nil, "", nil, err
}
var objMap = unstructuredObj.Object
dataMap, ok := objMap["data"].(map[string]interface{})
if !ok {
return nil, "", nil, fmt.Errorf("Configmap kappnav-config does not not contain \"data\" property")
}
unknownStatObj, ok := dataMap[statusUnknown]
if !ok {
return nil, "", nil, fmt.Errorf("Configmap kappnav-config does not contain status-unknown property")
}
unknownStat, ok := unknownStatObj.(string)
if !ok {
return nil, "", nil, fmt.Errorf("Configmap kappnav-config status-unknown not a string")
}
appStatPreced, ok := dataMap[appStatusPrecedence]
if !ok {
return nil, "", nil, fmt.Errorf("Configmap kappnav-config does not contain app-status-precedence property")
}
statusPrecedence, ok := appStatPreced.(string)
if !ok {
return nil, "", nil, fmt.Errorf("Configmap kappnav-config app-status-precedence not a JSON array")
}
ret, err := jsonToArrayOfString(statusPrecedence)
if err != nil {
return nil, "", nil, fmt.Errorf("In ConfigMap kappnav-config, the value of app-status-precedence not valid JSON: %s, parsing error: %s", statusPrecedence, err)
}
namespaces := make(map[string]string)
appNamespaces, ok := dataMap[appNamespaces]
if ok {
appNamespacesStr, ok := appNamespaces.(string)
if !ok {
return nil, "", nil, fmt.Errorf("Configmap kappnav-config app-namespaces is not a string")
}
namespaces = stringToNamespaceSet(appNamespacesStr)
}
return ret, unknownStat, namespaces, nil
}
func jsonToArrayOfString(str string) ([]string, error) {
bytes := []byte(str)
var interf interface{}
err := json.Unmarshal(bytes, &interf)
if err != nil {
return nil, err
}
var objArray []interface{}
objArray, ok := interf.([]interface{})
if !ok {
return nil, fmt.Errorf("value is not an array")
}
ret := make([]string, 0, len(objArray))
for _, val := range objArray {
tmp, ok := val.(string)
if !ok {
return nil, fmt.Errorf("value is not an array of string")
}
ret = append(ret, tmp)
}
return ret, nil
}
// Get cached status precedence
func (resController *ClusterWatcher) getStatusPrecedence() []string {
return resController.statusPrecedence
}
// Return true if a gvr is namespaced
func (resController *ClusterWatcher) isNamespaced(gvr schema.GroupVersionResource) bool {
if logger.IsEnabled(LogTypeEntry) {
logger.Log(CallerName(), LogTypeEntry, fmt.Sprintf("%s", gvr))
}
resController.mutex.Lock()
defer resController.mutex.Unlock()
ret := false
if rw := resController.resourceMap[gvr]; rw != nil {
ret = rw.namespaced
} else {
// TODO: in theory checking whether a reousrce is namespaced
// when resource doesn't exist shouldn't happen
}
if logger.IsEnabled(LogTypeExit) {
logger.Log(CallerName(), LogTypeExit, fmt.Sprintf("%s: %t", gvr, ret))
}
return ret
}
// isNamespacePermitted returns true if resources in given namespace are allowed in this kappnav instance
func (resController *ClusterWatcher) isNamespacePermitted(namespace string) bool {
if logger.IsEnabled(LogTypeEntry) {
logger.Log(CallerName(), LogTypeEntry, fmt.Sprintf("%s", namespace))
}
var ret = false
if len(resController.namespaces) == 0 {
// No namespaces means all resources
ret = true
} else if _, ok := resController.namespaces[namespace]; ok {
// Namespace must be in kappnav-config Configmap app-namespaces
ret = true
}
if logger.IsEnabled(LogTypeExit) {
logger.Log(CallerName(), LogTypeExit, fmt.Sprintf("%s: %t", namespace, ret))
}
return ret
}
// isEventPermitted returns true if the event object namespace is allowed in this kappnav instance
func (resController *ClusterWatcher) isEventPermitted(eventData *eventHandlerData) bool {
var ret = false
namespace, ok := getNamespace(eventData.obj)
if ok {
ret = resController.isNamespacePermitted(namespace)
} else {
ret = true
}
if logger.IsEnabled(LogTypeDebug) {
logger.Log(CallerName(), LogTypeDebug, fmt.Sprintf("gvr: %s key: %s: return: %t", eventData.gvr, eventData.key, ret))
}
return ret
}
// isAllNamespacesPermitted returns true if resources in all namespaces are allowed in this kappnav instance
func (resController *ClusterWatcher) isAllNamespacesPermitted() bool {
if logger.IsEnabled(LogTypeEntry) {
logger.Log(CallerName(), LogTypeEntry, "")
}
var ret = len(resController.namespaces) == 0
if logger.IsEnabled(LogTypeExit) {
logger.Log(CallerName(), LogTypeExit, fmt.Sprintf("%t:", ret))
}
return ret
}
// AddToWatch adds a GVR to the watch list
func (resController *ClusterWatcher) AddToWatch(gvr schema.GroupVersionResource) error {
if logger.IsEnabled(LogTypeInfo) {
logger.Log(CallerName(), LogTypeInfo, fmt.Sprintf(" %s\n", gvr))
}
resController.mutex.Lock()
resController.gvrsToWatch[gvr] = true
resController.mutex.Unlock()
// start watching this GVR
return resController.startWatch(gvr)
}
// ResourceWatcher stores information about one GVR being watched.
// In client-go, each GVR has its own cache.
type ResourceWatcher struct {
schema.GroupVersionResource
kind string
namespaced bool // true if resource has namespace
subResources map[string]string // all the sub resources, e.g., "status"
store cache.Store
controller cache.Controller
indexer cache.Indexer
queue workqueue.RateLimitingInterface // queued up events on resources
stopCh chan struct{} // channel to stop the controller for this resource
// handler *cache.ResourceEventHandlerFuncs
// handler *resourceActionFunc // callback
}
// Callback function to be implemeted
type resourceActionFunc func(resController *ClusterWatcher, rw *ResourceWatcher, eventData *eventHandlerData) error
// process next item on the queue. Return false if queue is closed
func processNextItem(resController *ClusterWatcher, watcher *ResourceWatcher /*, handler *resourceActionFunc*/) bool {
// Wait until there is a new item in the queue
tmp, quit := watcher.queue.Get()
if quit {
if logger.IsEnabled(LogTypeInfo) {
logger.Log(CallerName(), LogTypeInfo, fmt.Sprintf("queue for GVR %s closed", watcher.GroupVersionResource))
}
return false
}
defer watcher.queue.Done(tmp)
handlerData := tmp.(*eventHandlerData)
if logger.IsEnabled(LogTypeDebug) {
logger.Log(CallerName(), LogTypeDebug, fmt.Sprintf("processing %s, GVR %s from queue", handlerData.key, watcher.GroupVersionResource))
}
// call handler to process the data
// err := (*handler)(resController, watcher, handlerData)
err := resController.handlerMgr.callHandlers(watcher.GroupVersionResource, resController, watcher, handlerData)
handleError(watcher, err, handlerData)
return true
}
// Handle potential error when processing resource from the queue
func handleError(watcher *ResourceWatcher, err error, handlerData *eventHandlerData) {
if err == nil {
// no error
watcher.queue.Forget(handlerData)
return
}
if watcher.queue.NumRequeues(handlerData) < retryLimit {
// requeue for retry
if logger.IsEnabled(LogTypeError) {
logger.Log(CallerName(), LogTypeError, fmt.Sprintf("Error processing %v: %v. Requeueing", handlerData.key, err))
}
watcher.queue.AddRateLimited(handlerData)
return
}
// reached limit on retry
watcher.queue.Forget(handlerData)
utilruntime.HandleError(fmt.Errorf("Retry limit reached. Unable to process %q due to error %v", handlerData.key, err))
}
// getWatchGVRForKind gets the currently watched GVR for a core kind
func (resController *ClusterWatcher) getWatchGVRForKind(kind string) (schema.GroupVersionResource, bool) {
gvr, ok := coreKindToGVR[kind]
if !ok {
if logger.IsEnabled(LogTypeInfo) {
logger.Log(CallerName(), LogTypeInfo, fmt.Sprintf("kind: %s is not a core kappnav kind", kind))
}
return schema.GroupVersionResource{}, false
}
return resController.getWatchGVR(gvr)
}
// getWatchGVR gets the GVR from the resourceWatcher. It returns false if there is no resourceWatcher
// or the input GVR is different from the watched GVR
func (resController *ClusterWatcher) getWatchGVR(gvr schema.GroupVersionResource) (schema.GroupVersionResource, bool) {
resController.mutex.Lock()
rw, ok := resController.resourceMap[gvr]
resController.mutex.Unlock()
if ok {
if rw.GroupVersionResource != gvr {
if logger.IsEnabled(LogTypeDebug) {
logger.Log(CallerName(), LogTypeDebug, fmt.Sprintf("Watched GVR: %s different from input GVR: %s", rw.GroupVersionResource, gvr))
}
}
return rw.GroupVersionResource, true
}
if logger.IsEnabled(LogTypeExit) {
logger.Log(CallerName(), LogTypeExit, fmt.Sprintf("GVR: %s not found in resourceMap returning false", gvr))
}
return schema.GroupVersionResource{}, false
}
func (resController *ClusterWatcher) getGVRsForGroupKind(group string, kind string) (map[schema.GroupVersionResource]schema.GroupVersionResource, string, bool) {
// map group/kind to apiVersion
groupKind := group + "/" + kind
if logger.IsEnabled(LogTypeEntry) {
logger.Log(CallerName(), LogTypeEntry, fmt.Sprintf("Trying group/Kind: %s", groupKind))
}
gvrs, ok := resController.groupKindToGVR.Load(groupKind)
if ok {
if logger.IsEnabled(LogTypeDebug) {
logger.Log(CallerName(), LogTypeDebug, fmt.Sprintf("getGVRsForGroupKind for group: %s kind: %s returning GVRs: %v", group, kind, gvrs.(map[schema.GroupVersionResource]schema.GroupVersionResource)))
}
return gvrs.(map[schema.GroupVersionResource]schema.GroupVersionResource), group, true
}
if logger.IsEnabled(LogTypeWarning) {
logger.Log(CallerName(), LogTypeWarning, "No CRD found with group: "+group+" for kind: "+kind)
}
// no CRDs installed with the specified group/kind
// See if it's one of the core kinds for compatibility
gvr, ok := coreKindToGVR[kind]
if ok {
if logger.IsEnabled(LogTypeDebug) {
logger.Log(CallerName(), LogTypeDebug, fmt.Sprintf("Returning default GVR for group: %s kind: %s GVRs: %v", group, kind, gvr))
}
gvrSet := make(map[schema.GroupVersionResource]schema.GroupVersionResource, 1)
gvrSet[gvr] = gvr
return gvrSet, gvr.Group, true
}
if logger.IsEnabled(LogTypeExit) {
logger.Log(CallerName(), LogTypeExit, fmt.Sprintf("Returning false - no CRD found for group: %s kind: %s", group, kind))
}
return nil, "", false
}
// get resource watcher
func (resController *ClusterWatcher) getResourceWatcher(gvr schema.GroupVersionResource) *ResourceWatcher {
resController.mutex.Lock()
defer resController.mutex.Unlock()
return resController.resourceMap[gvr]
}
// list resources for a gvr. Return empty array if resource is not being watched.
func (resController *ClusterWatcher) listResources(gvr schema.GroupVersionResource) []interface{} {
resController.mutex.Lock()
rw, ok := resController.resourceMap[gvr]
resController.mutex.Unlock()
if ok && rw.store != nil {
return rw.store.List()
}
return make([]interface{}, 0)
}
// Get a resource from the cache
// Return:
// pionter to resource
// true if resource exists
// error ecountered to get the resource
func (resController *ClusterWatcher) getResource(gvr schema.GroupVersionResource, namespace string, name string) (interface{}, bool, error) {
resController.mutex.Lock()
rw, ok := resController.resourceMap[gvr]
var store cache.Store
if ok {
store = rw.store
}
resController.mutex.Unlock()
if ok && store != nil {
key := name
if namespace != "" {
key = namespace + "/" + key
}
return store.GetByKey(key)
}
return nil, false, fmt.Errorf("Unable to find resources %s %s %s", gvr, namespace, name)
}
// add a new entry to resource map
func (resController *ClusterWatcher) addResourceMapEntry(kind string, group string, version string, plural string, namespaced bool) {
if logger.IsEnabled(LogTypeEntry) {
logger.Log(CallerName(), LogTypeEntry, fmt.Sprintf("resource kind: %s, group: %s, version: %s, plural: %s namespaced: %t", logString(kind), logString(group), logString(version), logString(plural), namespaced))
}
var subResource string
if strings.Contains(plural, "/") {
split := strings.Split(plural, "/")
plural = split[0]
subResource = split[1]
}
resController.mutex.Lock()
gvr := schema.GroupVersionResource{Group: group, Version: version, Resource: plural}
rw, ok := resController.resourceMap[gvr]
if !ok {
// create new entry
rw = &ResourceWatcher{}
resController.resourceMap[gvr] = rw
}
apiVersionKind := version + "/" + kind
if group != "" {
apiVersionKind = group + "/" + apiVersionKind
groupKind := group + "/" + kind
gvrSet, ok := resController.groupKindToGVR.Load(groupKind)
if !ok {
gvrSet = make(map[schema.GroupVersionResource]schema.GroupVersionResource, 10)
}
gvrSet.(map[schema.GroupVersionResource]schema.GroupVersionResource)[gvr] = gvr
resController.groupKindToGVR.Store(groupKind, gvrSet)
}
if logger.IsEnabled(LogTypeInfo) {
logger.Log(CallerName(), LogTypeInfo, fmt.Sprintf("Mapping apiVersion/Kind: %s to GVR: %v", apiVersionKind, gvr))
}
resController.apiVersionKindToGVR.Store(apiVersionKind, gvr)
rw.Group = group
rw.Version = version
rw.Resource = plural
rw.kind = kind
rw.namespaced = namespaced
rw.subResources = map[string]string{}
if subResource != "" {
// just store subresource
rw.subResources[subResource] = subResource
resController.mutex.Unlock()
} else {
// Watch the resource if it should be watched
resController.mutex.Unlock()
resController.restartWatch(rw.GroupVersionResource)
if rw.GroupVersionResource == coreClusterServiceVersionGVR {
resController.initCSVOperationActions()
}
}
if logger.IsEnabled(LogTypeExit) {
logger.Log(CallerName(), LogTypeExit, "")
}
}
// Delete a resource map entry, when the resource definition is deleted
func (resController *ClusterWatcher) deleteResourceMapEntry(gvr schema.GroupVersionResource, kind string) {
resController.stopWatch(gvr)
resController.mutex.Lock()
defer resController.mutex.Unlock()
_, ok := resController.resourceMap[gvr]
if ok {
// can be deleted
delete(resController.resourceMap, gvr)
}
apiVersionKind := gvr.Version + "/" + kind
if gvr.Group != "" {
apiVersionKind = gvr.Group + "/" + apiVersionKind
groupKind := gvr.Group + "/" + kind
// don't delete an existing group/kind map entry for a different GVR (i.e. with a different version)
delete := true
existingGvr, ok := resController.groupKindToGVR.Load(groupKind)
if ok {
if ok && existingGvr != gvr {
if logger.IsEnabled(LogTypeInfo) {
logger.Log(CallerName(), LogTypeInfo, fmt.Sprintf("group/Kind map GVR: %s is not the GVR to be deleted: %s", existingGvr, gvr))
}
delete = false
}
}
if delete == true {
if logger.IsEnabled(LogTypeInfo) {
logger.Log(CallerName(), LogTypeInfo, fmt.Sprintf("Deleting group/Kind: %s for GVR: %s", groupKind, gvr))
}
resController.groupKindToGVR.Delete(apiVersionKind)
}
}
if logger.IsEnabled(LogTypeExit) {
logger.Log(CallerName(), LogTypeExit, fmt.Sprintf("Deleting apiVersion/Kind: %s for GVR: %s", apiVersionKind, gvr))
}
resController.apiVersionKindToGVR.Delete(apiVersionKind)
}
// print a resourceMapEntry
func (resController *ClusterWatcher) printResourceMapEntry(gvr schema.GroupVersionResource) {
resController.mutex.Lock()
rw, ok := resController.resourceMap[gvr]
var store cache.Store
if ok {
store = rw.store
}
resController.mutex.Unlock()
if ok {
keys := store.ListKeys()
if logger.IsEnabled(LogTypeInfo) {
logger.Log(CallerName(), LogTypeInfo, fmt.Sprintf("gvr %s\n", gvr))
logger.Log(CallerName(), LogTypeInfo, fmt.Sprintf(" keys: %s\n", keys))
}
} else {
if logger.IsEnabled(LogTypeInfo) {
logger.Log(CallerName(), LogTypeInfo, fmt.Sprintf("gvr %s not found in resourceMap\n", gvr))
}
}
}
func printAPIGroupList(list *metav1.APIGroupList) {
if logger.IsEnabled(LogTypeEntry) {
logger.Log(CallerName(), LogTypeEntry, "")
}
if logger.IsEnabled(LogTypeInfo) {
logger.Log(CallerName(), LogTypeInfo, fmt.Sprintf(" kind: %s, APIVersion %s\n", list.Kind, list.APIVersion))
}
for index, group := range list.Groups {
if logger.IsEnabled(LogTypeInfo) {
logger.Log(CallerName(), LogTypeInfo, fmt.Sprintf(" %d kind: %s APIVersion %s Name %s\n", index, group.Kind, group.APIVersion, group.Name))
}
for _, version := range group.Versions {
if logger.IsEnabled(LogTypeInfo) {
logger.Log(CallerName(), LogTypeInfo, fmt.Sprintf(" groupVersion: %s, version: %s\n", version.GroupVersion, version.Version))
}
}
}
if logger.IsEnabled(LogTypeExit) {
logger.Log(CallerName(), LogTypeExit, "")
}
}
/* Initialize list of resource group/api/version */
func (resController *ClusterWatcher) initResourceMap() error {
if logger.IsEnabled(LogTypeEntry) {
logger.Log(CallerName(), LogTypeEntry, "")
}
var discClient = resController.plugin.discoveryClient
var apiGroups *metav1.APIGroupList
apiGroups, err := discClient.ServerGroups()
if err != nil {
return err
}
printAPIGroupList(apiGroups)
var groups = apiGroups.Groups
var group metav1.APIGroup
for _, group = range groups {
// kube 1.16 / OCP 4.3 added apiextensions.k8s.io/v1
// so can no longer use only the preferred version.
if group.Name == "apiextensions.k8s.io" {
for i := 0; i < len(group.Versions); i++ {
if logger.IsEnabled(LogTypeInfo) {
logger.Log(CallerName(), LogTypeInfo, fmt.Sprintf("Processing apiextensions.k8s.io GroupVersion %s", group.Versions[i].GroupVersion))
}
resController.processResourceGroup(group.Versions[i].GroupVersion, discClient)
}
} else {
resController.processResourceGroup(group.PreferredVersion.GroupVersion, discClient)
}
}
if logger.IsEnabled(LogTypeExit) {
logger.Log(CallerName(), LogTypeExit, "")
}
return nil
}
func (resController *ClusterWatcher) processResourceGroup(groupVersion string, discClient discovery.DiscoveryInterface) error {
apiResourceList, err := discClient.ServerResourcesForGroupVersion(groupVersion)
if err != nil {
// If this groupVersion is not available, then disregard it
if logger.IsEnabled(LogTypeError) {
logger.Log(CallerName(), LogTypeError, fmt.Sprintf("Unable to get information about APIGroup %s, skipping", groupVersion))
}
return err
}
var group string
var version string
if strings.Contains(groupVersion, "/") {
gv := strings.Split(groupVersion, "/")
group = gv[0]
version = gv[1]
} else {
group = ""
version = groupVersion
}
for _, apiResource := range apiResourceList.APIResources {
var plural = apiResource.Name
resController.addResourceMapEntry(apiResource.Kind, group, version, plural, apiResource.Namespaced)
}
return nil
}
/* Resource events to be queued */
type eventHandlerFuncType int
const (
// AddFunc - function type for resource add events
AddFunc eventHandlerFuncType = iota
// UpdateFunc - function type for resource update events
UpdateFunc
// DeleteFunc - function type for resource delete events
DeleteFunc
)
type eventHandlerData struct {
funcType eventHandlerFuncType
kind string
gvr schema.GroupVersionResource
key string
obj interface{}
oldObj interface{} // for UpdateFunc
}
// Start watch on a GVR, if it should be watched, and not already being watched
// Otherwise, noop
func (resController *ClusterWatcher) startWatch(inputGVR schema.GroupVersionResource) error {
if logger.IsEnabled(LogTypeEntry) {
logger.Log(CallerName(), LogTypeEntry, fmt.Sprintf("Entry group: %s version: %s resource: %s\n groupversion: %s groupresource: %s", inputGVR.Group, inputGVR.Version, inputGVR.Resource, inputGVR.GroupVersion(), inputGVR.GroupResource()))
}
resController.mutex.Lock()
defer resController.mutex.Unlock()
var gvr = inputGVR // will be used by the ResourceEventHanderFuncs below
// not ready to watch this GVR
if !resController.gvrsToWatch[gvr] {
if logger.IsEnabled(LogTypeDebug) {
logger.Log(CallerName(), LogTypeDebug, "Returning nil, no gvrsToWatch")
}
return nil
}
rw, ok := resController.resourceMap[gvr]
if !ok {
// no entry for this resource GVR yet
if logger.IsEnabled(LogTypeDebug) {