-
Notifications
You must be signed in to change notification settings - Fork 620
/
Copy pathloadbalancer.go
2302 lines (2027 loc) · 93.9 KB
/
loadbalancer.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 2016 The Kubernetes Authors.
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 openstack
import (
"context"
"encoding/json"
"fmt"
"net/http"
"regexp"
"slices"
"strconv"
"strings"
"github.com/gophercloud/gophercloud/v2"
"github.com/gophercloud/gophercloud/v2/openstack/keymanager/v1/containers"
"github.com/gophercloud/gophercloud/v2/openstack/keymanager/v1/secrets"
"github.com/gophercloud/gophercloud/v2/openstack/loadbalancer/v2/listeners"
"github.com/gophercloud/gophercloud/v2/openstack/loadbalancer/v2/loadbalancers"
v2monitors "github.com/gophercloud/gophercloud/v2/openstack/loadbalancer/v2/monitors"
v2pools "github.com/gophercloud/gophercloud/v2/openstack/loadbalancer/v2/pools"
"github.com/gophercloud/gophercloud/v2/openstack/networking/v2/extensions/layer3/floatingips"
"github.com/gophercloud/gophercloud/v2/openstack/networking/v2/subnets"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/sets"
cloudprovider "k8s.io/cloud-provider"
"k8s.io/klog/v2"
netutils "k8s.io/utils/net"
"k8s.io/utils/ptr"
"k8s.io/cloud-provider-openstack/pkg/metrics"
cpoutil "k8s.io/cloud-provider-openstack/pkg/util"
cpoerrors "k8s.io/cloud-provider-openstack/pkg/util/errors"
netsets "k8s.io/cloud-provider-openstack/pkg/util/net/sets"
openstackutil "k8s.io/cloud-provider-openstack/pkg/util/openstack"
)
// Note: when creating a new Loadbalancer (VM), it can take some time before it is ready for use,
// this timeout is used for waiting until the Loadbalancer provisioning status goes to ACTIVE state.
const (
defaultLoadBalancerSourceRangesIPv4 = "0.0.0.0/0"
defaultLoadBalancerSourceRangesIPv6 = "::/0"
activeStatus = "ACTIVE"
errorStatus = "ERROR"
annotationXForwardedFor = "X-Forwarded-For"
ServiceAnnotationLoadBalancerInternal = "service.beta.kubernetes.io/openstack-internal-load-balancer"
ServiceAnnotationLoadBalancerNodeSelector = "loadbalancer.openstack.org/node-selector"
ServiceAnnotationLoadBalancerConnLimit = "loadbalancer.openstack.org/connection-limit"
ServiceAnnotationLoadBalancerFloatingNetworkID = "loadbalancer.openstack.org/floating-network-id"
ServiceAnnotationLoadBalancerFloatingSubnet = "loadbalancer.openstack.org/floating-subnet"
ServiceAnnotationLoadBalancerFloatingSubnetID = "loadbalancer.openstack.org/floating-subnet-id"
ServiceAnnotationLoadBalancerFloatingSubnetTags = "loadbalancer.openstack.org/floating-subnet-tags"
ServiceAnnotationLoadBalancerClass = "loadbalancer.openstack.org/class"
ServiceAnnotationLoadBalancerKeepFloatingIP = "loadbalancer.openstack.org/keep-floatingip"
ServiceAnnotationLoadBalancerPortID = "loadbalancer.openstack.org/port-id"
ServiceAnnotationLoadBalancerLbMethod = "loadbalancer.openstack.org/lb-method"
ServiceAnnotationLoadBalancerProxyEnabled = "loadbalancer.openstack.org/proxy-protocol"
ServiceAnnotationLoadBalancerSubnetID = "loadbalancer.openstack.org/subnet-id"
ServiceAnnotationLoadBalancerNetworkID = "loadbalancer.openstack.org/network-id"
ServiceAnnotationLoadBalancerMemberSubnetID = "loadbalancer.openstack.org/member-subnet-id"
ServiceAnnotationLoadBalancerTimeoutClientData = "loadbalancer.openstack.org/timeout-client-data"
ServiceAnnotationLoadBalancerTimeoutMemberConnect = "loadbalancer.openstack.org/timeout-member-connect"
ServiceAnnotationLoadBalancerTimeoutMemberData = "loadbalancer.openstack.org/timeout-member-data"
ServiceAnnotationLoadBalancerTimeoutTCPInspect = "loadbalancer.openstack.org/timeout-tcp-inspect"
ServiceAnnotationLoadBalancerXForwardedFor = "loadbalancer.openstack.org/x-forwarded-for"
ServiceAnnotationLoadBalancerFlavorID = "loadbalancer.openstack.org/flavor-id"
ServiceAnnotationLoadBalancerAvailabilityZone = "loadbalancer.openstack.org/availability-zone"
// ServiceAnnotationLoadBalancerEnableHealthMonitor defines whether to create health monitor for the load balancer
// pool, if not specified, use 'create-monitor' config. The health monitor can be created or deleted dynamically.
ServiceAnnotationLoadBalancerEnableHealthMonitor = "loadbalancer.openstack.org/enable-health-monitor"
ServiceAnnotationLoadBalancerHealthMonitorDelay = "loadbalancer.openstack.org/health-monitor-delay"
ServiceAnnotationLoadBalancerHealthMonitorTimeout = "loadbalancer.openstack.org/health-monitor-timeout"
ServiceAnnotationLoadBalancerHealthMonitorMaxRetries = "loadbalancer.openstack.org/health-monitor-max-retries"
ServiceAnnotationLoadBalancerHealthMonitorMaxRetriesDown = "loadbalancer.openstack.org/health-monitor-max-retries-down"
ServiceAnnotationLoadBalancerLoadbalancerHostname = "loadbalancer.openstack.org/hostname"
ServiceAnnotationLoadBalancerAddress = "loadbalancer.openstack.org/load-balancer-address"
// revive:disable:var-naming
ServiceAnnotationTlsContainerRef = "loadbalancer.openstack.org/default-tls-container-ref"
// revive:enable:var-naming
// See https://nip.io
defaultProxyHostnameSuffix = "nip.io"
ServiceAnnotationLoadBalancerID = "loadbalancer.openstack.org/load-balancer-id"
// Octavia resources name formats
servicePrefix = "kube_service_"
lbFormat = "%s%s_%s_%s"
listenerPrefix = "listener_"
listenerFormat = listenerPrefix + "%d_%s"
poolPrefix = "pool_"
poolFormat = poolPrefix + "%d_%s"
monitorPrefix = "monitor_"
monitorFormat = monitorPrefix + "%d_%s"
)
// LbaasV2 is a LoadBalancer implementation based on Octavia
type LbaasV2 struct {
LoadBalancer
}
var _ cloudprovider.LoadBalancer = &LbaasV2{}
// serviceConfig contains configurations for creating a Service.
type serviceConfig struct {
internal bool
connLimit int
configClassName string
lbNetworkID string
lbSubnetID string
lbMemberSubnetID string
lbPublicNetworkID string
lbPublicSubnetSpec *floatingSubnetSpec
nodeSelectors map[string]string
keepClientIP bool
poolLbMethod string
proxyProtocolVersion *v2pools.Protocol
timeoutClientData int
timeoutMemberConnect int
timeoutMemberData int
timeoutTCPInspect int
allowedCIDR []string
enableMonitor bool
flavorID string
availabilityZone string
tlsContainerRef string
lbID string
lbName string
supportLBTags bool
healthCheckNodePort int
healthMonitorDelay int
healthMonitorTimeout int
healthMonitorMaxRetries int
healthMonitorMaxRetriesDown int
preferredIPFamily corev1.IPFamily // preferred (the first) IP family indicated in service's `spec.ipFamilies`
}
type listenerKey struct {
Protocol listeners.Protocol
Port int
}
// getLoadbalancerByName get the load balancer which is in valid status by the given name/legacy name.
func getLoadbalancerByName(ctx context.Context, client *gophercloud.ServiceClient, name string, legacyName string) (*loadbalancers.LoadBalancer, error) {
var validLBs []loadbalancers.LoadBalancer
opts := loadbalancers.ListOpts{
Name: name,
}
allLoadbalancers, err := openstackutil.GetLoadBalancers(ctx, client, opts)
if err != nil {
return nil, err
}
if len(allLoadbalancers) == 0 {
if len(legacyName) > 0 {
// Backoff to get load balnacer by legacy name.
opts := loadbalancers.ListOpts{
Name: legacyName,
}
allLoadbalancers, err = openstackutil.GetLoadBalancers(ctx, client, opts)
if err != nil {
return nil, err
}
} else {
return nil, cpoerrors.ErrNotFound
}
}
for _, lb := range allLoadbalancers {
// All the ProvisioningStatus could be found here https://developer.openstack.org/api-ref/load-balancer/v2/index.html#provisioning-status-codes
if lb.ProvisioningStatus != "DELETED" && lb.ProvisioningStatus != "PENDING_DELETE" {
validLBs = append(validLBs, lb)
}
}
if len(validLBs) > 1 {
return nil, cpoerrors.ErrMultipleResults
}
if len(validLBs) == 0 {
return nil, cpoerrors.ErrNotFound
}
return &validLBs[0], nil
}
func popListener(existingListeners []listeners.Listener, id string) []listeners.Listener {
newListeners := []listeners.Listener{}
for _, existingListener := range existingListeners {
if existingListener.ID != id {
newListeners = append(newListeners, existingListener)
}
}
return newListeners
}
func getListenerProtocol(protocol corev1.Protocol, svcConf *serviceConfig) listeners.Protocol {
// Make neutron-lbaas code work
if svcConf != nil {
if svcConf.tlsContainerRef != "" {
return listeners.ProtocolTerminatedHTTPS
} else if svcConf.keepClientIP {
return listeners.ProtocolHTTP
}
}
switch protocol {
case corev1.ProtocolTCP:
return listeners.ProtocolTCP
case corev1.ProtocolUDP:
return listeners.ProtocolUDP
default:
return listeners.Protocol(protocol)
}
}
func (lbaas *LbaasV2) createOctaviaLoadBalancer(ctx context.Context, name, clusterName string, service *corev1.Service, nodes []*corev1.Node, svcConf *serviceConfig) (*loadbalancers.LoadBalancer, error) {
createOpts := loadbalancers.CreateOpts{
Name: name,
Description: fmt.Sprintf("Kubernetes external service %s/%s from cluster %s", service.Namespace, service.Name, clusterName),
Provider: lbaas.opts.LBProvider,
}
if svcConf.supportLBTags {
createOpts.Tags = []string{svcConf.lbName}
}
if svcConf.flavorID != "" {
createOpts.FlavorID = svcConf.flavorID
}
if svcConf.availabilityZone != "" {
createOpts.AvailabilityZone = svcConf.availabilityZone
}
vipPort := getStringFromServiceAnnotation(service, ServiceAnnotationLoadBalancerPortID, "")
lbClass := lbaas.opts.LBClasses[svcConf.configClassName]
if vipPort != "" {
createOpts.VipPortID = vipPort
} else {
if lbClass != nil && lbClass.SubnetID != "" {
createOpts.VipSubnetID = lbClass.SubnetID
} else {
createOpts.VipSubnetID = svcConf.lbSubnetID
}
if lbClass != nil && lbClass.NetworkID != "" {
createOpts.VipNetworkID = lbClass.NetworkID
} else if svcConf.lbNetworkID != "" {
createOpts.VipNetworkID = svcConf.lbNetworkID
} else {
klog.V(4).Infof("network-id parameter not passed, it will be inferred from subnet-id")
}
}
// For external load balancer, the LoadBalancerIP is a public IP address.
loadBalancerIP := service.Spec.LoadBalancerIP
if loadBalancerIP != "" {
if svcConf.internal || (svcConf.preferredIPFamily == corev1.IPv6Protocol) {
createOpts.VipAddress = loadBalancerIP
}
}
if !lbaas.opts.ProviderRequiresSerialAPICalls {
for portIndex, port := range service.Spec.Ports {
listenerCreateOpt := lbaas.buildListenerCreateOpt(ctx, port, svcConf, cpoutil.Sprintf255(listenerFormat, portIndex, name))
members, newMembers, err := lbaas.buildCreateMemberOpts(ctx, port, nodes, svcConf)
if err != nil {
return nil, err
}
poolCreateOpt := lbaas.buildPoolCreateOpt(string(listenerCreateOpt.Protocol), service, svcConf, cpoutil.Sprintf255(poolFormat, portIndex, name))
poolCreateOpt.Members = members
// Pool name must be provided to create fully populated loadbalancer
var withHealthMonitor string
if svcConf.enableMonitor {
opts := lbaas.buildMonitorCreateOpts(ctx, svcConf, port, cpoutil.Sprintf255(monitorFormat, portIndex, name))
poolCreateOpt.Monitor = &opts
withHealthMonitor = " with healthmonitor"
}
listenerCreateOpt.DefaultPool = &poolCreateOpt
createOpts.Listeners = append(createOpts.Listeners, listenerCreateOpt)
klog.V(2).Infof("Loadbalancer %s: adding pool%s using protocol %s with %d members", name, withHealthMonitor, poolCreateOpt.Protocol, len(newMembers))
}
}
mc := metrics.NewMetricContext("loadbalancer", "create")
loadbalancer, err := loadbalancers.Create(ctx, lbaas.lb, createOpts).Extract()
if mc.ObserveRequest(err) != nil {
var printObj interface{} = createOpts
if opts, err := json.Marshal(createOpts); err == nil {
printObj = string(opts)
}
return nil, fmt.Errorf("error creating loadbalancer %v: %v", printObj, err)
}
// In case subnet ID is not configured
if svcConf.lbMemberSubnetID == "" {
svcConf.lbMemberSubnetID = loadbalancer.VipSubnetID
}
if loadbalancer, err = openstackutil.WaitActiveAndGetLoadBalancer(ctx, lbaas.lb, loadbalancer.ID); err != nil {
if loadbalancer != nil && loadbalancer.ProvisioningStatus == errorStatus {
// If LB landed in ERROR state we should delete it and retry the creation later.
if err = lbaas.deleteLoadBalancer(ctx, loadbalancer, service, svcConf, true); err != nil {
return nil, fmt.Errorf("loadbalancer %s is in ERROR state and there was an error when removing it: %v", loadbalancer.ID, err)
}
return nil, fmt.Errorf("loadbalancer %s has gone into ERROR state, please check Octavia for details. Load balancer was "+
"deleted and its creation will be retried", loadbalancer.ID)
}
return nil, err
}
return loadbalancer, nil
}
// GetLoadBalancer returns whether the specified load balancer exists and its status
func (lbaas *LbaasV2) GetLoadBalancer(ctx context.Context, clusterName string, service *corev1.Service) (*corev1.LoadBalancerStatus, bool, error) {
name := lbaas.GetLoadBalancerName(ctx, clusterName, service)
legacyName := lbaas.getLoadBalancerLegacyName(service)
lbID := getStringFromServiceAnnotation(service, ServiceAnnotationLoadBalancerID, "")
var loadbalancer *loadbalancers.LoadBalancer
var err error
if lbID != "" {
loadbalancer, err = openstackutil.GetLoadbalancerByID(ctx, lbaas.lb, lbID)
} else {
loadbalancer, err = getLoadbalancerByName(ctx, lbaas.lb, name, legacyName)
}
if err != nil && cpoerrors.IsNotFound(err) {
return nil, false, nil
}
if loadbalancer == nil {
return nil, false, err
}
status := &corev1.LoadBalancerStatus{}
portID := loadbalancer.VipPortID
if portID != "" {
floatIP, err := openstackutil.GetFloatingIPByPortID(ctx, lbaas.network, portID)
if err != nil {
return nil, false, fmt.Errorf("failed when trying to get floating IP for port %s: %v", portID, err)
}
if floatIP != nil {
status.Ingress = []corev1.LoadBalancerIngress{{IP: floatIP.FloatingIP}}
} else {
status.Ingress = []corev1.LoadBalancerIngress{{IP: loadbalancer.VipAddress}}
}
}
return status, true, nil
}
// GetLoadBalancerName returns the constructed load balancer name.
func (lbaas *LbaasV2) GetLoadBalancerName(_ context.Context, clusterName string, service *corev1.Service) string {
return cpoutil.Sprintf255(lbFormat, servicePrefix, clusterName, service.Namespace, service.Name)
}
// getLoadBalancerLegacyName returns the legacy load balancer name for backward compatibility.
func (lbaas *LbaasV2) getLoadBalancerLegacyName(service *corev1.Service) string {
return cloudprovider.DefaultLoadBalancerName(service)
}
// The LB needs to be configured with instance addresses on the same
// subnet as the LB (aka opts.SubnetID). Currently, we're just
// guessing that the node's InternalIP is the right address.
// In case no InternalIP can be found, ExternalIP is tried.
// If neither InternalIP nor ExternalIP can be found an error is
// returned.
// If preferredIPFamily is specified, only address of the specified IP family can be returned.
func nodeAddressForLB(node *corev1.Node, preferredIPFamily corev1.IPFamily) (string, error) {
addrs := node.Status.Addresses
if len(addrs) == 0 {
return "", cpoerrors.ErrNoAddressFound
}
allowedAddrTypes := []corev1.NodeAddressType{corev1.NodeInternalIP, corev1.NodeExternalIP}
for _, allowedAddrType := range allowedAddrTypes {
for _, addr := range addrs {
if addr.Type == allowedAddrType {
switch preferredIPFamily {
case corev1.IPv4Protocol:
if netutils.IsIPv4String(addr.Address) {
return addr.Address, nil
}
case corev1.IPv6Protocol:
if netutils.IsIPv6String(addr.Address) {
return addr.Address, nil
}
default:
return addr.Address, nil
}
}
}
}
return "", cpoerrors.ErrNoAddressFound
}
// getKeyValueFromServiceAnnotation converts a comma-separated list of key-value
// pairs from the specified annotation into a map or returns the specified
// defaultSetting if the annotation is empty
func getKeyValueFromServiceAnnotation(service *corev1.Service, annotationKey string, defaultSetting string) map[string]string {
annotationValue := getStringFromServiceAnnotation(service, annotationKey, defaultSetting)
return cpoutil.StringToMap(annotationValue)
}
// getStringFromServiceAnnotation searches a given v1.Service for a specific annotationKey and either returns the annotation's value or a specified defaultSetting
func getStringFromServiceAnnotation(service *corev1.Service, annotationKey string, defaultSetting string) string {
klog.V(4).Infof("getStringFromServiceAnnotation(%s/%s, %v, %v)", service.Namespace, service.Name, annotationKey, defaultSetting)
if annotationValue, ok := service.Annotations[annotationKey]; ok {
//if there is an annotation for this setting, set the "setting" var to it
// annotationValue can be empty, it is working as designed
// it makes possible for instance provisioning loadbalancer without floatingip
klog.V(4).Infof("Found a Service Annotation: %v = %v", annotationKey, annotationValue)
return annotationValue
}
//if there is no annotation, set "settings" var to the value from cloud config
if defaultSetting != "" {
klog.V(4).Infof("Could not find a Service Annotation; falling back on cloud-config setting: %v = %v", annotationKey, defaultSetting)
}
return defaultSetting
}
// getIntFromServiceAnnotation searches a given v1.Service for a specific annotationKey and either returns the annotation's integer value or a specified defaultSetting
func getIntFromServiceAnnotation(service *corev1.Service, annotationKey string, defaultSetting int) int {
klog.V(4).Infof("getIntFromServiceAnnotation(%s/%s, %v, %v)", service.Namespace, service.Name, annotationKey, defaultSetting)
if annotationValue, ok := service.Annotations[annotationKey]; ok {
returnValue, err := strconv.Atoi(annotationValue)
if err != nil {
klog.Warningf("Could not parse int value from %q, failing back to default %s = %v, %v", annotationValue, annotationKey, defaultSetting, err)
return defaultSetting
}
klog.V(4).Infof("Found a Service Annotation: %v = %v", annotationKey, annotationValue)
return returnValue
}
klog.V(4).Infof("Could not find a Service Annotation; falling back to default setting: %v = %v", annotationKey, defaultSetting)
return defaultSetting
}
// getBoolFromServiceAnnotation searches a given v1.Service for a specific annotationKey and either returns the annotation's boolean value or a specified defaultSetting
// If the annotation is not found or is not a valid boolean ("true" or "false"), it falls back to the defaultSetting and logs a message accordingly.
func getBoolFromServiceAnnotation(service *corev1.Service, annotationKey string, defaultSetting bool) bool {
klog.V(4).Infof("getBoolFromServiceAnnotation(%s/%s, %v, %v)", service.Namespace, service.Name, annotationKey, defaultSetting)
if annotationValue, ok := service.Annotations[annotationKey]; ok {
returnValue := false
switch annotationValue {
case "true":
returnValue = true
case "false":
returnValue = false
default:
klog.Infof("Found a non-boolean Service Annotation: %v = %v (falling back to default setting: %v)", annotationKey, annotationValue, defaultSetting)
return defaultSetting
}
klog.V(4).Infof("Found a Service Annotation: %v = %v", annotationKey, returnValue)
return returnValue
}
klog.V(4).Infof("Could not find a Service Annotation; falling back to default setting: %v = %v", annotationKey, defaultSetting)
return defaultSetting
}
// getProxyProtocolFromServiceAnnotation searches a given v1.Service the ServiceAnnotationLoadBalancerProxyEnabled to guess if the proxyProtocol needs to be
// enabled and return the ProxyProtocol's version which is need to be applied
func getProxyProtocolFromServiceAnnotation(service *corev1.Service) *v2pools.Protocol {
switch getStringFromServiceAnnotation(service, ServiceAnnotationLoadBalancerProxyEnabled, "false") {
case "true":
return ptr.To(v2pools.ProtocolPROXY)
case "v1":
return ptr.To(v2pools.ProtocolPROXY)
case "v2":
return ptr.To(v2pools.ProtocolPROXYV2)
default:
return nil
}
}
// getSubnetIDForLB returns subnet-id for a specific node
func getSubnetIDForLB(ctx context.Context, network *gophercloud.ServiceClient, node corev1.Node, preferredIPFamily corev1.IPFamily) (string, error) {
ipAddress, err := nodeAddressForLB(&node, preferredIPFamily)
if err != nil {
return "", err
}
instanceID, _, err := instanceIDFromProviderID(node.Spec.ProviderID)
if err != nil {
return "", fmt.Errorf("can't determine instance ID from ProviderID when autodetecting LB subnet: %w", err)
}
ports, err := getAttachedPorts(ctx, network, instanceID)
if err != nil {
return "", err
}
for _, port := range ports {
for _, fixedIP := range port.FixedIPs {
if fixedIP.IPAddress == ipAddress {
return fixedIP.SubnetID, nil
}
}
}
return "", cpoerrors.ErrNotFound
}
// isPortMember returns true if IP and subnetID are one of the FixedIPs on the port
func isPortMember(port PortWithPortSecurity, ip string, subnetID string) bool {
for _, fixedIP := range port.FixedIPs {
if (subnetID == "" || subnetID == fixedIP.SubnetID) && ip == fixedIP.IPAddress {
return true
}
}
return false
}
// deleteListeners deletes listeners and its default pool.
func (lbaas *LbaasV2) deleteListeners(ctx context.Context, lbID string, listenerList []listeners.Listener) error {
for _, listener := range listenerList {
klog.InfoS("Deleting listener", "listenerID", listener.ID, "lbID", lbID)
pool, err := openstackutil.GetPoolByListener(ctx, lbaas.lb, lbID, listener.ID)
if err != nil && err != cpoerrors.ErrNotFound {
return fmt.Errorf("error getting pool for obsolete listener %s: %v", listener.ID, err)
}
if pool != nil {
klog.InfoS("Deleting pool", "poolID", pool.ID, "listenerID", listener.ID, "lbID", lbID)
// Delete pool automatically deletes all its members.
if err := openstackutil.DeletePool(ctx, lbaas.lb, pool.ID, lbID); err != nil {
return err
}
klog.InfoS("Deleted pool", "poolID", pool.ID, "listenerID", listener.ID, "lbID", lbID)
}
if err := openstackutil.DeleteListener(ctx, lbaas.lb, listener.ID, lbID); err != nil {
return err
}
klog.InfoS("Deleted listener", "listenerID", listener.ID, "lbID", lbID)
}
return nil
}
// deleteOctaviaListeners is used not simply for deleting listeners but only deleting listeners used to be created by the Service.
func (lbaas *LbaasV2) deleteOctaviaListeners(ctx context.Context, lbID string, listenerList []listeners.Listener, isLBOwner bool, lbName string) error {
for _, listener := range listenerList {
// If the listener was created by this Service before or after supporting shared LB.
if (isLBOwner && len(listener.Tags) == 0) || slices.Contains(listener.Tags, lbName) {
klog.InfoS("Deleting listener", "listenerID", listener.ID, "lbID", lbID)
pool, err := openstackutil.GetPoolByListener(ctx, lbaas.lb, lbID, listener.ID)
if err != nil && err != cpoerrors.ErrNotFound {
return fmt.Errorf("error getting pool for listener %s: %v", listener.ID, err)
}
if pool != nil {
klog.InfoS("Deleting pool", "poolID", pool.ID, "listenerID", listener.ID, "lbID", lbID)
// Delete pool automatically deletes all its members.
if err := openstackutil.DeletePool(ctx, lbaas.lb, pool.ID, lbID); err != nil {
return err
}
klog.InfoS("Deleted pool", "poolID", pool.ID, "listenerID", listener.ID, "lbID", lbID)
}
if err := openstackutil.DeleteListener(ctx, lbaas.lb, listener.ID, lbID); err != nil {
return err
}
klog.InfoS("Deleted listener", "listenerID", listener.ID, "lbID", lbID)
} else {
// This listener is created and managed by others, shouldn't delete.
klog.V(4).InfoS("Ignoring the listener used by others", "listenerID", listener.ID, "loadbalancerID", lbID, "tags", listener.Tags)
continue
}
}
return nil
}
func (lbaas *LbaasV2) createFloatingIP(ctx context.Context, msg string, floatIPOpts floatingips.CreateOpts) (*floatingips.FloatingIP, error) {
klog.V(4).Infof("%s floating ip with opts %+v", msg, floatIPOpts)
mc := metrics.NewMetricContext("floating_ip", "create")
floatIP, err := floatingips.Create(ctx, lbaas.network, floatIPOpts).Extract()
err = PreserveGopherError(err)
if mc.ObserveRequest(err) != nil {
return floatIP, fmt.Errorf("error creating LB floatingip: %v", err)
}
return floatIP, err
}
func (lbaas *LbaasV2) updateFloatingIP(ctx context.Context, floatingip *floatingips.FloatingIP, portID *string) (*floatingips.FloatingIP, error) {
floatUpdateOpts := floatingips.UpdateOpts{
PortID: portID,
}
if portID != nil {
klog.V(4).Infof("Attaching floating ip %q to loadbalancer port %q", floatingip.FloatingIP, *portID)
} else {
klog.V(4).Infof("Detaching floating ip %q from port %q", floatingip.FloatingIP, floatingip.PortID)
}
mc := metrics.NewMetricContext("floating_ip", "update")
floatingip, err := floatingips.Update(ctx, lbaas.network, floatingip.ID, floatUpdateOpts).Extract()
if mc.ObserveRequest(err) != nil {
return nil, fmt.Errorf("error updating LB floatingip %+v: %v", floatUpdateOpts, err)
}
return floatingip, nil
}
// ensureFloatingIP manages a FIP for a Service and returns the address that should be advertised in the
// .Status.LoadBalancer. In particular it will:
// 1. Lookup if any FIP is already attached to the VIP port of the LB.
// a) If it is and Service is internal, it will attempt to detach the FIP and delete it if it was created
// by cloud provider. This is to support cases of changing the internal annotation.
// b) If the Service is not the owner of the LB it will not contiue to prevent accidental exposure of the
// possible internal Services already existing on that LB.
// c) If it's external Service, it will use that existing FIP.
// 2. Lookup FIP specified in Spec.LoadBalancerIP and try to assign it to the LB VIP port.
// 3. Try to create and assign a new FIP:
// a) If Spec.LoadBalancerIP is not set, just create a random FIP in the external network and use that.
// b) If Spec.LoadBalancerIP is specified, try to create a FIP with that address. By default this is not allowed by
// the Neutron policy for regular users!
func (lbaas *LbaasV2) ensureFloatingIP(ctx context.Context, clusterName string, service *corev1.Service, lb *loadbalancers.LoadBalancer, svcConf *serviceConfig, isLBOwner bool) (string, error) {
serviceName := fmt.Sprintf("%s/%s", service.Namespace, service.Name)
// We need to fetch the FIP attached to load balancer's VIP port for both codepaths
portID := lb.VipPortID
floatIP, err := openstackutil.GetFloatingIPByPortID(ctx, lbaas.network, portID)
if err != nil {
return "", fmt.Errorf("failed when getting floating IP for port %s: %v", portID, err)
}
if floatIP != nil {
klog.V(4).Infof("Found floating ip %v by loadbalancer port id %q", floatIP, portID)
}
if svcConf.internal && isLBOwner {
// if we found a FIP, this is an internal service and we are the owner we should attempt to delete it
if floatIP != nil {
keepFloatingAnnotation := getBoolFromServiceAnnotation(service, ServiceAnnotationLoadBalancerKeepFloatingIP, false)
fipDeleted := false
if !keepFloatingAnnotation {
klog.V(4).Infof("Deleting floating IP %v attached to loadbalancer port id %q for internal service %s", floatIP, portID, serviceName)
fipDeleted, err = lbaas.deleteFIPIfCreatedByProvider(ctx, floatIP, portID, service)
if err != nil {
return "", err
}
}
if !fipDeleted {
// if FIP wasn't deleted (because of keep-floatingip annotation or not being created by us) we should still detach it
_, err = lbaas.updateFloatingIP(ctx, floatIP, nil)
if err != nil {
return "", err
}
}
}
return lb.VipAddress, nil
}
// first attempt: if we've found a FIP attached to LBs VIP port, we'll be using that.
// we cannot add a FIP to a shared LB when we're a secondary Service or we risk adding it to an internal
// Service and exposing it to the world unintentionally.
if floatIP == nil && !isLBOwner {
return "", fmt.Errorf("cannot attach a floating IP to a load balancer for a shared Service %s/%s, only owner Service can do that",
service.Namespace, service.Name)
}
// second attempt: fetch floating IP specified in service Spec.LoadBalancerIP
// if found, associate floating IP with loadbalancer's VIP port
loadBalancerIP := service.Spec.LoadBalancerIP
if floatIP == nil && loadBalancerIP != "" {
opts := floatingips.ListOpts{
FloatingIP: loadBalancerIP,
}
existingIPs, err := openstackutil.GetFloatingIPs(ctx, lbaas.network, opts)
if err != nil {
return "", fmt.Errorf("failed when trying to get existing floating IP %s, error: %v", loadBalancerIP, err)
}
klog.V(4).Infof("Found floating ips %v by loadbalancer ip %q", existingIPs, loadBalancerIP)
if len(existingIPs) > 0 {
floatingip := existingIPs[0]
if len(floatingip.PortID) == 0 {
floatIP, err = lbaas.updateFloatingIP(ctx, &floatingip, &portID)
if err != nil {
return "", err
}
} else {
return "", fmt.Errorf("floating IP %s is not available", loadBalancerIP)
}
}
}
// third attempt: create a new floating IP
if floatIP == nil {
if svcConf.lbPublicNetworkID != "" {
klog.V(2).Infof("Creating floating IP %s for loadbalancer %s", loadBalancerIP, lb.ID)
floatIPOpts := floatingips.CreateOpts{
FloatingNetworkID: svcConf.lbPublicNetworkID,
PortID: portID,
Description: fmt.Sprintf("Floating IP for Kubernetes external service %s from cluster %s", serviceName, clusterName),
}
if loadBalancerIP == "" && svcConf.lbPublicSubnetSpec.matcherConfigured() {
var foundSubnet subnets.Subnet
// tweak list options for tags
foundSubnets, err := svcConf.lbPublicSubnetSpec.listSubnetsForNetwork(ctx, lbaas, svcConf.lbPublicNetworkID)
if err != nil {
return "", err
}
if len(foundSubnets) == 0 {
return "", fmt.Errorf("no subnet matching %s found for network %s",
svcConf.lbPublicSubnetSpec, svcConf.lbPublicNetworkID)
}
// try to create floating IP in matching subnets (tags already filtered by list options)
klog.V(4).Infof("found %d subnets matching %s for network %s", len(foundSubnets),
svcConf.lbPublicSubnetSpec, svcConf.lbPublicNetworkID)
for _, subnet := range foundSubnets {
floatIPOpts.SubnetID = subnet.ID
floatIP, err = lbaas.createFloatingIP(ctx, fmt.Sprintf("Trying subnet %s for creating", subnet.Name), floatIPOpts)
if err == nil {
foundSubnet = subnet
break
}
klog.V(2).Infof("cannot use subnet %s: %v", subnet.Name, err)
}
if err != nil {
return "", fmt.Errorf("no free subnet matching %q found for network %s (last error %v)",
svcConf.lbPublicSubnetSpec, svcConf.lbPublicNetworkID, err)
}
klog.V(2).Infof("Successfully created floating IP %s for loadbalancer %s on subnet %s(%s)", floatIP.FloatingIP, lb.ID, foundSubnet.Name, foundSubnet.ID)
} else {
if svcConf.lbPublicSubnetSpec != nil {
floatIPOpts.SubnetID = svcConf.lbPublicSubnetSpec.subnetID
}
floatIPOpts.FloatingIP = loadBalancerIP
floatIP, err = lbaas.createFloatingIP(ctx, "Creating", floatIPOpts)
if err != nil {
return "", err
}
klog.V(2).Infof("Successfully created floating IP %s for loadbalancer %s", floatIP.FloatingIP, lb.ID)
}
} else {
msg := "Floating network configuration not provided for Service %s, forcing to ensure an internal load balancer service"
lbaas.eventRecorder.Eventf(service, corev1.EventTypeWarning, eventLBForceInternal, msg, serviceName)
klog.Warningf(msg, serviceName)
}
}
if floatIP != nil {
return floatIP.FloatingIP, nil
}
return lb.VipAddress, nil
}
func (lbaas *LbaasV2) ensureOctaviaHealthMonitor(ctx context.Context, lbID string, name string, pool *v2pools.Pool, port corev1.ServicePort, svcConf *serviceConfig) error {
monitorID := pool.MonitorID
if monitorID == "" {
// do nothing
if !svcConf.enableMonitor {
return nil
}
// a new monitor must be created
klog.V(2).Infof("Creating monitor for pool %s", pool.ID)
createOpts := lbaas.buildMonitorCreateOpts(ctx, svcConf, port, name)
return lbaas.createOctaviaHealthMonitor(ctx, createOpts, pool.ID, lbID)
}
// an existing monitor must be deleted
if !svcConf.enableMonitor {
klog.Infof("Deleting health monitor %s for pool %s", monitorID, pool.ID)
return openstackutil.DeleteHealthMonitor(ctx, lbaas.lb, monitorID, lbID)
}
// get an existing monitor status
monitor, err := openstackutil.GetHealthMonitor(ctx, lbaas.lb, monitorID)
if err != nil {
// return err on 404 is ok, since we get monitorID dynamically from the pool
return err
}
// recreate health monitor with a new type
createOpts := lbaas.buildMonitorCreateOpts(ctx, svcConf, port, name)
if createOpts.Type != monitor.Type {
klog.InfoS("Recreating health monitor for the pool", "pool", pool.ID, "oldMonitor", monitorID)
if err := openstackutil.DeleteHealthMonitor(ctx, lbaas.lb, monitorID, lbID); err != nil {
return err
}
return lbaas.createOctaviaHealthMonitor(ctx, createOpts, pool.ID, lbID)
}
// update new monitor parameters
if name != monitor.Name ||
svcConf.healthMonitorDelay != monitor.Delay ||
svcConf.healthMonitorTimeout != monitor.Timeout ||
svcConf.healthMonitorMaxRetries != monitor.MaxRetries ||
svcConf.healthMonitorMaxRetriesDown != monitor.MaxRetriesDown {
updateOpts := v2monitors.UpdateOpts{
Name: &name,
Delay: svcConf.healthMonitorDelay,
Timeout: svcConf.healthMonitorTimeout,
MaxRetries: svcConf.healthMonitorMaxRetries,
MaxRetriesDown: svcConf.healthMonitorMaxRetriesDown,
}
klog.Infof("Updating health monitor %s updateOpts %+v", monitorID, updateOpts)
return openstackutil.UpdateHealthMonitor(ctx, lbaas.lb, monitorID, updateOpts, lbID)
}
return nil
}
func (lbaas *LbaasV2) canUseHTTPMonitor(ctx context.Context, port corev1.ServicePort) bool {
if lbaas.opts.LBProvider == "ovn" {
// ovn-octavia-provider doesn't support HTTP monitors at all. We got to avoid creating it with ovn.
return false
}
if port.Protocol == corev1.ProtocolUDP {
// Older Octavia versions or OVN provider doesn't support HTTP monitors on UDP pools. We got to check if that's the case.
return openstackutil.IsOctaviaFeatureSupported(ctx, lbaas.lb, openstackutil.OctaviaFeatureHTTPMonitorsOnUDP, lbaas.opts.LBProvider)
}
return true
}
// buildMonitorCreateOpts returns a v2monitors.CreateOpts without PoolID for consumption of both, fully popuplated Loadbalancers and Monitors.
func (lbaas *LbaasV2) buildMonitorCreateOpts(ctx context.Context, svcConf *serviceConfig, port corev1.ServicePort, name string) v2monitors.CreateOpts {
opts := v2monitors.CreateOpts{
Name: name,
Type: string(port.Protocol),
Delay: svcConf.healthMonitorDelay,
Timeout: svcConf.healthMonitorTimeout,
MaxRetries: svcConf.healthMonitorMaxRetries,
MaxRetriesDown: svcConf.healthMonitorMaxRetriesDown,
}
if port.Protocol == corev1.ProtocolUDP {
opts.Type = "UDP-CONNECT"
}
if svcConf.healthCheckNodePort > 0 && lbaas.canUseHTTPMonitor(ctx, port) {
opts.Type = "HTTP"
opts.URLPath = "/healthz"
opts.HTTPMethod = "GET"
opts.ExpectedCodes = "200"
}
return opts
}
func (lbaas *LbaasV2) createOctaviaHealthMonitor(ctx context.Context, createOpts v2monitors.CreateOpts, poolID, lbID string) error {
// populate PoolID, attribute is omitted for consumption of the createOpts for fully populated Loadbalancer
createOpts.PoolID = poolID
monitor, err := openstackutil.CreateHealthMonitor(ctx, lbaas.lb, createOpts, lbID)
if err != nil {
return err
}
klog.Infof("Health monitor %s for pool %s created.", monitor.ID, poolID)
return nil
}
// Make sure the pool is created for the Service, nodes are added as pool members.
func (lbaas *LbaasV2) ensureOctaviaPool(ctx context.Context, lbID string, name string, listener *listeners.Listener, service *corev1.Service, port corev1.ServicePort, nodes []*corev1.Node, svcConf *serviceConfig) (*v2pools.Pool, error) {
pool, err := openstackutil.GetPoolByListener(ctx, lbaas.lb, lbID, listener.ID)
if err != nil && err != cpoerrors.ErrNotFound {
return nil, fmt.Errorf("error getting pool for listener %s: %v", listener.ID, err)
}
// By default, use the protocol of the listener
poolProto := v2pools.Protocol(listener.Protocol)
if svcConf.proxyProtocolVersion != nil {
poolProto = *svcConf.proxyProtocolVersion
} else if (svcConf.keepClientIP || svcConf.tlsContainerRef != "") && poolProto != v2pools.ProtocolHTTP {
poolProto = v2pools.ProtocolHTTP
}
// Delete the pool and its members if it already exists and has the wrong protocol
if pool != nil && v2pools.Protocol(pool.Protocol) != poolProto {
klog.InfoS("Deleting unused pool", "poolID", pool.ID, "listenerID", listener.ID, "lbID", lbID)
// Delete pool automatically deletes all its members.
if err := openstackutil.DeletePool(ctx, lbaas.lb, pool.ID, lbID); err != nil {
return nil, err
}
pool = nil
}
// If LBMethod changes, update the Pool with the new value
var poolLbMethod string
if svcConf.poolLbMethod != "" {
poolLbMethod = svcConf.poolLbMethod
} else {
// if LBMethod is not defined, fallback on default OCCM's default method
poolLbMethod = lbaas.opts.LBMethod
}
if pool != nil && pool.LBMethod != poolLbMethod {
klog.InfoS("Updating LoadBalancer LBMethod", "poolID", pool.ID, "listenerID", listener.ID, "lbID", lbID)
err = openstackutil.UpdatePool(ctx, lbaas.lb, lbID, pool.ID, v2pools.UpdateOpts{LBMethod: v2pools.LBMethod(poolLbMethod)})
if err != nil {
err = PreserveGopherError(err)
msg := fmt.Sprintf("Error updating LB method for LoadBalancer: %v", err)
klog.Errorf(msg, "poolID", pool.ID, "listenerID", listener.ID, "lbID", lbID)
lbaas.eventRecorder.Eventf(service, corev1.EventTypeWarning, eventLBLbMethodUnknown, msg)
} else {
pool.LBMethod = poolLbMethod
}
}
if pool == nil {
createOpt := lbaas.buildPoolCreateOpt(listener.Protocol, service, svcConf, name)
createOpt.ListenerID = listener.ID
klog.InfoS("Creating pool", "listenerID", listener.ID, "protocol", createOpt.Protocol)
pool, err = openstackutil.CreatePool(ctx, lbaas.lb, createOpt, lbID)
if err != nil {
return nil, err
}
klog.V(2).Infof("Pool %s created for listener %s", pool.ID, listener.ID)
}
if lbaas.opts.ProviderRequiresSerialAPICalls {
klog.V(2).Infof("Using serial API calls to update members for pool %s", pool.ID)
var nodePort int = int(port.NodePort)
if err := openstackutil.SeriallyReconcilePoolMembers(ctx, lbaas.lb, pool, nodePort, lbID, nodes); err != nil {
return nil, err
}
return pool, nil
}
curMembers := sets.New[string]()
poolMembers, err := openstackutil.GetMembersbyPool(ctx, lbaas.lb, pool.ID)
if err != nil {
klog.Errorf("failed to get members in the pool %s: %v", pool.ID, err)
}
for _, m := range poolMembers {
curMembers.Insert(fmt.Sprintf("%s-%s-%d-%d", m.Name, m.Address, m.ProtocolPort, m.MonitorPort))
}
members, newMembers, err := lbaas.buildBatchUpdateMemberOpts(ctx, port, nodes, svcConf)
if err != nil {
return nil, err
}
if !curMembers.Equal(newMembers) {
klog.V(2).Infof("Updating %d members for pool %s", len(members), pool.ID)
if err := openstackutil.BatchUpdatePoolMembers(ctx, lbaas.lb, lbID, pool.ID, members); err != nil {
return nil, err
}
klog.V(2).Infof("Successfully updated %d members for pool %s", len(members), pool.ID)
}
return pool, nil
}
func (lbaas *LbaasV2) buildPoolCreateOpt(listenerProtocol string, service *corev1.Service, svcConf *serviceConfig, name string) v2pools.CreateOpts {
// By default, use the protocol of the listener
poolProto := v2pools.Protocol(listenerProtocol)
if svcConf.proxyProtocolVersion != nil {
poolProto = *svcConf.proxyProtocolVersion
} else if (svcConf.keepClientIP || svcConf.tlsContainerRef != "") && poolProto != v2pools.ProtocolHTTP {
if svcConf.keepClientIP && svcConf.tlsContainerRef != "" {
klog.V(4).Infof("Forcing to use %q protocol for pool because annotations %q %q are set", v2pools.ProtocolHTTP, ServiceAnnotationLoadBalancerXForwardedFor, ServiceAnnotationTlsContainerRef)
} else if svcConf.keepClientIP {
klog.V(4).Infof("Forcing to use %q protocol for pool because annotation %q is set", v2pools.ProtocolHTTP, ServiceAnnotationLoadBalancerXForwardedFor)
} else {
klog.V(4).Infof("Forcing to use %q protocol for pool because annotations %q is set", v2pools.ProtocolHTTP, ServiceAnnotationTlsContainerRef)
}
poolProto = v2pools.ProtocolHTTP
}
affinity := service.Spec.SessionAffinity
var persistence *v2pools.SessionPersistence
switch affinity {
case corev1.ServiceAffinityNone:
persistence = nil
case corev1.ServiceAffinityClientIP:
persistence = &v2pools.SessionPersistence{Type: "SOURCE_IP"}
}
var lbMethod v2pools.LBMethod
if svcConf.poolLbMethod != "" {
lbMethod = v2pools.LBMethod(svcConf.poolLbMethod)