/
appManager.go
4047 lines (3748 loc) · 125 KB
/
appManager.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 appmanager
import (
"context"
"encoding/json"
"fmt"
"k8s.io/apimachinery/pkg/api/errors"
"net"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/F5Networks/k8s-bigip-ctlr/v2/pkg/vxlan"
"github.com/F5Networks/k8s-bigip-ctlr/v2/pkg/writer"
"k8s.io/apimachinery/pkg/util/intstr"
"github.com/F5Networks/k8s-bigip-ctlr/v2/pkg/teem"
netv1 "k8s.io/api/networking/v1"
cisAgent "github.com/F5Networks/k8s-bigip-ctlr/v2/pkg/agent"
bigIPPrometheus "github.com/F5Networks/k8s-bigip-ctlr/v2/pkg/prometheus"
. "github.com/F5Networks/k8s-bigip-ctlr/v2/pkg/resource"
log "github.com/F5Networks/k8s-bigip-ctlr/v2/pkg/vlogger"
routeapi "github.com/openshift/api/route/v1"
routeclient "github.com/openshift/client-go/route/clientset/versioned/typed/route/v1"
listersroutev1 "github.com/openshift/client-go/route/listers/route/v1"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
watch "k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes"
listerscorev1 "k8s.io/client-go/listers/core/v1"
rest "k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
)
type ResourceMap map[int32][]*ResourceConfig
// RoutesMap consists of List of route names indexed by namespace
type RoutesMap map[string][]string
type Manager struct {
resources *Resources
customProfiles *CustomProfileStore
irulesMap IRulesMap
intDgMap InternalDataGroupMap
agentCfgMap map[string]*AgentCfgMap
agentCfgMapSvcCache map[string]*SvcEndPointsCache
kubeClient kubernetes.Interface
restClientv1 rest.Interface
restClientv1beta1 rest.Interface
netClientv1 rest.Interface
routeClientV1 routeclient.RouteV1Interface
steadyState bool
queueLen int
processedItems int
processedResources map[string]bool
// Mutex to control access to processedResources map
processedResourcesMutex sync.Mutex
processedHostPath ProcessedHostPath
// Use internal node IPs
useNodeInternal bool
// Running in nodeport (or cluster) mode
isNodePort bool
// Mutex to control access to node data
// FIXME: Simple synchronization for now, it remains to be determined if we'll
// need something more complicated (channels, etc?)
oldNodesMutex sync.Mutex
// Nodes from previous iteration of node polling
oldNodes []Node
// Mutex for all informers (for informer CRUD)
informersMutex sync.Mutex
// Mutex for intDgMap
intDgMutex sync.Mutex
// App informer support
vsQueue workqueue.RateLimitingInterface
appInformers map[string]*appInformer
nodeInformer *nodeInformer
// Namespace informer support (namespace labels)
nsQueue workqueue.RateLimitingInterface
nsInformer cache.SharedIndexInformer
DynamicNS bool
// Event notifier
eventNotifier *EventNotifier
// Route configurations
routeConfig RouteConfig
// Currently configured node label selector
nodeLabelSelector string
// Strategy for resolving Ingress Hosts into IP addresses (LOOKUP or custom DNS)
resolveIng string
// Default IP for any Ingress with the 'controller-default' ip annotation
defaultIngIP string
// Optional SNAT pool name to be referenced by virtual servers
vsSnatPoolName string
// Use Secrets for SSL Profiles
useSecrets bool
// Channel for emitting events
eventChan chan interface{}
// Where the schemas reside locally
schemaLocal string
// map of rules that have been merged
mergedRulesMap map[string]map[string]MergedRuleEntry
// Whether to watch ConfigMap resources or not
manageConfigMaps bool
configMapLabel string
hubMode bool
manageIngress bool
manageIngressClassOnly bool
ingressClass string
// Ingress SSL security Context
rsrcSSLCtxt map[string]*v1.Secret
WatchedNS WatchedNamespaces
// AS3 Specific features that can be applied to a Route/Ingress
trustedCertsCfgmap string
intF5Res InternalF5ResourcesGroup
dgPath string
AgentCIS cisAgent.CISAgentInterface
// Processed routes for updating Admit Status
agRspChan chan interface{}
processAgentLabels func(map[string]string, string, string) bool
TeemData *teem.TeemsData
defaultRouteDomain int
poolMemberType string
// key is namespace/pod. stores list of npl annotation on pod
nplStore map[string]NPLAnnoations
// Mutex to control access to nplStore map
nplStoreMutex sync.Mutex
AgentName string
//vxlan
vxlanName string
ciliumTunnelName string
vxlanMode string
configWriter writer.Writer
staticRoutingMode bool
orchestrationCNI string
staticRouteNodeCIDR string
}
// Store of processed host-Path map
type ProcessedHostPath struct {
sync.Mutex
processedHostPathMap map[string]metav1.Time
}
// Watched Namespaces for global availability.
type WatchedNamespaces struct {
Namespaces []string
NamespaceLabel string
}
// NPL information from pod annotation
type NPLAnnotation struct {
PodPort int32 `json:"podPort"`
NodeIP string `json:"nodeIP"`
NodePort int32 `json:"nodePort"`
}
// List of NPL annotations
type NPLAnnoations []NPLAnnotation
// static route config section
type routeSection struct {
Entries []routeConfig `json:"routes"`
}
type routeConfig struct {
Name string `json:"name"`
Network string `json:"network"`
Gateway string `json:"gw"`
}
// Struct to allow NewManager to receive all or only specific parameters.
type Params struct {
KubeClient kubernetes.Interface
RouteClientV1 routeclient.RouteV1Interface
UseNodeInternal bool
IsNodePort bool
RouteConfig RouteConfig
ResolveIngress string
DefaultIngIP string
VsSnatPoolName string
NodeLabelSelector string
UseSecrets bool
SchemaLocal string
EventChan chan interface{}
ConfigWriter writer.Writer
// Package local for untesting only
restClient rest.Interface
steadyState bool
broadcasterFunc NewBroadcasterFunc
ManageConfigMaps bool
ManageIngress bool
ManageIngressClassOnly bool
HubMode bool
IngressClass string
Agent string
SchemaLocalPath string
TrustedCertsCfgmap string
// Data group path
DgPath string
AgRspChan chan interface{}
ProcessAgentLabels func(map[string]string, string, string) bool
UserAgent string
DefaultRouteDomain int
PoolMemberType string
//vxlan
VXLANName string
VXLANMode string
CiliumTunnelName string
StaticRoutingMode bool
OrchestrationCNI string
StaticRouteNodeCIDR string
}
// Configuration options for Routes in OpenShift
type RouteConfig struct {
RouteVSAddr string
RouteLabel string
HttpVs string
HttpsVs string
ClientSSL string
ServerSSL string
}
type SvcEndPointsCache struct {
members []Member
labelString string
}
var K8SCoreServices = map[string]bool{
"kube-dns": true,
"kube-scheduler": true,
"kube-controller-manager": true,
"kube-apiserver": true,
"docker-registry": true,
"kubernetes": true,
"registry-console": true,
"router": true,
"kubelet": true,
"console": true,
"alertmanager-main": true,
"alertmanager-operated": true,
"cluster-monitoring-operator": true,
"kube-state-metrics": true,
"node-exporter": true,
"prometheus-k8s": true,
"prometheus-operated": true,
"prometheus-operatorwebconsole": true,
"kube-proxy": true,
"flannel": true,
"etcd": true,
"antrea": true,
}
var OSCPCoreServices = map[string]bool{
"openshift": true,
"metrics": true,
"api": true,
"check-endpoints": true,
"oauth-openshift": true,
"cco-metrics": true,
"machine-approver": true,
"node-tuning-operator": true,
"performance-addon-operator-service": true,
"cluster-storage-operator-metrics": true,
"csi-snapshot-controller-operator-metrics": true,
"csi-snapshot-webhook": true,
"cluster-version-operator": true,
"downloads": true,
"controller-manager": true,
"dns-default": true,
"image-registry-operator": true,
"router-internal-default": true,
"apiserver": true,
"scheduler": true,
"cluster-autoscaler-operator": true,
"cluster-baremetal-operator-service": true,
"cluster-baremetal-webhook-service": true,
"machine-api-controllers": true,
"machine-api-operator": true,
"machine-api-operator-webhook": true,
"machine-config-controller": true,
"machine-config-daemon": true,
"certified-operators": true,
"community-operators": true,
"marketplace-operator-metrics": true,
"redhat-marketplace": true,
"redhat-operators": true,
"openshift-state-metrics": true,
"telemeter-client": true,
"thanos-querier": true,
"multus-admission-controller": true,
"network-metrics-service": true,
"network-check-source": true,
"network-check-target": true,
"catalog-operator-metrics": true,
"olm-operator-metrics": true,
"packageserver-service": true,
"sdn": true,
"sdn-controller": true,
}
const (
// Kinds of Resources
Namespaces = "namespaces"
Services = "services"
Endpoints = "endpoints"
Pod = "pod"
Nodes = "nodes"
Configmaps = "configmaps"
Ingresses = "ingresses"
Routes = "routes"
Secrets = "secrets"
IngressClasses = "ingressclasses"
hubModeInterval = 30 * time.Second //Hubmode ConfigMap resync interval
NPLPodAnnotation = "nodeportlocal.antrea.io"
NPLSvcAnnotation = "nodeportlocal.antrea.io/enabled"
// CNI
OVN_K8S = "ovn-k8s"
OVNK8sNodeSubnetAnnotation = "k8s.ovn.org/node-subnets"
OVNK8sNodeIPAnnotation = "k8s.ovn.org/node-primary-ifaddr"
// k8s.ovn.org/host-addresses is changed to k8s.ovn.org/host-cidrs in openshift 4.14
OVNK8sNodeIPAnnotation2 = "k8s.ovn.org/host-addresses"
OVNK8sNodeIPAnnotation3 = "k8s.ovn.org/host-cidrs"
CILIUM_K8S = "cilium-k8s"
CiliumK8sNodeSubnetAnnotation12 = "io.cilium.network.ipv4-pod-cidr"
CiliumK8sNodeSubnetAnnotation13 = "network.cilium.io/ipv4-pod-cidr"
)
// Create and return a new app manager that meets the Manager interface
func NewManager(params *Params) *Manager {
vsQueue := workqueue.NewNamedRateLimitingQueue(
workqueue.DefaultControllerRateLimiter(), "virtual-server-controller")
nsQueue := workqueue.NewNamedRateLimitingQueue(
workqueue.DefaultControllerRateLimiter(), "namespace-controller")
manager := Manager{
resources: NewResources(),
customProfiles: NewCustomProfiles(),
irulesMap: make(IRulesMap),
intDgMap: make(InternalDataGroupMap),
kubeClient: params.KubeClient,
restClientv1: params.restClient,
restClientv1beta1: params.restClient,
routeClientV1: params.RouteClientV1,
useNodeInternal: params.UseNodeInternal,
isNodePort: params.IsNodePort,
steadyState: params.steadyState,
queueLen: 0,
processedItems: 0,
routeConfig: params.RouteConfig,
nodeLabelSelector: params.NodeLabelSelector,
resolveIng: params.ResolveIngress,
defaultIngIP: params.DefaultIngIP,
vsSnatPoolName: params.VsSnatPoolName,
schemaLocal: params.SchemaLocal,
useSecrets: params.UseSecrets,
vsQueue: vsQueue,
nsQueue: nsQueue,
appInformers: make(map[string]*appInformer),
eventNotifier: NewEventNotifier(params.broadcasterFunc),
mergedRulesMap: make(map[string]map[string]MergedRuleEntry),
manageConfigMaps: params.ManageConfigMaps,
hubMode: params.HubMode,
manageIngress: params.ManageIngress,
manageIngressClassOnly: params.ManageIngressClassOnly,
ingressClass: params.IngressClass,
rsrcSSLCtxt: make(map[string]*v1.Secret),
trustedCertsCfgmap: params.TrustedCertsCfgmap,
intF5Res: make(map[string]InternalF5Resources),
dgPath: params.DgPath,
agRspChan: params.AgRspChan,
processAgentLabels: params.ProcessAgentLabels,
agentCfgMap: make(map[string]*AgentCfgMap),
agentCfgMapSvcCache: make(map[string]*SvcEndPointsCache),
defaultRouteDomain: params.DefaultRouteDomain,
poolMemberType: params.PoolMemberType,
AgentName: params.Agent,
vxlanName: params.VXLANName,
vxlanMode: params.VXLANMode,
ciliumTunnelName: params.CiliumTunnelName,
eventChan: params.EventChan,
configWriter: params.ConfigWriter,
staticRoutingMode: params.StaticRoutingMode,
orchestrationCNI: params.OrchestrationCNI,
staticRouteNodeCIDR: params.StaticRouteNodeCIDR,
}
manager.processedResources = make(map[string]bool)
manager.processedHostPath.processedHostPathMap = make(map[string]metav1.Time)
manager.nplStore = make(map[string]NPLAnnoations)
// Initialize agent response worker
go manager.agentResponseWorker()
if nil != manager.kubeClient && nil == manager.restClientv1 {
// This is the normal production case, but need the checks for unit tests.
manager.restClientv1 = manager.kubeClient.CoreV1().RESTClient()
}
if nil != manager.kubeClient && nil == manager.restClientv1beta1 {
// This is the normal production case, but need the checks for unit tests.
manager.restClientv1beta1 = manager.kubeClient.ExtensionsV1beta1().RESTClient()
}
if nil != manager.kubeClient && nil == manager.netClientv1 {
// This is the normal production case, but need the checks for unit tests.
manager.netClientv1 = manager.kubeClient.NetworkingV1().RESTClient()
}
return &manager
}
func (appMgr *Manager) watchingAllNamespacesLocked() bool {
if 0 == len(appMgr.appInformers) {
// Not watching any namespaces.
return false
}
_, watchingAll := appMgr.appInformers[""]
return watchingAll
}
func (appMgr *Manager) AddNamespace(
namespace string,
cfgMapSelector labels.Selector,
resyncPeriod time.Duration,
) error {
appMgr.informersMutex.Lock()
defer appMgr.informersMutex.Unlock()
_, err := appMgr.addNamespaceLocked(namespace, cfgMapSelector, resyncPeriod)
return err
}
func (appMgr *Manager) addNamespaceLocked(
namespace string,
cfgMapSelector labels.Selector,
resyncPeriod time.Duration,
) (*appInformer, error) {
// Check if watching all namespaces by checking all appInformers is created for "" namespace
if appMgr.watchingAllNamespacesLocked() {
return nil, fmt.Errorf(
"Cannot add additional namespaces when already watching all.")
}
if len(appMgr.appInformers) > 0 && "" == namespace {
return nil, fmt.Errorf(
"Cannot watch all namespaces when already watching specific ones.")
}
var appInf *appInformer
var found bool
if appInf, found = appMgr.appInformers[namespace]; found {
return appInf, nil
}
appInf = appMgr.newAppInformer(namespace, cfgMapSelector, resyncPeriod)
appMgr.appInformers[namespace] = appInf
return appInf, nil
}
func (appMgr *Manager) removeNamespace(namespace string) error {
appMgr.informersMutex.Lock()
defer appMgr.informersMutex.Unlock()
err := appMgr.removeNamespaceLocked(namespace)
return err
}
func (appMgr *Manager) removeNamespaceLocked(namespace string) error {
if _, found := appMgr.appInformers[namespace]; !found {
return fmt.Errorf("No informers exist for namespace %v\n", namespace)
}
delete(appMgr.appInformers, namespace)
return nil
}
// AddNodeInformer to watch the node udpates
func (appMgr *Manager) AddNodeInformer(resyncPeriod time.Duration) error {
appMgr.informersMutex.Lock()
defer appMgr.informersMutex.Unlock()
nodeOptions := func(options *metav1.ListOptions) {
options.LabelSelector = appMgr.nodeLabelSelector
}
appMgr.nodeInformer = &nodeInformer{
stopCh: make(chan struct{}),
nodeInformer: cache.NewSharedIndexInformer(
cache.NewFilteredListWatchFromClient(
appMgr.restClientv1,
"nodes",
"",
nodeOptions,
),
&v1.Node{},
resyncPeriod,
cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
),
}
appMgr.nodeInformer.nodeInformer.AddEventHandler(
&cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) { appMgr.setupNodeProcessing() },
UpdateFunc: func(obj, cur interface{}) { appMgr.setupNodeProcessing() },
DeleteFunc: func(obj interface{}) { appMgr.setupNodeProcessing() },
},
)
return nil
}
// AddNamespaceLabelInformer spins an informer to watch all namespaces with matching label
func (appMgr *Manager) AddNamespaceLabelInformer(
labelSelector labels.Selector,
resyncPeriod time.Duration,
) error {
appMgr.informersMutex.Lock()
defer appMgr.informersMutex.Unlock()
if nil != appMgr.nsInformer {
return fmt.Errorf("Already have a namespace label informer added.")
}
if 0 != len(appMgr.appInformers) {
return fmt.Errorf("Cannot set a namespace label informer when informers " +
"have been setup for one or more namespaces.")
}
optionsModifier := func(options *metav1.ListOptions) {
options.LabelSelector = labelSelector.String()
}
appMgr.nsInformer = cache.NewSharedIndexInformer(
cache.NewFilteredListWatchFromClient(
appMgr.restClientv1,
Namespaces,
"",
optionsModifier,
),
&v1.Namespace{},
resyncPeriod,
cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
)
appMgr.nsInformer.AddEventHandlerWithResyncPeriod(
&cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) { appMgr.enqueueNamespace(obj) },
UpdateFunc: func(old, cur interface{}) { appMgr.enqueueNamespace(cur) },
DeleteFunc: func(obj interface{}) { appMgr.enqueueNamespace(obj) },
},
resyncPeriod,
)
return nil
}
func (appMgr *Manager) enqueueNamespace(obj interface{}) {
ns := obj.(*v1.Namespace)
if !appMgr.DynamicNS && !appMgr.watchingAllNamespacesLocked() {
if _, ok := appMgr.getNamespaceInformer(ns.Name); !ok {
return
}
}
appMgr.nsQueue.Add(ns.ObjectMeta.Name)
}
func (appMgr *Manager) namespaceWorker() {
for appMgr.processNextNamespace() {
}
}
func (appMgr *Manager) processNextNamespace() bool {
key, quit := appMgr.nsQueue.Get()
if quit {
return false
}
defer appMgr.nsQueue.Done(key)
err := appMgr.syncNamespace(key.(string))
if err == nil {
appMgr.nsQueue.Forget(key)
return true
}
utilruntime.HandleError(fmt.Errorf("Sync %v failed with %v", key, err))
appMgr.nsQueue.AddRateLimited(key)
return true
}
func (appMgr *Manager) triggerSyncResources(ns string, inf *appInformer) {
enqueueSvcFromNamespace := func(namespace string, appInf *appInformer) {
objs, err := appInf.svcInformer.GetIndexer().ByIndex("namespace", namespace)
if err != nil {
log.Errorf("[CORE] Unable to fetch services from namespace: %v for periodic resync", namespace)
return
}
if objs != nil && len(objs) > 0 {
svc := objs[0].(*v1.Service)
svcKey := serviceQueueKey{
Namespace: namespace,
ServiceName: svc.Name,
ResourceKind: Services,
ResourceName: svc.Name,
Operation: OprTypeUpdate,
}
log.Debugf("[CORE] Periodic enqueue of Service from Namespace: %v, svc: %s", namespace, svc.Name)
appMgr.vsQueue.Add(svcKey)
}
}
if appMgr.watchingAllNamespacesLocked() {
namespaces := appMgr.GetWatchedNamespacesLockless()
if len(namespaces) == 1 && namespaces[0] == "" {
if appMgr.nsInformer == nil {
return
}
nsps := appMgr.nsInformer.GetIndexer().List()
namespaces = []string{}
for _, ns := range nsps {
namespaces = append(namespaces, ns.(*v1.Namespace).Name)
}
}
for _, ns := range namespaces {
if inf, ok := appMgr.getNamespaceInformerLocked(ns); ok {
enqueueSvcFromNamespace(ns, inf)
}
}
} else {
enqueueSvcFromNamespace(ns, inf)
}
}
func (appMgr *Manager) syncNamespace(nsName string) error {
startTime := time.Now()
var err error
defer func() {
endTime := time.Now()
log.Debugf("[CORE] Finished syncing namespace %+v (%v)",
nsName, endTime.Sub(startTime))
}()
_, exists, err := appMgr.nsInformer.GetIndexer().GetByKey(nsName)
if nil != err {
log.Warningf("[CORE] Error looking up namespace '%v': %v\n", nsName, err)
return err
}
appMgr.informersMutex.Lock()
defer appMgr.informersMutex.Unlock()
appInf, found := appMgr.getNamespaceInformerLocked(nsName)
if exists && found {
appMgr.triggerSyncResources(nsName, appInf)
return nil
}
// Skip deleting informers if watching specific namespaces
if !appMgr.DynamicNS {
return nil
}
if exists {
// exists but not found in informers map, add
cfgMapSelector, err := labels.Parse(DefaultConfigMapLabel)
if err != nil {
return fmt.Errorf("Failed to parse Label Selector string: %v", err)
}
appInf, err = appMgr.addNamespaceLocked(nsName, cfgMapSelector, 0)
if err != nil {
return fmt.Errorf("Failed to add informers for namespace %v: %v",
nsName, err)
}
appInf.start()
appInf.waitForCacheSync()
} else {
// does not exist but found in informers map, delete
// Clean up all resources that reference a removed namespace
appInf.stopInformers()
appMgr.removeNamespaceLocked(nsName)
appMgr.eventNotifier.DeleteNotifierForNamespace(nsName)
appMgr.resources.Lock()
rsDeleted := 0
appMgr.resources.ForEach(func(key ServiceKey, cfg *ResourceConfig) {
if key.Namespace == nsName {
if appMgr.resources.Delete(key, NameRef{}) {
rsDeleted += 1
}
}
})
appMgr.resources.Unlock()
// Handle Agent Specific ConfigMaps
if appMgr.AgentCIS.IsImplInAgent(ResourceTypeCfgMap) {
for _, cm := range appMgr.agentCfgMap {
if cm.Namespace == nsName {
cm.Operation = OprTypeDelete
rsDeleted += 1
}
}
}
if rsDeleted > 0 {
log.Warningf("[CORE] Error looking up namespace '%v': %v\n", nsName, err)
appMgr.deployResource()
}
}
return nil
}
func (appMgr *Manager) GetWatchedNamespaces() []string {
appMgr.informersMutex.Lock()
defer appMgr.informersMutex.Unlock()
return appMgr.GetWatchedNamespacesLockless()
}
func (appMgr *Manager) GetWatchedNamespacesLockless() []string {
var namespaces []string
for k, _ := range appMgr.appInformers {
namespaces = append(namespaces, k)
}
return namespaces
}
func (appMgr *Manager) GetNamespaceLabelInformer() cache.SharedIndexInformer {
return appMgr.nsInformer
}
type serviceQueueKey struct {
Namespace string
ServiceName string
ResourceKind string
ResourceName string
Operation string
Object interface{}
}
type nodeInformer struct {
nodeInformer cache.SharedIndexInformer
stopCh chan struct{}
}
type appInformer struct {
namespace string
cfgMapInformer cache.SharedIndexInformer
svcInformer cache.SharedIndexInformer
endptInformer cache.SharedIndexInformer
ingInformer cache.SharedIndexInformer
routeInformer cache.SharedIndexInformer
secretInformer cache.SharedIndexInformer
ingClassInformer cache.SharedIndexInformer
podInformer cache.SharedIndexInformer
stopCh chan struct{}
}
func (appMgr *Manager) newAppInformer(
namespace string,
cfgMapSelector labels.Selector,
resyncPeriod time.Duration,
) *appInformer {
log.Debugf("[CORE] Creating new app informer")
everything := func(options *metav1.ListOptions) {
options.LabelSelector = ""
}
appInf := appInformer{
namespace: namespace,
stopCh: make(chan struct{}),
svcInformer: cache.NewSharedIndexInformer(
cache.NewFilteredListWatchFromClient(
appMgr.restClientv1,
Services,
namespace,
everything,
),
&v1.Service{},
resyncPeriod,
cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
),
secretInformer: cache.NewSharedIndexInformer(
cache.NewFilteredListWatchFromClient(
appMgr.restClientv1,
Secrets,
namespace,
everything,
),
&v1.Secret{},
resyncPeriod,
cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
),
}
//enable podinformer for nodeport local
if appMgr.poolMemberType == NodePortLocal {
appInf.podInformer = cache.NewSharedIndexInformer(
cache.NewFilteredListWatchFromClient(
appMgr.restClientv1,
"pods",
namespace,
everything,
),
&v1.Pod{},
resyncPeriod,
cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
)
}
//For nodeport mode, disable ep informer
if appMgr.poolMemberType != NodePort {
appInf.endptInformer = cache.NewSharedIndexInformer(
cache.NewFilteredListWatchFromClient(
appMgr.restClientv1,
Endpoints,
namespace,
everything,
),
&v1.Endpoints{},
resyncPeriod,
cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
)
}
if true == appMgr.manageIngress {
log.Infof("[CORE] Watching Ingress resources.")
appInf.ingInformer = cache.NewSharedIndexInformer(
cache.NewFilteredListWatchFromClient(
appMgr.netClientv1,
Ingresses,
namespace,
everything,
),
&netv1.Ingress{},
resyncPeriod,
cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
)
appInf.ingClassInformer = cache.NewSharedIndexInformer(
cache.NewFilteredListWatchFromClient(
appMgr.netClientv1,
IngressClasses,
"",
everything,
),
&netv1.IngressClass{},
resyncPeriod,
cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
)
} else {
log.Infof("[CORE] Not watching Ingress resources.")
}
if false != appMgr.manageConfigMaps {
appMgr.configMapLabel = cfgMapSelector.String()
cfgMapOptions := func(options *metav1.ListOptions) {
options.LabelSelector = appMgr.configMapLabel
}
log.Infof("[CORE] Watching ConfigMap resources.")
//If Hubmode is enabled, process configmaps every 30 seconds to process unwatched namespace deployments
syncInterval := resyncPeriod
if appMgr.hubMode {
syncInterval = hubModeInterval
}
appInf.cfgMapInformer = cache.NewSharedIndexInformer(
cache.NewFilteredListWatchFromClient(
appMgr.restClientv1,
Configmaps,
namespace,
cfgMapOptions,
),
&v1.ConfigMap{},
syncInterval,
cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
)
} else {
log.Infof("[CORE] Not watching ConfigMap resources.")
}
if nil != appMgr.routeClientV1 {
// Ensure the default server cert is loaded
appMgr.loadDefaultCert()
appInf.routeInformer = cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
options.LabelSelector = appMgr.routeConfig.RouteLabel
return appMgr.routeClientV1.Routes(namespace).List(context.TODO(), options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.LabelSelector = appMgr.routeConfig.RouteLabel
return appMgr.routeClientV1.Routes(namespace).Watch(context.TODO(), options)
},
},
&routeapi.Route{},
resyncPeriod,
cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
)
}
if false != appMgr.manageConfigMaps {
log.Infof("[CORE] Handling ConfigMap resource events.")
// If Hubmode is enabled, process configmaps every 30 seconds to process unwatched namespace deployments
syncInterval := resyncPeriod
if appMgr.hubMode {
syncInterval = hubModeInterval
}
appInf.cfgMapInformer.AddEventHandlerWithResyncPeriod(
&cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) { appMgr.enqueueConfigMap(obj, OprTypeCreate) },
UpdateFunc: func(old, cur interface{}) {
if appMgr.hubMode || !reflect.DeepEqual(old, cur) {
appMgr.enqueueConfigMap(cur, OprTypeUpdate)
}
},
DeleteFunc: func(obj interface{}) { appMgr.enqueueConfigMap(obj, OprTypeDelete) },
},
syncInterval,
)
} else {
log.Infof("[CORE] Not handling ConfigMap resource events.")
}
appInf.svcInformer.AddEventHandlerWithResyncPeriod(
&cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) { appMgr.enqueueService(obj, OprTypeCreate) },
UpdateFunc: func(old, cur interface{}) { appMgr.enqueueService(cur, OprTypeUpdate) },
DeleteFunc: func(obj interface{}) { appMgr.enqueueService(obj, OprTypeDelete) },
},
resyncPeriod,
)
if appInf.endptInformer != nil {
appInf.endptInformer.AddEventHandlerWithResyncPeriod(
&cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) { appMgr.enqueueEndpoints(obj, OprTypeCreate) },
UpdateFunc: func(old, cur interface{}) { appMgr.enqueueEndpoints(cur, OprTypeUpdate) },
DeleteFunc: func(obj interface{}) { appMgr.enqueueEndpoints(obj, OprTypeDelete) },
},
resyncPeriod,
)
}
appInf.secretInformer.AddEventHandlerWithResyncPeriod(
&cache.ResourceEventHandlerFuncs{
// Making all operation types as update because each change in secret will update the ingress/configmap
AddFunc: func(obj interface{}) { appMgr.enqueueSecrets(obj, OprTypeUpdate) },
UpdateFunc: func(old, cur interface{}) { appMgr.enqueueSecrets(cur, OprTypeUpdate) },
DeleteFunc: func(obj interface{}) { appMgr.enqueueSecrets(obj, OprTypeUpdate) },
},
resyncPeriod,
)
if appInf.podInformer != nil {
appInf.podInformer.AddEventHandler(
&cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) { appMgr.enqueuePod(obj, OprTypeCreate) },
UpdateFunc: func(obj, cur interface{}) { appMgr.enqueuePod(cur, OprTypeUpdate) },
DeleteFunc: func(obj interface{}) { appMgr.enqueuePod(obj, OprTypeDelete) },
},
)
}
if true == appMgr.manageIngress {
log.Infof("[CORE] Handling Ingress resource events.")
appInf.ingInformer.AddEventHandlerWithResyncPeriod(
&cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) { appMgr.enqueueIngress(obj, OprTypeCreate) },
UpdateFunc: func(old, cur interface{}) { appMgr.enqueueIngressUpdate(cur, old, OprTypeUpdate) },
DeleteFunc: func(obj interface{}) { appMgr.enqueueIngress(obj, OprTypeDelete) },
},
resyncPeriod,
)
appInf.ingClassInformer.AddEventHandlerWithResyncPeriod(
&cache.ResourceEventHandlerFuncs{
//AddFunc: func(obj interface{}) { appMgr.enqueueIngress(obj, OprTypeCreate) },
//UpdateFunc: func(old, cur interface{}) { appMgr.enqueueIngress(cur, OprTypeUpdate) },
//DeleteFunc: func(obj interface{}) { appMgr.enqueueIngress(obj, OprTypeDelete) },
},
resyncPeriod,
)
} else {
log.Infof("[CORE] Not handling Ingress resource events.")
}
if nil != appMgr.routeClientV1 {
appInf.routeInformer.AddEventHandlerWithResyncPeriod(
&cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) { appMgr.enqueueRoute(obj, OprTypeCreate) },
UpdateFunc: func(old, cur interface{}) {
oldrt := old.(*routeapi.Route)
newrt := cur.(*routeapi.Route)
if reflect.DeepEqual(oldrt.Spec, newrt.Spec) {
return
}
appMgr.enqueueRoute(cur, OprTypeUpdate)
},
DeleteFunc: func(obj interface{}) { appMgr.enqueueRoute(obj, OprTypeDelete) },
},
resyncPeriod,
)
}