/
worker.go
4221 lines (3919 loc) · 139 KB
/
worker.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 (c) 2016-2021, F5 Networks, Inc.
*
* 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 controller
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"github.com/F5Networks/k8s-bigip-ctlr/v3/pkg/clustermanager"
"github.com/F5Networks/k8s-bigip-ctlr/v3/pkg/ipmanager"
"github.com/F5Networks/k8s-bigip-ctlr/v3/pkg/prometheus"
listerscorev1 "k8s.io/client-go/listers/core/v1"
"k8s.io/client-go/tools/cache"
"os"
"reflect"
"slices"
"sort"
"strings"
"time"
"k8s.io/apimachinery/pkg/util/intstr"
ficV1 "github.com/F5Networks/f5-ipam-controller/pkg/ipamapis/apis/fic/v1"
cisapiv1 "github.com/F5Networks/k8s-bigip-ctlr/v3/config/apis/cis/v1"
log "github.com/F5Networks/k8s-bigip-ctlr/v3/pkg/vlogger"
routeapi "github.com/openshift/api/route/v1"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
)
// nextGenResourceWorker starts the Custom Resource Worker.
func (ctlr *Controller) nextGenResourceWorker() {
log.Debugf("Starting resource worker")
ctlr.setInitialResourceCount()
// process the DeployConfig CR if present
if ctlr.CISConfigCRKey != "" {
ctlr.processGlobalDeployConfigCR()
}
// when CIS is running in the secondary mode then enable health probe on the primary cluster
if ctlr.multiClusterMode == SecondaryCIS {
ctlr.firstPollPrimaryClusterHealthStatus()
go ctlr.probePrimaryClusterHealthStatus()
}
// process static routes after DeployConfig CR if present is processed to support external cluster static routes during cis init
ctlr.processStaticRouteUpdate()
log.Infof("Started Controller")
for ctlr.processResources() {
}
}
func (ctlr *Controller) setInitialResourceCount() {
var rscCount int
for _, ns := range ctlr.getWatchingNamespaces() {
if ctlr.managedResources.ManageRoutes {
nrInf, found := ctlr.getNamespacedNativeInformer(ns)
if !found {
continue
}
routes, err := nrInf.routeInformer.GetIndexer().ByIndex("namespace", ns)
if err != nil {
continue
}
rscCount += len(routes)
}
if ctlr.managedResources.ManageCustomResources {
crInf, found := ctlr.getNamespacedCRInformer(ns)
if !found {
continue
}
if ctlr.managedResources.ManageVirtualServer {
vs, err := crInf.vsInformer.GetIndexer().ByIndex("namespace", ns)
if err != nil {
continue
}
rscCount += len(vs)
}
if ctlr.managedResources.ManageTransportServer {
ts, err := crInf.tsInformer.GetIndexer().ByIndex("namespace", ns)
if err != nil {
continue
}
rscCount += len(ts)
}
if ctlr.managedResources.ManageIL {
il, err := crInf.ilInformer.GetIndexer().ByIndex("namespace", ns)
if err != nil {
continue
}
rscCount += len(il)
}
if ctlr.managedResources.ManageEDNS {
if comInf, ok := ctlr.comInformers[ns]; ok {
edns, err := comInf.ednsInformer.GetIndexer().ByIndex("namespace", ns)
if err != nil {
continue
}
rscCount += len(edns)
}
}
}
comInf, found := ctlr.getNamespacedCommonInformer(ns)
if !found {
continue
}
services, err := comInf.svcInformer.GetIndexer().ByIndex("namespace", ns)
if err != nil {
continue
}
for _, obj := range services {
svc := obj.(*v1.Service)
if _, ok := K8SCoreServices[svc.Name]; ok {
continue
}
if ctlr.managedResources.ManageRoutes {
if _, ok := OSCPCoreServices[svc.Name]; ok {
continue
}
}
//if svc.Spec.Type == v1.ServiceTypeLoadBalancer {
// rscCount++
//}
}
}
ctlr.initialResourceCount = rscCount
}
// processResources gets resources from the resourceQueue and processes the resource
// depending on its kind.
func (ctlr *Controller) processResources() bool {
key, quit := ctlr.resourceQueue.Get()
if quit {
// The controller is shutting down.
log.Debugf("Resource Queue is empty, Going to StandBy Mode")
return false
}
var isRetryableError bool
defer ctlr.resourceQueue.Done(key)
// If CIS resources like CRDS, routes or servicetype LB are not present
// on startup, check initalresourcecount and update initState
if ctlr.initialResourceCount <= 0 {
ctlr.initState = false
}
rKey := key.(*rqKey)
log.Debugf("Processing Key: %v", rKey)
// During Init time, just process all the resources
if ctlr.initState && rKey.kind != Namespace {
if rKey.kind == VirtualServer || rKey.kind == TransportServer || rKey.kind == Service ||
rKey.kind == IngressLink || rKey.kind == Route || rKey.kind == ExternalDNS {
if rKey.kind == Service {
//if svc, ok := rKey.rsc.(*v1.Service); ok {
// if svc.Spec.Type == v1.ServiceTypeLoadBalancer {
// ctlr.initialResourceCount--
// } else {
// // return as we don't process other services at start up
// return true
// }
//}
return true
} else {
ctlr.initialResourceCount--
}
if ctlr.initialResourceCount <= 0 {
ctlr.initState = false
}
} else {
return true
}
}
rscDelete := false
if rKey.event == Delete {
rscDelete = true
}
// Check the type of resource and process accordingly.
switch rKey.kind {
case Route:
if !ctlr.managedResources.ManageRoutes {
break
}
route := rKey.rsc.(*routeapi.Route)
// processRoutes knows when to delete a VS (in the event of global config update and route delete)
// so should not trigger delete from here
resourceKey := resourceRef{
kind: Route,
namespace: route.Namespace,
name: route.Name,
}
if rKey.event == Create {
if _, ok := ctlr.resources.processedNativeResources[resourceKey]; ok {
break
}
}
if rscDelete {
delete(ctlr.resources.processedNativeResources, resourceKey)
// Delete the route entry from hostPath Map
ctlr.deleteHostPathMapEntry(route)
}
if rKey.event != Create {
// update the poolMem cache, clusterSvcResource & resource-svc maps
ctlr.deleteResourceExternalClusterSvcRouteReference(resourceKey)
}
if routeGroup, ok := ctlr.resources.invertedNamespaceLabelMap[route.Namespace]; ok {
err := ctlr.processRoutes(routeGroup, false)
if err != nil {
// TODO
utilruntime.HandleError(fmt.Errorf("Sync %v failed with %v", key, err))
isRetryableError = true
}
}
if rKey.event != Create && ctlr.multiClusterMode != "" {
ctlr.deleteUnrefereedMultiClusterInformers()
}
case ConfigCR:
cm := rKey.rsc.(*cisapiv1.DeployConfig)
err, ok := ctlr.processConfigCR(cm, rscDelete)
if err != nil {
utilruntime.HandleError(fmt.Errorf("[ERROR] Sync %v failed with %v", key, err))
break
}
if !ok {
isRetryableError = true
}
case VirtualServer:
if !ctlr.managedResources.ManageCustomResources {
break
}
virtual := rKey.rsc.(*cisapiv1.VirtualServer)
rscRefKey := resourceRef{
kind: VirtualServer,
name: virtual.Name,
namespace: virtual.Namespace,
}
if _, ok := ctlr.resources.processedNativeResources[rscRefKey]; ok {
if rKey.event == Create {
break
}
if rKey.event == Delete {
delete(ctlr.resources.processedNativeResources, rscRefKey)
}
}
if rKey.event != Create {
// update the poolMem cache, clusterSvcResource & resource-svc maps
ctlr.deleteResourceExternalClusterSvcRouteReference(rscRefKey)
}
err := ctlr.processVirtualServers(virtual, rscDelete)
if err != nil {
// TODO
utilruntime.HandleError(fmt.Errorf("Sync %v failed with %v", key, err))
isRetryableError = true
}
if rKey.event != Create && ctlr.multiClusterMode != "" {
ctlr.deleteUnrefereedMultiClusterInformers()
}
case TLSProfile:
if !ctlr.managedResources.ManageCustomResources {
break
}
tlsProfile := rKey.rsc.(*cisapiv1.TLSProfile)
virtuals := ctlr.getVirtualsForTLSProfile(tlsProfile)
// No Virtuals are effected with the change in TLSProfile.
if nil == virtuals {
break
}
for _, virtual := range virtuals {
err := ctlr.processVirtualServers(virtual, false)
if err != nil {
// TODO
utilruntime.HandleError(fmt.Errorf("Sync %v failed with %v", key, err))
isRetryableError = true
}
}
case K8sSecret:
secret := rKey.rsc.(*v1.Secret)
mcc := ctlr.getClusterForSecret(secret)
// TODO: Process all the resources again that refer to any resource running in the affected cluster?
if mcc != (cisapiv1.ExternalClusterConfig{}) {
err := ctlr.updateClusterConfigStore(secret, mcc, rscDelete)
if err != nil {
log.Warningf(err.Error())
}
break
}
if ctlr.managedResources.ManageRoutes {
routeGroup := ctlr.getRouteGroupForSecret(secret)
if routeGroup != "" {
_ = ctlr.processRoutes(routeGroup, false)
}
}
if ctlr.managedResources.ManageCustomResources {
tlsProfiles := ctlr.getTLSProfilesForSecret(secret)
for _, tlsProfile := range tlsProfiles {
virtuals := ctlr.getVirtualsForTLSProfile(tlsProfile)
// No Virtuals are effected with the change in TLSProfile.
if nil == virtuals {
break
}
for _, virtual := range virtuals {
err := ctlr.processVirtualServers(virtual, false)
if err != nil {
// TODO
utilruntime.HandleError(fmt.Errorf("Sync %v failed with %v", key, err))
isRetryableError = true
}
}
}
}
case TransportServer:
if !ctlr.managedResources.ManageCustomResources {
break
}
virtual := rKey.rsc.(*cisapiv1.TransportServer)
rscRefKey := resourceRef{
kind: TransportServer,
name: virtual.Name,
namespace: virtual.Namespace,
}
if _, ok := ctlr.resources.processedNativeResources[rscRefKey]; ok {
// Skip processing for create event if already processed
if rKey.event == Create {
break
}
// Remove resource key from processedNativeResources on delete event
if rKey.event == Delete {
delete(ctlr.resources.processedNativeResources, rscRefKey)
}
}
if rKey.event != Create {
// update the poolMem cache, clusterSvcResource & resource-svc maps
ctlr.deleteResourceExternalClusterSvcRouteReference(rscRefKey)
}
err := ctlr.processTransportServers(virtual, rscDelete)
if err != nil {
// TODO
utilruntime.HandleError(fmt.Errorf("Sync %v failed with %v", key, err))
isRetryableError = true
}
if rKey.event != Create && ctlr.multiClusterMode != "" {
ctlr.deleteUnrefereedMultiClusterInformers()
}
case IngressLink:
if !ctlr.managedResources.ManageCustomResources {
break
}
ingLink := rKey.rsc.(*cisapiv1.IngressLink)
log.Infof("Worker got IngressLink: %v\n", ingLink)
log.Infof("IngressLink Selector: %v\n", ingLink.Spec.Selector.String())
if rKey.event != Create {
rsRef := resourceRef{
name: ingLink.Name,
namespace: ingLink.Namespace,
kind: IngressLink,
}
// clean the CIS cache
ctlr.deleteResourceExternalClusterSvcRouteReference(rsRef)
}
err := ctlr.processIngressLink(ingLink, rscDelete)
if err != nil {
// TODO
utilruntime.HandleError(fmt.Errorf("Sync %v failed with %v", key, err))
isRetryableError = true
}
case ExternalDNS:
if !ctlr.managedResources.ManageRoutes && !ctlr.managedResources.ManageCustomResources {
break
}
edns := rKey.rsc.(*cisapiv1.ExternalDNS)
ctlr.processExternalDNS(edns, rscDelete)
case IPAM:
ipam := rKey.rsc.(*ficV1.IPAM)
ctlr.processIPAM(ipam)
case CustomPolicy:
cp := rKey.rsc.(*cisapiv1.Policy)
if ctlr.managedResources.ManageRoutes {
routeGroups := ctlr.getRouteGroupForCustomPolicy(cp.Namespace + "/" + cp.Name)
for _, routeGroup := range routeGroups {
_ = ctlr.processRoutes(routeGroup, false)
}
}
if ctlr.managedResources.ManageCustomResources {
virtuals := ctlr.getVirtualsForCustomPolicy(cp)
//Sync Custompolicy for Virtual Servers
for _, virtual := range virtuals {
err := ctlr.processVirtualServers(virtual, false)
if err != nil {
// TODO
utilruntime.HandleError(fmt.Errorf("Sync %v failed with %v", key, err))
isRetryableError = true
}
}
//Sync Custompolicy for Transport Servers
tsVirtuals := ctlr.getTransportServersForCustomPolicy(cp)
for _, virtual := range tsVirtuals {
err := ctlr.processTransportServers(virtual, false)
if err != nil {
// TODO
utilruntime.HandleError(fmt.Errorf("Sync %v failed with %v", key, err))
isRetryableError = true
}
}
//Sync Custompolicy for Services of type LB
lbServices := ctlr.getLBServicesForCustomPolicy(cp)
for _, lbService := range lbServices {
err := ctlr.processLBServices(lbService, false)
if err != nil {
// TODO
utilruntime.HandleError(fmt.Errorf("Sync %v failed with %v", key, err))
isRetryableError = true
}
}
}
case Service:
svc := rKey.rsc.(*v1.Service)
svcKey := MultiClusterServiceKey{
serviceName: svc.Name,
namespace: svc.Namespace,
clusterName: rKey.clusterName,
}
if svc.Spec.Type == v1.ServiceTypeLoadBalancer {
if rKey.event != Create {
rsRef := resourceRef{
name: svc.Name,
namespace: svc.Namespace,
kind: Service,
}
// clean the CIS cache
ctlr.deleteResourceExternalClusterSvcRouteReference(rsRef)
}
err := ctlr.processLBServices(svc, rscDelete)
if err != nil {
// TODO
utilruntime.HandleError(fmt.Errorf("Sync %v failed with %v", key, err))
isRetryableError = true
}
}
// Don't process the service as it's not used by any resource
if _, ok := ctlr.resources.poolMemCache[svcKey]; !ok {
log.Debugf("Skipping service '%v' as it's not used by any CIS monitored resource", svcKey)
break
}
_ = ctlr.processService(svc, rKey.clusterName)
// Update the poolMembers for affected resources
ctlr.updatePoolMembersForService(svcKey, rKey.svcPortUpdated)
case Endpoints:
ep := rKey.rsc.(*v1.Endpoints)
svc := ctlr.getServiceForEndpoints(ep, rKey.clusterName)
// No Services are effected with the change in service.
if nil == svc {
break
}
svcKey := MultiClusterServiceKey{
serviceName: svc.Name,
namespace: svc.Namespace,
clusterName: rKey.clusterName,
}
// Don't process the service as it's not used by any resource
if _, ok := ctlr.resources.poolMemCache[svcKey]; !ok {
log.Debugf("Skipping endpoint '%v/%v' as it's not used by any CIS monitored resource", ep.Namespace, ep.Name)
break
}
_ = ctlr.processService(svc, rKey.clusterName)
if svc.Spec.Type == v1.ServiceTypeLoadBalancer {
err := ctlr.processLBServices(svc, rscDelete)
if err != nil {
// TODO
utilruntime.HandleError(fmt.Errorf("Sync %v failed with %v", key, err))
isRetryableError = true
}
}
// Just update the endpoints instead of processing them entirely
ctlr.updatePoolMembersForService(svcKey, false)
case Pod:
pod := rKey.rsc.(*v1.Pod)
_ = ctlr.processPod(pod, rscDelete)
svc := ctlr.GetServicesForPod(pod, rKey.clusterName)
if nil == svc {
break
}
svcKey := MultiClusterServiceKey{
serviceName: svc.Name,
namespace: svc.Namespace,
clusterName: rKey.clusterName,
}
// Don't process the service as it's not used by any resource
if _, ok := ctlr.resources.poolMemCache[svcKey]; !ok {
log.Debugf("Skipping pod '%v/%v' as it's not used by any CIS monitored resource", pod.Namespace, pod.Name)
break
}
_ = ctlr.processService(svc, rKey.clusterName)
if svc.Spec.Type == v1.ServiceTypeLoadBalancer {
err := ctlr.processLBServices(svc, rscDelete)
if err != nil {
// TODO
utilruntime.HandleError(fmt.Errorf("Sync %v failed with %v", key, err))
isRetryableError = true
}
break
}
// Update the poolMembers for affected resources
ctlr.updatePoolMembersForService(svcKey, false)
if ctlr.managedResources.ManageRoutes && rscDelete == false && ctlr.resources.baseRouteConfig.AutoMonitor != None {
ctlr.UpdatePoolHealthMonitors(svcKey)
}
case Namespace:
ns := rKey.rsc.(*v1.Namespace)
nsName := ns.ObjectMeta.Name
if ctlr.managedResources.ManageRoutes {
var triggerDelete bool
if rscDelete {
// TODO: Delete all the resource configs from the store
if nrInf, ok := ctlr.nrInformers[nsName]; ok {
nrInf.stop()
delete(ctlr.nrInformers, nsName)
}
if comInf, ok := ctlr.comInformers[nsName]; ok {
comInf.stop(nsName)
delete(ctlr.comInformers, nsName)
}
ctlr.namespacesMutex.Lock()
delete(ctlr.namespaces, nsName)
ctlr.namespacesMutex.Unlock()
log.Debugf("Removed namespace: '%v' from CIS scope", nsName)
triggerDelete = true
} else {
ctlr.namespacesMutex.Lock()
ctlr.namespaces[nsName] = true
ctlr.namespacesMutex.Unlock()
_ = ctlr.addNamespacedInformers(nsName, true)
log.Debugf("Added namespace: '%v' to CIS scope", nsName)
}
if ctlr.namespaceLabelMode {
ctlr.processGlobalDeployConfigCR()
} else {
if routeGroup, ok := ctlr.resources.invertedNamespaceLabelMap[nsName]; ok {
_ = ctlr.processRoutes(routeGroup, triggerDelete)
}
}
}
if ctlr.managedResources.ManageCustomResources {
if rscDelete {
for _, vrt := range ctlr.getAllVirtualServers(nsName) {
err := ctlr.processVirtualServers(vrt, true)
if err != nil {
// TODO
utilruntime.HandleError(fmt.Errorf("Sync %v failed with %v", key, err))
isRetryableError = true
}
}
for _, ts := range ctlr.getAllTransportServers(nsName) {
err := ctlr.processTransportServers(ts, true)
if err != nil {
// TODO
utilruntime.HandleError(fmt.Errorf("Sync %v failed with %v", key, err))
isRetryableError = true
}
}
ctlr.crInformers[nsName].stop()
delete(ctlr.crInformers, nsName)
ctlr.namespacesMutex.Lock()
delete(ctlr.namespaces, nsName)
ctlr.namespacesMutex.Unlock()
log.Debugf("Removed namespace: '%v' from CIS scope", nsName)
} else {
ctlr.namespacesMutex.Lock()
ctlr.namespaces[nsName] = true
ctlr.namespacesMutex.Unlock()
_ = ctlr.addNamespacedInformers(nsName, true)
log.Debugf("Added namespace: '%v' to CIS scope", nsName)
}
}
case HACIS:
log.Debugf("posting declaration on primary cluster down event")
case NodeUpdate:
log.Debugf("posting declaration on node update")
default:
log.Errorf("Unknown resource Kind: %v", rKey.kind)
}
if isRetryableError {
ctlr.resourceQueue.AddRateLimited(key)
} else {
ctlr.resourceQueue.Forget(key)
}
if ctlr.initState {
return true
}
if (ctlr.resourceQueue.Len() == 0) ||
(ctlr.multiClusterMode == SecondaryCIS && rKey.kind == HACIS) {
if ctlr.multiClusterMode != "" {
// only standalone CIS & Primary CIS should post the teems data
if ctlr.multiClusterMode != SecondaryCIS {
// using node informers to count the clusters as it will be available in all CNIs
// adding 1 for the current cluster
ctlr.TeemData.ClusterCount = len(ctlr.multiClusterNodeInformers) + 1
//TODO add support for teems data
// go ctlr.TeemData.PostTeemsData()
}
} else {
// In non multi-cluster mode, we should post the teems data
//TODO add support for teems data
// go ctlr.TeemData.PostTeemsData()
}
// set prometheus resource metrics
ctlr.setPrometheusResourceCount()
// Put each BIGIPConfig per bigip pair into specific requestChannel
for bigip, bigipConfig := range ctlr.resources.bigIpMap {
if (!reflect.DeepEqual(bigipConfig.ltmConfig, LTMConfig{}) || !reflect.DeepEqual(bigipConfig.gtmConfig, GTMConfig{})) && ctlr.resources.isConfigUpdated(bigip) {
for _, bigIpKey := range getBigIpList(bigip) {
config := ResourceConfigRequest{
bigIpKey: bigIpKey,
bigIpResourceConfig: bigipConfig,
poolMemberType: ctlr.PoolMemberType,
}
config.reqMeta = ctlr.enqueueReq(bigipConfig, bigIpKey)
ctlr.RequestHandler.EnqueueRequestConfig(config)
}
}
}
ctlr.initState = false
ctlr.resources.updateCaches()
}
return true
}
func getBigIpList(config cisapiv1.BigIpConfig) []BigIpKey {
var bigIpList []BigIpKey
bigIpList = append(bigIpList, BigIpKey{BigIpAddress: config.BigIpAddress, BigIpLabel: config.BigIpLabel})
return bigIpList
}
// getServiceForEndpoints returns the service associated with endpoints.
func (ctlr *Controller) getServiceForEndpoints(ep *v1.Endpoints, clusterName string) *v1.Service {
var svc interface{}
var exists bool
var err error
svcKey := fmt.Sprintf("%s/%s", ep.Namespace, ep.Name)
if clusterName == "" {
comInf, ok := ctlr.getNamespacedCommonInformer(ep.Namespace)
if !ok {
log.Errorf("Informer not found for namespace: %v", ep.Namespace)
return nil
}
svc, exists, err = comInf.svcInformer.GetIndexer().GetByKey(svcKey)
} else {
poolInf, ok := ctlr.getNamespaceMultiClusterPoolInformer(ep.Namespace, clusterName)
if !ok {
log.Errorf("[MultiCluster] Informer not found for namespace %v and cluster %v", ep.Namespace, clusterName)
return nil
}
svc, exists, err = poolInf.svcInformer.GetIndexer().GetByKey(svcKey)
}
if err != nil {
log.Infof("%v Error fetching service %v %v from the store: %v", ctlr.getMultiClusterLog(), svcKey,
getClusterLog(clusterName), err)
return nil
}
if !exists {
log.Infof("%v Service %v %v doesn't exist", ctlr.getMultiClusterLog(), svcKey, getClusterLog(clusterName))
return nil
}
return svc.(*v1.Service)
}
// getVirtualsForTLSProfile gets the List of VirtualServers which are effected
// by the addition/deletion/updation of TLSProfile.
func (ctlr *Controller) getVirtualsForTLSProfile(tls *cisapiv1.TLSProfile) []*cisapiv1.VirtualServer {
allVirtuals := ctlr.getAllVirtualServers(tls.ObjectMeta.Namespace)
if nil == allVirtuals {
log.Infof("No VirtualServers found in namespace %s",
tls.ObjectMeta.Namespace)
return nil
}
// find VirtualServers that reference the TLSProfile
virtualsForTLSProfile := getVirtualServersForTLSProfile(allVirtuals, tls)
if nil == virtualsForTLSProfile {
log.Infof("Change in TLSProfile %s does not effect any VirtualServer",
tls.ObjectMeta.Name)
return nil
}
return virtualsForTLSProfile
}
func (ctlr *Controller) getVirtualsForCustomPolicy(plc *cisapiv1.Policy) []*cisapiv1.VirtualServer {
nsVirtuals := ctlr.getAllVirtualServers(plc.Namespace)
if nil == nsVirtuals {
log.Infof("No VirtualServers found in namespace %s",
plc.Namespace)
return nil
}
var plcVSs []*cisapiv1.VirtualServer
var plcVSNames []string
for _, vs := range nsVirtuals {
if vs.Spec.PolicyName == plc.Name {
plcVSs = append(plcVSs, vs)
plcVSNames = append(plcVSNames, vs.Name)
}
}
log.Debugf("VirtualServers %v are affected with Custom Policy %s: ",
plcVSNames, plc.Name)
return plcVSs
}
func (ctlr *Controller) getTransportServersForCustomPolicy(plc *cisapiv1.Policy) []*cisapiv1.TransportServer {
nsVirtuals := ctlr.getAllTransportServers(plc.Namespace)
if nil == nsVirtuals {
log.Infof("No VirtualServers found in namespace %s",
plc.Namespace)
return nil
}
var plcVSs []*cisapiv1.TransportServer
var plcVSNames []string
for _, vs := range nsVirtuals {
if vs.Spec.PolicyName == plc.Name {
plcVSs = append(plcVSs, vs)
plcVSNames = append(plcVSNames, vs.Name)
}
}
log.Debugf("VirtualServers %v are affected with Custom Policy %s: ",
plcVSNames, plc.Name)
return plcVSs
}
// getLBServicesForCustomPolicy gets all services of type LB affected by the policy
func (ctlr *Controller) getLBServicesForCustomPolicy(plc *cisapiv1.Policy) []*v1.Service {
LBServices := ctlr.getAllLBServices(plc.Namespace)
if nil == LBServices {
log.Infof("No LB service found in namespace %s",
plc.Namespace)
return nil
}
var plcSvcs []*v1.Service
var plcSvcNames []string
for _, svc := range LBServices {
if plcName, found := svc.Annotations[LBServicePolicyNameAnnotation]; found && plcName == plc.Name {
plcSvcs = append(plcSvcs, svc)
plcSvcNames = append(plcSvcNames, svc.Name)
}
}
log.Debugf("LB Services %v are affected with Custom Policy %s: ",
plcSvcNames, plc.Name)
return plcSvcs
}
// getAllVirtualServers returns list of all valid VirtualServers in rkey namespace.
func (ctlr *Controller) getAllVirtualServers(namespace string) []*cisapiv1.VirtualServer {
var allVirtuals []*cisapiv1.VirtualServer
crInf, ok := ctlr.getNamespacedCRInformer(namespace)
if !ok {
log.Errorf("Informer not found for namespace: %v", namespace)
return nil
}
var orderedVSs []interface{}
var err error
if namespace == "" {
orderedVSs = crInf.vsInformer.GetIndexer().List()
} else {
// Get list of VirtualServers and process them.
orderedVSs, err = crInf.vsInformer.GetIndexer().ByIndex("namespace", namespace)
if err != nil {
log.Errorf("Unable to get list of VirtualServers for namespace '%v': %v",
namespace, err)
return nil
}
}
for _, obj := range orderedVSs {
vs := obj.(*cisapiv1.VirtualServer)
// TODO: Validate the VirtualServers List to check if all the vs are valid.
allVirtuals = append(allVirtuals, vs)
}
return allVirtuals
}
// getAllVirtualServers returns list of all valid VirtualServers in rkey namespace.
func (ctlr *Controller) getAllVSFromMonitoredNamespaces() []*cisapiv1.VirtualServer {
var allVirtuals []*cisapiv1.VirtualServer
if ctlr.watchingAllNamespaces() {
return ctlr.getAllVirtualServers("")
}
for ns := range ctlr.namespaces {
allVirtuals = append(allVirtuals, ctlr.getAllVirtualServers(ns)...)
}
return allVirtuals
}
// getVirtualServersForTLS returns list of VirtualServers that are
// affected by the TLSProfile under process.
func getVirtualServersForTLSProfile(allVirtuals []*cisapiv1.VirtualServer,
tls *cisapiv1.TLSProfile) []*cisapiv1.VirtualServer {
var result []*cisapiv1.VirtualServer
tlsName := tls.ObjectMeta.Name
tlsNamespace := tls.ObjectMeta.Namespace
for _, vs := range allVirtuals {
if vs.ObjectMeta.Namespace == tlsNamespace && vs.Spec.TLSProfileName == tlsName {
found := false
for _, host := range tls.Spec.Hosts {
if vs.Spec.Host == host {
result = append(result, vs)
found = true
break
}
}
if !found {
log.Errorf("TLSProfile hostname is not same as virtual host %s for profile %s", vs.Spec.Host, vs.Spec.TLSProfileName)
}
}
}
return result
}
func (ctlr *Controller) getTerminationFromTLSProfileForVirtualServer(vs *cisapiv1.VirtualServer) string {
if vs.Spec.TLSProfileName == "" {
return ""
}
// get TLSProfile for VirtualServer
tlsProfile, err := ctlr.getTLSProfile(vs.Spec.TLSProfileName, vs.Namespace)
if err != nil {
log.Errorf("Error fetching TLSProfile %s: %v", vs.Spec.TLSProfileName, err)
return ""
}
return tlsProfile.Spec.TLS.Termination
}
func (ctlr *Controller) getTLSProfile(tlsName string, namespace string) (*cisapiv1.TLSProfile, error) {
tlsKey := fmt.Sprintf("%s/%s", namespace, tlsName)
// Initialize CustomResource Informer for required namespace
crInf, ok := ctlr.getNamespacedCRInformer(namespace)
if !ok {
return nil, fmt.Errorf("Informer not found for namespace: %v", namespace)
}
obj, tlsFound, _ := crInf.tlsInformer.GetIndexer().GetByKey(tlsKey)
if !tlsFound {
return nil, fmt.Errorf("TLSProfile %s does not exist", tlsName)
}
return obj.(*cisapiv1.TLSProfile), nil
}
func (ctlr *Controller) getTLSProfileForVirtualServer(vs *cisapiv1.VirtualServer) *cisapiv1.TLSProfile {
tlsName := vs.Spec.TLSProfileName
namespace := vs.Namespace
vsKey := fmt.Sprintf("%s/%s", vs.Namespace, vs.Name)
comInf, ok := ctlr.getNamespacedCommonInformer(namespace)
if !ok {
log.Errorf("Common Informer not found for namespace: %v", namespace)
return nil
}
// TODO: Create Internal Structure to hold TLSProfiles. Make API call only for a new TLSProfile
// Check if the TLSProfile exists and valid for us.
tlsProfile, err := ctlr.getTLSProfile(tlsName, namespace)
if err != nil {
log.Errorf("Error fetching TLSProfile %s: %v", tlsName, err)
return nil
}
// validate TLSProfile
validation := validateTLSProfile(tlsProfile)
if validation == false {
return nil
}
if tlsProfile.Spec.TLS.Reference == "secret" {
var match bool
if len(tlsProfile.Spec.TLS.ClientSSLs) > 0 {
for _, secret := range tlsProfile.Spec.TLS.ClientSSLs {
secretKey := namespace + "/" + secret
clientSecretobj, found, err := comInf.secretsInformer.GetIndexer().GetByKey(secretKey)
if err != nil || !found {
return nil
}
clientSecret := clientSecretobj.(*v1.Secret)
//validate at least one clientSSL certificates matches the VS hostname
if checkCertificateHost(vs.Spec.Host, VirtualServer, vsKey, clientSecret.Data["tls.crt"], clientSecret.Data["tls.key"]) {
match = true
break
}
}
} else {
secretKey := namespace + "/" + tlsProfile.Spec.TLS.ClientSSL
clientSecretobj, found, err := comInf.secretsInformer.GetIndexer().GetByKey(secretKey)
if err != nil || !found {
return nil
}
clientSecret := clientSecretobj.(*v1.Secret)
//validate clientSSL certificates and hostname
match = checkCertificateHost(vs.Spec.Host, VirtualServer, vsKey, clientSecret.Data["tls.crt"], clientSecret.Data["tls.key"])
}
if match == false {
return nil
}
}
if len(vs.Spec.Host) == 0 {
// VirtualServer without host may be used for group of services
// which are common amongst multiple hosts. Example: Error Page
// application may be common for multiple hosts.
// However, each host use a unique TLSProfile w.r.t SNI
return tlsProfile
}
for _, host := range tlsProfile.Spec.Hosts {
if host == vs.Spec.Host {
// TLSProfile Object
return tlsProfile
}
// check for wildcard match
if strings.HasPrefix(host, "*") {
host = strings.TrimPrefix(host, "*")
if strings.HasSuffix(vs.Spec.Host, host) {
// TLSProfile Object
return tlsProfile
}
}
}
log.Errorf("TLSProfile %s with host %s does not match with virtual server %s host.", tlsName, vs.Spec.Host, vs.ObjectMeta.Name)
return nil
}
func isTLSVirtualServer(vrt *cisapiv1.VirtualServer) bool {
return len(vrt.Spec.TLSProfileName) != 0
}
func doesVSHandleHTTP(vrt *cisapiv1.VirtualServer) bool {
if !isTLSVirtualServer(vrt) {
// If it is not TLS VirtualServer(HTTPS), then it is HTTP server
return true
}
// If Allow or Redirect happens then HTTP Traffic is being handled.
return vrt.Spec.HTTPTraffic == TLSAllowInsecure ||
vrt.Spec.HTTPTraffic == TLSRedirectInsecure
}
// doVSHandleHTTP checks if any of the associated vituals handle HTTP traffic and use same port