-
Notifications
You must be signed in to change notification settings - Fork 621
/
Copy pathloadbalancer.go
2681 lines (2369 loc) · 104 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"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/openstack/keymanager/v1/containers"
"github.com/gophercloud/gophercloud/openstack/loadbalancer/v2/listeners"
"github.com/gophercloud/gophercloud/openstack/loadbalancer/v2/loadbalancers"
v2monitors "github.com/gophercloud/gophercloud/openstack/loadbalancer/v2/monitors"
v2pools "github.com/gophercloud/gophercloud/openstack/loadbalancer/v2/pools"
neutrontags "github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/attributestags"
"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/layer3/floatingips"
"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/security/groups"
"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/security/rules"
neutronports "github.com/gophercloud/gophercloud/openstack/networking/v2/ports"
"github.com/gophercloud/gophercloud/openstack/networking/v2/subnets"
secgroups "github.com/gophercloud/utils/openstack/networking/v2/extensions/security/groups"
"gopkg.in/godo.v2/glob"
corev1 "k8s.io/api/core/v1"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/kubernetes"
cloudprovider "k8s.io/cloud-provider"
"k8s.io/klog/v2"
netutils "k8s.io/utils/net"
"k8s.io/utils/strings/slices"
"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 (
servicePrefix = "kube_service_"
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"
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"
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
lbFormat = "%s%s_%s_%s"
listenerFormat = "listener_%d_%s"
poolFormat = "pool_%d_%s"
monitorFormat = "monitor_%d_%s"
)
// LbaasV2 is a LoadBalancer implementation based on Octavia
type LbaasV2 struct {
LoadBalancer
}
// floatingSubnetSpec contains the specification of the public subnet to use for
// a public network. If given it may either describe the subnet id or
// a subnet name pattern for the subnet to use. If a pattern is given
// the first subnet matching the name pattern with an allocatable floating ip
// will be selected.
type floatingSubnetSpec struct {
subnetID string
subnet string
subnetTags string
}
// TweakSubNetListOpsFunction is used to modify List Options for subnets
type TweakSubNetListOpsFunction func(*subnets.ListOpts)
// matcher matches a subnet
type matcher func(subnet *subnets.Subnet) bool
type servicePatcher struct {
kclient kubernetes.Interface
base *corev1.Service
updated *corev1.Service
}
var _ cloudprovider.LoadBalancer = &LbaasV2{}
// negate returns a negated matches for a given one
func negate(f matcher) matcher { return func(s *subnets.Subnet) bool { return !f(s) } }
func andMatcher(a, b matcher) matcher {
if a == nil {
return b
}
if b == nil {
return a
}
return func(s *subnets.Subnet) bool {
return a(s) && b(s)
}
}
// reexpNameMatcher creates a subnet matcher matching a subnet by name for a given regexp.
func regexpNameMatcher(r *regexp.Regexp) matcher {
return func(s *subnets.Subnet) bool { return r.FindString(s.Name) == s.Name }
}
// subnetNameMatcher creates a subnet matcher matching a subnet by name for a given glob
// or regexp
func subnetNameMatcher(pat string) (matcher, error) {
// try to create floating IP in matching subnets
var match matcher
not := false
if strings.HasPrefix(pat, "!") {
not = true
pat = pat[1:]
}
if strings.HasPrefix(pat, "~") {
rexp, err := regexp.Compile(pat[1:])
if err != nil {
return nil, fmt.Errorf("invalid subnet regexp pattern %q: %s", pat[1:], err)
}
match = regexpNameMatcher(rexp)
} else {
match = regexpNameMatcher(glob.Globexp(pat))
}
if not {
match = negate(match)
}
return match, nil
}
// subnetTagMatcher matches a subnet by a given tag spec
func subnetTagMatcher(tags string) matcher {
// try to create floating IP in matching subnets
var match matcher
list, not, all := tagList(tags)
match = func(s *subnets.Subnet) bool {
for _, tag := range list {
found := false
for _, t := range s.Tags {
if t == tag {
found = true
break
}
}
if found {
if !all {
return !not
}
} else {
if all {
return not
}
}
}
return not != all
}
return match
}
func (s *floatingSubnetSpec) Configured() bool {
if s != nil && (s.subnetID != "" || s.MatcherConfigured()) {
return true
}
return false
}
func (s *floatingSubnetSpec) ListSubnetsForNetwork(lbaas *LbaasV2, networkID string) ([]subnets.Subnet, error) {
matcher, err := s.Matcher(false)
if err != nil {
return nil, err
}
list, err := lbaas.listSubnetsForNetwork(networkID, s.tweakListOpts)
if err != nil {
return nil, err
}
if matcher == nil {
return list, nil
}
// filter subnets according to spec
var foundSubnets []subnets.Subnet
for _, subnet := range list {
if matcher(&subnet) {
foundSubnets = append(foundSubnets, subnet)
}
}
return foundSubnets, nil
}
// tweakListOpts can be used to optimize a subnet list query for the
// actually described subnet filter
func (s *floatingSubnetSpec) tweakListOpts(opts *subnets.ListOpts) {
if s.subnetTags != "" {
list, not, all := tagList(s.subnetTags)
tags := strings.Join(list, ",")
if all {
if not {
opts.NotTagsAny = tags // at least one tag must be missing
} else {
opts.Tags = tags // all tags must be present
}
} else {
if not {
opts.NotTags = tags // none of the tags are present
} else {
opts.TagsAny = tags // at least one tag is present
}
}
}
}
func (s *floatingSubnetSpec) MatcherConfigured() bool {
if s != nil && s.subnetID == "" && (s.subnet != "" || s.subnetTags != "") {
return true
}
return false
}
func addField(s, name, value string) string {
if value == "" {
return s
}
if s == "" {
s += ", "
}
return fmt.Sprintf("%s%s: %q", s, name, value)
}
func (s *floatingSubnetSpec) String() string {
if s == nil || (s.subnetID == "" && s.subnet == "" && s.subnetTags == "") {
return "<none>"
}
pat := addField("", "subnetID", s.subnetID)
pat = addField(pat, "pattern", s.subnet)
return addField(pat, "tags", s.subnetTags)
}
func (s *floatingSubnetSpec) Matcher(tag bool) (matcher, error) {
if !s.MatcherConfigured() {
return nil, nil
}
var match matcher
var err error
if s.subnet != "" {
match, err = subnetNameMatcher(s.subnet)
if err != nil {
return nil, err
}
}
if tag && s.subnetTags != "" {
match = andMatcher(match, subnetTagMatcher(s.subnetTags))
}
if match == nil {
match = func(s *subnets.Subnet) bool { return true }
}
return match, nil
}
func tagList(tags string) ([]string, bool, bool) {
not := strings.HasPrefix(tags, "!")
if not {
tags = tags[1:]
}
all := strings.HasPrefix(tags, "&")
if all {
tags = tags[1:]
}
list := strings.Split(tags, ",")
for i := range list {
list[i] = strings.TrimSpace(list[i])
}
return list, not, all
}
// 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
keepClientIP bool
enableProxyProtocol bool
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(client *gophercloud.ServiceClient, name string, legacyName string) (*loadbalancers.LoadBalancer, error) {
var validLBs []loadbalancers.LoadBalancer
opts := loadbalancers.ListOpts{
Name: name,
}
allLoadbalancers, err := openstackutil.GetLoadBalancers(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(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 getSecurityGroupName(service *corev1.Service) string {
securityGroupName := fmt.Sprintf("lb-sg-%s-%s-%s", service.UID, service.Namespace, service.Name)
//OpenStack requires that the name of a security group is shorter than 255 bytes.
if len(securityGroupName) > 255 {
securityGroupName = securityGroupName[:255]
}
return securityGroupName
}
func getSecurityGroupRules(client *gophercloud.ServiceClient, opts rules.ListOpts) ([]rules.SecGroupRule, error) {
mc := metrics.NewMetricContext("security_group_rule", "list")
page, err := rules.List(client, opts).AllPages()
if mc.ObserveRequest(err) != nil {
return nil, err
}
return rules.ExtractRules(page)
}
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(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 != "" && svcConf.internal {
createOpts.VipAddress = loadBalancerIP
}
if !lbaas.opts.ProviderRequiresSerialAPICalls {
for portIndex, port := range service.Spec.Ports {
listenerCreateOpt := lbaas.buildListenerCreateOpt(port, svcConf, cpoutil.Sprintf255(listenerFormat, portIndex, name))
members, newMembers, err := lbaas.buildBatchUpdateMemberOpts(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(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(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(lbaas.lb, loadbalancer.ID); err != nil {
if loadbalancer.ProvisioningStatus == errorStatus {
// If LB landed in ERROR state we should delete it and retry the creation later.
if err = lbaas.deleteLoadBalancer(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(ctx, clusterName, service)
lbID := getStringFromServiceAnnotation(service, ServiceAnnotationLoadBalancerID, "")
var loadbalancer *loadbalancers.LoadBalancer
var err error
if lbID != "" {
loadbalancer, err = openstackutil.GetLoadbalancerByID(lbaas.lb, lbID)
} else {
loadbalancer, err = getLoadbalancerByName(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(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(_ context.Context, _ string, 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
}
// 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
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:
returnValue = 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
}
// getSubnetIDForLB returns subnet-id for a specific node
func getSubnetIDForLB(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(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
}
// applyNodeSecurityGroupIDForLB associates the security group with all the ports on the nodes.
func applyNodeSecurityGroupIDForLB(network *gophercloud.ServiceClient, nodes []*corev1.Node, sg string) error {
for _, node := range nodes {
serverID, _, err := instanceIDFromProviderID(node.Spec.ProviderID)
if err != nil {
return fmt.Errorf("error getting server ID from the node: %w", err)
}
listOpts := neutronports.ListOpts{DeviceID: serverID}
allPorts, err := openstackutil.GetPorts(network, listOpts)
if err != nil {
return err
}
for _, port := range allPorts {
// If the Security Group is already present on the port, skip it.
if slices.Contains(port.SecurityGroups, sg) {
continue
}
// Add the SG to the port
// TODO(dulek): This isn't an atomic operation. In order to protect from lost update issues we should use
// `revision_number` handling to make sure our update to `security_groups` field wasn't preceded
// by a different one. Same applies to a removal of the SG.
newSGs := append(port.SecurityGroups, sg)
updateOpts := neutronports.UpdateOpts{SecurityGroups: &newSGs}
mc := metrics.NewMetricContext("port", "update")
res := neutronports.Update(network, port.ID, updateOpts)
if mc.ObserveRequest(res.Err) != nil {
return fmt.Errorf("failed to update security group for port %s: %v", port.ID, res.Err)
}
}
}
return nil
}
// disassociateSecurityGroupForLB removes the given security group from the ports
func disassociateSecurityGroupForLB(network *gophercloud.ServiceClient, sg string) error {
// Find all the ports that have the security group associated.
listOpts := neutronports.ListOpts{SecurityGroups: []string{sg}}
allPorts, err := openstackutil.GetPorts(network, listOpts)
if err != nil {
return err
}
// Disassocate security group and remove the tag.
for _, port := range allPorts {
existingSGs := sets.NewString()
for _, sgID := range port.SecurityGroups {
existingSGs.Insert(sgID)
}
existingSGs.Delete(sg)
// Update port security groups
newSGs := existingSGs.List()
// TODO(dulek): This should be done using Neutron's revision_number to make sure
// we don't trigger a lost update issue.
updateOpts := neutronports.UpdateOpts{SecurityGroups: &newSGs}
mc := metrics.NewMetricContext("port", "update")
res := neutronports.Update(network, port.ID, updateOpts)
if mc.ObserveRequest(res.Err) != nil {
return fmt.Errorf("failed to update security group for port %s: %v", port.ID, res.Err)
}
// Remove the security group ID tag from the port. Please note we don't tag ports with SG IDs anymore,
// so this stays for backward compatibility. It's reasonable to delete it in the future. 404s are ignored.
if slices.Contains(port.Tags, sg) {
mc = metrics.NewMetricContext("port_tag", "delete")
err := neutrontags.Delete(network, "ports", port.ID, sg).ExtractErr()
if mc.ObserveRequest(err) != nil {
return fmt.Errorf("failed to remove tag %s to port %s: %v", sg, port.ID, res.Err)
}
}
}
return nil
}
// deleteListeners deletes listeners and its default pool.
func (lbaas *LbaasV2) deleteListeners(lbID string, listenerList []listeners.Listener) error {
for _, listener := range listenerList {
klog.InfoS("Deleting listener", "listenerID", listener.ID, "lbID", lbID)
pool, err := openstackutil.GetPoolByListener(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(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(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(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) || cpoutil.Contains(listener.Tags, lbName) {
klog.InfoS("Deleting listener", "listenerID", listener.ID, "lbID", lbID)
pool, err := openstackutil.GetPoolByListener(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(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(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(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(lbaas.network, floatIPOpts).Extract()
err = PreserveGopherError(err)
if mc.ObserveRequest(err) != nil {
return floatIP, fmt.Errorf("error creating LB floatingip: %s", err)
}
return floatIP, err
}
func (lbaas *LbaasV2) updateFloatingIP(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(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(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(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(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(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(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(&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(lbaas, svcConf.lbPublicNetworkID)
if err != nil {
return "", err
}
if len(foundSubnets) == 0 {