forked from stackitcloud/cloud-provider-stackit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloadbalancer_test.go
More file actions
730 lines (658 loc) · 29.4 KB
/
loadbalancer_test.go
File metadata and controls
730 lines (658 loc) · 29.4 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
package ccm
import (
"context"
"errors"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
stackitconfig "github.com/stackitcloud/cloud-provider-stackit/pkg/stackit/config"
"github.com/stackitcloud/stackit-sdk-go/services/loadbalancer"
"go.uber.org/mock/gomock"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/cloud-provider/api"
"github.com/stackitcloud/cloud-provider-stackit/pkg/stackit"
)
var notYetReadyError = api.NewRetryError("waiting for load balancer to become ready. This error is normal while the load balancer starts.", 10*time.Second).Error()
const (
sampleLBName = "k8s-svc-89ec9a0e-6b00-4e2f-b57b-02e89193093d-echo"
sampleCredentialsRef = "credentials-12345"
)
var _ = Describe("LoadBalancer", func() {
var (
mockClient *stackit.MockLoadbalancerClient
lbInModeIgnoreAndObs *LoadBalancer
loadBalancer *LoadBalancer
clusterName string
projectID string
lbOpts stackitconfig.LoadBalancerOpts
)
BeforeEach(func() {
clusterName = "my-cluster"
projectID = "my-project"
lbOpts = stackitconfig.LoadBalancerOpts{NetworkID: "my-network"}
ctrl := gomock.NewController(GinkgoT())
mockClient = stackit.NewMockLoadbalancerClient(ctrl)
var err error
lbInModeIgnoreAndObs, err = NewLoadBalancer(mockClient, projectID, lbOpts, &MetricsRemoteWrite{
endpoint: "test-endpoint",
username: "test-username",
password: "test-password",
})
Expect(err).NotTo(HaveOccurred())
loadBalancer, err = NewLoadBalancer(mockClient, projectID, lbOpts, nil)
Expect(err).NotTo(HaveOccurred())
})
Describe("GetLoadBalancerName", func() {
It("should generate the name based on the UID and name", func() {
name := loadBalancer.GetLoadBalancerName(context.Background(), clusterName, &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
UID: "00000000-0000-0000-0000-000000000000",
Name: "my-load-balancer",
},
})
Expect(name).To(Equal("k8s-svc-00000000-0000-0000-0000-000000000000-my-load-balancer"))
})
It("should truncate names that are too long", func() {
name := loadBalancer.GetLoadBalancerName(context.Background(), clusterName, &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
UID: "00000000-0000-0000-0000-000000000000",
Name: "lb-tooooo-long-name",
},
})
Expect(name).To(HaveLen(63))
Expect(name).To(Equal("k8s-svc-00000000-0000-0000-0000-000000000000-lb-tooooo-long-nam"))
})
It("should not truncate names that are exactly 63 chars long", func() {
name := loadBalancer.GetLoadBalancerName(context.Background(), clusterName, &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
UID: "00000000-0000-0000-0000-000000000000",
Name: "name-exactly-right",
},
})
Expect(name).To(HaveLen(63))
Expect(name).To(Equal("k8s-svc-00000000-0000-0000-0000-000000000000-name-exactly-right"))
})
It("should produce DNS-compatible names by removing trailing dashes", func() {
name := loadBalancer.GetLoadBalancerName(context.Background(), clusterName, &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
UID: "00000000-0000-0000-0000-000000000000",
Name: "ske-meets-stackit-lb",
},
})
Expect(name).To(HaveLen(62))
Expect(name).To(Equal("k8s-svc-00000000-0000-0000-0000-000000000000-ske-meets-stackit"))
})
})
Describe("GetLoadBalancer", func() {
It("should report LB does not exist", func() {
mockClient.EXPECT().GetLoadBalancer(gomock.Any(), projectID, gomock.Any()).Return(nil, stackit.ErrorNotFound)
svc := minimalLoadBalancerService()
_, exists, err := loadBalancer.GetLoadBalancer(context.Background(), clusterName, svc)
Expect(err).NotTo(HaveOccurred())
Expect(exists).To(BeFalse())
})
convertToLB := func(spec *loadbalancer.CreateLoadBalancerPayload) *loadbalancer.LoadBalancer {
return &loadbalancer.LoadBalancer{
Errors: &[]loadbalancer.LoadBalancerError{},
ExternalAddress: spec.ExternalAddress,
Listeners: spec.Listeners,
Name: spec.Name,
Networks: spec.Networks,
Options: spec.Options,
Status: new(loadbalancer.LOADBALANCERSTATUS_READY),
TargetPools: spec.TargetPools,
Version: new("current-version"),
}
}
DescribeTable("should report status for external LB",
func(hasExternalAddress bool) {
svc := minimalLoadBalancerService()
spec, _, err := lbSpecFromService(svc, []*corev1.Node{}, lbOpts, nil)
Expect(err).NotTo(HaveOccurred())
myLb := convertToLB(spec)
if !hasExternalAddress {
// LB has no external address yet
myLb.ExternalAddress = nil
}
mockClient.EXPECT().GetLoadBalancer(gomock.Any(), projectID, gomock.Any()).Return(myLb, nil)
status, found, err := loadBalancer.GetLoadBalancer(context.Background(), clusterName, svc)
Expect(err).NotTo(HaveOccurred())
Expect(found).To(BeTrue())
if hasExternalAddress {
Expect(status.Ingress).To(Equal([]corev1.LoadBalancerIngress{
{IP: *spec.ExternalAddress},
}))
} else {
Expect(status.Ingress).To(BeNil())
}
},
Entry("when externalAddress is set", true),
Entry("when externalAddress is not set", false),
)
DescribeTable("should report status for internal LB",
func(hasPrivateAddress bool) {
svc := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
UID: "00000000-0000-0000-0000-000000000000",
Annotations: map[string]string{
"lb.stackit.cloud/internal-lb": "true",
},
},
Spec: corev1.ServiceSpec{
Type: corev1.ServiceTypeLoadBalancer,
},
}
spec, _, err := lbSpecFromService(svc, []*corev1.Node{}, lbOpts, nil)
Expect(err).NotTo(HaveOccurred())
myLb := convertToLB(spec)
Expect(myLb.ExternalAddress).To(BeNil())
if hasPrivateAddress {
myLb.PrivateAddress = new("10.20.30.40")
}
mockClient.EXPECT().GetLoadBalancer(gomock.Any(), projectID, gomock.Any()).Return(myLb, nil)
status, found, err := loadBalancer.GetLoadBalancer(context.Background(), clusterName, svc)
Expect(err).NotTo(HaveOccurred())
Expect(found).To(BeTrue())
if hasPrivateAddress {
Expect(status.Ingress).To(Equal([]corev1.LoadBalancerIngress{
{IP: *myLb.PrivateAddress},
}))
} else {
Expect(status.Ingress).To(BeNil())
}
},
Entry("when PrivateAddress is set", true),
Entry("when PrivateAddress is not set", false),
)
})
Describe("EnsureLoadBalancer", func() {
It("ensure load balancer should trigger load balancer creation if LB doesn't exist", func() {
mockClient.EXPECT().GetLoadBalancer(gomock.Any(), projectID, gomock.Any()).Return(nil, stackit.ErrorNotFound)
mockClient.EXPECT().CreateLoadBalancer(gomock.Any(), projectID, gomock.Any()).MinTimes(1).Return(&loadbalancer.LoadBalancer{}, nil)
_, err := loadBalancer.EnsureLoadBalancer(context.Background(), clusterName, minimalLoadBalancerService(), []*corev1.Node{})
Expect(err).To(MatchError(notYetReadyError))
// Expected CreateLoadBalancer to have been called.
})
It("should create a load balancer with observability configured", func() {
mockClient.EXPECT().GetLoadBalancer(gomock.Any(), projectID, gomock.Any()).Return(nil, stackit.ErrorNotFound)
mockClient.EXPECT().ListCredentials(gomock.Any(), projectID).Return(&loadbalancer.ListCredentialsResponse{
Credentials: &[]loadbalancer.CredentialsResponse{},
}, nil)
// TODO: match payload
mockClient.EXPECT().CreateCredentials(gomock.Any(), projectID, gomock.Any()).MinTimes(1).
DoAndReturn(func(_ context.Context, _ string, payload loadbalancer.CreateCredentialsPayload) (*loadbalancer.CreateCredentialsResponse, error) {
return &loadbalancer.CreateCredentialsResponse{
Credential: &loadbalancer.CredentialsResponse{
CredentialsRef: new("my-credential-ref"),
DisplayName: new(*payload.DisplayName),
Username: new(*payload.Username),
},
}, nil
})
mockClient.EXPECT().CreateLoadBalancer(gomock.Any(), projectID, gomock.Any()).MinTimes(1).Return(&loadbalancer.LoadBalancer{}, nil)
_, err := lbInModeIgnoreAndObs.EnsureLoadBalancer(context.Background(), clusterName, minimalLoadBalancerService(), []*corev1.Node{})
Expect(err).To(MatchError(notYetReadyError))
// Expected CreateCredentials to have been called.
// Expected CreateLoadBalancer to have been called.
})
It("should update observability credential if credentials are specified in load balancer", func() {
svc := minimalLoadBalancerService()
spec, _, err := lbSpecFromService(svc, []*corev1.Node{}, lbOpts, &loadbalancer.LoadbalancerOptionObservability{
Metrics: &loadbalancer.LoadbalancerOptionMetrics{
CredentialsRef: new(sampleCredentialsRef),
PushUrl: &lbInModeIgnoreAndObs.metricsRemoteWrite.endpoint,
},
})
Expect(err).NotTo(HaveOccurred())
myLb := &loadbalancer.LoadBalancer{
Errors: &[]loadbalancer.LoadBalancerError{},
ExternalAddress: spec.ExternalAddress,
Listeners: spec.Listeners,
Name: spec.Name,
Networks: spec.Networks,
Options: spec.Options,
PrivateAddress: spec.PrivateAddress,
Status: new(loadbalancer.LOADBALANCERSTATUS_READY),
TargetPools: spec.TargetPools,
Version: new("current-version"),
PlanId: new("p10"),
}
mockClient.EXPECT().GetLoadBalancer(gomock.Any(), projectID, gomock.Any()).Return(myLb, nil)
mockClient.EXPECT().UpdateCredentials(gomock.Any(), projectID, sampleCredentialsRef, gomock.Any()).MinTimes(1).Return(nil)
_, err = lbInModeIgnoreAndObs.EnsureLoadBalancer(context.Background(), clusterName, svc, []*corev1.Node{})
Expect(err).NotTo(HaveOccurred())
// Expected UpdateCredentials to have been called.
})
It("should update the load balancer if the service changed", func() {
svc := minimalLoadBalancerService()
spec, _, err := lbSpecFromService(svc, []*corev1.Node{}, lbOpts, nil)
Expect(err).NotTo(HaveOccurred())
myLb := &loadbalancer.LoadBalancer{
Errors: &[]loadbalancer.LoadBalancerError{},
ExternalAddress: spec.ExternalAddress,
Listeners: spec.Listeners,
Name: spec.Name,
Networks: spec.Networks,
Options: spec.Options,
PrivateAddress: spec.PrivateAddress,
Status: new(loadbalancer.LOADBALANCERSTATUS_READY),
TargetPools: spec.TargetPools,
Version: new("current-version"),
}
mockClient.EXPECT().GetLoadBalancer(gomock.Any(), projectID, gomock.Any()).Return(myLb, nil)
// For simplicity, we return the original load balancer. In reality, the updated load balancer should be returned.
mockClient.EXPECT().UpdateLoadBalancer(
gomock.Any(),
projectID,
loadBalancer.GetLoadBalancerName(context.Background(), clusterName, svc),
versionMatcher("current-version"),
).MinTimes(1).Return(myLb, nil)
svc = svc.DeepCopy()
svc.Spec.Ports = append(svc.Spec.Ports, corev1.ServicePort{
Name: "a-port",
Protocol: corev1.ProtocolTCP,
Port: 80,
NodePort: 1234,
})
_, err = loadBalancer.EnsureLoadBalancer(context.Background(), clusterName, svc, []*corev1.Node{})
Expect(err).NotTo(HaveOccurred())
// Expect UpdateLoadBalancer to have been called.
})
// This only happens when nodes have changed while the controller wasn't running.
// If the controller is watching, then UpdateLoadBalancer is called instead.
It("should update the load balancer if the nodes change", func() {
nodeA := &corev1.Node{
ObjectMeta: metav1.ObjectMeta{Name: "nodeA"},
// Nodes need an internal address, otherwise they will be ignored.
Status: corev1.NodeStatus{Addresses: []corev1.NodeAddress{{Type: corev1.NodeInternalIP, Address: "10.0.0.1"}}},
}
nodeB := &corev1.Node{
ObjectMeta: metav1.ObjectMeta{Name: "nodeB"},
Status: corev1.NodeStatus{Addresses: []corev1.NodeAddress{{Type: corev1.NodeInternalIP, Address: "10.0.0.1"}}},
}
svc := minimalLoadBalancerService()
// We need at least one port for nodes to have an effect.
svc.Spec.Ports = append(svc.Spec.Ports, corev1.ServicePort{
Name: "a-port",
Protocol: corev1.ProtocolTCP,
Port: 80,
NodePort: 1234,
})
spec, _, err := lbSpecFromService(svc, []*corev1.Node{nodeA}, lbOpts, nil)
Expect(err).NotTo(HaveOccurred())
myLb := &loadbalancer.LoadBalancer{
Errors: &[]loadbalancer.LoadBalancerError{},
ExternalAddress: spec.ExternalAddress,
Listeners: spec.Listeners,
Name: spec.Name,
Networks: spec.Networks,
Options: spec.Options,
PrivateAddress: spec.PrivateAddress,
Status: new(loadbalancer.LOADBALANCERSTATUS_READY),
TargetPools: spec.TargetPools,
Version: new("current-version"),
}
mockClient.EXPECT().GetLoadBalancer(gomock.Any(), projectID, gomock.Any()).Return(myLb, nil)
// For simplicity, we return the original load balancer. In reality, the updated load balancer should be returned.
mockClient.EXPECT().UpdateLoadBalancer(
gomock.Any(),
projectID,
loadBalancer.GetLoadBalancerName(context.Background(), clusterName, svc),
versionMatcher("current-version"),
).MinTimes(1).Return(myLb, nil)
_, err = loadBalancer.EnsureLoadBalancer(context.Background(), clusterName, svc, []*corev1.Node{nodeA, nodeB})
Expect(err).NotTo(HaveOccurred())
// Expect UpdateLoadBalancer to have been called.
})
It("should delete observability credentials and delete reference from load balancer if controller is not configured (monitoring extension disabled)", func() {
svc := minimalLoadBalancerService()
spec, _, err := lbSpecFromService(svc, []*corev1.Node{}, lbOpts, &loadbalancer.LoadbalancerOptionObservability{
Metrics: &loadbalancer.LoadbalancerOptionMetrics{
CredentialsRef: new(sampleCredentialsRef),
PushUrl: new("test-endpoint"),
},
})
Expect(err).NotTo(HaveOccurred())
myLb := &loadbalancer.LoadBalancer{
Errors: &[]loadbalancer.LoadBalancerError{},
ExternalAddress: spec.ExternalAddress,
Listeners: spec.Listeners,
Name: spec.Name,
Networks: spec.Networks,
Options: spec.Options,
PrivateAddress: spec.PrivateAddress,
Status: new(loadbalancer.LOADBALANCERSTATUS_READY),
TargetPools: spec.TargetPools,
Version: new("current-version"),
}
mockClient.EXPECT().GetLoadBalancer(gomock.Any(), projectID, gomock.Any()).Return(myLb, nil)
// Check order to ensure that the reference is removed before the credentials are removed.
// The API rejects deletions of used credentials.
gomock.InOrder(
// For simplicity, we return the original load balancer. In reality, the updated load balancer should be returned.
mockClient.EXPECT().UpdateLoadBalancer(
gomock.Any(),
projectID,
loadBalancer.GetLoadBalancerName(context.Background(), clusterName, svc),
gomock.All(
versionMatcher("current-version"),
hasNoObservabilityConfigured(),
),
).MinTimes(1).Return(myLb, nil),
mockClient.EXPECT().DeleteCredentials(gomock.Any(), projectID, gomock.Any()).MinTimes(1).Return(nil),
)
_, err = loadBalancer.EnsureLoadBalancer(context.Background(), clusterName, svc, []*corev1.Node{})
Expect(err).NotTo(HaveOccurred())
// Expect UpdateLoadBalancer to have been called.
// Expect DeleteCredentials to have been called.
})
})
Describe("EnsureLoadBalancerDeleted", func() {
It("should trigger load balancer deletion", func() {
mockClient.EXPECT().GetLoadBalancer(gomock.Any(), projectID, gomock.Any()).Return(&loadbalancer.LoadBalancer{}, nil)
mockClient.EXPECT().ListCredentials(gomock.Any(), projectID).Return(&loadbalancer.ListCredentialsResponse{
Credentials: &[]loadbalancer.CredentialsResponse{},
}, nil)
mockClient.EXPECT().DeleteLoadBalancer(gomock.Any(), projectID, gomock.Any()).MinTimes(1).Return(nil)
err := loadBalancer.EnsureLoadBalancerDeleted(context.Background(), clusterName, minimalLoadBalancerService())
Expect(err).NotTo(HaveOccurred())
// Expect DeleteLoadBalancer to have been called.
})
It("should finalize deletion if LB API returns not found", func() {
mockClient.EXPECT().GetLoadBalancer(gomock.Any(), projectID, gomock.Any()).Return(nil, stackit.ErrorNotFound)
err := loadBalancer.EnsureLoadBalancerDeleted(context.Background(), clusterName, minimalLoadBalancerService())
Expect(err).NotTo(HaveOccurred())
// Expect DeleteLoadBalancer not to have been called.
})
It("should finalize deletion if load balancer is state terminating", func() {
mockClient.EXPECT().GetLoadBalancer(gomock.Any(), projectID, gomock.Any()).Return(&loadbalancer.LoadBalancer{
Status: new(loadbalancer.LOADBALANCERSTATUS_TERMINATING),
}, nil)
err := loadBalancer.EnsureLoadBalancerDeleted(context.Background(), clusterName, minimalLoadBalancerService())
Expect(err).NotTo(HaveOccurred())
// Expect DeleteLoadBalancer not to have been called.
})
It("should report no error if LB not found", func() {
mockClient.EXPECT().GetLoadBalancer(gomock.Any(), projectID, gomock.Any()).Return(nil, stackit.ErrorNotFound)
svc := minimalLoadBalancerService()
err := loadBalancer.EnsureLoadBalancerDeleted(context.Background(), clusterName, svc)
Expect(err).NotTo(HaveOccurred())
})
It("should trigger load balancer deletion", func() {
mockClient.EXPECT().GetLoadBalancer(gomock.Any(), projectID, gomock.Any()).Return(&loadbalancer.LoadBalancer{}, nil)
mockClient.EXPECT().ListCredentials(gomock.Any(), projectID).Return(&loadbalancer.ListCredentialsResponse{
Credentials: &[]loadbalancer.CredentialsResponse{},
}, nil)
mockClient.EXPECT().DeleteLoadBalancer(gomock.Any(), projectID, gomock.Any()).MinTimes(1).Return(nil)
svc := minimalLoadBalancerService()
err := loadBalancer.EnsureLoadBalancerDeleted(context.Background(), clusterName, svc)
Expect(err).NotTo(HaveOccurred())
// Expect DeleteLoadBalancer to have been called.
})
It("should delete observability credentials of load balancer with static IP", func() {
svc := minimalLoadBalancerService()
name := loadBalancer.GetLoadBalancerName(context.Background(), "", svc)
mockClient.EXPECT().GetLoadBalancer(gomock.Any(), projectID, gomock.Any()).Return(&loadbalancer.LoadBalancer{
Options: &loadbalancer.LoadBalancerOptions{
Observability: &loadbalancer.LoadbalancerOptionObservability{
Metrics: &loadbalancer.LoadbalancerOptionMetrics{
CredentialsRef: new(sampleCredentialsRef),
PushUrl: new("http://localhost"),
},
},
EphemeralAddress: new(false),
},
ExternalAddress: new("8.8.4.4"),
Listeners: &[]loadbalancer.Listener{},
}, nil)
gomock.InOrder(
mockClient.EXPECT().UpdateLoadBalancer(gomock.Any(), projectID, name, gomock.All(
hasNoObservabilityConfigured(), externalAddressSet("8.8.4.4"),
)).MinTimes(1).Return(&loadbalancer.LoadBalancer{}, nil),
mockClient.EXPECT().DeleteCredentials(gomock.Any(), projectID, sampleCredentialsRef).MinTimes(1).Return(nil),
mockClient.EXPECT().ListCredentials(gomock.Any(), projectID).Return(&loadbalancer.ListCredentialsResponse{
Credentials: &[]loadbalancer.CredentialsResponse{},
}, nil),
mockClient.EXPECT().DeleteLoadBalancer(gomock.Any(), projectID, name).MinTimes(1).Return(nil),
)
err := loadBalancer.EnsureLoadBalancerDeleted(context.Background(), clusterName, svc)
Expect(err).NotTo(HaveOccurred())
})
It("should delete observability credentials of load balancer with ephemeral IP", func() {
svc := minimalLoadBalancerService()
// Ensure load balancer is ephemeral.
delete(svc.Annotations, externalIPAnnotation)
name := loadBalancer.GetLoadBalancerName(context.Background(), "", svc)
mockClient.EXPECT().GetLoadBalancer(gomock.Any(), projectID, gomock.Any()).Return(&loadbalancer.LoadBalancer{
Options: &loadbalancer.LoadBalancerOptions{
Observability: &loadbalancer.LoadbalancerOptionObservability{
Metrics: &loadbalancer.LoadbalancerOptionMetrics{
CredentialsRef: new(sampleCredentialsRef),
PushUrl: new("http://localhost"),
},
},
EphemeralAddress: new(true),
},
ExternalAddress: new("0.0.0.0 (ephemeral)"),
Listeners: &[]loadbalancer.Listener{},
}, nil)
gomock.InOrder(
mockClient.EXPECT().UpdateLoadBalancer(gomock.Any(), projectID, name, gomock.All(
hasNoObservabilityConfigured(), externalAddressNotSet(), ephemeralAddress(),
)).MinTimes(1).Return(&loadbalancer.LoadBalancer{}, nil),
mockClient.EXPECT().DeleteCredentials(gomock.Any(), projectID, sampleCredentialsRef).MinTimes(1).Return(nil),
mockClient.EXPECT().ListCredentials(gomock.Any(), projectID).Return(&loadbalancer.ListCredentialsResponse{
Credentials: &[]loadbalancer.CredentialsResponse{},
}, nil),
mockClient.EXPECT().DeleteLoadBalancer(gomock.Any(), projectID, name).MinTimes(1).Return(nil),
)
err := loadBalancer.EnsureLoadBalancerDeleted(context.Background(), clusterName, svc)
Expect(err).NotTo(HaveOccurred())
})
})
Describe("UpdateLoadBalancer", func() {
It("should update targets", func() {
mockClient.EXPECT().UpdateTargetPool(gomock.Any(), projectID, gomock.Any(), "my-port", gomock.Any()).MinTimes(1)
svc := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
"lb.stackit.cloud/external-address": "123.124.88.99",
},
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
{
Name: "my-port",
Protocol: corev1.ProtocolTCP,
Port: 80,
NodePort: 8080,
},
},
},
}
err := loadBalancer.UpdateLoadBalancer(context.Background(), clusterName, svc, []*corev1.Node{})
Expect(err).NotTo(HaveOccurred())
// Expect UpdateTargetPool to have been called.
})
})
Describe("reconcileObservabilityCredentials", func() {
It("should do nothing if no credentials are in the environment", func() {
credentialRef, err := loadBalancer.reconcileObservabilityCredentials(context.Background(), nil, "my-loadbalancer")
Expect(err).NotTo(HaveOccurred())
Expect(credentialRef).To(BeNil())
})
It("should update credentials if they exist", func() {
pushURL := "test-endpoint"
mockClient.EXPECT().UpdateCredentials(gomock.Any(), projectID, sampleCredentialsRef, gomock.Any()).MinTimes(1).Return(nil)
credentialRef, err := lbInModeIgnoreAndObs.reconcileObservabilityCredentials(context.Background(), &loadbalancer.LoadBalancer{
Name: new(sampleLBName),
Options: &loadbalancer.LoadBalancerOptions{
Observability: &loadbalancer.LoadbalancerOptionObservability{
Metrics: &loadbalancer.LoadbalancerOptionMetrics{
CredentialsRef: new(sampleCredentialsRef),
},
},
},
}, sampleLBName)
Expect(err).NotTo(HaveOccurred())
Expect(*credentialRef).To(Equal(loadbalancer.LoadbalancerOptionObservability{
Metrics: &loadbalancer.LoadbalancerOptionMetrics{
CredentialsRef: new(sampleCredentialsRef),
PushUrl: &pushURL,
},
}))
})
It("should try to update credentials if they exist", func() {
errTest := errors.New("update credentials test error")
mockClient.EXPECT().UpdateCredentials(gomock.Any(), projectID, sampleCredentialsRef, gomock.Any()).MinTimes(1).Return(errTest)
credentialRef, err := lbInModeIgnoreAndObs.reconcileObservabilityCredentials(context.Background(), &loadbalancer.LoadBalancer{
Name: new(sampleLBName),
Options: &loadbalancer.LoadBalancerOptions{
Observability: &loadbalancer.LoadbalancerOptionObservability{
Metrics: &loadbalancer.LoadbalancerOptionMetrics{
CredentialsRef: new(sampleCredentialsRef),
},
},
},
}, sampleLBName)
Expect(err).To(MatchError(errTest))
Expect(credentialRef).To(BeNil())
})
It("should create credentials if they do not exist", func() {
mockClient.EXPECT().ListCredentials(gomock.Any(), projectID).Return(&loadbalancer.ListCredentialsResponse{
Credentials: &[]loadbalancer.CredentialsResponse{},
}, nil)
mockClient.EXPECT().CreateCredentials(gomock.Any(), projectID, gomock.Any()).MinTimes(1).Return(&loadbalancer.CreateCredentialsResponse{
Credential: &loadbalancer.CredentialsResponse{
CredentialsRef: new(sampleCredentialsRef),
DisplayName: new(sampleLBName),
Username: new("test-username"),
},
}, nil)
credentialRef, err := lbInModeIgnoreAndObs.reconcileObservabilityCredentials(context.Background(), &loadbalancer.LoadBalancer{
Name: new(sampleLBName),
}, sampleLBName)
Expect(err).NotTo(HaveOccurred())
Expect(*credentialRef).To(Equal(loadbalancer.LoadbalancerOptionObservability{
Metrics: &loadbalancer.LoadbalancerOptionMetrics{
CredentialsRef: new(sampleCredentialsRef),
PushUrl: new("test-endpoint"),
},
}))
})
It("should return error if creating new credentials fails", func() {
mockClient.EXPECT().ListCredentials(gomock.Any(), projectID).Return(&loadbalancer.ListCredentialsResponse{
Credentials: &[]loadbalancer.CredentialsResponse{},
}, nil)
errTest := errors.New("delete credentials test error")
mockClient.EXPECT().CreateCredentials(gomock.Any(), projectID, gomock.Any()).MinTimes(1).Return(nil, errTest)
credentialRef, err := lbInModeIgnoreAndObs.reconcileObservabilityCredentials(context.Background(), &loadbalancer.LoadBalancer{
Name: new(sampleLBName),
}, sampleLBName)
Expect(err).To(MatchError(errTest))
Expect(credentialRef).To(BeNil())
})
})
Describe("cleanUpCredentials", func() {
It("should delete matching and only matching observability credentials", func() {
gomock.InOrder(
mockClient.EXPECT().ListCredentials(gomock.Any(), projectID).Return(&loadbalancer.ListCredentialsResponse{
Credentials: &[]loadbalancer.CredentialsResponse{
{
CredentialsRef: new("matching-1"),
DisplayName: new("my-loadbalancer"),
Username: new("luke"),
},
{
CredentialsRef: new("display-name-not-match"),
DisplayName: new("other-loadbalancer"),
Username: new("leia"),
},
{
CredentialsRef: new("matching-2"),
DisplayName: new("my-loadbalancer"),
Username: new("chewie"),
},
{
CredentialsRef: new("no-display-name"),
DisplayName: nil,
Username: new("han"),
},
},
}, nil).MinTimes(1),
mockClient.EXPECT().DeleteCredentials(gomock.Any(), projectID, "matching-1").MinTimes(1),
mockClient.EXPECT().DeleteCredentials(gomock.Any(), projectID, "matching-2").MinTimes(1),
)
Expect(lbInModeIgnoreAndObs.cleanUpCredentials(context.Background(), "my-loadbalancer")).To(Succeed())
})
})
})
var _ = DescribeTable("loadBalancerStatus",
func(lb *loadbalancer.LoadBalancer, svc *corev1.Service, expect *corev1.LoadBalancerStatus) {
Expect(loadBalancerStatus(lb, svc)).To(Equal(expect))
},
Entry("empty address", &loadbalancer.LoadBalancer{}, &corev1.Service{}, &corev1.LoadBalancerStatus{}),
Entry("address present",
&loadbalancer.LoadBalancer{ExternalAddress: new("1.2.3.4")}, &corev1.Service{},
&corev1.LoadBalancerStatus{Ingress: []corev1.LoadBalancerIngress{{IP: "1.2.3.4"}}},
),
Entry("IP mode proxy",
&loadbalancer.LoadBalancer{ExternalAddress: new("1.2.3.4")},
&corev1.Service{ObjectMeta: metav1.ObjectMeta{Annotations: map[string]string{ipModeProxyAnnotation: "true"}}},
&corev1.LoadBalancerStatus{Ingress: []corev1.LoadBalancerIngress{{IP: "1.2.3.4", IPMode: new(corev1.LoadBalancerIPModeProxy)}}},
),
)
// minimalLoadBalancerService returns a service that is valid for provisioning a load balancer by the CCM.
// It should be used in tests that don't expect a particular configuration.
func minimalLoadBalancerService() *corev1.Service {
return &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
UID: "00000000-0000-0000-0000-000000000000",
Annotations: map[string]string{
"lb.stackit.cloud/external-address": "123.124.88.99",
},
},
Spec: corev1.ServiceSpec{
Type: corev1.ServiceTypeLoadBalancer,
},
}
}
// versionMatcher ensures that the given UpdateLoadBalancerPayload has version specified.
func versionMatcher(version string) gomock.Matcher {
return gomock.Cond(func(x any) bool {
lb := x.(*loadbalancer.UpdateLoadBalancerPayload)
if lb.Version == nil {
return false
}
return *lb.Version == version
})
}
// hasNoObservabilityConfigured ensures that the given UpdateLoadBalancerPayload has no observability specified.
func hasNoObservabilityConfigured() gomock.Matcher {
return gomock.Cond(func(x any) bool {
lb := x.(*loadbalancer.UpdateLoadBalancerPayload)
return lb.Options == nil || lb.Options.Observability == nil
})
}
// externalAddressSet ensures that the given UpdateLoadBalancerPayload has external address set to address.
func externalAddressSet(address string) gomock.Matcher {
return gomock.Cond(func(x any) bool {
lb := x.(*loadbalancer.UpdateLoadBalancerPayload)
return lb.ExternalAddress != nil && *lb.ExternalAddress == address
})
}
// externalAddressNotSet ensures that the given UpdateLoadBalancerPayload has no external address set.
func externalAddressNotSet() gomock.Matcher {
return gomock.Cond(func(x any) bool {
lb := x.(*loadbalancer.UpdateLoadBalancerPayload)
return lb.ExternalAddress == nil
})
}
// ephemeralAddress ensures that the given UpdateLoadBalancerPayload has an ephemeral address enabled.
func ephemeralAddress() gomock.Matcher {
return gomock.Cond(func(x any) bool {
lb := x.(*loadbalancer.UpdateLoadBalancerPayload)
return lb.Options != nil && lb.Options.EphemeralAddress != nil && *lb.Options.EphemeralAddress
})
}