forked from apache/cloudstack-kubernetes-provider
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloudstack_loadbalancer.go
More file actions
1687 lines (1447 loc) · 60.7 KB
/
Copy pathcloudstack_loadbalancer.go
File metadata and controls
1687 lines (1447 loc) · 60.7 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"
"fmt"
"net"
"sort"
"strconv"
"strings"
"github.com/apache/cloudstack-go/v2/cloudstack"
"github.com/blang/semver/v4"
"k8s.io/klog/v2"
corev1 "k8s.io/api/core/v1"
cloudprovider "k8s.io/cloud-provider"
)
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 = "service.beta.kubernetes.io/cloudstack-load-balancer-hostname"
// ServiceAnnotationLoadBalancerSourceCidrs is the annotation used on the
// service to specify the source CIDR list for a CloudStack load balancer.
// The CIDR list is a comma-separated list of CIDR ranges (e.g., "10.0.0.0/8,192.168.1.0/24").
// If not specified, the default is to allow all sources ("0.0.0.0/0").
ServiceAnnotationLoadBalancerSourceCidrs = "service.beta.kubernetes.io/cloudstack-load-balancer-source-cidrs"
// ServiceAnnotationLoadBalancerIPAssociatedByController indicates that the controller
// associated the IP address. This annotation is set by the controller when it associates
// an unallocated IP, and is used to determine if the IP should be disassociated on deletion.
ServiceAnnotationLoadBalancerIPAssociatedByController = "service.beta.kubernetes.io/cloudstack-load-balancer-ip-associated-by-controller" //nolint:gosec
)
// cidrListUpdateVersion is the first CloudStack release whose updateLoadBalancerRule API
// accepts a cidrlist. Below it, a changed source CIDR list can only be applied by deleting
// the rule and creating it again.
var cidrListUpdateVersion = semver.Version{Major: 4, Minor: 22, Patch: 0}
type loadBalancer struct {
*cloudstack.CloudStackClient
name string
algorithm string
hostIDs []string
ipAddr string
ipAddrID string
networkID string
projectID string
rules map[string]*cloudstack.LoadBalancerRule
duplicateRules []*cloudstack.LoadBalancerRule
networks map[string]*cloudstack.Network
ipAssociatedByController bool
}
// ruleChange is what applying a desired service port does to its load balancer rule.
type ruleChange int
const (
ruleMissing ruleChange = iota // no rule exists, so one is created
ruleUpToDate // the existing rule is left alone
ruleNeedsUpdate // the existing rule is updated in place
ruleNeedsRecreate // the existing rule is deleted and created again
)
// desiredLBRule describes the load balancer rule a service port should be represented by,
// together with the existing CloudStack rule it resolved to (if any) and what applying it does.
type desiredLBRule struct {
name string
port corev1.ServicePort
protocol LoadBalancerProtocol
existing *cloudstack.LoadBalancerRule // nil when change is ruleMissing
change ruleChange
}
// createsRule reports whether applying this port creates a load balancer rule, and so needs
// its public port free of any other rule first.
func (d desiredLBRule) createsRule() bool {
return d.change == ruleMissing || d.change == ruleNeedsRecreate
}
// 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).Infof("GetLoadBalancer(%v, %v, %v)", clusterName, service.Namespace, service.Name)
// Get the load balancer details and existing rules.
lb, err := cs.getLoadBalancer(service)
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 = append(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) {
klog.V(4).Infof("EnsureLoadBalancer(%v, %v, %v, %v, %v, %v)", clusterName, service.Namespace, service.Name, service.Spec.LoadBalancerIP, service.Spec.Ports, nodes)
if len(service.Spec.Ports) == 0 {
return nil, fmt.Errorf("requested load balancer with no ports")
}
// Get the load balancer details and existing rules.
lb, err := cs.getLoadBalancer(service)
if err != nil {
return nil, err
}
if err := lb.deleteDuplicateRules(); 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
}
if !lb.hasLoadBalancerIP() {
// Create or retrieve the load balancer IP.
if err := lb.getLoadBalancerIP(service.Spec.LoadBalancerIP); err != nil {
return nil, err
}
if lb.ipAddr != "" && lb.ipAddr != service.Spec.LoadBalancerIP {
defer func(lb *loadBalancer) {
if err != nil {
if err := lb.releaseLoadBalancerIP(); err != nil {
klog.Errorf(err.Error())
}
}
}(lb)
}
// If the controller associated the IP and matches the service spec, set the annotation to persist this information.
if lb.ipAssociatedByController && lb.ipAddr == service.Spec.LoadBalancerIP {
if err := cs.setServiceAnnotation(ctx, service, ServiceAnnotationLoadBalancerIPAssociatedByController, "true"); err != nil {
// Log the error but don't fail - the annotation is helpful but not critical
klog.Warningf("Failed to set annotation on service %s/%s: %v", service.Namespace, service.Name, err)
}
}
}
klog.V(4).Infof("Load balancer %v is associated with IP %v", lb.name, lb.ipAddr)
// Resolve every service port to the rule that should represent it.
desired, err := lb.resolveLoadBalancerRules(service, cs.version)
if err != nil {
return nil, err
}
network, _, err := lb.Network.GetNetworkByID(lb.networkID, cloudstack.WithProject(lb.projectID))
if err != nil {
return nil, err
}
blocking, rest := lb.partitionObsoleteRules(desired)
// Obsolete rules holding a public port that a new rule needs have to go first, or
// CloudStack rejects the create as a port conflict.
if err := lb.pruneRules(blocking, desired, network); err != nil {
return nil, err
}
if err := lb.applyLoadBalancerRules(desired, service, network, cs.version); err != nil {
return nil, err
}
// Everything else is removed only once the desired rules are in place, so a failure here
// can never leave the service without the rules it does need.
if err := lb.pruneRules(rest, desired, network); err != nil {
return nil, err
}
status = &corev1.LoadBalancerStatus{}
// If hostname is explicitly set using service annotation
// Workaround for https://github.com/kubernetes/kubernetes/issues/66607
if hostname := getStringFromServiceAnnotation(service, ServiceAnnotationLoadBalancerLoadbalancerHostname, ""); hostname != "" {
status.Ingress = []corev1.LoadBalancerIngress{{Hostname: hostname}}
return status, nil
}
// Default to IP
status.Ingress = []corev1.LoadBalancerIngress{{IP: lb.ipAddr}}
return status, 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).Infof("UpdateLoadBalancer(%v, %v, %v, %v)", clusterName, service.Namespace, service.Name, nodes)
// Get the load balancer details and existing rules.
lb, err := cs.getLoadBalancer(service)
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 {
p := lb.LoadBalancer.NewListLoadBalancerRuleInstancesParams(lbRule.Id)
// Retrieve all VMs currently associated to this load balancer rule. There
// is one per load balanced node, so this grows with the cluster.
instances, err := listAll(p, func() (int, []*cloudstack.VirtualMachine, error) {
l, err := lb.LoadBalancer.ListLoadBalancerRuleInstances(p)
if err != nil {
return 0, nil, err
}
return l.Count, l.LoadBalancerRuleInstances, nil
})
if err != nil {
return fmt.Errorf("error retrieving associated instances: %v", err)
}
assign, remove := symmetricDifference(lb.hostIDs, instances)
if len(assign) > 0 {
klog.V(4).Infof("Assigning new hosts (%v) to load balancer rule: %v", assign, lbRule.Name)
if err := lb.assignHostsToRule(lbRule, assign); err != nil {
return err
}
}
if len(remove) > 0 {
klog.V(4).Infof("Removing old hosts (%v) from load balancer rule: %v", assign, lbRule.Name)
if err := lb.removeHostsFromRule(lbRule, remove); err != nil {
return err
}
}
}
return nil
}
func isFirewallSupported(services []cloudstack.NetworkServiceInternal) bool {
for _, svc := range services {
if svc.Name == "Firewall" {
return true
}
}
return false
}
func isNetworkACLSupported(services []cloudstack.NetworkServiceInternal) bool {
for _, svc := range services {
if svc.Name == "NetworkACL" {
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).Infof("EnsureLoadBalancerDeleted(%v, %v, %v)", clusterName, service.Namespace, service.Name)
// Get the load balancer details and existing rules.
lb, err := cs.getLoadBalancer(service)
if err != nil {
return err
}
// Reported only once this service's own resources are gone, so a retry sees the
// leftover duplicate as an ordinary rule and deletes it through the path above.
sweepErr := lb.deleteDuplicateRules()
if sweepErr != nil {
klog.Errorf("Error removing duplicate load balancer rules for %v/%v: %v", service.Namespace, service.Name, sweepErr)
}
for _, lbRule := range lb.rules {
klog.V(4).Infof("Deleting firewall rules / Network ACLs for load balancer: %v", lbRule.Name)
protocol := ProtocolFromLoadBalancer(lbRule.Protocol)
if protocol == LoadBalancerProtocolInvalid {
klog.Errorf("Error parsing protocol: %v", lbRule.Protocol)
} else {
port, err := strconv.ParseInt(lbRule.Publicport, 10, 32)
if err != nil {
klog.Errorf("Error parsing port: %v", err)
} else {
networkId, err := cs.getNetworkIDFromIPAddress(lb.ipAddrID)
if err != nil {
return err
}
network, count, err := lb.Network.GetNetworkByID(networkId, cloudstack.WithProject(lb.projectID))
if err != nil {
if count == 0 {
klog.Errorf("No network found with ID: %v", networkId)
return err
}
return err
}
if network.Vpcid == "" {
_, err = lb.deleteFirewallRule(lbRule.Publicipid, int(port), protocol)
if err != nil {
klog.Errorf("Error deleting firewall rule: %v", err)
}
} else {
klog.V(4).Infof("Deleting network ACLs for %v - %v", int(port), protocol)
_, err = lb.deleteNetworkACLRule(int(port), protocol, networkId)
if err != nil {
klog.Errorf("Error deleting Network ACL rule: %v", err)
}
}
}
klog.V(4).Infof("Deleting load balancer rule: %v", lbRule.Name)
if err := lb.deleteLoadBalancerRule(lbRule); err != nil {
return err
}
}
}
if lb.ipAddr != "" {
// If the IP was allocated by the controller (not specified in service spec), release it.
if lb.ipAddr != service.Spec.LoadBalancerIP {
klog.V(4).Infof("Releasing load balancer IP: %v", lb.ipAddr)
if err := lb.releaseLoadBalancerIP(); err != nil {
return err
}
} else {
// If the IP was specified in service spec, check if it was associated by the controller.
// First, check if there's an annotation indicating the controller associated it.
// If not, check if there are any other load balancer rules using this IP.
shouldDisassociate := getBoolFromServiceAnnotation(service, ServiceAnnotationLoadBalancerIPAssociatedByController, false)
if shouldDisassociate {
// Annotation is set, so check if there are any other load balancer rules using this IP.
// Since we've already deleted all rules for this service, any remaining rules must belong
// to other services. If no other rules exist, it's safe to disassociate the IP.
ip, count, err := lb.Address.GetPublicIpAddressByID(lb.ipAddrID, cloudstack.WithProject(lb.projectID))
if err != nil {
klog.Errorf("Error retrieving IP address %v for disassociation check: %v", lb.ipAddr, err)
shouldDisassociate = false
} else if count > 0 && ip.Allocated != "" {
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 {
klog.Errorf("Error checking for other load balancer rules using IP %v: %v", lb.ipAddr, err)
shouldDisassociate = false
} else if otherRules.Count > 0 {
// Other load balancer rules are using this IP (other services are using it),
// so don't disassociate.
shouldDisassociate = false
}
}
}
if shouldDisassociate {
klog.V(4).Infof("Disassociating IP %v that was associated by the controller", lb.ipAddr)
if err := lb.releaseLoadBalancerIP(); err != nil {
return err
}
}
}
}
return sweepErr
}
// GetLoadBalancerName retrieves the name of the LoadBalancer.
func (cs *CSCloud) GetLoadBalancerName(ctx context.Context, clusterName string, service *corev1.Service) string {
return cloudprovider.DefaultLoadBalancerName(service)
}
// getLoadBalancer retrieves the IP address and ID and all the existing rules it can find.
func (cs *CSCloud) getLoadBalancer(service *corev1.Service) (*loadBalancer, error) {
lb := &loadBalancer{
CloudStackClient: cs.client,
name: cs.GetLoadBalancerName(context.TODO(), "", service),
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)
}
// The keyword is matched as a substring server side, so this can return more
// rules than just this service's and has to be paged through.
lbRules, err := listAll(p, func() (int, []*cloudstack.LoadBalancerRule, error) {
l, err := cs.client.LoadBalancer.ListLoadBalancerRules(p)
if err != nil {
return 0, nil, err
}
return l.Count, l.LoadBalancerRules, nil
})
if err != nil {
return nil, fmt.Errorf("error retrieving load balancer rules: %v", err)
}
lbRules = dedupeByID(lbRules, func(rule *cloudstack.LoadBalancerRule) string { return rule.Id })
// Keeping the rule on the address the Service is already published on stops a
// duplicate sweep from deleting the rule that clients and DNS are pointing at. The
// same address is the one the rules are reconciled towards when they span several.
// Without one, the first-listed rule wins here as it does in the sweep.
preferredIP := service.Spec.LoadBalancerIP
if preferredIP == "" && len(service.Status.LoadBalancer.Ingress) > 0 {
preferredIP = service.Status.LoadBalancer.Ingress[0].IP
}
for _, lbRule := range lbRules {
if existing, seen := lb.rules[lbRule.Name]; seen {
duplicate := lbRule
if lbRule.Publicip == preferredIP && existing.Publicip != preferredIP {
duplicate = existing
}
klog.Warningf("Duplicate load balancer rule %v for service %v/%v, removing %v on %v", lbRule.Name, service.Namespace, service.Name, duplicate.Id, duplicate.Publicip)
lb.duplicateRules = append(lb.duplicateRules, duplicate)
if duplicate == lbRule {
continue
}
}
lb.rules[lbRule.Name] = lbRule
if lb.ipAddr != "" && lb.ipAddr != lbRule.Publicip {
klog.Warningf("Load balancer for service %v/%v has rules associated with different IP's: %v, %v", service.Namespace, service.Name, lb.ipAddr, lbRule.Publicip)
}
if lb.ipAddr == "" || (lbRule.Publicip == preferredIP && lb.ipAddr != preferredIP) {
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
}
// Get network ID from Public IP Address
// Every failure returns an error: GetNetworkByID does not reject an empty ID but
// matches an unfiltered network list, so ("", nil) would resolve to any network.
func (cs *CSCloud) getNetworkIDFromIPAddress(publicIpId string) (string, error) {
ip, count, err := cs.client.Address.GetPublicIpAddressByID(publicIpId, cloudstack.WithProject(cs.projectID))
if err != nil {
klog.Errorf("Failed to fetch the public IP for id: %v", publicIpId)
return "", err
}
if count == 0 {
return "", fmt.Errorf("no public IP address found with ID %v", publicIpId)
}
if ip.Associatednetworkid != "" {
network, _, netErr := cs.client.Network.GetNetworkByID(ip.Associatednetworkid, cloudstack.WithProject(cs.projectID))
if netErr != nil {
klog.Errorf("Failed to fetch the network for id: %v", ip.Associatednetworkid)
return "", netErr
}
return network.Id, nil
}
return "", fmt.Errorf("public IP address %v is not associated with a network", publicIpId)
}
// verifyHosts verifies if all hosts belong to the same network, and returns the host ID's and network ID.
func (cs *CSCloud) verifyHosts(nodes []*corev1.Node) ([]string, string, error) {
hostNames := 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
}
p := cs.client.VirtualMachine.NewListVirtualMachinesParams()
p.SetListall(true)
p.SetDetails([]string{"min", "nics"})
if cs.projectID != "" {
p.SetProjectid(cs.projectID)
}
vms, err := listAll(p, func() (int, []*cloudstack.VirtualMachine, error) {
l, err := cs.client.VirtualMachine.ListVirtualMachines(p)
if err != nil {
return 0, nil, err
}
return l.Count, l.VirtualMachines, nil
})
if err != nil {
return nil, "", fmt.Errorf("error retrieving list of hosts: %v", err)
}
var hostIDs []string
var networkID string
seen := map[string]bool{} // used to check whether the changing set of VMs contains one we had already seen in another page.
// Check if the virtual machine is in the hosts slice, then add the corresponding ID.
for _, vm := range vms {
if !hostNames[strings.ToLower(vm.Name)] || seen[vm.Id] {
continue
}
seen[vm.Id] = true
if networkID != "" && networkID != vm.Nic[0].Networkid {
return nil, "", fmt.Errorf("found hosts that belong to different networks")
}
networkID = vm.Nic[0].Networkid
hostIDs = append(hostIDs, vm.Id)
}
if len(hostIDs) == 0 || len(networkID) == 0 {
return nil, "", fmt.Errorf("none of the hosts matched the list of VMs retrieved from CS API")
}
return hostIDs, networkID, 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()
}
// getPublicIPAddressID retrieves the ID of the given IP, and sets the address and it's 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: %v", 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 is not allocated, associate it.
if l.PublicIpAddresses[0].Allocated == "" {
return lb.associatePublicIPAddress()
}
return nil
}
// associatePublicIPAddress associates a new IP and sets the address and it's 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: %v", 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: %v", err)
}
lb.ipAddr = r.Ipaddress
lb.ipAddrID = r.Id
lb.ipAssociatedByController = true
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: %v", lb.ipAddr, err)
}
return nil
}
func (lb *loadBalancer) getCIDRList(service *corev1.Service) ([]string, error) {
sourceCIDRs := getStringFromServiceAnnotation(service, ServiceAnnotationLoadBalancerSourceCidrs, defaultAllowedCIDR)
var cidrList []string
if sourceCIDRs != "" {
cidrList = strings.Split(sourceCIDRs, ",")
for i, cidr := range cidrList {
cidr = strings.TrimSpace(cidr)
if _, _, err := net.ParseCIDR(cidr); err != nil {
return nil, fmt.Errorf("invalid CIDR %s in annotation %s: %w", cidr, ServiceAnnotationLoadBalancerSourceCidrs, err)
}
cidrList[i] = cidr
}
}
return cidrList, nil
}
// splitCIDRList splits the CIDR list of an existing CloudStack rule into its entries.
// CloudStack has reported these both comma and space separated, and a CIDR can contain
// neither character, so treat both as separators.
func splitCIDRList(cidrList string) []string {
return strings.FieldsFunc(cidrList, func(r rune) bool {
return r == ',' || r == ' '
})
}
// resolveLoadBalancerRules maps every service port to the load balancer rule that should
// represent it, claiming each match as it goes so that what remains in lb.rules is exactly
// the obsolete set and no rule can be claimed twice. It changes nothing in CloudStack: a rule
// that has to be recreated is only deleted when it is applied, so an error on a later port, or
// anywhere before the apply phase, leaves the existing rule serving.
func (lb *loadBalancer) resolveLoadBalancerRules(service *corev1.Service, version semver.Version) ([]desiredLBRule, error) {
desired := make([]desiredLBRule, 0, len(service.Spec.Ports))
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)
lbRule := lb.findLoadBalancerRule(lbRuleName, port, protocol)
change, err := lb.checkLoadBalancerRule(lbRule, lbRuleName, port, protocol, service, version)
if err != nil {
return nil, err
}
if lbRule != nil {
// Claim by the rule's actual name: after a protocol change it still carries the old one.
delete(lb.rules, lbRule.Name)
}
desired = append(desired, desiredLBRule{
name: lbRuleName,
port: port,
protocol: protocol,
existing: lbRule,
change: change,
})
}
return desired, nil
}
// findLoadBalancerRule locates the existing CloudStack rule for a desired service port. It
// prefers an exact name match, then falls back to matching on the tuple. That fallback is what
// lets a protocol change (tcp <-> tcp-proxy) update the existing rule instead of creating a
// conflicting one.
//
// Only rules on the IP being reconciled towards are eligible; a rule on any other IP is left
// for the prune pass, which also cleans up the firewall rules it leaves behind.
func (lb *loadBalancer) findLoadBalancerRule(lbRuleName string, port corev1.ServicePort, protocol LoadBalancerProtocol) *cloudstack.LoadBalancerRule {
if lbRule, ok := lb.rules[lbRuleName]; ok && lbRule.Publicipid == lb.ipAddrID {
return lbRule
}
publicPort := strconv.Itoa(int(port.Port))
var names []string
for name, lbRule := range lb.rules {
if lbRule.Publicipid == lb.ipAddrID &&
ProtocolFromLoadBalancer(lbRule.Protocol).IPProtocol() == protocol.IPProtocol() &&
lbRule.Publicport == publicPort {
names = append(names, name)
}
}
if len(names) == 0 {
return nil
}
// Map iteration order is randomized; sort so the pick is deterministic.
sort.Strings(names)
if len(names) > 1 {
klog.Warningf("Multiple load balancer rules match %s port %s: %v; using %v", protocol.IPProtocol(), publicPort, names, names[0])
}
return lb.rules[names[0]]
}
// portProtocol is the tuple CloudStack refuses to place two load balancer rules on, and that
// firewall and network ACL rules are keyed on. IPProtocol maps both tcp and tcp-proxy to
// "tcp", so a tcp and a tcp-proxy rule on one port share a tuple, and one firewall/ACL rule.
type portProtocol struct {
ipProtocol string
publicPort int32
}
// obsoleteRule is a rule no desired service port claimed, with its tuple already parsed.
type obsoleteRule struct {
rule *cloudstack.LoadBalancerRule
protocol LoadBalancerProtocol
tuple portProtocol
}
// partitionObsoleteRules splits the rules left in lb.rules — those no desired port claimed —
// into the ones holding a tuple that a rule still to be created needs, and the rest.
func (lb *loadBalancer) partitionObsoleteRules(desired []desiredLBRule) (blocking, rest []obsoleteRule) {
// CloudStack refuses two load balancer rules with overlapping public port ranges on one
// IP whatever their protocols, so the port alone decides what blocks a create. Note this
// is deliberately coarser than the firewall/ACL claim, which is per protocol because
// firewall rules are.
neededPorts := make(map[int32]bool)
for _, d := range desired {
if d.createsRule() {
neededPorts[d.port.Port] = true
}
}
// Iterate in name order so the prune sequence is reproducible.
names := make([]string, 0, len(lb.rules))
for name := range lb.rules {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
lbRule := lb.rules[name]
port, err := strconv.ParseInt(lbRule.Publicport, 10, 32)
if err != nil {
klog.Warningf("Skipping obsolete load balancer rule %v (%v on public IP %v) with invalid public port %q: %v", lbRule.Name, lbRule.Id, lbRule.Publicipid, lbRule.Publicport, err)
continue
}
// Conflicts are per public IP, so only a rule on the IP being reconciled towards can
// block a create.
blocksACreate := lbRule.Publicipid == lb.ipAddrID && neededPorts[int32(port)]
// A protocol the provider cannot interpret leaves its firewall or ACL rule
// unresolvable, so such a rule is normally left alone. One holding a port a create
// needs still has to go, or CloudStack rejects that create as a port conflict.
protocol := ProtocolFromLoadBalancer(lbRule.Protocol)
if protocol == LoadBalancerProtocolInvalid && !blocksACreate {
klog.Warningf("Skipping obsolete load balancer rule %v (%v on public IP %v) with unknown protocol %q", lbRule.Name, lbRule.Id, lbRule.Publicipid, lbRule.Protocol)
continue
}
obsolete := obsoleteRule{
rule: lbRule,
protocol: protocol,
tuple: portProtocol{protocol.IPProtocol(), int32(port)},
}
if blocksACreate {
blocking = append(blocking, obsolete)
} else {
rest = append(rest, obsolete)
}
}
return blocking, rest
}
// ruleNetworkID is the network whose ACL rules an existing load balancer rule was opened in, or
// "" when that network cannot be established. CloudStack omits the network on rules of some
// network types; such a rule is known to belong to the network being reconciled towards only
// when it sits on the public IP being reconciled towards.
func (lb *loadBalancer) ruleNetworkID(lbRule *cloudstack.LoadBalancerRule) string {
if lbRule.Networkid != "" {
return lbRule.Networkid
}
if lbRule.Publicipid == lb.ipAddrID {
return lb.networkID
}
return ""
}
// claimedTuples are the tuples the desired service ports still need, and whose firewall or
// network ACL rules therefore have to survive a prune.
func claimedTuples(desired []desiredLBRule) map[portProtocol]bool {
claimed := make(map[portProtocol]bool, len(desired))
for _, d := range desired {
claimed[portProtocol{d.protocol.IPProtocol(), d.port.Port}] = true
}
return claimed
}
// pruneFirewallRule deletes the firewall rule admitting traffic to an obsolete load balancer
// rule. Firewall rules belong to a single public IP, so a claim only covers a rule on the IP
// the service is being reconciled towards.
func (lb *loadBalancer) pruneFirewallRule(o obsoleteRule, claimed map[portProtocol]bool) error {
lbRule, port := o.rule, int(o.tuple.publicPort)
if claimed[o.tuple] && lbRule.Publicipid == lb.ipAddrID {
klog.V(4).Infof("Keeping firewall rules of obsolete load balancer rule %v (%v:%v:%v): still claimed by a service port", lbRule.Name, o.protocol, lbRule.Publicip, port)
return nil
}
klog.V(4).Infof("Deleting firewall rules associated with load balancer rule: %v (%v:%v:%v)", lbRule.Name, o.protocol, lbRule.Publicip, port)
_, err := lb.deleteFirewallRule(lbRule.Publicipid, port, o.protocol)
return err
}
// pruneNetworkACLRule deletes the network ACL rule admitting traffic to an obsolete load
// balancer rule, in the network that rule belongs to. ACL rules belong to a network rather than
// an IP, so a claim only covers a rule in the network the service is being reconciled towards.
func (lb *loadBalancer) pruneNetworkACLRule(o obsoleteRule, claimed map[portProtocol]bool, networkID string) error {
lbRule, port := o.rule, int(o.tuple.publicPort)
if claimed[o.tuple] && networkID == lb.networkID {
klog.V(4).Infof("Keeping Network ACL rules of obsolete load balancer rule %v (%v:%v:%v): still claimed by a service port", lbRule.Name, o.protocol, networkID, port)
return nil
}
klog.V(4).Infof("Deleting Network ACL rules associated with load balancer rule: %v (%v:%v:%v)", lbRule.Name, o.protocol, networkID, port)
_, err := lb.deleteNetworkACLRule(port, o.protocol, networkID)
return err
}
// rememberNetwork records a network already fetched, so resolving the network of a rule in it
// costs no further call.
func (lb *loadBalancer) rememberNetwork(networkID string, network *cloudstack.Network) {
if lb.networks == nil {
lb.networks = make(map[string]*cloudstack.Network)
}
lb.networks[networkID] = network
}
// networkByID is the network with the given ID, or nil when CloudStack no longer has it. An
// empty ID is nil rather than a lookup, which GetNetworkByID would answer with an arbitrary
// network from an unfiltered list. GetNetworkByID reports not-found as an error with a count of
// 0, so the count has to be checked before the error.
func (lb *loadBalancer) networkByID(networkID string) (*cloudstack.Network, error) {
if networkID == "" {
return nil, nil
}
if network, ok := lb.networks[networkID]; ok {
return network, nil
}
network, count, err := lb.Network.GetNetworkByID(networkID, cloudstack.WithProject(lb.projectID))
switch {
case count == 0:
network = nil
case err != nil:
return nil, fmt.Errorf("error fetching network %v: %v", networkID, err)
}
lb.rememberNetwork(networkID, network)
return network, nil
}
// ruleNetwork is the network an existing load balancer rule was created in, or nil when that
// network cannot be established, either because CloudStack reported no network for the rule or
// because the network has since been deleted.
func (lb *loadBalancer) ruleNetwork(lbRule *cloudstack.LoadBalancerRule) (*cloudstack.Network, error) {
return lb.networkByID(lb.ruleNetworkID(lbRule))
}
// pruneRuleOpening deletes the firewall or network ACL rule admitting traffic to an obsolete
// load balancer rule, unless a desired service port still claims that same opening. Which of
// the two a rule has follows the network that rule belongs to, not the one being reconciled
// towards, so a rule left behind in a network of the other kind does not keep its opening.
//
// A rule with an uninterpretable protocol keeps its opening, which cannot be identified without
// one. A rule whose network cannot be established still has its firewall rule deleted, that
// being scoped to the rule's own public IP, while any ACL rule is left in place.
func (lb *loadBalancer) pruneRuleOpening(o obsoleteRule, claimed map[portProtocol]bool) error {
if o.protocol == LoadBalancerProtocolInvalid {
klog.Warningf("Leaving the firewall or Network ACL rule of obsolete load balancer rule %v in place: unknown protocol %v", o.rule.Name, o.rule.Protocol)
return nil
}
network, err := lb.ruleNetwork(o.rule)
if err != nil {
return err
}
switch {
case network == nil:
klog.Warningf("Cannot establish the network of obsolete load balancer rule %v; leaving any Network ACL rule of it in place", o.rule.Name)
return lb.pruneFirewallRule(o, claimed)
case isFirewallSupported(network.Service):
return lb.pruneFirewallRule(o, claimed)
case isNetworkACLSupported(network.Service):
return lb.pruneNetworkACLRule(o, claimed, network.Id)
}
return nil
}
// pruneRules deletes the given obsolete rules along with their firewall or network ACL rules.
// A firewall/ACL rule is kept when a desired port still claims the same tuple, since the two
// load balancer rules share it and pruning would strip the survivor of its opening.
//
// The network being reconciled towards is taken as already fetched, so only a rule belonging to
// some other network costs a lookup of its own.
//
// A rule that fails to delete is reported but does not stop the others being pruned.
func (lb *loadBalancer) pruneRules(obsolete []obsoleteRule, desired []desiredLBRule, network *cloudstack.Network) error {
lb.rememberNetwork(network.Id, network)
claimed := claimedTuples(desired)
var firstErr error
recordErr := func(err error) {
klog.Errorf("Error pruning obsolete load balancer rule: %v", err)
if firstErr == nil {
firstErr = err
}
}
for _, o := range obsolete {
if err := lb.pruneRuleOpening(o, claimed); err != nil {
recordErr(err)
continue
}
klog.V(4).Infof("Deleting obsolete load balancer rule: %v", o.rule.Name)
if err := lb.deleteLoadBalancerRule(o.rule); err != nil {