forked from apache/cloudstack-kubernetes-provider
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcloudstack_loadbalancer.go
More file actions
1423 lines (1176 loc) · 50.5 KB
/
cloudstack_loadbalancer.go
File metadata and controls
1423 lines (1176 loc) · 50.5 KB
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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 cloudstack
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"github.com/apache/cloudstack-go/v2/cloudstack"
corev1 "k8s.io/api/core/v1"
cloudprovider "k8s.io/cloud-provider"
"k8s.io/klog/v2"
utilnet "k8s.io/utils/net"
)
const (
// defaultAllowedCIDR is the network range that is allowed on the firewall
// by default when no explicit CIDR list is given on a LoadBalancer.
defaultAllowedCIDR = "0.0.0.0/0"
// ServiceAnnotationLoadBalancerProxyProtocol is the annotation used on the
// service to enable the proxy protocol on a CloudStack load balancer.
// Note that this protocol only applies to TCP service ports and
// CloudStack >= 4.6 is required for it to work.
ServiceAnnotationLoadBalancerProxyProtocol = "service.beta.kubernetes.io/cloudstack-load-balancer-proxy-protocol"
// ServiceAnnotationLoadBalancerLoadbalancerHostname can be used in conjunction
// with PROXY protocol to allow the service to be accessible from inside the
// cluster. This is a workaround for https://github.com/kubernetes/kubernetes/issues/66607
ServiceAnnotationLoadBalancerLoadbalancerHostname = "service.beta.kubernetes.io/cloudstack-load-balancer-hostname"
// ServiceAnnotationLoadBalancerAddress is the annotation for the IP address assigned to the load balancer.
// Users can set this annotation to request a specific IP address, replacing the deprecated spec.LoadBalancerIP field.
// This annotation takes precedence; spec.LoadBalancerIP is only used as a fallback.
ServiceAnnotationLoadBalancerAddress = "service.beta.kubernetes.io/cloudstack-load-balancer-address"
// ServiceAnnotationLoadBalancerKeepIP is a boolean annotation that, when set to "true",
// prevents the public IP from being released when the service is deleted.
ServiceAnnotationLoadBalancerKeepIP = "service.beta.kubernetes.io/cloudstack-load-balancer-keep-ip"
// ServiceAnnotationLoadBalancerID stores the CloudStack public IP UUID associated with the load balancer.
// Used for efficient ID-based lookups instead of keyword-based searches.
ServiceAnnotationLoadBalancerID = "service.beta.kubernetes.io/cloudstack-load-balancer-id"
// ServiceAnnotationLoadBalancerNetworkID stores the CloudStack network UUID associated with the load balancer.
// Used together with ServiceAnnotationLoadBalancerID for scoped ID-based lookups.
ServiceAnnotationLoadBalancerNetworkID = "service.beta.kubernetes.io/cloudstack-load-balancer-network-id"
// Used to construct the load balancer name.
servicePrefix = "K8s_svc_"
lbNameFormat = "%s%s_%s_%s"
)
type loadBalancer struct {
*cloudstack.CloudStackClient
name string
algorithm string
hostIDs []string
ipAddr string
ipAddrID string
networkID string
projectID string
rules map[string]*cloudstack.LoadBalancerRule
}
// GetLoadBalancer returns whether the specified load balancer exists, and if so, what its status is.
func (cs *CSCloud) GetLoadBalancer(ctx context.Context, clusterName string, service *corev1.Service) (*corev1.LoadBalancerStatus, bool, error) {
klog.V(4).InfoS("GetLoadBalancer", "cluster", clusterName, "service", klog.KObj(service))
// Get the load balancer details and existing rules.
name := cs.GetLoadBalancerName(ctx, clusterName, service)
legacyName := cs.getLoadBalancerLegacyName(ctx, clusterName, service)
lb, err := cs.getLoadBalancer(service, name, legacyName)
if err != nil {
return nil, false, err
}
// If we don't have any rules, the load balancer does not exist.
if len(lb.rules) == 0 {
return nil, false, nil
}
klog.V(4).Infof("Found a load balancer associated with IP %v", lb.ipAddr)
status := &corev1.LoadBalancerStatus{}
status.Ingress = []corev1.LoadBalancerIngress{{IP: lb.ipAddr}}
return status, true, nil
}
// EnsureLoadBalancer creates a new load balancer, or updates the existing one. Returns the status of the balancer.
func (cs *CSCloud) EnsureLoadBalancer(ctx context.Context, clusterName string, service *corev1.Service, nodes []*corev1.Node) (status *corev1.LoadBalancerStatus, err error) { //nolint:gocognit,gocyclo,nestif,maintidx
klog.V(4).InfoS("EnsureLoadBalancer", "cluster", clusterName, "service", klog.KObj(service))
serviceName := fmt.Sprintf("%s/%s", service.Namespace, service.Name)
if len(service.Spec.Ports) == 0 {
return nil, errors.New("requested load balancer with no ports")
}
// Patch the service with new/updated annotations if needed after EnsureLoadBalancer finishes.
patcher := newServicePatcher(cs.kclient, service)
defer func() { err = patcher.Patch(ctx, err) }()
// Get the load balancer details and existing rules.
name := cs.GetLoadBalancerName(ctx, clusterName, service)
legacyName := cs.getLoadBalancerLegacyName(ctx, clusterName, service)
lb, err := cs.getLoadBalancer(service, name, legacyName)
if err != nil {
return nil, err
}
// Set the load balancer algorithm.
switch service.Spec.SessionAffinity {
case corev1.ServiceAffinityNone:
lb.algorithm = "roundrobin"
case corev1.ServiceAffinityClientIP:
lb.algorithm = "source"
default:
return nil, fmt.Errorf("unsupported load balancer affinity: %v", service.Spec.SessionAffinity)
}
// Verify that all the hosts belong to the same network, and retrieve their ID's.
lb.hostIDs, lb.networkID, err = cs.verifyHosts(nodes)
if err != nil {
return nil, err
}
// Resolve the desired IP: annotation takes precedence, spec.LoadBalancerIP is fallback.
desiredIP := getLoadBalancerAddress(service)
if !lb.hasLoadBalancerIP() { //nolint:nestif
// Before allocating a new IP, check the service annotation for a previously assigned IP.
// This handles recovery from partial failures where the IP was allocated and annotated
// but subsequent operations (rule creation) failed.
annotatedIP := getStringFromServiceAnnotation(service, ServiceAnnotationLoadBalancerAddress, "")
if annotatedIP != "" {
found, lookupErr := lb.lookupPublicIPAddress(annotatedIP)
if lookupErr != nil {
klog.Warningf("Error looking up annotated IP %v for recovery: %v", annotatedIP, lookupErr)
} else if found {
klog.V(4).Infof("Recovered previously allocated IP %v from annotation", annotatedIP)
}
}
if !lb.hasLoadBalancerIP() {
// Create or retrieve the load balancer IP.
if err := lb.getLoadBalancerIP(desiredIP); err != nil {
return nil, err
}
}
msg := fmt.Sprintf("Created new load balancer for service %s with algorithm '%s' and IP address %s", serviceName, lb.algorithm, lb.ipAddr)
cs.eventRecorder.Event(service, corev1.EventTypeNormal, "CreatedLoadBalancer", msg)
klog.Info(msg)
} else if desiredIP != "" && desiredIP != lb.ipAddr {
// IP reassignment on an active load balancer is not supported.
// Users must delete and recreate the service to change the IP.
msg := fmt.Sprintf("Load balancer IP change from %s to %s is not supported; delete and recreate the service to use a different IP", lb.ipAddr, desiredIP)
cs.eventRecorder.Event(service, corev1.EventTypeWarning, "IPChangeNotSupported", msg)
klog.Warning(msg)
}
klog.V(4).Infof("Load balancer %v is associated with IP %v", lb.name, lb.ipAddr)
// Set the load balancer annotations on the Service
setServiceAnnotation(service, ServiceAnnotationLoadBalancerAddress, lb.ipAddr)
setServiceAnnotation(service, ServiceAnnotationLoadBalancerID, lb.ipAddrID)
setServiceAnnotation(service, ServiceAnnotationLoadBalancerNetworkID, lb.networkID)
for _, port := range service.Spec.Ports {
// Construct the protocol name first, we need it a few times
protocol := ProtocolFromServicePort(port, service)
if protocol == LoadBalancerProtocolInvalid {
return nil, fmt.Errorf("unsupported load balancer protocol: %v", port.Protocol)
}
// All ports have their own load balancer rule, so add the port to lbName to keep the names unique.
lbRuleName := fmt.Sprintf("%s-%s-%d", lb.name, protocol, port.Port)
// If the load balancer rule exists and is up-to-date, we move on to the next rule.
lbRule, needsUpdate, err := lb.checkLoadBalancerRule(lbRuleName, port, protocol)
if err != nil {
return nil, err
}
if lbRule != nil { //nolint:nestif
if needsUpdate {
klog.V(4).Infof("Updating load balancer rule: %v", lbRuleName)
if err := lb.updateLoadBalancerRule(lbRuleName, protocol); err != nil {
return nil, err
}
} else {
klog.V(4).Infof("Load balancer rule %v is up-to-date", lbRuleName)
}
if err := lb.reconcileHostsForRule(lbRule, lb.hostIDs); err != nil {
return nil, err
}
// Delete the rule from the map, to prevent it being deleted.
delete(lb.rules, lbRuleName)
} else {
klog.V(4).Infof("Creating load balancer rule: %v", lbRuleName)
lbRule, err = lb.createLoadBalancerRule(lbRuleName, port, protocol)
if err != nil {
return nil, err
}
klog.V(4).Infof("Assigning hosts (%v) to load balancer rule: %v", lb.hostIDs, lbRuleName)
if err = lb.assignHostsToRule(lbRule, lb.hostIDs); err != nil {
return nil, err
}
}
network, count, err := lb.Network.GetNetworkByID(lb.networkID, cloudstack.WithProject(lb.projectID))
if err != nil {
if count == 0 {
return nil, fmt.Errorf("could not find network with ID %s: %w", lb.networkID, err)
}
return nil, fmt.Errorf("failed to get network with ID %s: %w", lb.networkID, err)
}
lbSourceRanges, err := getLoadBalancerSourceRanges(service)
if err != nil {
return nil, err
}
if lbRule != nil && isFirewallSupported(network.Service) {
klog.V(4).Infof("Creating firewall rules for load balancer rule: %v (%v:%v:%v)", lbRuleName, protocol, lbRule.Publicip, port.Port)
if _, err := lb.updateFirewallRule(lbRule.Publicipid, int(port.Port), protocol, lbSourceRanges.StringSlice()); err != nil {
return nil, err
}
} else {
msg := fmt.Sprintf("LoadBalancerSourceRanges are ignored for Service %s because this CloudStack network does not support it", serviceName)
cs.eventRecorder.Event(service, corev1.EventTypeWarning, "LoadBalancerSourceRangesIgnored", msg)
klog.Warning(msg)
}
}
// Cleanup any rules that are now still in the rules map, as they are no longer needed.
for _, lbRule := range lb.rules {
protocol := ProtocolFromLoadBalancer(lbRule.Protocol)
if protocol == LoadBalancerProtocolInvalid {
return nil, fmt.Errorf("error parsing protocol %v: %w", lbRule.Protocol, err)
}
port, err := strconv.ParseInt(lbRule.Publicport, 10, 32)
if err != nil {
return nil, fmt.Errorf("error parsing port %s: %w", lbRule.Publicport, err)
}
klog.V(4).Infof("Deleting firewall rules associated with load balancer rule: %v (%v:%v:%v)", lbRule.Name, protocol, lbRule.Publicip, port)
if _, err := lb.deleteFirewallRule(lbRule.Publicipid, int(port), protocol); err != nil {
return nil, err
}
klog.V(4).Infof("Deleting obsolete load balancer rule: %v", lbRule.Name)
if err := lb.deleteLoadBalancerRule(lbRule); err != nil {
return nil, err
}
}
return lb.generateLoadBalancerStatus(service), nil
}
// UpdateLoadBalancer updates hosts under the specified load balancer.
func (cs *CSCloud) UpdateLoadBalancer(ctx context.Context, clusterName string, service *corev1.Service, nodes []*corev1.Node) error {
klog.V(4).InfoS("UpdateLoadBalancer", "cluster", clusterName, "service", klog.KObj(service))
// Get the load balancer details and existing rules.
name := cs.GetLoadBalancerName(ctx, clusterName, service)
legacyName := cs.getLoadBalancerLegacyName(ctx, clusterName, service)
lb, err := cs.getLoadBalancer(service, name, legacyName)
if err != nil {
return err
}
// Verify that all the hosts belong to the same network, and retrieve their ID's.
lb.hostIDs, _, err = cs.verifyHosts(nodes)
if err != nil {
return err
}
for _, lbRule := range lb.rules {
if err := lb.reconcileHostsForRule(lbRule, lb.hostIDs); err != nil {
return err
}
}
return nil
}
// isFirewallSupported checks whether a CloudStack network supports the Firewall service.
func isFirewallSupported(services []cloudstack.NetworkServiceInternal) bool {
for _, svc := range services {
if svc.Name == "Firewall" {
return true
}
}
return false
}
// EnsureLoadBalancerDeleted deletes the specified load balancer if it exists, returning
// nil if the load balancer specified either didn't exist or was successfully deleted.
func (cs *CSCloud) EnsureLoadBalancerDeleted(ctx context.Context, clusterName string, service *corev1.Service) error {
klog.V(4).InfoS("EnsureLoadBalancerDeleted", "cluster", clusterName, "service", klog.KObj(service))
// Get the load balancer details and existing rules.
name := cs.GetLoadBalancerName(ctx, clusterName, service)
legacyName := cs.getLoadBalancerLegacyName(ctx, clusterName, service)
lb, err := cs.getLoadBalancer(service, name, legacyName)
if err != nil {
return err
}
// If no rules exist, the load balancer doesn't exist. However, an IP may have been
// orphaned from a previous partial failure. Check the service annotation for cleanup.
if len(lb.rules) == 0 {
klog.V(4).Infof("No load balancer rules found for service, checking annotation for orphaned IP")
return cs.releaseOrphanedIPIfNeeded(lb, service)
}
serviceName := fmt.Sprintf("%s/%s", service.Namespace, service.Name)
var deletionErrors []error
// Delete all firewall rules and load balancer rules
for _, lbRule := range lb.rules {
klog.V(4).Infof("Processing deletion of load balancer rule: %v", lbRule.Name)
// Parse protocol
protocol := ProtocolFromLoadBalancer(lbRule.Protocol)
if protocol == LoadBalancerProtocolInvalid {
err := fmt.Errorf("error parsing protocol %v for rule %v", lbRule.Protocol, lbRule.Name)
klog.Errorf("%v", err)
deletionErrors = append(deletionErrors, err)
// Continue to delete other rules even if this one fails
continue
}
// Parse port
port, err := strconv.ParseInt(lbRule.Publicport, 10, 32)
if err != nil {
err := fmt.Errorf("error parsing port %s for rule %v: %w", lbRule.Publicport, lbRule.Name, err)
klog.Errorf("%v", err)
deletionErrors = append(deletionErrors, err)
// Continue to delete other rules even if this one fails
continue
}
// Delete firewall rules first
klog.V(4).Infof("Deleting firewall rules for load balancer rule: %v (IP:%v, Port:%d, Protocol:%v)",
lbRule.Name, lbRule.Publicip, port, protocol)
if _, err := lb.deleteFirewallRule(lbRule.Publicipid, int(port), protocol); err != nil {
err := fmt.Errorf("error deleting firewall rules for rule %v: %w", lbRule.Name, err)
klog.Errorf("%v", err)
deletionErrors = append(deletionErrors, err)
// Continue to delete the load balancer rule even if firewall deletion fails
}
// Delete load balancer rule
klog.V(4).Infof("Deleting load balancer rule: %v", lbRule.Name)
if err := lb.deleteLoadBalancerRule(lbRule); err != nil {
err := fmt.Errorf("error deleting load balancer rule %v: %w", lbRule.Name, err)
klog.Errorf("%v", err)
deletionErrors = append(deletionErrors, err)
// Continue to attempt IP cleanup even if this rule deletion fails
}
}
// Delete the public IP address if appropriate
if lb.ipAddr != "" { //nolint:nestif
klog.V(4).Infof("Processing public IP deletion for load balancer: IP=%v, ID=%v", lb.ipAddr, lb.ipAddrID)
// Check if we should release the IP
shouldReleaseIP, err := cs.shouldReleaseLoadBalancerIP(lb, service)
switch {
case err != nil:
err := fmt.Errorf("error determining if IP should be released: %w", err)
klog.Errorf("%v", err)
deletionErrors = append(deletionErrors, err)
case shouldReleaseIP:
klog.V(4).Infof("Releasing load balancer IP: %v", lb.ipAddr)
if err := lb.releaseLoadBalancerIP(); err != nil {
err := fmt.Errorf("error releasing load balancer IP %v: %w", lb.ipAddr, err)
klog.Errorf("%v", err)
deletionErrors = append(deletionErrors, err)
} else {
msg := fmt.Sprintf("Released load balancer IP %s for service %s", lb.ipAddr, serviceName)
cs.eventRecorder.Event(service, corev1.EventTypeNormal, "ReleasedLoadBalancerIP", msg)
klog.Info(msg)
}
default:
klog.V(4).Infof("Load balancer IP %v is in use by other services, keeping it allocated", lb.ipAddr)
}
}
// Return aggregated errors if any occurred
if len(deletionErrors) > 0 {
msg := fmt.Sprintf("Encountered %d error(s) while deleting load balancer for service %s", len(deletionErrors), serviceName)
klog.Warningf("%s: %v", msg, deletionErrors)
cs.eventRecorder.Event(service, corev1.EventTypeWarning, "DeletingLoadBalancerFailed", msg)
// Return the first error or a combined error message
return fmt.Errorf("load balancer deletion completed with errors: %w", deletionErrors[0])
}
msg := "Successfully deleted load balancer for service " + serviceName
cs.eventRecorder.Event(service, corev1.EventTypeNormal, "DeletedLoadBalancer", msg)
klog.Info(msg)
return nil
}
// shouldReleaseLoadBalancerIP determines whether the public IP should be released.
func (cs *CSCloud) shouldReleaseLoadBalancerIP(lb *loadBalancer, service *corev1.Service) (bool, error) {
// If the keep-ip annotation is set to true, don't release the IP.
// The user is responsible for managing the lifecycle of kept IPs.
if getBoolFromServiceAnnotation(service, ServiceAnnotationLoadBalancerKeepIP, false) {
klog.V(4).Infof("IP %v has keep-ip annotation set, not releasing", lb.ipAddr)
return false, nil
}
// Check if this IP is used by other load balancer rules (other services)
p := lb.LoadBalancer.NewListLoadBalancerRulesParams()
p.SetPublicipid(lb.ipAddrID)
p.SetListall(true)
if lb.projectID != "" {
p.SetProjectid(lb.projectID)
}
otherRules, err := lb.LoadBalancer.ListLoadBalancerRules(p)
if err != nil {
return false, fmt.Errorf("error checking for other load balancer rules using IP %v: %w", lb.ipAddr, err)
}
// If other rules exist, this IP is in use by other services
if otherRules.Count > 0 {
klog.V(4).Infof("IP %v has %d other load balancer rule(s) in use, not releasing", lb.ipAddr, otherRules.Count)
return false, nil
}
// IP is safe to release - it's either controller-allocated or no longer in use
klog.V(4).Infof("IP %v is no longer in use and safe to release", lb.ipAddr)
return true, nil
}
// releaseOrphanedIPIfNeeded checks the service annotation for an orphaned IP and releases it if appropriate.
// This handles the case where all LB rules were successfully deleted but IP release failed on a prior attempt.
func (cs *CSCloud) releaseOrphanedIPIfNeeded(lb *loadBalancer, service *corev1.Service) error {
annotatedIP := getStringFromServiceAnnotation(service, ServiceAnnotationLoadBalancerAddress, "")
if annotatedIP == "" {
return nil
}
found, lookupErr := lb.lookupPublicIPAddress(annotatedIP)
if lookupErr != nil {
klog.Warningf("Error looking up annotated IP %v during delete: %v", annotatedIP, lookupErr)
return nil
}
if !found {
return nil
}
shouldRelease, shouldErr := cs.shouldReleaseLoadBalancerIP(lb, service)
if shouldErr != nil {
klog.Warningf("Error checking if annotated IP %v should be released: %v", annotatedIP, shouldErr)
return nil
}
if !shouldRelease {
klog.V(4).Infof("Annotated IP %v should not be released (keep-ip set or has other rules)", annotatedIP)
return nil
}
if releaseErr := lb.releaseLoadBalancerIP(); releaseErr != nil {
return fmt.Errorf("error releasing orphaned load balancer IP %v: %w", annotatedIP, releaseErr)
}
serviceName := fmt.Sprintf("%s/%s", service.Namespace, service.Name)
msg := fmt.Sprintf("Released orphaned load balancer IP %s for service %s", annotatedIP, serviceName)
cs.eventRecorder.Event(service, corev1.EventTypeNormal, "ReleasedOrphanedIP", msg)
klog.Info(msg)
return nil
}
// GetLoadBalancerName returns the name of the LoadBalancer.
func (cs *CSCloud) GetLoadBalancerName(_ context.Context, clusterName string, service *corev1.Service) string {
return Sprintf255(lbNameFormat, servicePrefix, clusterName, service.Namespace, service.Name)
}
// getLoadBalancerLegacyName returns the legacy load balancer name for backward compatibility.
func (cs *CSCloud) getLoadBalancerLegacyName(_ context.Context, _ string, service *corev1.Service) string {
return cloudprovider.DefaultLoadBalancerName(service)
}
// filterRulesByPrefix returns only the rules whose Name starts with the given prefix.
// This is needed because CloudStack's SetKeyword uses LIKE %keyword% matching,
// which can return rules belonging to other services with overlapping name substrings.
func filterRulesByPrefix(rules []*cloudstack.LoadBalancerRule, prefix string) []*cloudstack.LoadBalancerRule {
var filtered []*cloudstack.LoadBalancerRule
for _, rule := range rules {
if strings.HasPrefix(rule.Name, prefix) {
filtered = append(filtered, rule)
}
}
return filtered
}
// getLoadBalancer tries to find the load balancer using ID-based lookup first (if annotations
// are present), then falls back to the keyword-based name lookup.
func (cs *CSCloud) getLoadBalancer(service *corev1.Service, name, legacyName string) (*loadBalancer, error) {
if ipAddrID := getLoadBalancerID(service); ipAddrID != "" {
networkID := getLoadBalancerNetworkID(service)
klog.V(4).Infof("Attempting ID-based load balancer lookup: ipAddrID=%v, networkID=%v", ipAddrID, networkID)
lb, err := cs.getLoadBalancerByID(name, ipAddrID, networkID)
if err != nil {
return nil, err
}
if len(lb.rules) > 0 {
return lb, nil
}
klog.V(4).Infof("ID-based lookup returned no rules, falling back to name-based lookup")
}
return cs.getLoadBalancerByName(name, legacyName)
}
// getLoadBalancerByName retrieves the IP address and ID and all the existing rules it can find.
func (cs *CSCloud) getLoadBalancerByName(name, legacyName string) (*loadBalancer, error) {
lb := &loadBalancer{
CloudStackClient: cs.client,
name: name,
projectID: cs.projectID,
rules: make(map[string]*cloudstack.LoadBalancerRule),
}
p := cs.client.LoadBalancer.NewListLoadBalancerRulesParams()
p.SetKeyword(lb.name)
p.SetListall(true)
if cs.projectID != "" {
p.SetProjectid(cs.projectID)
}
l, err := cs.client.LoadBalancer.ListLoadBalancerRules(p)
if err != nil {
return nil, fmt.Errorf("error retrieving load balancer rules: %w", err)
}
// Filter keyword results to exact prefix matches. CloudStack's SetKeyword uses
// LIKE %keyword% matching, so searching for "foo" can also return "foobar" rules.
filtered := filterRulesByPrefix(l.LoadBalancerRules, lb.name+"-")
// If no rules were found, check the legacy name.
if len(filtered) == 0 { //nolint:nestif
if len(legacyName) > 0 {
p.SetKeyword(legacyName)
l, err = cs.client.LoadBalancer.ListLoadBalancerRules(p)
if err != nil {
return nil, fmt.Errorf("error retrieving load balancer rules: %w", err)
}
legacyFiltered := filterRulesByPrefix(l.LoadBalancerRules, legacyName+"-")
if len(legacyFiltered) > 0 {
lb.name = legacyName
filtered = legacyFiltered
}
} else {
return lb, nil
}
}
for _, lbRule := range filtered {
lb.rules[lbRule.Name] = lbRule
if lb.ipAddr != "" && lb.ipAddr != lbRule.Publicip {
klog.Warningf("Load balancer %v has rules associated with different IP's: %v, %v", lb.name, lb.ipAddr, lbRule.Publicip)
}
lb.ipAddr = lbRule.Publicip
lb.ipAddrID = lbRule.Publicipid
}
klog.V(4).Infof("Load balancer %v contains %d rule(s)", lb.name, len(lb.rules))
return lb, nil
}
// getLoadBalancerByID retrieves load balancer rules by public IP ID and network ID.
// This is more reliable than keyword-based search as it uses exact ID matching.
func (cs *CSCloud) getLoadBalancerByID(name, ipAddrID, networkID string) (*loadBalancer, error) {
lb := &loadBalancer{
CloudStackClient: cs.client,
name: name,
projectID: cs.projectID,
rules: make(map[string]*cloudstack.LoadBalancerRule),
}
p := cs.client.LoadBalancer.NewListLoadBalancerRulesParams()
p.SetPublicipid(ipAddrID)
p.SetListall(true)
if networkID != "" {
p.SetNetworkid(networkID)
}
if cs.projectID != "" {
p.SetProjectid(cs.projectID)
}
l, err := cs.client.LoadBalancer.ListLoadBalancerRules(p)
if err != nil {
return nil, fmt.Errorf("error retrieving load balancer rules by IP ID %v: %w", ipAddrID, err)
}
for _, lbRule := range l.LoadBalancerRules {
lb.rules[lbRule.Name] = lbRule
if lb.ipAddr != "" && lb.ipAddr != lbRule.Publicip {
klog.Warningf("Load balancer %v has rules associated with different IP's: %v, %v", lb.name, lb.ipAddr, lbRule.Publicip)
}
lb.ipAddr = lbRule.Publicip
lb.ipAddrID = lbRule.Publicipid
lb.networkID = lbRule.Networkid
}
klog.V(4).Infof("Load balancer %v (by ID %v) contains %d rule(s)", lb.name, ipAddrID, len(lb.rules))
return lb, nil
}
// verifyHosts verifies if all hosts belong to the same network, and returns the host ID's and network ID.
// During rolling upgrades some nodes may not yet have a corresponding VM in CloudStack, so we tolerate
// partial matches: as long as at least one node can be resolved we return the matched set and log
// warnings for the nodes we could not find.
func (cs *CSCloud) verifyHosts(nodes []*corev1.Node) ([]string, string, error) {
hostNames := map[string]bool{}
// providerVMIDs maps CloudStack VM IDs extracted from node.Spec.ProviderID
// so we can match by ID in addition to name.
providerVMIDs := map[string]bool{}
for _, node := range nodes {
// node.Name can be an FQDN as well, and CloudStack VM names aren't
// To match, we need to Split the domain part off here, if present
hostNames[strings.Split(strings.ToLower(node.Name), ".")[0]] = true
// Also extract the VM ID from the ProviderID for a more reliable match.
if node.Spec.ProviderID != "" {
if id, _, err := instanceIDFromProviderID(node.Spec.ProviderID); err == nil {
providerVMIDs[id] = true
}
}
}
// Fetch all VMs using pagination to avoid missing VMs when the project has many instances.
allVMs, err := cs.listAllVirtualMachines()
if err != nil {
return nil, "", fmt.Errorf("error retrieving list of hosts: %w", err)
}
var hostIDs []string
var networkID string
matchedNames := map[string]bool{}
var skippedNoNIC []string
// Check if the virtual machine is in the hosts slice, then add the corresponding ID.
for _, vm := range allVMs {
nameMatch := hostNames[strings.ToLower(vm.Name)]
idMatch := providerVMIDs[vm.Id]
if nameMatch || idMatch {
if len(vm.Nic) == 0 {
klog.Warningf("Skipping VM %v (id: %v) as it contains no active network interfaces (may still be provisioning)", vm.Name, vm.Id)
skippedNoNIC = append(skippedNoNIC, vm.Name)
// Skip VM's without any active network interfaces. This happens during rollout f.e.
continue
}
if networkID != "" && networkID != vm.Nic[0].Networkid {
return nil, "", errors.New("found hosts that belong to different networks")
}
networkID = vm.Nic[0].Networkid
hostIDs = append(hostIDs, vm.Id)
matchedNames[strings.ToLower(vm.Name)] = true
}
}
// Log warnings for nodes that could not be matched — this is expected during rolling upgrades.
var unmatchedNodes []string
for _, node := range nodes {
shortName := strings.Split(strings.ToLower(node.Name), ".")[0]
if !matchedNames[shortName] {
unmatchedNodes = append(unmatchedNodes, node.Name)
}
}
if len(unmatchedNodes) > 0 {
klog.Warningf("Could not match %d node(s) to CloudStack VMs (may be provisioning or terminating): %v", len(unmatchedNodes), unmatchedNodes)
}
if len(skippedNoNIC) > 0 {
klog.Warningf("Skipped %d VM(s) with no NICs (still provisioning): %v", len(skippedNoNIC), skippedNoNIC)
}
if len(hostIDs) == 0 || len(networkID) == 0 {
return nil, "", fmt.Errorf("could not match any of the %d node(s) to VMs in CloudStack (unmatched: %v, skipped-no-nic: %v)",
len(nodes), unmatchedNodes, skippedNoNIC)
}
klog.V(4).Infof("Matched %d of %d nodes to CloudStack VMs", len(hostIDs), len(nodes))
return hostIDs, networkID, nil
}
// listAllVirtualMachines retrieves all VMs using pagination to handle large projects.
func (cs *CSCloud) listAllVirtualMachines() ([]*cloudstack.VirtualMachine, error) {
var allVMs []*cloudstack.VirtualMachine
page := 1
pageSize := 500
for {
p := cs.client.VirtualMachine.NewListVirtualMachinesParams()
p.SetListall(true)
p.SetDetails([]string{"min", "nics"})
p.SetPage(page)
p.SetPagesize(pageSize)
if cs.projectID != "" {
p.SetProjectid(cs.projectID)
}
l, err := cs.client.VirtualMachine.ListVirtualMachines(p)
if err != nil {
return nil, fmt.Errorf("failed to list virtual machines: %w", err)
}
allVMs = append(allVMs, l.VirtualMachines...)
// If we got fewer results than the page size, we've reached the last page.
if len(l.VirtualMachines) < pageSize {
break
}
page++
}
return allVMs, nil
}
// hasLoadBalancerIP returns true if we have a load balancer address and ID.
func (lb *loadBalancer) hasLoadBalancerIP() bool {
return lb.ipAddr != "" && lb.ipAddrID != ""
}
// getLoadBalancerIP retrieves an existing IP or associates a new IP.
func (lb *loadBalancer) getLoadBalancerIP(loadBalancerIP string) error {
if loadBalancerIP != "" {
return lb.getPublicIPAddress(loadBalancerIP)
}
return lb.associatePublicIPAddress()
}
// lookupPublicIPAddress checks whether the given IP address is already allocated in CloudStack.
// If found and allocated, it sets lb.ipAddr and lb.ipAddrID and returns (true, nil).
// If not found or not allocated, it returns (false, nil) without modifying lb state.
// Unlike getPublicIPAddress, this method does NOT call associatePublicIPAddress for unallocated IPs.
func (lb *loadBalancer) lookupPublicIPAddress(ip string) (bool, error) {
p := lb.Address.NewListPublicIpAddressesParams()
p.SetIpaddress(ip)
p.SetAllocatedonly(true)
p.SetListall(true)
if lb.projectID != "" {
p.SetProjectid(lb.projectID)
}
l, err := lb.Address.ListPublicIpAddresses(p)
if err != nil {
return false, fmt.Errorf("error looking up IP address %v: %w", ip, err)
}
if l.Count != 1 {
return false, nil
}
lb.ipAddr = l.PublicIpAddresses[0].Ipaddress
lb.ipAddrID = l.PublicIpAddresses[0].Id
return true, nil
}
// getPublicIPAddressID retrieves the ID of the given IP, and sets the address and its ID.
func (lb *loadBalancer) getPublicIPAddress(loadBalancerIP string) error {
klog.V(4).Infof("Retrieve load balancer IP details: %v", loadBalancerIP)
p := lb.Address.NewListPublicIpAddressesParams()
p.SetIpaddress(loadBalancerIP)
p.SetAllocatedonly(false)
p.SetListall(true)
if lb.projectID != "" {
p.SetProjectid(lb.projectID)
}
l, err := lb.Address.ListPublicIpAddresses(p)
if err != nil {
return fmt.Errorf("error retrieving IP address: %w", err)
}
if l.Count != 1 {
return fmt.Errorf("could not find IP address %v. Found %d addresses", loadBalancerIP, l.Count)
}
lb.ipAddr = l.PublicIpAddresses[0].Ipaddress
lb.ipAddrID = l.PublicIpAddresses[0].Id
// If the IP Address is not allocated then associate it
if l.PublicIpAddresses[0].Allocated == "" {
return lb.associatePublicIPAddress()
}
return nil
}
// associatePublicIPAddress associates a new IP and sets the address and its ID.
func (lb *loadBalancer) associatePublicIPAddress() error {
klog.V(4).Infof("Allocate new IP for load balancer: %v", lb.name)
// If a network belongs to a VPC, the IP address needs to be associated with
// the VPC instead of with the network.
network, count, err := lb.Network.GetNetworkByID(lb.networkID, cloudstack.WithProject(lb.projectID))
if err != nil {
if count == 0 {
return fmt.Errorf("could not find network %v", lb.networkID)
}
return fmt.Errorf("error retrieving network: %w", err)
}
p := lb.Address.NewAssociateIpAddressParams()
if network.Vpcid != "" {
p.SetVpcid(network.Vpcid)
} else {
p.SetNetworkid(lb.networkID)
}
if lb.projectID != "" {
p.SetProjectid(lb.projectID)
}
if lb.ipAddr != "" {
p.SetIpaddress(lb.ipAddr)
}
// Associate a new IP address
r, err := lb.Address.AssociateIpAddress(p)
if err != nil {
return fmt.Errorf("error associating new IP address: %w", err)
}
lb.ipAddr = r.Ipaddress
lb.ipAddrID = r.Id
return nil
}
// releasePublicIPAddress releases an associated IP.
func (lb *loadBalancer) releaseLoadBalancerIP() error {
p := lb.Address.NewDisassociateIpAddressParams(lb.ipAddrID)
if _, err := lb.Address.DisassociateIpAddress(p); err != nil {
return fmt.Errorf("error releasing load balancer IP %v: %w", lb.ipAddr, err)
}
return nil
}
// checkLoadBalancerRule checks if the rule already exists and if it does, if it can be updated. If
// it does exist but cannot be updated, it will delete the existing rule so it can be created again.
func (lb *loadBalancer) checkLoadBalancerRule(lbRuleName string, port corev1.ServicePort, protocol LoadBalancerProtocol) (*cloudstack.LoadBalancerRule, bool, error) {
lbRule, ok := lb.rules[lbRuleName]
if !ok {
return nil, false, nil
}
// Check if any of the values we cannot update (those that require a new load balancer rule) are changed.
if lbRule.Publicip == lb.ipAddr && lbRule.Privateport == strconv.Itoa(int(port.NodePort)) && lbRule.Publicport == strconv.Itoa(int(port.Port)) {
updateAlgo := lbRule.Algorithm != lb.algorithm
updateProto := lbRule.Protocol != protocol.CSProtocol()
return lbRule, updateAlgo || updateProto, nil
}
// Delete the load balancer rule so we can create a new one using the new values.
if err := lb.deleteLoadBalancerRule(lbRule); err != nil {
return nil, false, err
}
return nil, false, nil
}
// updateLoadBalancerRule updates a load balancer rule.
func (lb *loadBalancer) updateLoadBalancerRule(lbRuleName string, protocol LoadBalancerProtocol) error {
lbRule := lb.rules[lbRuleName]
p := lb.LoadBalancer.NewUpdateLoadBalancerRuleParams(lbRule.Id)
p.SetAlgorithm(lb.algorithm)
p.SetProtocol(protocol.CSProtocol())
_, err := lb.LoadBalancer.UpdateLoadBalancerRule(p)
if err != nil {
return fmt.Errorf("failed to update loadbalancer rule with ID %s: %w", lbRule.Id, err)
}
return nil
}
// createLoadBalancerRule creates a new load balancer rule and returns its ID.
func (lb *loadBalancer) createLoadBalancerRule(lbRuleName string, port corev1.ServicePort, protocol LoadBalancerProtocol) (*cloudstack.LoadBalancerRule, error) {
p := lb.LoadBalancer.NewCreateLoadBalancerRuleParams(
lb.algorithm,
lbRuleName,
int(port.NodePort),
int(port.Port),
)
p.SetNetworkid(lb.networkID)
p.SetPublicipid(lb.ipAddrID)
p.SetProtocol(protocol.CSProtocol())
// Do not open the firewall implicitly, we always create explicit firewall rules
p.SetOpenfirewall(false)
// Create a new load balancer rule.
r, err := lb.LoadBalancer.CreateLoadBalancerRule(p)
if err != nil {
return nil, fmt.Errorf("error creating load balancer rule %v: %w", lbRuleName, err)
}
lbRule := &cloudstack.LoadBalancerRule{
Id: r.Id,
Algorithm: r.Algorithm,
Cidrlist: r.Cidrlist,
Name: r.Name,
Networkid: r.Networkid,
Privateport: r.Privateport,
Publicport: r.Publicport,
Publicip: r.Publicip,
Publicipid: r.Publicipid,
Protocol: r.Protocol,
}
return lbRule, nil
}
// deleteLoadBalancerRule deletes a load balancer rule.
func (lb *loadBalancer) deleteLoadBalancerRule(lbRule *cloudstack.LoadBalancerRule) error {
p := lb.LoadBalancer.NewDeleteLoadBalancerRuleParams(lbRule.Id)
if _, err := lb.LoadBalancer.DeleteLoadBalancerRule(p); err != nil {
return fmt.Errorf("error deleting load balancer rule %v: %w", lbRule.Name, err)
}
// Delete the rule from the map as it no longer exists
delete(lb.rules, lbRule.Name)
return nil