-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathloadbalancers.go
More file actions
1532 lines (1348 loc) · 51.5 KB
/
Copy pathloadbalancers.go
File metadata and controls
1532 lines (1348 loc) · 51.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
package linode
import (
"context"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/netip"
"os"
"reflect"
"strconv"
"strings"
"time"
"github.com/cilium/cilium/pkg/k8s/apis/cilium.io/v2alpha1"
ciliumclient "github.com/cilium/cilium/pkg/k8s/client/clientset/versioned/typed/cilium.io/v2alpha1"
"github.com/linode/linodego"
v1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
cloudprovider "k8s.io/cloud-provider"
"k8s.io/klog/v2"
"github.com/linode/linode-cloud-controller-manager/cloud/annotations"
"github.com/linode/linode-cloud-controller-manager/cloud/linode/client"
"github.com/linode/linode-cloud-controller-manager/cloud/linode/options"
"github.com/linode/linode-cloud-controller-manager/cloud/linode/services"
"github.com/linode/linode-cloud-controller-manager/sentry"
)
var (
errNoNodesAvailable = errors.New("no nodes available for nodebalancer")
maxConnThrottleStringLen int = 20
eventIPChangeIgnoredWarning = "nodebalancer-ipv4-change-ignored"
// validProtocols is a map of valid protocols
validProtocols = map[string]bool{
string(linodego.ProtocolTCP): true,
string(linodego.ProtocolUDP): true,
string(linodego.ProtocolHTTP): true,
string(linodego.ProtocolHTTPS): true,
}
// validProxyProtocols is a map of valid proxy protocols
validProxyProtocols = map[string]bool{
string(linodego.ProxyProtocolNone): true,
string(linodego.ProxyProtocolV1): true,
string(linodego.ProxyProtocolV2): true,
}
// validTCPAlgorithms is a map of valid TCP algorithms
validTCPAlgorithms = map[string]bool{
string(linodego.AlgorithmRoundRobin): true,
string(linodego.AlgorithmLeastConn): true,
string(linodego.AlgorithmSource): true,
}
// validUDPAlgorithms is a map of valid UDP algorithms
validUDPAlgorithms = map[string]bool{
string(linodego.AlgorithmRoundRobin): true,
string(linodego.AlgorithmRingHash): true,
string(linodego.AlgorithmLeastConn): true,
}
// validHTTPStickiness is a map of valid HTTP stickiness options
validHTTPStickiness = map[string]bool{
string(linodego.StickinessNone): true,
string(linodego.StickinessHTTPCookie): true,
string(linodego.StickinessTable): true,
}
// validHTTPSStickiness is the same as validHTTPStickiness, but for HTTPS
validHTTPSStickiness = map[string]bool{
string(linodego.StickinessNone): true,
string(linodego.StickinessHTTPCookie): true,
string(linodego.StickinessTable): true,
}
// validUDPStickiness is a map of valid UDP stickiness options
validUDPStickiness = map[string]bool{
string(linodego.StickinessNone): true,
string(linodego.StickinessSession): true,
string(linodego.StickinessSourceIP): true,
}
// validNBConfigChecks is a map of valid NodeBalancer config checks
validNBConfigChecks = map[string]bool{
string(linodego.CheckNone): true,
string(linodego.CheckHTTP): true,
string(linodego.CheckHTTPBody): true,
string(linodego.CheckConnection): true,
}
)
type lbNotFoundError struct {
serviceNn string
nodeBalancerID int
}
func (e lbNotFoundError) Error() string {
if e.nodeBalancerID != 0 {
return fmt.Sprintf("LoadBalancer (%d) not found for service (%s)", e.nodeBalancerID, e.serviceNn)
}
return fmt.Sprintf("LoadBalancer not found for service (%s)", e.serviceNn)
}
type loadbalancers struct {
client client.Client
zone string
kubeClient kubernetes.Interface
ciliumClient ciliumclient.CiliumV2alpha1Interface
loadBalancerType string
}
type portConfigAnnotation struct {
TLSSecretName string `json:"tls-secret-name"`
Protocol string `json:"protocol"`
ProxyProtocol string `json:"proxy-protocol"`
Algorithm string `json:"algorithm"`
Stickiness string `json:"stickiness"`
UDPCheckPort string `json:"udp-check-port"`
}
type portConfig struct {
TLSSecretName string
Protocol linodego.ConfigProtocol
ProxyProtocol linodego.ConfigProxyProtocol
Port int
Algorithm linodego.ConfigAlgorithm
Stickiness linodego.ConfigStickiness
UDPCheckPort int
}
// newLoadbalancers returns a cloudprovider.LoadBalancer whose concrete type is a *loadbalancer.
func newLoadbalancers(client client.Client, zone string) cloudprovider.LoadBalancer {
return &loadbalancers{client: client, zone: zone, loadBalancerType: options.Options.LoadBalancerType}
}
func (l *loadbalancers) getNodeBalancerForService(ctx context.Context, service *v1.Service) (*linodego.NodeBalancer, error) {
rawID := service.GetAnnotations()[annotations.AnnLinodeNodeBalancerID]
id, idErr := strconv.Atoi(rawID)
hasIDAnn := idErr == nil && id != 0
if hasIDAnn {
sentry.SetTag(ctx, "load_balancer_id", rawID)
return l.getNodeBalancerByID(ctx, service, id)
}
return l.getNodeBalancerByStatus(ctx, service)
}
func (l *loadbalancers) getLatestServiceLoadBalancerStatus(ctx context.Context, service *v1.Service) (v1.LoadBalancerStatus, error) {
err := l.retrieveKubeClient()
if err != nil {
return v1.LoadBalancerStatus{}, err
}
service, err = l.kubeClient.CoreV1().Services(service.Namespace).Get(ctx, service.Name, metav1.GetOptions{})
if err != nil {
return v1.LoadBalancerStatus{}, err
}
return service.Status.LoadBalancer, nil
}
// getNodeBalancerByStatus attempts to get the NodeBalancer from the IP or hostname specified in the
// most recent LoadBalancer status.
func (l *loadbalancers) getNodeBalancerByStatus(ctx context.Context, service *v1.Service) (nb *linodego.NodeBalancer, err error) {
lb := service.Status.LoadBalancer
updatedLb, err := l.getLatestServiceLoadBalancerStatus(ctx, service)
if err != nil {
klog.V(3).Infof("failed to get latest LoadBalancer status for service (%s): %v", getServiceNn(service), err)
} else {
lb = updatedLb
}
for _, ingress := range lb.Ingress {
if ingress.IP != "" {
address, err := netip.ParseAddr(ingress.IP)
if err != nil {
klog.Warningf("failed to parse IP address %s from service %s/%s status, error: %s", ingress.IP, service.Namespace, service.Name, err)
} else {
return l.getNodeBalancerByIP(ctx, service, address)
}
}
if ingress.Hostname != "" {
return l.getNodeBalancerByHostname(ctx, service, ingress.Hostname)
}
}
return nil, lbNotFoundError{serviceNn: getServiceNn(service)}
}
// cleanupOldNodeBalancer removes the service's disowned NodeBalancer if there is one.
//
// The current NodeBalancer from getNodeBalancerForService is compared to the most recent
// LoadBalancer status; if they are different (because of an updated NodeBalancerID
// annotation), the old one is deleted.
func (l *loadbalancers) cleanupOldNodeBalancer(ctx context.Context, service *v1.Service) error {
// unless there's an annotation, we can never get a past and current NB to differ,
// because they're looked up the same way
if _, ok := service.GetAnnotations()[annotations.AnnLinodeNodeBalancerID]; !ok {
return nil
}
previousNB, err := l.getNodeBalancerByStatus(ctx, service)
if err != nil {
var targetError lbNotFoundError
if errors.As(err, &targetError) {
return nil
} else {
return err
}
}
nb, err := l.getNodeBalancerForService(ctx, service)
if err != nil {
return err
}
if previousNB.ID == nb.ID {
return nil
}
if err := l.client.DeleteNodeBalancer(ctx, previousNB.ID); err != nil {
return err
}
klog.Infof("successfully deleted old NodeBalancer (%d) for service (%s)", previousNB.ID, getServiceNn(service))
return nil
}
// GetLoadBalancerName returns the name of the load balancer.
//
// GetLoadBalancer will not modify service.
func (l *loadbalancers) GetLoadBalancerName(_ context.Context, _ string, _ *v1.Service) string {
unixNano := strconv.FormatInt(time.Now().UnixNano(), 16)
return fmt.Sprintf("%s-%s", options.Options.NodeBalancerPrefix, unixNano[len(unixNano)-12:])
}
// GetLoadBalancer returns the *v1.LoadBalancerStatus of service.
//
// GetLoadBalancer will not modify service.
func (l *loadbalancers) GetLoadBalancer(ctx context.Context, clusterName string, service *v1.Service) (*v1.LoadBalancerStatus, bool, error) {
ctx = sentry.SetHubOnContext(ctx)
sentry.SetTag(ctx, "cluster_name", clusterName)
sentry.SetTag(ctx, "service", service.Name)
// Handle LoadBalancers backed by Cilium
if l.loadBalancerType == ciliumLBType {
return &v1.LoadBalancerStatus{
Ingress: service.Status.LoadBalancer.Ingress,
}, true, nil
}
nb, err := l.getNodeBalancerForService(ctx, service)
if err != nil {
var targetError lbNotFoundError
if errors.As(err, &targetError) {
return nil, false, nil
} else {
sentry.CaptureError(ctx, err)
return nil, false, err
}
}
return makeLoadBalancerStatus(service, nb), true, nil
}
// EnsureLoadBalancer ensures that the cluster is running a load balancer for
// service.
//
// EnsureLoadBalancer will not modify service or nodes.
func (l *loadbalancers) EnsureLoadBalancer(ctx context.Context, clusterName string, service *v1.Service, nodes []*v1.Node) (lbStatus *v1.LoadBalancerStatus, err error) {
ctx = sentry.SetHubOnContext(ctx)
sentry.SetTag(ctx, "cluster_name", clusterName)
sentry.SetTag(ctx, "service", service.Name)
serviceNn := getServiceNn(service)
// Handle LoadBalancers backed by Cilium
if l.loadBalancerType == ciliumLBType {
klog.Infof("handling LoadBalancer Service %s as %s", serviceNn, ciliumLBClass)
if err = l.ensureCiliumBGPPeeringPolicy(ctx); err != nil {
klog.Infof("Failed to ensure CiliumBGPPeeringPolicy: %v", err)
return nil, err
}
// check for existing CiliumLoadBalancerIPPool for service
var pool *v2alpha1.CiliumLoadBalancerIPPool
pool, err = l.getCiliumLBIPPool(ctx, service)
if err != nil && !k8serrors.IsNotFound(err) {
klog.Infof("Failed to get CiliumLoadBalancerIPPool: %s", err.Error())
return nil, err
}
// if the CiliumLoadBalancerIPPool doesn't exist, it's not nil, instead an empty struct
// gets returned, so we check if this is so via the Name being empty
if pool != nil && pool.Name != "" {
klog.Infof("Cilium LB IP pool %s for Service %s ensured", pool.Name, serviceNn)
// ingress will be set by Cilium
return &v1.LoadBalancerStatus{
Ingress: service.Status.LoadBalancer.Ingress,
}, nil
}
var ipHolderSuffix string
if options.Options.IpHolderSuffix != "" {
ipHolderSuffix = options.Options.IpHolderSuffix
klog.Infof("using parameter-based IP Holder suffix %s for Service %s", ipHolderSuffix, serviceNn)
}
// CiliumLoadBalancerIPPool does not yet exist for the service
var sharedIP string
if sharedIP, err = l.createSharedIP(ctx, nodes, ipHolderSuffix); err != nil {
klog.Errorf("Failed to request shared instance IP: %s", err.Error())
return nil, err
}
if _, err = l.createCiliumLBIPPool(ctx, service, sharedIP); err != nil {
klog.Infof("Failed to create CiliumLoadBalancerIPPool: %s", err.Error())
return nil, err
}
// ingress will be set by Cilium
return &v1.LoadBalancerStatus{
Ingress: service.Status.LoadBalancer.Ingress,
}, nil
}
// Handle LoadBalancers backed by NodeBalancers
var nb *linodego.NodeBalancer
nb, err = l.getNodeBalancerForService(ctx, service)
if err == nil {
if err = l.updateNodeBalancer(ctx, clusterName, service, nodes, nb); err != nil {
sentry.CaptureError(ctx, err)
return nil, err
}
} else {
var targetError lbNotFoundError
if errors.As(err, &targetError) {
if service.GetAnnotations()[annotations.AnnLinodeNodeBalancerID] != "" {
// a load balancer annotation has been created so a NodeBalancer is coming, error out and retry later
klog.Infof("NodeBalancer created but not available yet, waiting...")
sentry.CaptureError(ctx, err)
return nil, err
}
if nb, err = l.buildLoadBalancerRequest(ctx, clusterName, service, nodes); err != nil {
sentry.CaptureError(ctx, err)
return nil, err
}
klog.Infof("created new NodeBalancer (%d) for service (%s)", nb.ID, serviceNn)
} else {
sentry.CaptureError(ctx, err)
return nil, err
}
}
klog.Infof("NodeBalancer (%d) has been ensured for service (%s)", nb.ID, serviceNn)
lbStatus = makeLoadBalancerStatus(service, nb)
if !l.shouldPreserveNodeBalancer(service) {
if err := l.cleanupOldNodeBalancer(ctx, service); err != nil {
sentry.CaptureError(ctx, err)
return nil, err
}
}
return lbStatus, nil
}
func (l *loadbalancers) createIPChangeWarningEvent(ctx context.Context, service *v1.Service, nb *linodego.NodeBalancer, newIP string) {
_, err := l.kubeClient.CoreV1().Events(service.Namespace).Create(ctx, &v1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("%s-%d", eventIPChangeIgnoredWarning, time.Now().Unix()),
Namespace: service.Namespace,
},
InvolvedObject: v1.ObjectReference{
Kind: "Service",
Namespace: service.Namespace,
Name: service.Name,
UID: service.UID,
},
Type: "Warning",
Reason: "NodeBalancerIPChangeIgnored",
Message: fmt.Sprintf("IPv4 annotation changed to %s, but NodeBalancer (%d) IP cannot be updated after creation. It will remain %s", newIP, nb.ID, *nb.IPv4),
Source: v1.EventSource{
Component: "linode-cloud-controller-manager",
},
}, metav1.CreateOptions{})
if err != nil {
klog.Errorf("failed to create NodeBalancerIPChangeIgnored event for service %s: %s", getServiceNn(service), err)
}
}
func (l *loadbalancers) updateNodeBalancer(
ctx context.Context,
clusterName string,
service *v1.Service,
nodes []*v1.Node,
nb *linodego.NodeBalancer,
) (err error) {
if len(nodes) == 0 {
return fmt.Errorf("%w: service %s", errNoNodesAvailable, getServiceNn(service))
}
// Check for IPv4 annotation change
if ipv4, ok := service.GetAnnotations()[annotations.AnnLinodeLoadBalancerReservedIPv4]; ok && ipv4 != *nb.IPv4 {
// Log the error in the CCM's logfile
klog.Warningf("IPv4 annotation has changed for service (%s) from %s to %s, but NodeBalancer (%d) IP cannot be updated after creation",
getServiceNn(service), *nb.IPv4, ipv4, nb.ID)
// Issue a k8s cluster event warning
l.createIPChangeWarningEvent(ctx, service, nb, ipv4)
}
connThrottle := getConnectionThrottle(service)
if connThrottle != nb.ClientConnThrottle {
update := nb.GetUpdateOptions()
update.ClientConnThrottle = &connThrottle
nb, err = l.client.UpdateNodeBalancer(ctx, nb.ID, update)
if err != nil {
sentry.CaptureError(ctx, err)
return err
}
}
tags := l.GetLoadBalancerTags(ctx, clusterName, service)
if !reflect.DeepEqual(nb.Tags, tags) {
update := nb.GetUpdateOptions()
update.Tags = &tags
nb, err = l.client.UpdateNodeBalancer(ctx, nb.ID, update)
if err != nil {
sentry.CaptureError(ctx, err)
return err
}
}
fwClient := services.LinodeClient{Client: l.client}
err = fwClient.UpdateNodeBalancerFirewall(ctx, l.GetLoadBalancerName(ctx, clusterName, service), tags, service, nb)
if err != nil {
return err
}
// Get all of the NodeBalancer's configs
nbCfgs, err := l.client.ListNodeBalancerConfigs(ctx, nb.ID, nil)
if err != nil {
sentry.CaptureError(ctx, err)
return err
}
// Delete any configs for ports that have been removed from the Service
if err = l.deleteUnusedConfigs(ctx, nbCfgs, service.Spec.Ports); err != nil {
sentry.CaptureError(ctx, err)
return err
}
// Add or overwrite configs for each of the Service's ports
for _, port := range service.Spec.Ports {
// Construct a new config for this port
newNBCfg, err := l.buildNodeBalancerConfig(ctx, service, port)
if err != nil {
sentry.CaptureError(ctx, err)
return err
}
// Look for an existing config for this port
var currentNBCfg *linodego.NodeBalancerConfig
for i := range nbCfgs {
nbc := nbCfgs[i]
if nbc.Port == int(port.Port) {
currentNBCfg = &nbc
break
}
}
oldNBNodeIDs := make(map[string]int)
if currentNBCfg != nil {
// Obtain list of current NB nodes and convert it to map of node IDs
var currentNBNodes []linodego.NodeBalancerNode
currentNBNodes, err = l.client.ListNodeBalancerNodes(ctx, nb.ID, currentNBCfg.ID, nil)
if err != nil {
// This error can be ignored, because if we fail to get nodes we can anyway rebuild the config from scratch,
// it would just cause the NB to reload config even if the node list did not change, so we prefer to send IDs when it is possible.
klog.Warningf("Unable to list existing nodebalancer nodes for NB %d config %d, error: %s", nb.ID, newNBCfg.ID, err)
}
for _, node := range currentNBNodes {
oldNBNodeIDs[node.Address] = node.ID
}
klog.Infof("Nodebalancer %d had nodes %v", nb.ID, oldNBNodeIDs)
} else {
klog.Infof("No preexisting nodebalancer for port %v found.", port.Port)
}
// Add all of the Nodes to the config
newNBNodes := make([]linodego.NodeBalancerConfigRebuildNodeOptions, 0, len(nodes))
subnetID := 0
if options.Options.NodeBalancerBackendIPv4SubnetID != 0 {
subnetID = options.Options.NodeBalancerBackendIPv4SubnetID
}
backendIPv4Range, ok := service.GetAnnotations()[annotations.NodeBalancerBackendIPv4Range]
if ok {
if err = validateNodeBalancerBackendIPv4Range(backendIPv4Range); err != nil {
return err
}
}
if len(options.Options.VPCNames) > 0 && !options.Options.DisableNodeBalancerVPCBackends {
var id int
id, err = l.getSubnetIDForSVC(ctx, service)
if err != nil {
sentry.CaptureError(ctx, err)
return fmt.Errorf("Error getting subnet ID for service %s: %w", service.Name, err)
}
subnetID = id
}
for _, node := range nodes {
var newNodeOpts *linodego.NodeBalancerConfigRebuildNodeOptions
newNodeOpts, err = l.buildNodeBalancerNodeConfigRebuildOptions(node, port.NodePort, subnetID, newNBCfg.Protocol)
if err != nil {
sentry.CaptureError(ctx, err)
return fmt.Errorf("failed to build NodeBalancer node config options for node %s: %w", node.Name, err)
}
oldNodeID, ok := oldNBNodeIDs[newNodeOpts.Address]
if ok {
newNodeOpts.ID = oldNodeID
} else {
klog.Infof("No preexisting node id for %v found.", newNodeOpts.Address)
}
newNBNodes = append(newNBNodes, *newNodeOpts)
}
// If there's no existing config, create it
var rebuildOpts linodego.NodeBalancerConfigRebuildOptions
if currentNBCfg == nil {
createOpts := newNBCfg.GetCreateOptions()
currentNBCfg, err = l.client.CreateNodeBalancerConfig(ctx, nb.ID, createOpts)
if err != nil {
sentry.CaptureError(ctx, err)
return fmt.Errorf("[port %d] error creating NodeBalancer config: %w", int(port.Port), err)
}
rebuildOpts = currentNBCfg.GetRebuildOptions()
// SSLCert and SSLKey return <REDACTED> from the API, so copy the
// value that we sent in create for the rebuild
rebuildOpts.SSLCert = newNBCfg.SSLCert
rebuildOpts.SSLKey = newNBCfg.SSLKey
} else {
rebuildOpts = newNBCfg.GetRebuildOptions()
}
rebuildOpts.Nodes = newNBNodes
if _, err = l.client.RebuildNodeBalancerConfig(ctx, nb.ID, currentNBCfg.ID, rebuildOpts); err != nil {
sentry.CaptureError(ctx, err)
return fmt.Errorf("[port %d] error rebuilding NodeBalancer config: %w", int(port.Port), err)
}
}
return nil
}
// UpdateLoadBalancer updates the NodeBalancer to have configs that match the Service's ports
func (l *loadbalancers) UpdateLoadBalancer(ctx context.Context, clusterName string, service *v1.Service, nodes []*v1.Node) (err error) {
ctx = sentry.SetHubOnContext(ctx)
sentry.SetTag(ctx, "cluster_name", clusterName)
sentry.SetTag(ctx, "service", service.Name)
// handle LoadBalancers backed by Cilium
if l.loadBalancerType == ciliumLBType {
klog.Infof("handling update for LoadBalancer Service %s/%s as %s", service.Namespace, service.Name, ciliumLBClass)
serviceNn := getServiceNn(service)
var ipHolderSuffix string
if options.Options.IpHolderSuffix != "" {
ipHolderSuffix = options.Options.IpHolderSuffix
klog.V(3).Infof("using parameter-based IP Holder suffix %s for Service %s", ipHolderSuffix, serviceNn)
}
// make sure that IPs are shared properly on the Node if using load-balancers not backed by NodeBalancers
for _, node := range nodes {
if err = l.handleIPSharing(ctx, node, ipHolderSuffix); err != nil {
return err
}
}
return nil
}
// UpdateLoadBalancer is invoked with a nil LoadBalancerStatus; we must fetch the latest
// status for NodeBalancer discovery.
serviceWithStatus := service.DeepCopy()
serviceWithStatus.Status.LoadBalancer, err = l.getLatestServiceLoadBalancerStatus(ctx, service)
if err != nil {
return fmt.Errorf("failed to get latest LoadBalancer status for service (%s): %w", getServiceNn(service), err)
}
nb, err := l.getNodeBalancerForService(ctx, serviceWithStatus)
if err != nil {
sentry.CaptureError(ctx, err)
return err
}
if !l.shouldPreserveNodeBalancer(service) {
if err := l.cleanupOldNodeBalancer(ctx, service); err != nil {
sentry.CaptureError(ctx, err)
return err
}
}
return l.updateNodeBalancer(ctx, clusterName, serviceWithStatus, nodes, nb)
}
// Delete any NodeBalancer configs for ports that no longer exist on the Service
// Note: Don't build a map or other lookup structure here, it is not worth the overhead
func (l *loadbalancers) deleteUnusedConfigs(ctx context.Context, nbConfigs []linodego.NodeBalancerConfig, servicePorts []v1.ServicePort) error {
for _, nbc := range nbConfigs {
found := false
for _, sp := range servicePorts {
if nbc.Port == int(sp.Port) {
found = true
}
}
if !found {
if err := l.client.DeleteNodeBalancerConfig(ctx, nbc.NodeBalancerID, nbc.ID); err != nil {
return err
}
}
}
return nil
}
// shouldPreserveNodeBalancer determines whether a NodeBalancer should be deleted based on the
// service's preserve annotation.
func (l *loadbalancers) shouldPreserveNodeBalancer(service *v1.Service) bool {
return getServiceBoolAnnotation(service, annotations.AnnLinodeLoadBalancerPreserve)
}
// EnsureLoadBalancerDeleted deletes the specified loadbalancer if it exists.
// nil is returned if the load balancer for service does not exist or is
// successfully deleted.
//
// EnsureLoadBalancerDeleted will not modify service.
func (l *loadbalancers) EnsureLoadBalancerDeleted(ctx context.Context, clusterName string, service *v1.Service) error {
ctx = sentry.SetHubOnContext(ctx)
sentry.SetTag(ctx, "cluster_name", clusterName)
sentry.SetTag(ctx, "service", service.Name)
// Handle LoadBalancers backed by Cilium
if l.loadBalancerType == ciliumLBType {
klog.Infof("handling LoadBalancer Service %s/%s as %s", service.Namespace, service.Name, ciliumLBClass)
if err := l.deleteSharedIP(ctx, service); err != nil {
return err
}
// delete CiliumLoadBalancerIPPool for service
if err := l.deleteCiliumLBIPPool(ctx, service); err != nil && !k8serrors.IsNotFound(err) {
klog.Infof("Failed to delete CiliumLoadBalancerIPPool")
return err
}
return nil
}
// Handle LoadBalancers backed by NodeBalancers
serviceNn := getServiceNn(service)
if len(service.Status.LoadBalancer.Ingress) == 0 {
klog.Infof("short-circuiting deletion of NodeBalancer for service(%s) as LoadBalancer ingress is not present", serviceNn)
return nil
}
nb, err := l.getNodeBalancerForService(ctx, service)
if err != nil {
var targetError lbNotFoundError
if errors.As(err, &targetError) {
klog.Infof("short-circuiting deletion for NodeBalancer for service (%s) as one does not exist: %s", serviceNn, err)
return nil
} else {
klog.Errorf("failed to get NodeBalancer for service (%s): %s", serviceNn, err)
sentry.CaptureError(ctx, err)
return err
}
}
if l.shouldPreserveNodeBalancer(service) {
klog.Infof(
"short-circuiting deletion of NodeBalancer (%d) for service (%s) as annotated with %s",
nb.ID,
serviceNn,
annotations.AnnLinodeLoadBalancerPreserve,
)
return nil
}
fwClient := services.LinodeClient{Client: l.client}
if err = fwClient.DeleteNodeBalancerFirewall(ctx, service, nb); err != nil {
return err
}
if err = l.client.DeleteNodeBalancer(ctx, nb.ID); err != nil {
klog.Errorf("failed to delete NodeBalancer (%d) for service (%s): %s", nb.ID, serviceNn, err)
sentry.CaptureError(ctx, err)
return err
}
klog.Infof("successfully deleted NodeBalancer (%d) for service (%s)", nb.ID, serviceNn)
return nil
}
func (l *loadbalancers) getNodeBalancerByHostname(ctx context.Context, service *v1.Service, hostname string) (*linodego.NodeBalancer, error) {
lbs, err := l.client.ListNodeBalancers(ctx, nil)
if err != nil {
return nil, err
}
for _, lb := range lbs {
if *lb.Hostname == hostname {
klog.V(2).Infof("found NodeBalancer (%d) for service (%s) via hostname (%s)", lb.ID, getServiceNn(service), hostname)
return &lb, nil
}
}
return nil, lbNotFoundError{serviceNn: getServiceNn(service)}
}
func (l *loadbalancers) getNodeBalancerByIP(ctx context.Context, service *v1.Service, ip netip.Addr) (*linodego.NodeBalancer, error) {
var filter string
if ip.Is6() {
filter = fmt.Sprintf(`{"ipv6": "%v"}`, ip.String())
} else {
filter = fmt.Sprintf(`{"ipv4": "%v"}`, ip.String())
}
lbs, err := l.client.ListNodeBalancers(ctx, &linodego.ListOptions{Filter: filter})
if err != nil {
return nil, err
}
if len(lbs) == 0 {
return nil, lbNotFoundError{serviceNn: getServiceNn(service)}
}
// filter by subnet ID if specified for frontend vpc ip
frontendSubnetID := service.GetAnnotations()[annotations.NodeBalancerFrontendSubnetID]
if frontendSubnetID != "" {
for _, lb := range lbs {
if lb.FrontendAddressType != nil && *lb.FrontendAddressType == "vpc" &&
lb.FrontendVPCSubnetID != nil && strconv.Itoa(*lb.FrontendVPCSubnetID) == frontendSubnetID {
return &lb, nil
}
}
return nil, lbNotFoundError{serviceNn: getServiceNn(service)}
}
klog.V(2).Infof("found NodeBalancer (%d) for service (%s) via IP (%s)", lbs[0].ID, getServiceNn(service), ip.String())
return &lbs[0], nil
}
func (l *loadbalancers) getNodeBalancerByID(ctx context.Context, service *v1.Service, id int) (*linodego.NodeBalancer, error) {
nb, err := l.client.GetNodeBalancer(ctx, id)
if err != nil {
var targetError *linodego.Error
if errors.As(err, &targetError) && targetError.Code == http.StatusNotFound {
return nil, lbNotFoundError{serviceNn: getServiceNn(service), nodeBalancerID: id}
}
return nil, err
}
return nb, nil
}
func (l *loadbalancers) GetLoadBalancerTags(_ context.Context, clusterName string, service *v1.Service) []string {
tags := []string{}
if clusterName != "" {
tags = append(tags, clusterName)
}
tags = append(tags, options.Options.NodeBalancerTags...)
tagStr, ok := service.GetAnnotations()[annotations.AnnLinodeLoadBalancerTags]
if ok {
return append(tags, strings.Split(tagStr, ",")...)
}
return tags
}
// GetLinodeNBType returns the NodeBalancer type for the service.
func (l *loadbalancers) GetLinodeNBType(service *v1.Service) linodego.NodeBalancerPlanType {
typeStr, ok := service.GetAnnotations()[annotations.AnnLinodeNodeBalancerType]
if ok {
// For Safety - avoid typos and inconsistent casing
typeStr = strings.ToLower(typeStr)
switch linodego.NodeBalancerPlanType(typeStr) {
case linodego.NBTypeCommon: // need to add this because of the golint check
return linodego.NBTypeCommon
case linodego.NBTypePremium:
return linodego.NBTypePremium
case linodego.NBTypePremium40GB:
return linodego.NBTypePremium40GB
default:
klog.Warningf("Invalid NodeBalancer type '%s' specified in annotation for service %s/%s. Valid types are: %s, %s, %s. Defaulting to %s.",
typeStr, service.Namespace, service.Name, linodego.NBTypeCommon, linodego.NBTypePremium, linodego.NBTypePremium40GB, options.Options.DefaultNBType)
}
}
return linodego.NodeBalancerPlanType(options.Options.DefaultNBType)
}
// getVPCCreateOptions returns the VPC options for the NodeBalancer creation.
// Order of precedence:
// 1. NodeBalancerBackendIPv4Range annotation
// 2. NodeBalancerBackendVPCName and NodeBalancerBackendSubnetName annotation
// 3. NodeBalancerBackendIPv4SubnetID/NodeBalancerBackendIPv4SubnetName flag
// 4. NodeBalancerBackendIPv4Subnet flag
// 5. Default to using the subnet ID of the service's VPC
func (l *loadbalancers) getVPCCreateOptions(ctx context.Context, service *v1.Service) ([]linodego.NodeBalancerVPCOptions, error) {
// Evaluate subnetID based on annotations or flags
subnetID, err := l.getSubnetIDForSVC(ctx, service)
if err != nil {
return nil, err
}
// Precedence 1: If the user has specified a NodeBalancerBackendIPv4Range, use that
backendIPv4Range, ok := service.GetAnnotations()[annotations.NodeBalancerBackendIPv4Range]
if ok {
if err := validateNodeBalancerBackendIPv4Range(backendIPv4Range); err != nil {
return nil, err
}
// If the user has specified a NodeBalancerBackendIPv4Range, use that
// for the NodeBalancer backend ipv4 range
if backendIPv4Range != "" {
vpcCreateOpts := []linodego.NodeBalancerVPCOptions{
{
SubnetID: subnetID,
IPv4Range: backendIPv4Range,
},
}
return vpcCreateOpts, nil
}
}
// Precedence 2: If the user wants to overwrite the default VPC name or subnet name
// and have specified it in the annotations, use it to set subnetID
// and auto-allocate subnets from it for the NodeBalancer
_, vpcInAnnotation := service.GetAnnotations()[annotations.NodeBalancerBackendVPCName]
_, subnetInAnnotation := service.GetAnnotations()[annotations.NodeBalancerBackendSubnetName]
if vpcInAnnotation || subnetInAnnotation {
vpcCreateOpts := []linodego.NodeBalancerVPCOptions{
{
SubnetID: subnetID,
},
}
return vpcCreateOpts, nil
}
// Precedence 3: If the user has specified a NodeBalancerBackendIPv4SubnetID, use that
// and auto-allocate subnets from it for the NodeBalancer
if options.Options.NodeBalancerBackendIPv4SubnetID != 0 {
vpcCreateOpts := []linodego.NodeBalancerVPCOptions{
{
SubnetID: options.Options.NodeBalancerBackendIPv4SubnetID,
},
}
return vpcCreateOpts, nil
}
// Precedence 4: If the user has specified a NodeBalancerBackendIPv4Subnet, use that
// and auto-allocate subnets from it for the NodeBalancer
if options.Options.NodeBalancerBackendIPv4Subnet != "" {
vpcCreateOpts := []linodego.NodeBalancerVPCOptions{
{
SubnetID: subnetID,
IPv4Range: options.Options.NodeBalancerBackendIPv4Subnet,
IPv4RangeAutoAssign: true,
},
}
return vpcCreateOpts, nil
}
// Default to using the subnet ID of the service's VPC
vpcCreateOpts := []linodego.NodeBalancerVPCOptions{
{
SubnetID: subnetID,
},
}
return vpcCreateOpts, nil
}
// getFrontendVPCCreateOptions returns the VPC options for the NodeBalancer frontend VPC creation.
// Order of precedence:
// 1. Frontend Subnet ID Annotation - Direct subnet ID
// 2. Frontend VPC/Subnet Name Annotations - Resolve by name
// 3. Frontend IPv4/IPv6 Range Annotations - Optional CIDR ranges
func (l *loadbalancers) getFrontendVPCCreateOptions(ctx context.Context, service *v1.Service) ([]linodego.NodeBalancerVPCOptions, error) {
frontendIPv4Range, hasIPv4Range := service.GetAnnotations()[annotations.NodeBalancerFrontendIPv4Range]
frontendIPv6Range, hasIPv6Range := service.GetAnnotations()[annotations.NodeBalancerFrontendIPv6Range]
vpcName, hasVPCName := service.GetAnnotations()[annotations.NodeBalancerFrontendVPCName]
subnetName, hasSubnetName := service.GetAnnotations()[annotations.NodeBalancerFrontendSubnetName]
frontendSubnetID, hasSubnetID := service.GetAnnotations()[annotations.NodeBalancerFrontendSubnetID]
// If no frontend VPC annotations are present, do not configure a frontend VPC.
if !hasIPv4Range && !hasIPv6Range && !hasVPCName && !hasSubnetName && !hasSubnetID {
return nil, nil
}
if err := validateNodeBalancerFrontendIPRange(frontendIPv4Range, "IPv4"); err != nil {
return nil, err
}
if err := validateNodeBalancerFrontendIPRange(frontendIPv6Range, "IPv6"); err != nil {
return nil, err
}
var subnetID int
var err error
switch {
case hasSubnetID:
subnetID, err = strconv.Atoi(frontendSubnetID)
if err != nil {
return nil, fmt.Errorf("invalid frontend subnet ID: %w", err)
}
case hasVPCName && hasSubnetName:
subnetID, err = l.getSubnetIDByVPCAndSubnetNames(ctx, vpcName, subnetName)
if err != nil {
return nil, err
}
default:
// Ranges are optional but still require a subnet to target.
return nil, fmt.Errorf("frontend VPC configuration requires either subnet-id or both vpc-name and subnet-name annotations")
}
vpcCreateOpts := []linodego.NodeBalancerVPCOptions{
{
SubnetID: subnetID,
IPv4Range: frontendIPv4Range,
IPv6Range: frontendIPv6Range,
},
}
return vpcCreateOpts, nil
}
// getSubnetIDByVPCAndSubnetNames returns the subnet ID for the given VPC name and subnet name.
func (l *loadbalancers) getSubnetIDByVPCAndSubnetNames(ctx context.Context, vpcName, subnetName string) (int, error) {
if vpcName == "" || subnetName == "" {
return 0, fmt.Errorf("frontend VPC configuration requires either subnet-id annotation or both vpc-name and subnet-name annotations. No vpc-name or subnet-name annotation found")
}
vpcID, err := services.GetVPCID(ctx, l.client, vpcName)
if err != nil {
return 0, fmt.Errorf("failed to get VPC ID for frontend VPC '%s': %w", vpcName, err)
}
// Use the VPC ID and Subnet Name to get the subnet ID
return services.GetSubnetID(ctx, l.client, vpcID, subnetName)
}
func (l *loadbalancers) createNodeBalancer(ctx context.Context, clusterName string, service *v1.Service, configs []*linodego.NodeBalancerConfigCreateOptions) (lb *linodego.NodeBalancer, err error) {
connThrottle := getConnectionThrottle(service)
label := l.GetLoadBalancerName(ctx, clusterName, service)
tags := l.GetLoadBalancerTags(ctx, clusterName, service)
nbType := l.GetLinodeNBType(service)
createOpts := linodego.NodeBalancerCreateOptions{
Label: &label,
Region: l.zone,
ClientConnThrottle: &connThrottle,
Configs: configs,
Tags: tags,
Type: nbType,
}
if len(options.Options.VPCNames) > 0 && !options.Options.DisableNodeBalancerVPCBackends {
createOpts.VPCs, err = l.getVPCCreateOptions(ctx, service)
if err != nil {
return nil, err
}
}
// Add frontend VPC configuration
if frontendVPCs, err := l.getFrontendVPCCreateOptions(ctx, service); err != nil {
return nil, err
} else if len(frontendVPCs) > 0 {
createOpts.FrontendVPCs = frontendVPCs
}
// Check for static IPv4 address annotation
if ipv4, ok := service.GetAnnotations()[annotations.AnnLinodeLoadBalancerReservedIPv4]; ok {
createOpts.IPv4 = &ipv4
}
fwid, ok := service.GetAnnotations()[annotations.AnnLinodeCloudFirewallID]
if ok {
firewallID, err := strconv.Atoi(fwid)
if err != nil {
return nil, err
}
createOpts.FirewallID = firewallID
} else {
// There's no firewallID already set, see if we need to create a new fw, look for the acl annotation.
_, ok := service.GetAnnotations()[annotations.AnnLinodeCloudFirewallACL]
if ok {
fwcreateOpts, err := services.CreateFirewallOptsForSvc(label, tags, service)
if err != nil {
return nil, err
}
fw, err := l.client.CreateFirewall(ctx, *fwcreateOpts)
if err != nil {
return nil, err
}
createOpts.FirewallID = fw.ID
}
// no need to deal with firewalls, continue creating nb's