/
appManager.go
2510 lines (2306 loc) · 72.7 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-2019, 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 (
"encoding/json"
"fmt"
"github.com/F5Networks/k8s-bigip-ctlr/pkg/teem"
"net"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/F5Networks/k8s-bigip-ctlr/pkg/postmanager"
bigIPPrometheus "github.com/F5Networks/k8s-bigip-ctlr/pkg/prometheus"
log "github.com/F5Networks/k8s-bigip-ctlr/pkg/vlogger"
"github.com/F5Networks/k8s-bigip-ctlr/pkg/writer"
v1 "k8s.io/api/core/v1"
"k8s.io/api/extensions/v1beta1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
watch "k8s.io/apimachinery/pkg/watch"
rest "k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
"github.com/miekg/dns"
routeapi "github.com/openshift/api/route/v1"
routeclient "github.com/openshift/client-go/route/clientset/versioned/typed/route/v1"
)
const DefaultConfigMapLabel = "f5type in (virtual-server)"
const vsStatusBindAddrAnnotation = "status.virtual-server.f5.com/ip"
const ingressSslRedirect = "ingress.kubernetes.io/ssl-redirect"
const ingressAllowHttp = "ingress.kubernetes.io/allow-http"
const healthMonitorAnnotation = "virtual-server.f5.com/health"
const k8sIngressClass = "kubernetes.io/ingress.class"
const f5VsBindAddrAnnotation = "virtual-server.f5.com/ip"
const f5VsHttpPortAnnotation = "virtual-server.f5.com/http-port"
const f5VsHttpsPortAnnotation = "virtual-server.f5.com/https-port"
const f5VsBalanceAnnotation = "virtual-server.f5.com/balance"
const f5VsPartitionAnnotation = "virtual-server.f5.com/partition"
const f5VsURLRewriteAnnotation = "virtual-server.f5.com/rewrite-target-url"
const f5VsWhitelistSourceRangeAnnotation = "virtual-server.f5.com/whitelist-source-range"
const f5VsAppRootAnnotation = "virtual-server.f5.com/rewrite-app-root"
const f5ClientSslProfileAnnotation = "virtual-server.f5.com/clientssl"
const f5ServerSslProfileAnnotation = "virtual-server.f5.com/serverssl"
const f5ServerSslSecureAnnotation = "virtual-server.f5.com/secure-serverssl"
const defaultSslServerCAName = "openshift_route_cluster_default-ca"
const f5VsWAFPolicy = "virtual-server.f5.com/waf"
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
kubeClient kubernetes.Interface
restClientv1 rest.Interface
restClientv1beta1 rest.Interface
routeClientV1 routeclient.RouteV1Interface
configWriter writer.Writer
steadyState bool
queueLen int
processedItems int
// 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 irulesMap
irulesMutex sync.Mutex
// Mutex for intDgMap
intDgMutex sync.Mutex
// App informer support
vsQueue workqueue.RateLimitingInterface
appInformers map[string]*appInformer
as3Informer *appInformer
// Namespace informer support (namespace labels)
nsQueue workqueue.RateLimitingInterface
nsInformer cache.SharedIndexInformer
// 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
manageIngress bool
manageIngressClassOnly bool
ingressClass string
TeemData *teem.TeemsData
// Orchestration agent: AS3 or CCCL
Agent string
// Ingress SSL security Context
rsrcSSLCtxt map[string]*v1.Secret
AS3Manager
}
// AS3Manager holds all the AS3 orchestration specific Data
type AS3Manager struct {
as3Members map[Member]struct{}
as3Validation bool
sslInsecure bool
enableTLS string
tls13CipherGroupReference string
ciphers string
trustedCertsCfgmap string
// Active User Defined ConfigMap details
as3ActiveConfig AS3Config
// List of Watched Endpoints for user-defined AS3
watchedAS3Endpoints map[string]struct{}
// Watched namespaces
WatchedNS WatchedNamespaces
As3SchemaLatest string
// AS3 Specific features that can be applied to a Route/Ingress
intF5Res InternalF5ResourcesGroup
// Override existing as3 declaration with this configmap
OverrideAS3Decl string
// Path of schemas reside locally
SchemaLocalPath string
// Flag to check schema validation using reference or string
As3SchemaFlag bool
// Processed routes for updating Admit Status
RoutesProcessed RoutesMap
// POSTs configuration to BIG-IP using AS3
PostManager *postmanager.PostManager
// To put list of tenants in BIG-IP REST call URL that are in AS3 declaration
FilterTenants bool
}
// AS3Config consists of all the AS3 related configurations
type AS3Config struct {
configmap AS3ConfigMap
routeConfig as3ADC
overrrideAS3Config as3Declaration
unifiedDeclaration as3Declaration
}
// ActiveAS3ConfigMap user defined ConfigMap for global availability.
type AS3ConfigMap struct {
Name string // AS3 specific ConfigMap name
Data as3Declaration // if AS3 Name is present, populate this with AS3 template data.
}
// Watched Namespaces for global availability.
type WatchedNamespaces struct {
Namespaces []string
NamespaceLabel string
}
// Struct to allow NewManager to receive all or only specific parameters.
type Params struct {
KubeClient kubernetes.Interface
RouteClientV1 routeclient.RouteV1Interface
ConfigWriter writer.Writer
UseNodeInternal bool
IsNodePort bool
RouteConfig RouteConfig
ResolveIngress string
DefaultIngIP string
VsSnatPoolName string
NodeLabelSelector string
UseSecrets bool
EventChan chan interface{}
// Package local for unit testing only
restClient rest.Interface
steadyState bool
broadcasterFunc NewBroadcasterFunc
SchemaLocal string
ManageConfigMaps bool
ManageIngress bool
ManageIngressClassOnly bool
IngressClass string
AS3Validation bool
SSLInsecure bool
EnableTLS string
TLS13CipherGroupReference string
Ciphers string
TrustedCertsCfgmap string
Agent string
OverrideAS3Decl string
SchemaLocalPath string
FilterTenants bool
}
// Configuration options for Routes in OpenShift
type RouteConfig struct {
RouteVSAddr string
RouteLabel string
HttpVs string
HttpsVs string
ClientSSL string
ServerSSL string
}
var RoutesProcessed []*routeapi.Route
// 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,
configWriter: params.ConfigWriter,
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,
useSecrets: params.UseSecrets,
eventChan: params.EventChan,
vsQueue: vsQueue,
nsQueue: nsQueue,
appInformers: make(map[string]*appInformer),
eventNotifier: NewEventNotifier(params.broadcasterFunc),
schemaLocal: params.SchemaLocal,
mergedRulesMap: make(map[string]map[string]mergedRuleEntry),
manageConfigMaps: params.ManageConfigMaps,
manageIngress: params.ManageIngress,
manageIngressClassOnly: params.ManageIngressClassOnly,
ingressClass: params.IngressClass,
Agent: getValidAgent(params.Agent),
rsrcSSLCtxt: make(map[string]*v1.Secret),
AS3Manager: AS3Manager{
as3Members: make(map[Member]struct{}, 0),
as3Validation: params.AS3Validation,
sslInsecure: params.SSLInsecure,
enableTLS: params.EnableTLS,
tls13CipherGroupReference: params.TLS13CipherGroupReference,
ciphers: params.Ciphers,
trustedCertsCfgmap: params.TrustedCertsCfgmap,
OverrideAS3Decl: params.OverrideAS3Decl,
intF5Res: make(map[string]InternalF5Resources),
SchemaLocalPath: params.SchemaLocal,
RoutesProcessed: make(RoutesMap),
FilterTenants: params.FilterTenants,
},
}
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()
}
return &manager
}
func getValidAgent(inputString string) string {
agent := "cccl"
switch inputString {
case "as3":
agent = "as3"
default:
log.Debugf("Unknown agent input %v", inputString)
}
log.Debugf("Using agent %v", agent)
return agent
}
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) {
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
}
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)
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) syncNamespace(nsName string) error {
startTime := time.Now()
defer func() {
endTime := time.Now()
log.Debugf("Finished syncing namespace %+v (%v)",
nsName, endTime.Sub(startTime))
}()
_, exists, err := appMgr.nsInformer.GetIndexer().GetByKey(nsName)
if nil != err {
log.Warningf("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 {
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, "") {
rsDeleted += 1
}
}
})
appMgr.resources.Unlock()
if rsDeleted > 0 {
appMgr.outputConfig()
}
}
return nil
}
func (appMgr *Manager) GetWatchedNamespaces() []string {
appMgr.informersMutex.Lock()
defer appMgr.informersMutex.Unlock()
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
AS3Name string // as3 Specific configMap name
AS3Data string // if AS3Name is present, populate this with as3 tmpl data
}
type appInformer struct {
namespace string
cfgMapInformer cache.SharedIndexInformer
svcInformer cache.SharedIndexInformer
endptInformer cache.SharedIndexInformer
ingInformer cache.SharedIndexInformer
routeInformer cache.SharedIndexInformer
nodeInformer cache.SharedIndexInformer
stopCh chan struct{}
}
func (appMgr *Manager) newAppInformer(
namespace string,
cfgMapSelector labels.Selector,
resyncPeriod time.Duration,
) *appInformer {
log.Debugf("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},
),
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("Watching Ingress resources.")
appInf.ingInformer = cache.NewSharedIndexInformer(
cache.NewFilteredListWatchFromClient(
appMgr.restClientv1beta1,
"ingresses",
namespace,
everything,
),
&v1beta1.Ingress{},
resyncPeriod,
cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
)
} else {
log.Infof("Not watching Ingress resources.")
}
if false != appMgr.manageConfigMaps {
cfgMapOptions := func(options *metav1.ListOptions) {
options.LabelSelector = cfgMapSelector.String()
}
log.Infof("Watching ConfigMap resources.")
appInf.cfgMapInformer = cache.NewSharedIndexInformer(
cache.NewFilteredListWatchFromClient(
appMgr.restClientv1,
"configmaps",
namespace,
cfgMapOptions,
),
&v1.ConfigMap{},
resyncPeriod,
cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
)
} else {
log.Infof("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(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.LabelSelector = appMgr.routeConfig.RouteLabel
return appMgr.routeClientV1.Routes(namespace).Watch(options)
},
},
&routeapi.Route{},
resyncPeriod,
cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
)
}
if false != appMgr.manageConfigMaps {
log.Infof("Handling ConfigMap resource events.")
appInf.cfgMapInformer.AddEventHandlerWithResyncPeriod(
&cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) { appMgr.enqueueConfigMap(obj) },
UpdateFunc: func(old, cur interface{}) { appMgr.enqueueConfigMap(cur) },
DeleteFunc: func(obj interface{}) { appMgr.enqueueDeletedConfigMap(obj) },
},
resyncPeriod,
)
} else {
log.Infof("Not handling ConfigMap resource events.")
}
appInf.svcInformer.AddEventHandlerWithResyncPeriod(
&cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) { appMgr.enqueueService(obj) },
UpdateFunc: func(old, cur interface{}) { appMgr.enqueueService(cur) },
DeleteFunc: func(obj interface{}) { appMgr.enqueueService(obj) },
},
resyncPeriod,
)
appInf.endptInformer.AddEventHandlerWithResyncPeriod(
&cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) { appMgr.enqueueEndpoints(obj) },
UpdateFunc: func(old, cur interface{}) { appMgr.enqueueEndpoints(cur) },
DeleteFunc: func(obj interface{}) { appMgr.enqueueEndpoints(obj) },
},
resyncPeriod,
)
if true == appMgr.manageIngress {
log.Infof("Handling Ingress resource events.")
appInf.ingInformer.AddEventHandlerWithResyncPeriod(
&cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) { appMgr.enqueueIngress(obj) },
UpdateFunc: func(old, cur interface{}) { appMgr.enqueueIngress(cur) },
DeleteFunc: func(obj interface{}) { appMgr.enqueueIngress(obj) },
},
resyncPeriod,
)
} else {
log.Infof("Not handling Ingress resource events.")
}
if nil != appMgr.routeClientV1 {
appInf.routeInformer.AddEventHandlerWithResyncPeriod(
&cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) { appMgr.enqueueRoute(obj) },
UpdateFunc: func(old, cur interface{}) { appMgr.enqueueRoute(cur) },
DeleteFunc: func(obj interface{}) { appMgr.enqueueRoute(obj) },
},
resyncPeriod,
)
}
return &appInf
}
func (appMgr *Manager) enqueueConfigMap(obj interface{}) {
if ok, keys := appMgr.checkValidConfigMap(obj); ok {
for _, key := range keys {
appMgr.vsQueue.Add(*key)
}
}
}
func (appMgr *Manager) enqueueDeletedConfigMap(obj interface{}) {
cm := obj.(*v1.ConfigMap)
if val, ok := cm.ObjectMeta.Labels["as3"]; ok {
if as3Val, err := strconv.ParseBool(val); err == nil {
if as3Val {
appMgr.as3ActiveConfig.configmap.Data = ""
appMgr.as3ActiveConfig.configmap.Name = ""
cm.ObjectMeta.Name = ""
cm.Data = map[string]string{"template": ""}
}
}
}
if ok, keys := appMgr.checkValidConfigMap(cm); ok {
for _, key := range keys {
appMgr.vsQueue.Add(*key)
}
}
}
func (appMgr *Manager) enqueueService(obj interface{}) {
if ok, keys := appMgr.checkValidService(obj); ok {
for _, key := range keys {
appMgr.vsQueue.Add(*key)
}
}
}
func (appMgr *Manager) enqueueEndpoints(obj interface{}) {
if ok, keys := appMgr.checkValidEndpoints(obj); ok {
for _, key := range keys {
appMgr.vsQueue.Add(*key)
}
}
}
func (appMgr *Manager) enqueueNode(obj interface{}) {
if ok, keys := appMgr.checkValidNode(obj); ok {
for _, key := range keys {
appMgr.vsQueue.Add(*key)
}
}
}
func (appMgr *Manager) enqueueIngress(obj interface{}) {
if ok, keys := appMgr.checkValidIngress(obj); ok {
for _, key := range keys {
appMgr.vsQueue.Add(*key)
}
}
}
func (appMgr *Manager) enqueueRoute(obj interface{}) {
if ok, keys := appMgr.checkValidRoute(obj); ok {
for _, key := range keys {
appMgr.vsQueue.Add(*key)
}
}
}
func (appMgr *Manager) getNamespaceInformer(
ns string,
) (*appInformer, bool) {
appMgr.informersMutex.Lock()
defer appMgr.informersMutex.Unlock()
appInf, found := appMgr.getNamespaceInformerLocked(ns)
return appInf, found
}
func (appMgr *Manager) getNamespaceInformerLocked(
ns string,
) (*appInformer, bool) {
toFind := ns
if appMgr.watchingAllNamespacesLocked() {
toFind = ""
}
appInf, found := appMgr.appInformers[toFind]
return appInf, found
}
func (appInf *appInformer) start() {
if nil != appInf.svcInformer {
go appInf.svcInformer.Run(appInf.stopCh)
}
if nil != appInf.endptInformer {
go appInf.endptInformer.Run(appInf.stopCh)
}
if nil != appInf.ingInformer {
go appInf.ingInformer.Run(appInf.stopCh)
}
if nil != appInf.routeInformer {
go appInf.routeInformer.Run(appInf.stopCh)
}
if nil != appInf.cfgMapInformer {
go appInf.cfgMapInformer.Run(appInf.stopCh)
}
if nil != appInf.nodeInformer {
go appInf.nodeInformer.Run(appInf.stopCh)
}
}
func (appInf *appInformer) waitForCacheSync() {
cacheSyncs := []cache.InformerSynced{}
if nil != appInf.svcInformer {
cacheSyncs = append(cacheSyncs, appInf.svcInformer.HasSynced)
}
if nil != appInf.endptInformer {
cacheSyncs = append(cacheSyncs, appInf.endptInformer.HasSynced)
}
if nil != appInf.ingInformer {
cacheSyncs = append(cacheSyncs, appInf.ingInformer.HasSynced)
}
if nil != appInf.routeInformer {
cacheSyncs = append(cacheSyncs, appInf.routeInformer.HasSynced)
}
if nil != appInf.cfgMapInformer {
cacheSyncs = append(cacheSyncs, appInf.cfgMapInformer.HasSynced)
}
if nil != appInf.nodeInformer {
cacheSyncs = append(cacheSyncs, appInf.nodeInformer.HasSynced)
}
cache.WaitForCacheSync(
appInf.stopCh,
cacheSyncs...,
)
}
func (appInf *appInformer) stopInformers() {
close(appInf.stopCh)
}
func (appMgr *Manager) IsNodePort() bool {
return appMgr.isNodePort
}
func (appMgr *Manager) UseNodeInternal() bool {
return appMgr.useNodeInternal
}
func (appMgr *Manager) ConfigWriter() writer.Writer {
return appMgr.configWriter
}
func (appMgr *Manager) Run(stopCh <-chan struct{}) {
go appMgr.runImpl(stopCh)
}
func (appMgr *Manager) runImpl(stopCh <-chan struct{}) {
defer utilruntime.HandleCrash()
defer appMgr.vsQueue.ShutDown()
defer appMgr.nsQueue.ShutDown()
if nil != appMgr.nsInformer {
// Using one worker for namespace label changes.
appMgr.startAndSyncNamespaceInformer(stopCh)
go wait.Until(appMgr.namespaceWorker, time.Second, stopCh)
}
appMgr.startAndSyncAppInformers()
// Using only one virtual server worker currently.
go wait.Until(appMgr.virtualServerWorker, time.Second, stopCh)
<-stopCh
appMgr.stopAppInformers()
}
func (appMgr *Manager) startAndSyncNamespaceInformer(stopCh <-chan struct{}) {
appMgr.informersMutex.Lock()
defer appMgr.informersMutex.Unlock()
go appMgr.nsInformer.Run(stopCh)
cache.WaitForCacheSync(stopCh, appMgr.nsInformer.HasSynced)
}
func (appMgr *Manager) startAndSyncAppInformers() {
appMgr.informersMutex.Lock()
defer appMgr.informersMutex.Unlock()
appMgr.startAppInformersLocked()
appMgr.waitForCacheSyncLocked()
}
func (appMgr *Manager) startAppInformersLocked() {
for _, appInf := range appMgr.appInformers {
appInf.start()
}
if nil != appMgr.as3Informer {
appMgr.as3Informer.start()
}
}
func (appMgr *Manager) waitForCacheSync() {
appMgr.informersMutex.Lock()
defer appMgr.informersMutex.Unlock()
appMgr.waitForCacheSyncLocked()
}
func (appMgr *Manager) waitForCacheSyncLocked() {
for _, appInf := range appMgr.appInformers {
appInf.waitForCacheSync()
}
if nil != appMgr.as3Informer {
appMgr.as3Informer.waitForCacheSync()
}
}
func (appMgr *Manager) stopAppInformers() {
appMgr.informersMutex.Lock()
defer appMgr.informersMutex.Unlock()
for _, appInf := range appMgr.appInformers {
appInf.stopInformers()
}
if nil != appMgr.as3Informer {
appMgr.as3Informer.stopInformers()
}
}
func (appMgr *Manager) virtualServerWorker() {
for appMgr.processNextVirtualServer() {
}
}
// Get all Namespaces being watched based on Namespaces provided, Namespace Label or all
func (appMgr *Manager) GetAllWatchedNamespaces() []string {
var namespaces []string
switch {
case len(appMgr.WatchedNS.Namespaces) != 0:
namespaces = appMgr.WatchedNS.Namespaces
case len(appMgr.WatchedNS.NamespaceLabel) != 0:
NsListOptions := metav1.ListOptions{
LabelSelector: appMgr.WatchedNS.NamespaceLabel,
}
nsL, err := appMgr.kubeClient.CoreV1().Namespaces().List(NsListOptions)
if err != nil {
log.Errorf("Error getting Namespaces with Namespace label - %v.", err)
}
for _, v := range nsL.Items {
namespaces = append(namespaces, v.Name)
}
default:
namespaces = append(namespaces, "")
}
return namespaces
}
// Get the count of Services from the Namespaces being watched.
func (appMgr *Manager) getServiceCount() int {
qLen := 0
for _, ns := range appMgr.GetAllWatchedNamespaces() {
services, err := appMgr.kubeClient.CoreV1().Services(ns).List(metav1.ListOptions{})
qLen += len(services.Items)
if err != nil {
log.Errorf("Failed getting Services from watched namespace : %v.", err)
qLen = appMgr.vsQueue.Len()
}
}
return qLen
}
func (appMgr *Manager) processNextVirtualServer() bool {
key, quit := appMgr.vsQueue.Get()
k := key.(serviceQueueKey)
if !appMgr.steadyState && appMgr.processedItems == 0 {
appMgr.queueLen = appMgr.getServiceCount()
}
if len(k.AS3Name) != 0 {
appMgr.as3ActiveConfig.configmap.Name = k.AS3Name
log.Debugf("[AS3] Active ConfigMap: (%s)\n", k.AS3Name)
appMgr.vsQueue.Done(key)
if !appMgr.steadyState {
appMgr.processedItems++
}
log.Debugf("[AS3] Processing AS3 cfgMap (%s) with AS3 Manager.\n", k.AS3Name)
appMgr.processUserDefinedAS3(k.AS3Data)
appMgr.vsQueue.Forget(key)
return false
}
if quit {
// The controller is shutting down.
return false
}
defer appMgr.vsQueue.Done(key)
err := appMgr.syncVirtualServer(key.(serviceQueueKey))
if err == nil {
if !appMgr.steadyState {
appMgr.processedItems++
}
appMgr.vsQueue.Forget(key)
return true
}
utilruntime.HandleError(fmt.Errorf("Sync %v failed with %v", key, err))