-
Notifications
You must be signed in to change notification settings - Fork 84
/
worker.go
712 lines (619 loc) · 21.8 KB
/
worker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
package main
import (
"context"
"math"
"reflect"
"sort"
"time"
"fmt"
"runtime/debug"
"strings"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/cloudformation"
log "github.com/sirupsen/logrus"
"github.com/zalando-incubator/kube-ingress-aws-controller/aws"
"github.com/zalando-incubator/kube-ingress-aws-controller/certs"
"github.com/zalando-incubator/kube-ingress-aws-controller/kubernetes"
"github.com/zalando-incubator/kube-ingress-aws-controller/problem"
)
type loadBalancer struct {
ingresses map[string][]*kubernetes.Ingress
scheme string
stack *aws.Stack
existingStackCertificateARNs map[string]time.Time
shared bool
http2 bool
clusterLocal bool
securityGroup string
sslPolicy string
ipAddressType string
wafWebACLID string
certTTL time.Duration
cwAlarms aws.CloudWatchAlarmList
loadBalancerType string
}
const (
ready int = iota
update
missing
delete
)
const (
cniEventRateLimit = 5 * time.Second
)
func (l *loadBalancer) Status() int {
if l.clusterLocal {
return ready
}
if l.stack.ShouldDelete() {
return delete
}
if len(l.ingresses) != 0 && l.stack == nil {
return missing
}
if firstRun || !l.inSync() && l.stack.IsComplete() {
return update
}
return ready
}
// inSync checks if the loadBalancer is in sync with the backing CF stack. It's
// considered in sync when certs found for the ingresses match those already
// defined on the stack and the cloudwatch alarm config is up-to-date.
func (l *loadBalancer) inSync() bool {
return reflect.DeepEqual(l.CertificateARNs(), l.stack.CertificateARNs) &&
l.stack.CWAlarmConfigHash == l.cwAlarms.Hash() &&
l.wafWebACLID == l.stack.WAFWebACLID
}
// addIngress adds an ingress object to the load balancer.
// The function returns true when the ingress was successfully added. The
// adding can fail in case the load balancer reached its limit of ingress
// certificates or if the scheme doesn't match.
func (l *loadBalancer) addIngress(certificateARNs []string, ingress *kubernetes.Ingress, maxCerts int) bool {
if ingress.ClusterLocal {
if ingresses, ok := l.ingresses[kubernetes.DefaultClusterLocalDomain]; ok {
l.ingresses[kubernetes.DefaultClusterLocalDomain] = append(ingresses, ingress)
} else {
l.ingresses[kubernetes.DefaultClusterLocalDomain] = []*kubernetes.Ingress{ingress}
}
return true
}
resourceName := fmt.Sprintf("%s/%s", ingress.Namespace, ingress.Name)
owner := ""
if l.stack != nil {
owner = l.stack.OwnerIngress
}
if owner != "" && resourceName != owner {
return false
}
if !ingress.Shared && resourceName != owner {
return false
}
// settings that would require a new load balancer no matter if it's
// shared or not.
if l.ipAddressType != ingress.IPAddressType ||
l.scheme != ingress.Scheme ||
l.loadBalancerType != ingress.LoadBalancerType ||
l.http2 != ingress.HTTP2 {
return false
}
// settings that can be changed on an existing load balancer if it's
// NOT shared.
if ingress.Shared && (l.securityGroup != ingress.SecurityGroup ||
l.sslPolicy != ingress.SSLPolicy ||
l.wafWebACLID != ingress.WAFWebACLID) {
return false
}
// check if we can fit the ingress on the load balancer based on
// maxCerts
newCerts := 0
for _, certificateARN := range certificateARNs {
if _, ok := l.ingresses[certificateARN]; ok {
continue
}
newCerts++
}
// if adding this ingress would result in more than maxCerts, then we
// don't add the ingress
if len(l.ingresses)+newCerts > maxCerts {
return false
}
for _, certificateARN := range certificateARNs {
l.ingresses[certificateARN] = append(l.ingresses[certificateARN], ingress)
}
l.shared = ingress.Shared
return true
}
// CertificateARNs returns a map of certificates and their expiry times.
func (l *loadBalancer) CertificateARNs() map[string]time.Time {
certificates := make(map[string]time.Time, len(l.ingresses))
for arn, ingresses := range l.ingresses {
// only include certificates required by at least one ingress.
if len(ingresses) > 0 {
certificates[arn] = time.Time{}
}
}
for arn, ttl := range l.existingStackCertificateARNs {
if _, ok := certificates[arn]; !ok {
if ttl.IsZero() {
certificates[arn] = time.Now().UTC().Add(l.certTTL)
} else if ttl.After(time.Now().UTC()) {
certificates[arn] = ttl
}
}
}
return certificates
}
// Owner returns the ingress resource owning the load balancer. If there are no
// owners it will return an empty string meaning the load balancer is shared
// between multiple ingresses.
func (l *loadBalancer) Owner() string {
if l.shared {
return ""
}
for _, ingresses := range l.ingresses {
for _, ingress := range ingresses {
return fmt.Sprintf("%s/%s", ingress.Namespace, ingress.Name)
}
}
return ""
}
// CertificatesFinder interface represents a list of certificates
// and some basic operations than can be performed on them.
type CertificatesFinder interface {
CertificateSummaries() []*certs.CertificateSummary
CertificateExists(certificateARN string) bool
FindMatchingCertificateIDs([]string) []string
}
// Certificates represents a generic list of certificates
type Certificates struct {
certARNSet map[string]struct{}
certificateSummaries []*certs.CertificateSummary
}
func NewCertificates(certs []*certs.CertificateSummary) *Certificates {
certARNSet := make(map[string]struct{}, len(certs))
for _, cert := range certs {
certARNSet[cert.ID()] = struct{}{}
}
return &Certificates{
certARNSet: certARNSet,
certificateSummaries: certs,
}
}
// CertificateSummaries returns summaries of all certificates
func (c *Certificates) CertificateSummaries() []*certs.CertificateSummary {
return c.certificateSummaries
}
// CertificateExists checks if certificate with given ARN/ID is present in the collection
func (c *Certificates) CertificateExists(arn string) bool {
_, ok := c.certARNSet[arn]
return ok
}
// FindMatchingCertificateIDs get IDs of all certificates matching to given hostnames
func (c *Certificates) FindMatchingCertificateIDs(hostnames []string) []string {
certificateSummaries := certs.FindBestMatchingCertificates(c.certificateSummaries, hostnames)
certIDs := make([]string, 0, len(certificateSummaries))
for _, cert := range certificateSummaries {
certIDs = append(certIDs, cert.ID())
}
return certIDs
}
func startPolling(
ctx context.Context,
certsProvider certs.CertificatesProvider,
certsPerALB int,
certTTL time.Duration,
awsAdapter *aws.Adapter,
kubeAdapter *kubernetes.Adapter,
pollingInterval time.Duration,
globalWAFACL string,
) {
for {
if errs := doWork(certsProvider, certsPerALB, certTTL, awsAdapter, kubeAdapter, globalWAFACL).Errors(); len(errs) > 0 {
for _, err := range errs {
log.Error(err)
}
} else {
metrics.lastSyncTimestamp.SetToCurrentTime()
}
firstRun = false
log.Debugf("Start polling sleep %s", pollingInterval)
select {
case <-time.After(pollingInterval):
case <-ctx.Done():
return
}
}
}
func doWork(
certsProvider certs.CertificatesProvider,
certsPerALB int,
certTTL time.Duration,
awsAdapter *aws.Adapter,
kubeAdapter *kubernetes.Adapter,
globalWAFACL string,
) (problems *problem.List) {
problems = new(problem.List)
defer func() {
if r := recover(); r != nil {
debug.PrintStack()
problems.Add("panic caused by: %v", r)
}
}()
ingresses, err := kubeAdapter.ListResources()
if err != nil {
return problems.Add("failed to list ingress resources: %w", err)
}
stacks, err := awsAdapter.FindManagedStacks()
if err != nil {
return problems.Add("failed to list managed stacks: %w", err)
}
for _, stack := range stacks {
if err := stack.Err(); err != nil {
problems.Add("stack %s error: %w", stack.Name, err)
}
}
err = awsAdapter.UpdateAutoScalingGroupsAndInstances()
if err != nil {
return problems.Add("failed to get instances from EC2: %w", err)
}
certificateSummaries, err := certsProvider.GetCertificates()
if err != nil {
return problems.Add("failed to get certificates: %w", err)
}
cwAlarms, err := getCloudWatchAlarms(kubeAdapter, cwAlarmConfigMapLocation)
if err != nil {
return problems.Add("failed to retrieve cloudwatch alarm configuration: %w", err)
}
counts := countByIngressType(ingresses)
metrics.ingressesTotal.Set(float64(counts[kubernetes.TypeIngress]))
metrics.routegroupsTotal.Set(float64(counts[kubernetes.TypeRouteGroup]))
metrics.stacksTotal.Set(float64(len(stacks)))
metrics.ownedAutoscalingGroupsTotal.Set(float64(len(awsAdapter.OwnedAutoScalingGroups)))
metrics.targetedAutoscalingGroupsTotal.Set(float64(len(awsAdapter.TargetedAutoScalingGroups)))
metrics.instancesTotal.Set(float64(awsAdapter.CachedInstances()))
metrics.standaloneInstancesTotal.Set(float64(len(awsAdapter.SingleInstances())))
metrics.certificatesTotal.Set(float64(len(certificateSummaries)))
metrics.cloudWatchAlarmsTotal.Set(float64(len(cwAlarms)))
log.Debugf("Found %d ingress(es)", counts[kubernetes.TypeIngress])
log.Debugf("Found %d route group(s)", counts[kubernetes.TypeRouteGroup])
log.Debugf("Found %d stack(s)", len(stacks))
log.Debugf("Found %d owned auto scaling group(s)", len(awsAdapter.OwnedAutoScalingGroups))
log.Debugf("Found %d targeted auto scaling group(s)", len(awsAdapter.TargetedAutoScalingGroups))
log.Debugf("Found %d EC2 instance(s)", awsAdapter.CachedInstances())
log.Debugf("Found %d single instance(s)", len(awsAdapter.SingleInstances()))
log.Debugf("Found %d certificate(s)", len(certificateSummaries))
log.Debugf("Found %d cloudwatch alarm configuration(s)", len(cwAlarms))
awsAdapter.UpdateTargetGroupsAndAutoScalingGroups(stacks, problems)
certs := NewCertificates(certificateSummaries)
model := buildManagedModel(certs, certsPerALB, certTTL, ingresses, stacks, cwAlarms, globalWAFACL)
log.Debugf("Have %d model(s)", len(model))
for _, loadBalancer := range model {
switch loadBalancer.Status() {
case delete:
deleteStack(awsAdapter, loadBalancer, problems)
case missing:
createStack(awsAdapter, loadBalancer, problems)
updateIngress(kubeAdapter, loadBalancer, problems)
case ready:
updateIngress(kubeAdapter, loadBalancer, problems)
case update:
updateStack(awsAdapter, loadBalancer, problems)
updateIngress(kubeAdapter, loadBalancer, problems)
}
}
return
}
func countByIngressType(ingresses []*kubernetes.Ingress) map[kubernetes.IngressType]int {
counts := make(map[kubernetes.IngressType]int)
for _, ing := range ingresses {
counts[ing.ResourceType]++
}
return counts
}
func sortStacks(stacks []*aws.Stack) {
sort.Slice(stacks, func(i, j int) bool {
if len(stacks[i].CertificateARNs) == len(stacks[j].CertificateARNs) {
return stacks[i].Name < stacks[j].Name
}
return len(stacks[i].CertificateARNs) > len(stacks[j].CertificateARNs)
})
}
func getAllLoadBalancers(certs CertificatesFinder, certTTL time.Duration, stacks []*aws.Stack) []*loadBalancer {
loadBalancers := make([]*loadBalancer, 0, len(stacks))
for _, stack := range stacks {
lb := &loadBalancer{
stack: stack,
existingStackCertificateARNs: make(map[string]time.Time, len(stack.CertificateARNs)),
ingresses: make(map[string][]*kubernetes.Ingress),
scheme: stack.Scheme,
shared: stack.OwnerIngress == "",
securityGroup: stack.SecurityGroup,
sslPolicy: stack.SSLPolicy,
ipAddressType: stack.IpAddressType,
loadBalancerType: stack.LoadBalancerType,
http2: stack.HTTP2,
wafWebACLID: stack.WAFWebACLID,
certTTL: certTTL,
}
// initialize ingresses map with existing certificates from the stack.
// Also filter the stack certificates so we have a set of
// certificates which are still availale, compared to what was
// latest stored on the stack.
for cert, expiry := range stack.CertificateARNs {
if certs.CertificateExists(cert) {
lb.existingStackCertificateARNs[cert] = expiry
lb.ingresses[cert] = make([]*kubernetes.Ingress, 0)
}
}
loadBalancers = append(loadBalancers, lb)
}
return loadBalancers
}
func matchIngressesToLoadBalancers(
loadBalancers []*loadBalancer,
certs CertificatesFinder,
certsPerALB int,
ingresses []*kubernetes.Ingress,
) []*loadBalancer {
clusterLocalLB := &loadBalancer{
clusterLocal: true,
ingresses: make(map[string][]*kubernetes.Ingress),
}
loadBalancers = append(loadBalancers, clusterLocalLB)
for _, ingress := range ingresses {
if ingress.ClusterLocal {
clusterLocalLB.addIngress(nil, ingress, math.MaxInt64)
continue
}
var certificateARNs []string
if ingress.CertificateARN != "" {
if !certs.CertificateExists(ingress.CertificateARN) {
log.Errorf("Failed to find certificate %s for %s", ingress.CertificateARN, ingress)
continue
}
certificateARNs = []string{ingress.CertificateARN}
} else {
certificateARNs = certs.FindMatchingCertificateIDs(ingress.Hostnames)
if len(certificateARNs) == 0 {
log.Errorf("No certificates found for hostnames %v of %s", ingress.Hostnames, ingress)
continue
}
}
// try to add ingress to existing ALB stacks until certificate
// limit is exeeded.
added := false
for _, lb := range loadBalancers {
// TODO(mlarsen): hack to phase out old load balancers
// which can't be updated to include type
// specification.
// Can be removed in a later version
supportedLBType := lb.loadBalancerType == aws.LoadBalancerTypeApplication ||
lb.loadBalancerType == aws.LoadBalancerTypeNetwork
if !supportedLBType {
continue
}
if lb.addIngress(certificateARNs, ingress, certsPerALB) {
added = true
break
}
}
// if the ingress was not added to the ALB stack because of
// non-matching scheme, non-matching security group or too many certificates, add a new
// stack.
if !added {
i := make(map[string][]*kubernetes.Ingress, len(certificateARNs))
for _, certificateARN := range certificateARNs {
i[certificateARN] = []*kubernetes.Ingress{ingress}
}
loadBalancers = append(
loadBalancers,
&loadBalancer{
ingresses: i,
scheme: ingress.Scheme,
shared: ingress.Shared,
securityGroup: ingress.SecurityGroup,
sslPolicy: ingress.SSLPolicy,
ipAddressType: ingress.IPAddressType,
loadBalancerType: ingress.LoadBalancerType,
http2: ingress.HTTP2,
wafWebACLID: ingress.WAFWebACLID,
},
)
}
}
return loadBalancers
}
// addCloudWatchAlarms attaches CloudWatch Alarms to each load balancer model
// in the list. It ensures that the alarm config is copied so that it can be
// adjusted safely for each load balancer.
func attachCloudWatchAlarms(loadBalancers []*loadBalancer, cwAlarms aws.CloudWatchAlarmList) {
for _, loadBalancer := range loadBalancers {
lbAlarms := make(aws.CloudWatchAlarmList, len(cwAlarms))
copy(lbAlarms, cwAlarms)
loadBalancer.cwAlarms = lbAlarms
}
}
func attachGlobalWAFACL(ings []*kubernetes.Ingress, globalWAFACL string) {
for _, ing := range ings {
if ing.WAFWebACLID != "" {
continue
}
ing.WAFWebACLID = globalWAFACL
}
}
func buildManagedModel(
certs CertificatesFinder,
certsPerALB int,
certTTL time.Duration,
ingresses []*kubernetes.Ingress,
stacks []*aws.Stack,
cwAlarms aws.CloudWatchAlarmList,
globalWAFACL string,
) []*loadBalancer {
sortStacks(stacks)
attachGlobalWAFACL(ingresses, globalWAFACL)
model := getAllLoadBalancers(certs, certTTL, stacks)
model = matchIngressesToLoadBalancers(model, certs, certsPerALB, ingresses)
attachCloudWatchAlarms(model, cwAlarms)
return model
}
func createStack(awsAdapter *aws.Adapter, lb *loadBalancer, problems *problem.List) {
certificates := make([]string, 0, len(lb.ingresses))
for cert := range lb.ingresses {
certificates = append(certificates, cert)
}
log.Infof("Creating stack for certificates %q / ingress %q", certificates, lb.ingresses)
stackId, err := awsAdapter.CreateStack(certificates, lb.scheme, lb.securityGroup, lb.Owner(), lb.sslPolicy, lb.ipAddressType, lb.wafWebACLID, lb.cwAlarms, lb.loadBalancerType, lb.http2)
if err != nil {
if isAlreadyExistsError(err) {
lb.stack, err = awsAdapter.GetStack(stackId)
if err == nil {
return
}
}
problems.Add("failed to create stack %q: %w", certificates, err)
} else {
metrics.changesTotal.created("stack")
log.Infof("Stack %q for certificates %q created", stackId, certificates)
}
}
func updateStack(awsAdapter *aws.Adapter, lb *loadBalancer, problems *problem.List) {
certificates := lb.CertificateARNs()
log.Infof("Updating %q stack for %d certificates / %d ingresses", lb.scheme, len(certificates), len(lb.ingresses))
stackId, err := awsAdapter.UpdateStack(lb.stack.Name, certificates, lb.scheme, lb.securityGroup, lb.Owner(), lb.sslPolicy, lb.ipAddressType, lb.wafWebACLID, lb.cwAlarms, lb.loadBalancerType, lb.http2)
if isNoUpdatesToBePerformedError(err) {
log.Debugf("Stack(%q) is already up to date", certificates)
} else if err != nil {
problems.Add("failed to update stack %q: %w", certificates, err)
} else {
metrics.changesTotal.updated("stack")
log.Infof("Stack %q for certificate %q updated", stackId, certificates)
}
}
func isAlreadyExistsError(err error) bool {
if awsErr, ok := err.(awserr.Error); ok {
return awsErr.Code() == cloudformation.ErrCodeAlreadyExistsException
}
return false
}
func isNoUpdatesToBePerformedError(err error) bool {
if err == nil {
return false
}
if _, ok := err.(awserr.Error); ok {
return strings.Contains(err.Error(), "No updates are to be performed")
}
return false
}
func updateIngress(kubeAdapter *kubernetes.Adapter, lb *loadBalancer, problems *problem.List) {
var dnsName string
if lb.clusterLocal {
dnsName = kubernetes.DefaultClusterLocalDomain
} else {
// only update ingress if the stack exists and is in a complete state.
if lb.stack == nil || !lb.stack.IsComplete() {
return
}
dnsName = strings.ToLower(lb.stack.DNSName) // lower case to satisfy Kubernetes reqs
}
for _, ingresses := range lb.ingresses {
for _, ing := range ingresses {
if err := kubeAdapter.UpdateIngressLoadBalancer(ing, dnsName); err != nil {
if err == kubernetes.ErrUpdateNotNeeded {
log.Debugf("Update not needed for %s with DNS name %s", ing, dnsName)
} else {
problems.Add("failed to update %s: %w", ing, err)
}
} else {
metrics.changesTotal.updated(string(ing.ResourceType))
log.Infof("Updated %s with DNS name %s", ing, dnsName)
}
}
}
}
func deleteStack(awsAdapter *aws.Adapter, lb *loadBalancer, problems *problem.List) {
stackName := lb.stack.Name
if err := awsAdapter.DeleteStack(lb.stack); err != nil {
problems.Add("failed to delete stack %q: %w", stackName, err)
} else {
metrics.changesTotal.deleted("stack")
log.Infof("Deleted orphaned stack %q", stackName)
}
}
// getCloudWatchAlarms retrieves CloudWatch Alarm configuration from a
// ConfigMap described by configMapLoc. If configMapLoc is nil, an empty alarm
// configuration will be returned. Returns any error that might occur while
// retrieving the configuration.
func getCloudWatchAlarms(kubeAdapter *kubernetes.Adapter, configMapLoc *kubernetes.ResourceLocation) (aws.CloudWatchAlarmList, error) {
if configMapLoc == nil {
return aws.CloudWatchAlarmList{}, nil
}
configMap, err := kubeAdapter.GetConfigMap(configMapLoc.Namespace, configMapLoc.Name)
if err != nil {
return nil, err
}
return getCloudWatchAlarmsFromConfigMap(configMap), nil
}
// getCloudWatchAlarmsFromConfigMap extracts cloudwatch alarm configuration
// from ConfigMap data. It will collect alarm configuration from all ConfigMap
// data keys it finds. If a ConfigMap data key contains invalid data, an error
// is logged and the key will be ignored. The sort order of the resulting slice
// is guaranteed to be stable.
func getCloudWatchAlarmsFromConfigMap(configMap *kubernetes.ConfigMap) aws.CloudWatchAlarmList {
configList := aws.CloudWatchAlarmList{}
keys := make([]string, 0, len(configMap.Data))
for k := range configMap.Data {
keys = append(keys, k)
}
sort.Strings(keys)
for _, key := range keys {
data := []byte(configMap.Data[key])
list, err := aws.NewCloudWatchAlarmListFromYAML(data)
if err != nil {
log.Warnf("Ignoring cloudwatch alarm configuration from config map key %q due to error: %v", key, err)
continue
}
configList = append(configList, list...)
}
return configList
}
// cniEventHandler syncronizes the events from kubernetes and the status updates from the load balancer controller.
// Events updates a rate limited.
func cniEventHandler(ctx context.Context, targetCNIcfg *aws.TargetCNIconfig,
targetSetter func([]string, []string) error, informer func(context.Context, chan<- []string) error) {
log.Infoln("Starting CNI event handler")
rateLimiter := time.NewTicker(cniEventRateLimit)
defer rateLimiter.Stop()
endpointCh := make(chan []string, 10)
go func() {
err := informer(ctx, endpointCh)
if err != nil {
log.Errorf("Informer failed: %v", err)
return
}
}()
var cniTargetGroupARNs, endpoints []string
for {
select {
case <-ctx.Done():
return
case cniTargetGroupARNs = <-targetCNIcfg.TargetGroupCh:
log.Debugf("new message target groups: %v", cniTargetGroupARNs)
case endpoints = <-endpointCh:
log.Debugf("new message endpoints: %v", endpoints)
}
// prevent cleanup due to startup inconsistenty, arns and endpoints can be empty but never nil
if cniTargetGroupARNs == nil || endpoints == nil {
continue
}
if len(endpointCh) > 0 || len(targetCNIcfg.TargetGroupCh) > 0 {
log.Debugf("flushing, messages queued: %d:%d", len(endpointCh), len(cniTargetGroupARNs))
continue
}
<-rateLimiter.C
err := targetSetter(endpoints, cniTargetGroupARNs)
if err != nil {
log.Error(err)
}
}
}