-
Notifications
You must be signed in to change notification settings - Fork 193
/
resourceConfig.go
2797 lines (2602 loc) · 97.7 KB
/
resourceConfig.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 (
"encoding/json"
"fmt"
"net"
"reflect"
"sort"
"strconv"
"strings"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/tools/cache"
routeapi "github.com/openshift/api/route/v1"
cisapiv1 "github.com/F5Networks/k8s-bigip-ctlr/v3/config/apis/cis/v1"
log "github.com/F5Networks/k8s-bigip-ctlr/v3/pkg/vlogger"
v1 "k8s.io/api/core/v1"
)
// NewResourceStore is Constructor for ResourceStore
func NewResourceStore() *ResourceStore {
var rs ResourceStore
rs.Init()
return &rs
}
func newMultiClusterResourceStore() *MultiClusterResourceStore {
var rs MultiClusterResourceStore
rs.rscSvcMap = make(map[resourceRef]map[MultiClusterServiceKey]MultiClusterServiceConfig)
rs.clusterSvcMap = make(map[string]map[MultiClusterServiceKey]map[MultiClusterServiceConfig]map[PoolIdentifier]struct{})
return &rs
}
// Init is Receiver to initialize the object.
func (rs *ResourceStore) Init() {
rs.bigIpMap = make(BigIpMap)
rs.bigIpMapCache = make(BigIpMap)
rs.poolMemCache = make(PoolMemberCache)
rs.nplStore = make(NPLStore)
rs.extdSpecMap = make(extendedSpecMap)
rs.invertedNamespaceLabelMap = make(map[string]string)
rs.processedNativeResources = make(map[resourceRef]struct{})
rs.externalClustersConfig = make(map[string]cisapiv1.ExternalClusterConfig)
}
func NewCustomProfile(
profile ProfileRef,
certificates []certificate,
serverName string,
sni bool,
peerCertMode,
caFile string,
chainCA string,
tlsCipher cisapiv1.TLSCipher,
) CustomProfile {
cp := CustomProfile{
Name: profile.Name,
Partition: profile.Partition,
Context: profile.Context,
Certificates: certificates,
ServerName: serverName,
SNIDefault: sni,
PeerCertMode: peerCertMode,
ChainCA: chainCA,
}
if peerCertMode == PeerCertRequired {
cp.CAFile = caFile
}
if tlsCipher.TLSVersion == string(TLSVerion1_3) {
cp.CipherGroup = tlsCipher.CipherGroup
} else {
cp.Ciphers = tlsCipher.Ciphers
}
return cp
}
func NewIRule(name, partition, code string) *IRule {
return &IRule{
Name: name,
Partition: partition,
Code: code,
}
}
// Creates an IRule if it doesn't already exist
func (rsCfg *ResourceConfig) addIRule(name, partition, rule string) {
key := NameRef{
Name: name,
Partition: partition,
}
if _, found := rsCfg.IRulesMap[key]; !found {
rsCfg.IRulesMap[key] = NewIRule(name, partition, rule)
}
}
func (rsCfg *ResourceConfig) removeIRule(name, partition string) {
key := NameRef{
Name: name,
Partition: partition,
}
delete(rsCfg.IRulesMap, key)
}
// Creates an InternalDataGroup if it doesn't already exist
func (rsCfg *ResourceConfig) addInternalDataGroup(name, partition string) DataGroupNamespaceMap {
key := NameRef{
Name: name,
Partition: partition,
}
if _, found := rsCfg.IntDgMap[key]; !found {
rsCfg.IntDgMap[key] = make(DataGroupNamespaceMap)
}
return rsCfg.IntDgMap[key]
}
func JoinBigipPath(partition, objName string) string {
if objName == "" {
return ""
}
if partition == "" {
return objName
}
return fmt.Sprintf("/%s/%s", partition, objName)
}
// Adds an IRule reference to a Virtual object
func (v *Virtual) AddIRule(ruleName string) bool {
for _, irule := range v.IRules {
// Skip adding iRule for "none" value
if irule == ruleName || irule == "none" {
return false
}
}
v.IRules = append(v.IRules, ruleName)
return true
}
func (slice ProfileRefs) Less(i, j int) bool {
return ((slice[i].Partition < slice[j].Partition) ||
(slice[i].Partition == slice[j].Partition &&
slice[i].Name < slice[j].Name))
}
func (slice ProfileRefs) Len() int {
return len(slice)
}
func (slice ProfileRefs) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
// Return the required ports for VS (depending on sslRedirect/allowHttp vals)
func (ctlr *Controller) virtualPorts(input interface{}) []portStruct {
http := portStruct{
protocol: "http",
port: DEFAULT_HTTP_PORT,
}
https := portStruct{
protocol: "https",
port: DEFAULT_HTTPS_PORT,
}
var ports []portStruct
switch input.(type) {
case *cisapiv1.VirtualServer:
vs := input.(*cisapiv1.VirtualServer)
if vs.Spec.VirtualServerHTTPPort != 0 {
http.port = vs.Spec.VirtualServerHTTPPort
}
if vs.Spec.VirtualServerHTTPSPort != 0 {
https.port = vs.Spec.VirtualServerHTTPSPort
}
ports = append(ports, http)
if len(vs.Spec.TLSProfileName) != 0 {
ports = append(ports, https)
}
}
return ports
}
// format the virtual server name for an VirtualServer
func formatVirtualServerName(ip string, port int32) string {
// Strip any bracket characters; replace special characters ". : /"
// with "-" and "%" with ".", for naming purposes
ip = strings.Trim(ip, "[]")
ip = AS3NameFormatter(ip)
return fmt.Sprintf("crd_%s_%d", ip, port)
}
// format the virtual server name for an VirtualServer
func formatCustomVirtualServerName(name string, port int32) string {
// Replace special characters ". : /"
// with "-" and "%" with ".", for naming purposes
name = AS3NameFormatter(name)
return fmt.Sprintf("%s_%d", name, port)
}
func (ctlr *Controller) framePoolNameForTS(ns string, pool cisapiv1.TSPool, host string) string {
poolName := pool.Name
if poolName == "" {
targetPort := pool.ServicePort
if (intstr.IntOrString{}) == targetPort {
svcNamespace := ns
if pool.ServiceNamespace != "" {
svcNamespace = pool.ServiceNamespace
}
targetPort = ctlr.fetchTargetPort(svcNamespace, pool.Service, pool.ServicePort, "")
}
poolName = ctlr.formatPoolName(ns, pool.Service, targetPort, pool.NodeMemberLabel, host, "")
}
return poolName
}
func (ctlr *Controller) framePoolNameForDefaultPool(ns string, pool cisapiv1.DefaultPool, host string) string {
poolName := pool.Name
if poolName == "" {
targetPort := pool.ServicePort
if (intstr.IntOrString{}) == targetPort {
svcNamespace := ns
if pool.ServiceNamespace != "" {
svcNamespace = pool.ServiceNamespace
}
targetPort = ctlr.fetchTargetPort(svcNamespace, pool.Service, pool.ServicePort, "")
}
poolName = ctlr.formatPoolName(ns, pool.Service, targetPort, pool.NodeMemberLabel, host, "")
}
return poolName
}
func (ctlr *Controller) framePoolNameForVs(ns string, pool cisapiv1.VSPool, host string, cxt SvcBackendCxt) string {
poolName := pool.Name
if poolName == "" || pool.AlternateBackends != nil {
targetPort := pool.ServicePort
svcNamespace := ns
if cxt.SvcNamespace != "" {
svcNamespace = cxt.SvcNamespace
}
if (intstr.IntOrString{}) == targetPort {
targetPort = ctlr.fetchTargetPort(svcNamespace, cxt.Name, pool.ServicePort, cxt.Cluster)
}
poolName = ctlr.formatPoolName(svcNamespace, cxt.Name, targetPort, pool.NodeMemberLabel, host, cxt.Cluster)
}
return poolName
}
// format the pool name for an VirtualServer
func (ctlr *Controller) formatPoolName(namespace, svc string, port intstr.IntOrString, nodeMemberLabel string, host, cluster string) string {
servicePort := fetchPortString(port)
poolName := fmt.Sprintf("%s_%s_%s", svc, servicePort, namespace)
if len(host) > 0 {
poolName = fmt.Sprintf("%s_%s", poolName, host)
}
if nodeMemberLabel != "" {
nodeMemberLabel = strings.ReplaceAll(nodeMemberLabel, "=", "_")
poolName = fmt.Sprintf("%s_%s", poolName, nodeMemberLabel)
}
// Attach cluster name to pool name only in case of multi-cluster ratio mode
if ctlr.multiClusterMode != "" && ctlr.haModeType == Ratio {
if cluster == "" {
cluster = ctlr.multiClusterConfigs.LocalClusterName
}
if cluster != "" {
poolName = fmt.Sprintf("%s_%s", poolName, cluster)
}
}
return AS3NameFormatter(poolName)
}
// format the monitor name for an VirtualServer pool
func formatMonitorName(namespace, svc string, monitorType string, port intstr.IntOrString, hostName string, path string) string {
monitorName := fmt.Sprintf("%s_%s", svc, namespace)
if len(hostName) > 0 {
monitorName = monitorName + fmt.Sprintf("_%s", hostName)
}
if len(path) > 0 && path != "/" {
if path[0] == '/' {
monitorName = monitorName + fmt.Sprintf("%s", path)
} else {
monitorName = monitorName + fmt.Sprintf("_%s", path)
}
}
if monitorType != "" && (port.IntVal != 0 || port.StrVal != "") {
servicePort := fetchPortString(port)
monitorName = monitorName + fmt.Sprintf("_%s_%s", monitorType, servicePort)
}
return AS3NameFormatter(monitorName)
}
// format the policy name for VirtualServer
func formatPolicyName(hostname, hostGroup, name string) string {
host := hostname
if hostGroup != "" {
host = hostGroup
}
if strings.HasPrefix(host, "*") {
host = strings.Replace(host, "*", "wildcard", 1)
}
policyName := fmt.Sprintf("%s_%s_%s", name, host, "policy")
return AS3NameFormatter(policyName)
}
// fetch target port from service
func (ctlr *Controller) fetchTargetPort(namespace, svcName string, servicePort intstr.IntOrString, cluster string) intstr.IntOrString {
var targetPort intstr.IntOrString
var svcIndexer cache.Indexer
var svc *v1.Service
svcKey := namespace + "/" + svcName
if cluster == "" {
if ctlr.watchingAllNamespaces() {
svcIndexer = ctlr.comInformers[""].svcInformer.GetIndexer()
} else {
if informer, ok := ctlr.comInformers[namespace]; ok {
svcIndexer = informer.svcInformer.GetIndexer()
} else {
return targetPort
}
}
item, found, _ := svcIndexer.GetByKey(svcKey)
if !found {
log.Debugf("service '%v' not found", svcKey)
var err error
item, found, err = ctlr.getSvcFromHACluster(namespace, svcName)
if !found {
if err != nil {
log.Debugf("[MultiCluster] could not fetch service %v ", err)
}
return targetPort
}
}
svc = item.(*v1.Service)
} else {
if _, ok := ctlr.multiClusterPoolInformers[cluster]; ok {
var poolInf *MultiClusterPoolInformer
var found bool
if poolInf, found = ctlr.multiClusterPoolInformers[cluster][""]; !found {
poolInf, found = ctlr.multiClusterPoolInformers[cluster][namespace]
}
if !found {
// If informers not found for the namespace, return empty targetPort
log.Warningf("[MultiCluster] Informer not found for namespace: %v in cluster: %s", namespace, cluster)
return targetPort
}
if poolInf.svcInformer != nil {
item, mFound, _ := poolInf.svcInformer.GetIndexer().GetByKey(svcKey)
if !mFound {
log.Warningf("[MultiCluster] service '%v' %s not found", svcKey, getClusterLog(cluster))
return targetPort
}
svc = item.(*v1.Service)
} else {
// If service informer not found return empty targetPort
return targetPort
}
} else {
// If informers not found for the cluster, return empty targetPort
return targetPort
}
}
for _, port := range svc.Spec.Ports {
if servicePort.StrVal == "" {
if port.Port == servicePort.IntVal {
// In case of named targetPort, send service port name to match endpoint name as targetPort
if port.TargetPort.StrVal != "" {
// port name is required when using the named targetPort
if port.Name != "" {
return intstr.IntOrString{StrVal: port.Name}
} else {
log.Errorf("port name should be defined with the named targetPort for service %v", svcKey)
return targetPort
}
}
return port.TargetPort
}
} else {
if port.Name == servicePort.StrVal {
// In case of named targetPort, send service port name to match endpoint name as targetPort
if port.TargetPort.StrVal != "" {
// port name is required when using the named targetPort
return intstr.IntOrString{StrVal: port.Name}
}
return port.TargetPort
}
}
}
return targetPort
}
// Prepares resource config based on VirtualServer resource config
func (ctlr *Controller) prepareRSConfigFromVirtualServer(
rsCfg *ResourceConfig,
vs *cisapiv1.VirtualServer,
passthroughVS bool,
tlsTermination string,
) error {
var httpsPort int32
var httpPort int32
if vs.Spec.VirtualServerHTTPSPort == 0 {
httpsPort = DEFAULT_HTTPS_PORT
} else {
httpsPort = vs.Spec.VirtualServerHTTPSPort
}
if vs.Spec.VirtualServerHTTPPort == 0 {
httpPort = DEFAULT_HTTP_PORT
} else {
httpPort = vs.Spec.VirtualServerHTTPPort
}
var snat string
snat = DEFAULT_SNAT
var pools Pools
var rules *Rules
rsRef := resourceRef{
name: vs.Name,
namespace: vs.Namespace,
kind: VirtualServer,
}
framedPools := make(map[string]struct{})
///TODO: get bigipLabel from cr resource or service address cr resource
// //Phase1 setting bigipLabel to default
bigipLabel := BigIPLabel
for _, pl := range vs.Spec.Pools {
//Fetch service backends with weights for pool
backendSvcs := ctlr.GetPoolBackends(&pl)
for _, SvcBackend := range backendSvcs {
poolName := ctlr.framePoolNameForVs(vs.Namespace, pl, vs.Spec.Host, SvcBackend)
if _, ok := framedPools[poolName]; ok {
// Pool with same name framed earlier, so skipping this pool
log.Debugf("Duplicate pool name: %v in Virtual Server: %v/%v", poolName, vs.Namespace, vs.Name)
continue
}
framedPools[poolName] = struct{}{}
svcNamespace := vs.Namespace
if SvcBackend.SvcNamespace != "" {
svcNamespace = SvcBackend.SvcNamespace
}
targetPort := ctlr.fetchTargetPort(svcNamespace, SvcBackend.Name, pl.ServicePort, SvcBackend.Cluster)
if (intstr.IntOrString{}) == targetPort {
targetPort = pl.ServicePort
}
pool := Pool{
Name: poolName,
Partition: rsCfg.Virtual.Partition,
ServiceName: SvcBackend.Name,
ServiceNamespace: svcNamespace,
ServicePort: targetPort,
NodeMemberLabel: pl.NodeMemberLabel,
Balance: pl.Balance,
MinimumMonitors: pl.MinimumMonitors,
ReselectTries: pl.ReselectTries,
ServiceDownAction: pl.ServiceDownAction,
Cluster: SvcBackend.Cluster, // In all modes other than ratio, the cluster is ""
}
if ctlr.multiClusterMode != "" {
//check for external service reference
if len(pl.MultiClusterServices) > 0 {
if _, ok := ctlr.multiClusterResources.rscSvcMap[rsRef]; !ok {
// only process if vs key is not present. else skip the processing
// on vs update we are clearing the resource service
// if event comes from vs then we will read and populate data, else we will skip processing
ctlr.processResourceExternalClusterServices(rsRef, pl.MultiClusterServices)
} else {
// prepare one of extended services key from pool
// to check if pool is processed before and svckey exists in rscSvcMap
// If not external cluster services for this pool will be added to rscSvcMap
externalSvcKey := MultiClusterServiceKey{
clusterName: pl.MultiClusterServices[0].ClusterName,
serviceName: pl.MultiClusterServices[0].SvcName,
namespace: pl.MultiClusterServices[0].Namespace,
}
// for multiple pools scenario vs resource reference exists after first pool is processed
// we still need to process if svckey doesnt exist in multicluster cluster rsMap
if _, ok := ctlr.multiClusterResources.rscSvcMap[rsRef][externalSvcKey]; !ok {
ctlr.processResourceExternalClusterServices(rsRef, pl.MultiClusterServices)
}
}
}
if ctlr.haModeType != Ratio {
if svcs, ok := ctlr.multiClusterResources.rscSvcMap[rsRef]; ok {
for svc, config := range svcs {
// update the clusterSvcMap
ctlr.updatePoolIdentifierForService(svc, rsRef, config.svcPort, pool.Name, pool.Partition, rsCfg.Virtual.Name, pl.Path, bigipLabel)
}
}
pool.MultiClusterServices = pl.MultiClusterServices
// update the multicluster resource serviceMap with local cluster services
ctlr.updateMultiClusterResourceServiceMap(rsCfg, rsRef, pl.Service, pl.Path, pool, pl.ServicePort, "", bigipLabel)
// update the multicluster resource serviceMap with HA pair cluster services
if ctlr.haModeType == Active && ctlr.multiClusterConfigs.HAPairClusterName != "" {
ctlr.updateMultiClusterResourceServiceMap(rsCfg, rsRef, pl.Service, pl.Path, pool, pl.ServicePort,
ctlr.multiClusterConfigs.HAPairClusterName, bigipLabel)
}
} else {
// Update the multiCluster resource service map for each pool which constitutes a service in case of ratio mode
ctlr.updateMultiClusterResourceServiceMap(rsCfg, rsRef, SvcBackend.Name, pl.Path, pool, pl.ServicePort, SvcBackend.Cluster, bigipLabel)
}
} else {
ctlr.updateMultiClusterResourceServiceMap(rsCfg, rsRef, pl.Service, pl.Path, pool, pl.ServicePort, "", bigipLabel)
}
// Update the pool Members
ctlr.updatePoolMembersForResources(&pool)
if len(pool.Members) > 0 {
rsCfg.MetaData.Active = true
}
if !reflect.DeepEqual(pl.Monitor, cisapiv1.Monitor{}) {
ctlr.createVirtualServerMonitor(pl.Monitor, &pool, rsCfg, pl.ServicePort, vs.Spec.Host, pl.Path,
vs.ObjectMeta.Namespace+"/"+vs.ObjectMeta.Name, SvcBackend.Cluster)
} else if pl.Monitors != nil {
var formatPort intstr.IntOrString
for _, monitor := range pl.Monitors {
if monitor.TargetPort != 0 {
formatPort = intstr.IntOrString{IntVal: monitor.TargetPort}
} else {
formatPort = pl.ServicePort
}
ctlr.createVirtualServerMonitor(monitor, &pool, rsCfg, formatPort, vs.Spec.Host, pl.Path,
vs.ObjectMeta.Namespace+"/"+vs.ObjectMeta.Name, SvcBackend.Cluster)
}
}
pools = append(pools, pool)
if tlsTermination != "" {
//Handle AB datagroup for secure virtualserver
if rsCfg.Virtual.VirtualAddress.Port == httpsPort || (rsCfg.Virtual.VirtualAddress.Port == httpPort && strings.ToLower(vs.Spec.HTTPTraffic) == TLSAllowInsecure) {
ctlr.updateDataGroupForABVirtualServer(&pl,
getRSCfgResName(rsCfg.Virtual.Name, AbDeploymentDgName),
rsCfg.Virtual.Partition,
vs.Namespace,
rsCfg.IntDgMap,
pl.ServicePort,
vs.Spec.Host,
tlsTermination,
)
//path based AB deployment/Cluster ratio not supported for passthrough
if (isVsPathBasedABDeployment(&pl) || isVsPathBasedRatioDeployment(&pl, ctlr.haModeType)) &&
(tlsTermination == TLSEdge ||
(tlsTermination == TLSReencrypt && strings.ToLower(vs.Spec.HTTPTraffic) != TLSAllowInsecure)) {
ctlr.HandlePathBasedABIRule(rsCfg, vs.Spec.Host, tlsTermination)
}
// handle AB traffic for edge termination with allow
if (isVSABDeployment(&pl) || ctlr.haModeType == Ratio) && rsCfg.Virtual.VirtualAddress.Port == httpPort && strings.ToLower(vs.Spec.HTTPTraffic) == TLSAllowInsecure {
ctlr.HandlePathBasedABIRule(rsCfg, vs.Spec.Host, tlsTermination)
}
}
} else {
if isVSABDeployment(&pl) || ctlr.haModeType == Ratio {
// Handle AB datagroup for insecure virtualserver
ctlr.updateDataGroupForABVirtualServer(&pl,
getRSCfgResName(rsCfg.Virtual.Name, AbDeploymentDgName),
rsCfg.Virtual.Partition,
vs.Namespace,
rsCfg.IntDgMap,
pl.ServicePort,
vs.Spec.Host,
tlsTermination,
)
// Handle AB path based IRules for insecure virtualserver
ctlr.HandlePathBasedABIRule(rsCfg, vs.Spec.Host, tlsTermination)
}
}
}
}
rsCfg.Pools = append(rsCfg.Pools, pools...)
// handle the default pool for virtual
ctlr.handleDefaultPool(rsCfg, vs, rsRef)
// set the SNAT policy to auto if it's not defined by end user
if vs.Spec.SNAT == "" {
if rsCfg.Virtual.SNAT == "" {
rsCfg.Virtual.SNAT = snat
}
} else {
rsCfg.Virtual.SNAT = vs.Spec.SNAT
}
if len(rsCfg.ServiceAddress) == 0 {
for _, sa := range vs.Spec.ServiceIPAddress {
rsCfg.ServiceAddress = append(rsCfg.ServiceAddress, ServiceAddress(sa))
}
}
// set the WAF policy
if vs.Spec.WAF != "" {
rsCfg.Virtual.WAF = vs.Spec.WAF
}
// set the ConnectionMirroring
if vs.Spec.ConnectionMirroring != "" {
rsCfg.Virtual.ConnectionMirroring = vs.Spec.ConnectionMirroring
}
//Attach allowVlans.
if len(vs.Spec.AllowVLANs) > 0 {
rsCfg.Virtual.AllowVLANs = vs.Spec.AllowVLANs
}
if vs.Spec.PersistenceProfile != "" {
rsCfg.Virtual.PersistenceProfile = vs.Spec.PersistenceProfile
}
if len(vs.Spec.Profiles.TCP.Client) > 0 || len(vs.Spec.Profiles.TCP.Server) > 0 {
rsCfg.Virtual.TCP.Client = vs.Spec.Profiles.TCP.Client
rsCfg.Virtual.TCP.Server = vs.Spec.Profiles.TCP.Server
}
if len(vs.Spec.Profiles.HTTP2.Client) > 0 || len(vs.Spec.Profiles.HTTP2.Server) > 0 {
rsCfg.Virtual.HTTP2.Client = vs.Spec.Profiles.HTTP2.Client
rsCfg.Virtual.HTTP2.Server = vs.Spec.Profiles.HTTP2.Server
}
if vs.Spec.DOS != "" {
rsCfg.Virtual.ProfileDOS = vs.Spec.DOS
}
if len(vs.Spec.AllowSourceRange) > 0 {
rsCfg.Virtual.AllowSourceRange = vs.Spec.AllowSourceRange
}
if vs.Spec.BotDefense != "" {
rsCfg.Virtual.ProfileBotDefense = vs.Spec.BotDefense
}
if vs.Spec.ProfileMultiplex != "" {
rsCfg.Virtual.ProfileMultiplex = vs.Spec.ProfileMultiplex
}
// check if custom http port set on virtual
if vs.Spec.VirtualServerHTTPPort != 0 {
httpPort = vs.Spec.VirtualServerHTTPPort
}
// Do not Create Virtual Server L7 Forwarding policies if HTTPTraffic is set to None or Redirect
if len(vs.Spec.TLSProfileName) > 0 &&
rsCfg.Virtual.VirtualAddress.Port == httpPort &&
(vs.Spec.HTTPTraffic == TLSNoInsecure || vs.Spec.HTTPTraffic == TLSRedirectInsecure) {
return nil
}
// skip the policy creation for passthrough termination
if !passthroughVS {
rules = ctlr.prepareVirtualServerRules(vs, rsCfg)
if rules == nil {
return fmt.Errorf("failed to create LTM Rules")
}
policyName := formatPolicyName(vs.Spec.Host, vs.Spec.HostGroup, rsCfg.Virtual.Name)
rsCfg.AddRuleToPolicy(policyName, vs.Namespace, rules)
}
// Attach user specified iRules
if len(vs.Spec.IRules) > 0 {
rsCfg.Virtual.IRules = append(rsCfg.Virtual.IRules, vs.Spec.IRules...)
}
// Append all the hosts from a host group/ single host
if vs.Spec.Host != "" {
rsCfg.MetaData.hosts = append(rsCfg.MetaData.hosts, vs.Spec.Host)
}
return nil
}
func (ctlr *Controller) createVirtualServerMonitor(monitor cisapiv1.Monitor, pool *Pool, rsCfg *ResourceConfig,
formatPort intstr.IntOrString, host, path, vsName string, cluster string) {
if !reflect.DeepEqual(monitor, Monitor{}) {
if monitor.Reference == BIGIP {
if monitor.Name != "" {
pool.MonitorNames = append(pool.MonitorNames, MonitorName{Name: monitor.Name, Reference: monitor.Reference})
} else {
log.Errorf("missing monitor name with bigip reference in virtual server: %v", vsName)
return
}
} else {
if (monitor.Type == HTTPS || monitor.Type == HTTP) && monitor.Send == "" {
log.Errorf("missing send string for monitor. skipping monitor for virtual server: %v", vsName)
return
}
monitorName := monitor.Name
if monitorName == "" {
monitorName = formatMonitorName(pool.ServiceNamespace, pool.ServiceName, monitor.Type, formatPort, host,
path)
}
// Format the monitor name in case of multi cluster ratio mode
monitorName = ctlr.formatMonitorNameForMultiCluster(monitorName, cluster)
pool.MonitorNames = append(pool.MonitorNames, MonitorName{Name: JoinBigipPath(rsCfg.Virtual.Partition, monitorName)})
monitor := Monitor{
Name: monitorName,
Partition: rsCfg.Virtual.Partition,
Type: monitor.Type,
Interval: monitor.Interval,
Send: monitor.Send,
Recv: monitor.Recv,
Timeout: monitor.Timeout,
TargetPort: monitor.TargetPort,
}
rsCfg.Monitors = append(rsCfg.Monitors, monitor)
}
}
}
func (ctlr *Controller) createTransportServerMonitor(monitor cisapiv1.Monitor, pool *Pool, rsCfg *ResourceConfig,
formatPort intstr.IntOrString, vsNamespace, vsName string) {
if !reflect.DeepEqual(monitor, Monitor{}) {
if monitor.Reference == BIGIP {
if monitor.Name != "" {
pool.MonitorNames = append(pool.MonitorNames, MonitorName{Name: monitor.Name, Reference: monitor.Reference})
} else {
log.Errorf("missing monitor name with bigip reference in transport server: %v", vsNamespace+"/"+vsName)
return
}
} else {
monitorName := monitor.Name
if monitorName == "" {
monitorName = formatMonitorName(vsNamespace, pool.ServiceName, monitor.Type, formatPort, "", "")
}
pool.MonitorNames = append(pool.MonitorNames, MonitorName{Name: JoinBigipPath(rsCfg.Virtual.Partition, monitorName)})
monitor := Monitor{
Name: monitorName,
Partition: rsCfg.Virtual.Partition,
Type: monitor.Type,
Interval: monitor.Interval,
Send: monitor.Send,
Recv: monitor.Recv,
Timeout: monitor.Timeout,
TargetPort: monitor.TargetPort,
}
rsCfg.Monitors = append(rsCfg.Monitors, monitor)
}
}
}
// Handle the default pool for virtual server
func (ctlr *Controller) handleDefaultPool(
rsCfg *ResourceConfig,
vs *cisapiv1.VirtualServer,
rsRef resourceRef,
) {
// if it's an insecure virtual server and vs traffic is redirect or none, we should not add the default pool
if rsCfg.MetaData.Protocol == HTTP && len(vs.Spec.TLSProfileName) > 0 && (vs.Spec.HTTPTraffic == TLSRedirectInsecure || vs.Spec.HTTPTraffic == TLSNoInsecure) {
return
}
///TODO: get bigipLabel from cr resource or service address cr resource
// //Phase1 setting bigipLabel to default
bigipLabel := BigIPLabel
if !reflect.DeepEqual(vs.Spec.DefaultPool, cisapiv1.DefaultPool{}) {
if vs.Spec.DefaultPool.Reference == BIGIP && vs.Spec.DefaultPool.Name != "" {
rsCfg.Virtual.PoolName = vs.Spec.DefaultPool.Name
rsCfg.MetaData.defaultPoolType = BIGIP
} else if vs.Spec.DefaultPool.Reference == ServiceRef {
rsCfg.Virtual.PoolName = ctlr.framePoolNameForDefaultPool(vs.Namespace, vs.Spec.DefaultPool, vs.Spec.Host)
svcNamespace := vs.Namespace
if vs.Spec.DefaultPool.ServiceNamespace != "" {
svcNamespace = vs.Spec.DefaultPool.ServiceNamespace
}
targetPort := ctlr.fetchTargetPort(svcNamespace, vs.Spec.DefaultPool.Service, vs.Spec.DefaultPool.ServicePort, "")
if (intstr.IntOrString{}) == targetPort {
targetPort = vs.Spec.DefaultPool.ServicePort
}
pool := Pool{
Name: rsCfg.Virtual.PoolName,
Partition: rsCfg.Virtual.Partition,
ServiceName: vs.Spec.DefaultPool.Service,
ServiceNamespace: svcNamespace,
ServicePort: targetPort,
NodeMemberLabel: vs.Spec.DefaultPool.NodeMemberLabel,
Balance: vs.Spec.DefaultPool.Balance,
ReselectTries: vs.Spec.DefaultPool.ReselectTries,
ServiceDownAction: vs.Spec.DefaultPool.ServiceDownAction,
}
if vs.Spec.DefaultPool.Monitors != nil {
for _, mtr := range vs.Spec.DefaultPool.Monitors {
var monitorName string
if mtr.Name != "" && mtr.Reference == BIGIP {
pool.MonitorNames = append(pool.MonitorNames, MonitorName{Name: mtr.Name, Reference: mtr.Reference})
} else {
var formatPort intstr.IntOrString
if mtr.TargetPort != 0 {
formatPort = intstr.IntOrString{IntVal: mtr.TargetPort}
} else {
formatPort = vs.Spec.DefaultPool.ServicePort
}
if mtr.Name == "" {
monitorName = formatMonitorName(svcNamespace, rsCfg.Virtual.PoolName, mtr.Type, formatPort, vs.Spec.Host, "")
}
pool.MonitorNames = append(pool.MonitorNames, MonitorName{Name: JoinBigipPath(rsCfg.Virtual.Partition, monitorName)})
mntr := Monitor{
Name: monitorName,
Partition: rsCfg.Virtual.Partition,
Type: mtr.Type,
Interval: mtr.Interval,
Send: mtr.Send,
Recv: mtr.Recv,
Timeout: mtr.Timeout,
TargetPort: mtr.TargetPort,
}
rsCfg.Monitors = append(rsCfg.Monitors, mntr)
}
}
}
ctlr.updateMultiClusterResourceServiceMap(rsCfg, rsRef, vs.Spec.DefaultPool.Service, "", pool, vs.Spec.DefaultPool.ServicePort, "", bigipLabel)
// Update the pool Members
ctlr.updatePoolMembersForResources(&pool)
rsCfg.Pools = append(rsCfg.Pools, pool)
}
}
}
func (rsCfg *ResourceConfig) AddRuleToPolicy(policyName, partition string, rules *Rules) {
// Update the existing policy with rules
// Otherwise create new policy and set
if policy := rsCfg.FindPolicy(PolicyControlForward); policy != nil {
policy.AddRules(rules)
rsCfg.SetPolicy(*policy)
return
}
plcy := createPolicy(*rules, policyName, partition)
if plcy != nil {
rsCfg.SetPolicy(*plcy)
}
}
// function updates the rscfg as per the passed parameter for routes as well as for virtual server
func (ctlr *Controller) handleTLS(
rsCfg *ResourceConfig,
tlsContext TLSContext,
) bool {
if rsCfg.Virtual.VirtualAddress.Port == tlsContext.httpsPort {
if tlsContext.termination != TLSPassthrough {
clientSSL := tlsContext.bigIPSSLProfiles.clientSSLs
serverSSL := tlsContext.bigIPSSLProfiles.serverSSLs
// Process Profile
switch tlsContext.referenceType {
case BIGIP:
log.Debugf("Processing BIGIP referenced profiles for '%s' '%s'/'%s'",
tlsContext.resourceType, tlsContext.namespace, tlsContext.name)
// Process referenced BIG-IP clientSSL
if len(clientSSL) > 0 {
for _, profile := range clientSSL {
clientProfRef := ConvertStringToProfileRef(
profile, CustomProfileClient, tlsContext.namespace)
rsCfg.Virtual.AddOrUpdateProfile(clientProfRef)
}
}
// Process referenced BIG-IP serverSSL
if len(serverSSL) > 0 {
for _, profile := range serverSSL {
serverProfRef := ConvertStringToProfileRef(
profile, CustomProfileServer, tlsContext.namespace)
rsCfg.Virtual.AddOrUpdateProfile(serverProfRef)
}
}
log.Debugf("Updated BIGIP referenced profiles for '%s' '%s'/'%s'",
tlsContext.resourceType, tlsContext.namespace, tlsContext.name)
case Secret:
// Process ClientSSL stored as kubernetes secret
var namespace string
if ctlr.watchingAllNamespaces() {
namespace = ""
} else {
namespace = tlsContext.namespace
}
if len(clientSSL) > 0 {
var secrets []*v1.Secret
for _, secretName := range clientSSL {
secretKey := tlsContext.namespace + "/" + secretName
if _, ok := ctlr.comInformers[namespace]; !ok {
return false
}
obj, found, err := ctlr.comInformers[namespace].secretsInformer.GetIndexer().GetByKey(secretKey)
if err != nil || !found {
log.Errorf("secret %s not found for '%s' '%s'/'%s'",
clientSSL, tlsContext.resourceType, tlsContext.namespace, tlsContext.name)
return false
}
secrets = append(secrets, obj.(*v1.Secret))
}
err, _ := ctlr.createSecretClientSSLProfile(rsCfg, secrets, ctlr.resources.baseRouteConfig.TLSCipher, CustomProfileClient)
if err != nil {
log.Errorf("error %v encountered while creating clientssl profile for '%s' '%s'/'%s'",
err, tlsContext.resourceType, tlsContext.namespace, tlsContext.name)
return false
}
}
// Process ServerSSL stored as kubernetes secret
if len(serverSSL) > 0 {
var secrets []*v1.Secret
for _, secret := range serverSSL {
secretKey := tlsContext.namespace + "/" + secret
if _, ok := ctlr.comInformers[namespace]; !ok {
return false
}
obj, found, err := ctlr.comInformers[namespace].secretsInformer.GetIndexer().GetByKey(secretKey)
if err != nil || !found {
log.Errorf("secret %s not found for '%s' '%s'/'%s'",
serverSSL, tlsContext.resourceType, tlsContext.namespace, tlsContext.name)
return false
}
secrets = append(secrets, obj.(*v1.Secret))
err, _ = ctlr.createSecretServerSSLProfile(rsCfg, secrets, ctlr.resources.baseRouteConfig.TLSCipher, CustomProfileServer)
if err != nil {
log.Errorf("error %v encountered while creating serverssl profile for '%s' '%s'/'%s'",
err, tlsContext.resourceType, tlsContext.namespace, tlsContext.name)
return false
}
}
}
case Certificate:
// Prepare SSL Transient Context
if tlsContext.bigIPSSLProfiles.key != "" && tlsContext.bigIPSSLProfiles.certificate != "" {
cert := certificate{Cert: tlsContext.bigIPSSLProfiles.certificate, Key: tlsContext.bigIPSSLProfiles.key}
err, _ := ctlr.createClientSSLProfile(rsCfg, []certificate{cert},
fmt.Sprintf("%s-clientssl", tlsContext.name), tlsContext.namespace, ctlr.resources.baseRouteConfig.TLSCipher, CustomProfileClient)
if err != nil {
log.Debugf("error %v encountered while creating clientssl profile for '%s' '%s'/'%s'",
err, tlsContext.resourceType, tlsContext.namespace, tlsContext.name)
return false
}
}
// Create Server SSL profile for bigip
if tlsContext.bigIPSSLProfiles.destinationCACertificate != "" {
var err error
cert := certificate{Cert: tlsContext.bigIPSSLProfiles.destinationCACertificate}
if tlsContext.bigIPSSLProfiles.caCertificate != "" {
err, _ = ctlr.createServerSSLProfile(rsCfg, []certificate{cert},
tlsContext.bigIPSSLProfiles.caCertificate, tlsContext.name, tlsContext.namespace, ctlr.resources.baseRouteConfig.TLSCipher, CustomProfileServer)
} else {
err, _ = ctlr.createServerSSLProfile(rsCfg, []certificate{cert},
"", fmt.Sprintf("%s-serverssl", tlsContext.name), tlsContext.namespace, ctlr.resources.baseRouteConfig.TLSCipher, CustomProfileServer)
}
if err != nil {
log.Debugf("error %v encountered while creating serverssl profile for '%s' '%s'/'%s'",
err, tlsContext.resourceType, tlsContext.namespace, tlsContext.name)
return false
}
}
default:
log.Errorf("Invalid reference type provided for '%s' '%s'/'%s'",
tlsContext.resourceType, tlsContext.namespace, tlsContext.name)
return false
}
// TLS Cert/Key
for _, poolPathRef := range tlsContext.poolPathRefs {
switch tlsContext.termination {
case TLSEdge:
serverSsl := "false"
for _, hostname := range poolPathRef.aliasHostnames {
sslPath := hostname + poolPathRef.path
sslPath = strings.TrimSuffix(sslPath, "/")
updateDataGroup(rsCfg.IntDgMap, getRSCfgResName(rsCfg.Virtual.Name, EdgeServerSslDgName),
rsCfg.Virtual.Partition, tlsContext.namespace, sslPath, serverSsl, DataGroupType)
}
case TLSReencrypt:
for _, hostname := range poolPathRef.aliasHostnames {
sslPath := hostname + poolPathRef.path
sslPath = strings.TrimSuffix(sslPath, "/")
if len(serverSSL) > 0 {
if tlsContext.referenceType == BIGIP {
// for bigip referenced profiles we need to add entries for all profiles