forked from kubernetes-sigs/aws-load-balancer-controller
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tagging_manager.go
474 lines (431 loc) · 15.1 KB
/
tagging_manager.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
package elbv2
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
awssdk "github.com/aws/aws-sdk-go/aws"
elbv2sdk "github.com/aws/aws-sdk-go/service/elbv2"
"github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi"
"github.com/go-logr/logr"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/util/sets"
"github.com/sonal-chauhan/aws-load-balancer-controller/pkg/algorithm"
"github.com/sonal-chauhan/aws-load-balancer-controller/pkg/aws/services"
"github.com/sonal-chauhan/aws-load-balancer-controller/pkg/config"
"github.com/sonal-chauhan/aws-load-balancer-controller/pkg/deploy/tracking"
)
const (
// ELBV2 API supports up to 20 resource per DescribeTags API call.
defaultDescribeTagsChunkSize = 20
)
// LoadBalancer with it's tags.
type LoadBalancerWithTags struct {
LoadBalancer *elbv2sdk.LoadBalancer
Tags map[string]string
}
// TargetGroup with it's tags.
type TargetGroupWithTags struct {
TargetGroup *elbv2sdk.TargetGroup
Tags map[string]string
}
// Listener with it's tags.
type ListenerWithTags struct {
Listener *elbv2sdk.Listener
Tags map[string]string
}
// ListenerRule with tags
type ListenerRuleWithTags struct {
ListenerRule *elbv2sdk.Rule
Tags map[string]string
}
// options for ReconcileTags API.
type ReconcileTagsOptions struct {
// CurrentTags on resources.
// when it's nil, the TaggingManager will try to get the CurrentTags from AWS
CurrentTags map[string]string
// IgnoredTagKeys defines the tag keys that should be ignored.
// these tags shouldn't be altered or deleted.
IgnoredTagKeys []string
}
func (opts *ReconcileTagsOptions) ApplyOptions(options []ReconcileTagsOption) {
for _, option := range options {
option(opts)
}
}
type ReconcileTagsOption func(opts *ReconcileTagsOptions)
// WithCurrentTags is a reconcile option that supplies current tags.
func WithCurrentTags(tags map[string]string) ReconcileTagsOption {
return func(opts *ReconcileTagsOptions) {
opts.CurrentTags = tags
}
}
// WithIgnoredTagKeys is a reconcile option that configures IgnoredTagKeys.
func WithIgnoredTagKeys(ignoredTagKeys []string) ReconcileTagsOption {
return func(opts *ReconcileTagsOptions) {
opts.IgnoredTagKeys = append(opts.IgnoredTagKeys, ignoredTagKeys...)
}
}
// abstraction around tagging operations for ELBV2.
type TaggingManager interface {
// ReconcileTags will reconcile tags on resources.
ReconcileTags(ctx context.Context, arn string, desiredTags map[string]string, opts ...ReconcileTagsOption) error
// ListLoadBalancers returns LoadBalancers that matches any of the tagging requirements.
ListLoadBalancers(ctx context.Context, tagFilters ...tracking.TagFilter) ([]LoadBalancerWithTags, error)
// ListTargetGroups returns TargetGroups that matches any of the tagging requirements.
ListTargetGroups(ctx context.Context, tagFilters ...tracking.TagFilter) ([]TargetGroupWithTags, error)
// ListListeners returns the LoadBalancer listeners along with tags
ListListeners(ctx context.Context, lbARN string) ([]ListenerWithTags, error)
// ListListenerRules returns the Listener Rules along with tags
ListListenerRules(ctx context.Context, lsARN string) ([]ListenerRuleWithTags, error)
}
// NewDefaultTaggingManager constructs default TaggingManager.
func NewDefaultTaggingManager(elbv2Client services.ELBV2, vpcID string, featureGates config.FeatureGates, rgt services.RGT, logger logr.Logger) *defaultTaggingManager {
return &defaultTaggingManager{
elbv2Client: elbv2Client,
vpcID: vpcID,
featureGates: featureGates,
logger: logger,
describeTagsChunkSize: defaultDescribeTagsChunkSize,
rgt: rgt,
}
}
var _ TaggingManager = &defaultTaggingManager{}
// default implementation for TaggingManager
// @TODO: deprecate ELB API and only use AWS Resource Groups Tagging API to optimize this implementation once RGT has PrivateLink support.
type defaultTaggingManager struct {
elbv2Client services.ELBV2
vpcID string
featureGates config.FeatureGates
logger logr.Logger
describeTagsChunkSize int
rgt services.RGT
}
func (m *defaultTaggingManager) ReconcileTags(ctx context.Context, arn string, desiredTags map[string]string, opts ...ReconcileTagsOption) error {
reconcileOpts := ReconcileTagsOptions{
CurrentTags: nil,
IgnoredTagKeys: nil,
}
reconcileOpts.ApplyOptions(opts)
currentTags := reconcileOpts.CurrentTags
if currentTags == nil {
tagsByARN, err := m.describeResourceTagsNative(ctx, []string{arn})
if err != nil {
return err
}
currentTags = tagsByARN[arn]
}
tagsToUpdate, tagsToRemove := algorithm.DiffStringMap(desiredTags, currentTags)
for _, ignoredTagKey := range reconcileOpts.IgnoredTagKeys {
delete(tagsToUpdate, ignoredTagKey)
delete(tagsToRemove, ignoredTagKey)
}
if len(tagsToUpdate) > 0 {
req := &elbv2sdk.AddTagsInput{
ResourceArns: []*string{awssdk.String(arn)},
Tags: convertTagsToSDKTags(tagsToUpdate),
}
m.logger.Info("adding resource tags",
"arn", arn,
"change", tagsToUpdate)
if _, err := m.elbv2Client.AddTagsWithContext(ctx, req); err != nil {
return err
}
m.logger.Info("added resource tags",
"arn", arn)
}
if len(tagsToRemove) > 0 {
tagKeys := sets.StringKeySet(tagsToRemove).List()
req := &elbv2sdk.RemoveTagsInput{
ResourceArns: []*string{awssdk.String(arn)},
TagKeys: awssdk.StringSlice(tagKeys),
}
m.logger.Info("removing resource tags",
"arn", arn,
"change", tagKeys)
if _, err := m.elbv2Client.RemoveTagsWithContext(ctx, req); err != nil {
return err
}
m.logger.Info("removed resource tags",
"arn", arn)
}
return nil
}
func (m *defaultTaggingManager) ListListeners(ctx context.Context, lbARN string) ([]ListenerWithTags, error) {
req := &elbv2sdk.DescribeListenersInput{
LoadBalancerArn: awssdk.String(lbARN),
}
listeners, err := m.elbv2Client.DescribeListenersAsList(ctx, req)
if err != nil {
return nil, err
}
lsARNs := make([]string, 0, len(listeners))
lsByARN := make(map[string]*elbv2sdk.Listener, len(listeners))
for _, listener := range listeners {
lsARN := awssdk.StringValue(listener.ListenerArn)
lsARNs = append(lsARNs, lsARN)
lsByARN[lsARN] = listener
}
var tagsByARN map[string]map[string]string
if m.featureGates.Enabled(config.ListenerRulesTagging) {
tagsByARN, err = m.describeResourceTagsNative(ctx, lsARNs)
if err != nil {
return nil, err
}
}
var sdkLSs []ListenerWithTags
for _, arn := range lsARNs {
tags := tagsByARN[arn]
sdkLSs = append(sdkLSs, ListenerWithTags{
Listener: lsByARN[arn],
Tags: tags,
})
}
return sdkLSs, err
}
func (m *defaultTaggingManager) ListListenerRules(ctx context.Context, lsARN string) ([]ListenerRuleWithTags, error) {
req := &elbv2sdk.DescribeRulesInput{
ListenerArn: awssdk.String(lsARN),
}
rules, err := m.elbv2Client.DescribeRulesAsList(ctx, req)
if err != nil {
return nil, err
}
lrARNs := make([]string, 0, len(rules))
lrByARN := make(map[string]*elbv2sdk.Rule, len(rules))
for _, rule := range rules {
lrARN := awssdk.StringValue(rule.RuleArn)
lrARNs = append(lrARNs, lrARN)
lrByARN[lrARN] = rule
}
var tagsByARN map[string]map[string]string
if m.featureGates.Enabled(config.ListenerRulesTagging) {
tagsByARN, err = m.describeResourceTagsNative(ctx, lrARNs)
if err != nil {
return nil, err
}
}
var sdkLRs []ListenerRuleWithTags
for _, arn := range lrARNs {
tags := tagsByARN[arn]
sdkLRs = append(sdkLRs, ListenerRuleWithTags{
ListenerRule: lrByARN[arn],
Tags: tags,
})
}
return sdkLRs, err
}
func (m *defaultTaggingManager) ListLoadBalancers(ctx context.Context, tagFilters ...tracking.TagFilter) ([]LoadBalancerWithTags, error) {
if m.featureGates.Enabled(config.EnableRGTAPI) {
return m.listLoadBalancersRGT(ctx, tagFilters)
}
return m.listLoadBalancersNative(ctx, tagFilters)
}
func (m *defaultTaggingManager) ListTargetGroups(ctx context.Context, tagFilters ...tracking.TagFilter) ([]TargetGroupWithTags, error) {
if m.featureGates.Enabled(config.EnableRGTAPI) {
return m.listTargetGroupsRGT(ctx, tagFilters)
}
return m.listTargetGroupsNative(ctx, tagFilters)
}
func (m *defaultTaggingManager) listLoadBalancersRGT(ctx context.Context, tagFilters []tracking.TagFilter) ([]LoadBalancerWithTags, error) {
// use a map to avoid potential duplication in returned resources
resourceTagsByARN := make(map[string][]*resourcegroupstaggingapi.Tag)
for _, tagFilter := range tagFilters {
req := &resourcegroupstaggingapi.GetResourcesInput{
TagFilters: convertTagFiltersToRGTTagFilters(tagFilter),
ResourceTypeFilters: aws.StringSlice([]string{services.ResourceTypeELBLoadBalancer}),
}
resources, err := m.rgt.GetResourcesAsList(ctx, req)
if err != nil {
return nil, err
}
for _, resource := range resources {
if _, exists := resourceTagsByARN[aws.StringValue(resource.ResourceARN)]; !exists {
resourceTagsByARN[aws.StringValue(resource.ResourceARN)] = resource.Tags
}
}
}
var matchedLBs []LoadBalancerWithTags
for resourceARN, resourceTags := range resourceTagsByARN {
elbv2Req := &elbv2sdk.DescribeLoadBalancersInput{
LoadBalancerArns: []*string{&resourceARN},
}
elbv2Resp, err := m.elbv2Client.DescribeLoadBalancersAsList(ctx, elbv2Req)
if err != nil {
return nil, err
}
if len(elbv2Resp) == 0 {
return nil, errors.Errorf("no load balancer found for the arn: %v", resourceARN)
}
matchedLBs = append(matchedLBs, LoadBalancerWithTags{
LoadBalancer: elbv2Resp[0],
Tags: services.ParseRGTTags(resourceTags),
})
}
return matchedLBs, nil
}
func (m *defaultTaggingManager) listLoadBalancersNative(ctx context.Context, tagFilters []tracking.TagFilter) ([]LoadBalancerWithTags, error) {
req := &elbv2sdk.DescribeLoadBalancersInput{}
lbs, err := m.elbv2Client.DescribeLoadBalancersAsList(ctx, req)
if err != nil {
return nil, err
}
lbARNsWithinVPC := make([]string, 0, len(lbs))
lbByARNWithinVPC := make(map[string]*elbv2sdk.LoadBalancer, len(lbs))
for _, lb := range lbs {
if awssdk.StringValue(lb.VpcId) != m.vpcID {
continue
}
lbARN := awssdk.StringValue(lb.LoadBalancerArn)
lbARNsWithinVPC = append(lbARNsWithinVPC, lbARN)
lbByARNWithinVPC[lbARN] = lb
}
tagsByARN, err := m.describeResourceTagsNative(ctx, lbARNsWithinVPC)
if err != nil {
return nil, err
}
var matchedLBs []LoadBalancerWithTags
for _, arn := range lbARNsWithinVPC {
tags := tagsByARN[arn]
matchedAnyTagFilter := false
for _, tagFilter := range tagFilters {
if tagFilter.Matches(tags) {
matchedAnyTagFilter = true
break
}
}
if matchedAnyTagFilter {
matchedLBs = append(matchedLBs, LoadBalancerWithTags{
LoadBalancer: lbByARNWithinVPC[arn],
Tags: tags,
})
}
}
return matchedLBs, nil
}
func (m *defaultTaggingManager) listTargetGroupsRGT(ctx context.Context, tagFilters []tracking.TagFilter) ([]TargetGroupWithTags, error) {
// use a map to avoid potential duplication in returned resources
resourceTagsByARN := make(map[string][]*resourcegroupstaggingapi.Tag)
for _, tagFilter := range tagFilters {
req := &resourcegroupstaggingapi.GetResourcesInput{
TagFilters: convertTagFiltersToRGTTagFilters(tagFilter),
ResourceTypeFilters: aws.StringSlice([]string{services.ResourceTypeELBTargetGroup}),
}
resources, err := m.rgt.GetResourcesAsList(ctx, req)
if err != nil {
return nil, err
}
for _, resource := range resources {
if _, exists := resourceTagsByARN[aws.StringValue(resource.ResourceARN)]; !exists {
resourceTagsByARN[aws.StringValue(resource.ResourceARN)] = resource.Tags
}
}
}
var matchedTGs []TargetGroupWithTags
for resourceARN, resourceTags := range resourceTagsByARN {
elbv2Req := &elbv2sdk.DescribeTargetGroupsInput{
TargetGroupArns: []*string{&resourceARN},
}
elbv2Resp, err := m.elbv2Client.DescribeTargetGroupsAsList(ctx, elbv2Req)
if err != nil {
return nil, err
}
if len(elbv2Resp) == 0 {
return nil, errors.Errorf("no target group found for the arn: %v", resourceARN)
}
matchedTGs = append(matchedTGs, TargetGroupWithTags{
TargetGroup: elbv2Resp[0],
Tags: services.ParseRGTTags(resourceTags),
})
}
return matchedTGs, nil
}
func (m *defaultTaggingManager) listTargetGroupsNative(ctx context.Context, tagFilters []tracking.TagFilter) ([]TargetGroupWithTags, error) {
req := &elbv2sdk.DescribeTargetGroupsInput{}
tgs, err := m.elbv2Client.DescribeTargetGroupsAsList(ctx, req)
if err != nil {
return nil, err
}
tgARNsWithinVPC := make([]string, 0, len(tgs))
tgByARNWithinVPC := make(map[string]*elbv2sdk.TargetGroup, len(tgs))
for _, tg := range tgs {
if awssdk.StringValue(tg.VpcId) != m.vpcID {
continue
}
tgARN := awssdk.StringValue(tg.TargetGroupArn)
tgARNsWithinVPC = append(tgARNsWithinVPC, tgARN)
tgByARNWithinVPC[tgARN] = tg
}
tagsByARN, err := m.describeResourceTagsNative(ctx, tgARNsWithinVPC)
if err != nil {
return nil, err
}
var matchedTGs []TargetGroupWithTags
for _, arn := range tgARNsWithinVPC {
tags := tagsByARN[arn]
matchedAnyTagFilter := false
for _, tagFilter := range tagFilters {
if tagFilter.Matches(tags) {
matchedAnyTagFilter = true
break
}
}
if matchedAnyTagFilter {
matchedTGs = append(matchedTGs, TargetGroupWithTags{
TargetGroup: tgByARNWithinVPC[arn],
Tags: tags,
})
}
}
return matchedTGs, nil
}
// describeResourceTagsNative describes tags for elbv2 resources.
// returns tags indexed by resource ARN.
func (m *defaultTaggingManager) describeResourceTagsNative(ctx context.Context, arns []string) (map[string]map[string]string, error) {
tagsByARN := make(map[string]map[string]string, len(arns))
arnsChunks := algorithm.ChunkStrings(arns, m.describeTagsChunkSize)
for _, arnsChunk := range arnsChunks {
req := &elbv2sdk.DescribeTagsInput{
ResourceArns: awssdk.StringSlice(arnsChunk),
}
resp, err := m.elbv2Client.DescribeTagsWithContext(ctx, req)
if err != nil {
return nil, err
}
for _, tagDescription := range resp.TagDescriptions {
tagsByARN[awssdk.StringValue(tagDescription.ResourceArn)] = convertSDKTagsToTags(tagDescription.Tags)
}
}
return tagsByARN, nil
}
// convert tags into AWS SDK tag presentation.
func convertTagsToSDKTags(tags map[string]string) []*elbv2sdk.Tag {
if len(tags) == 0 {
return nil
}
sdkTags := make([]*elbv2sdk.Tag, 0, len(tags))
for _, key := range sets.StringKeySet(tags).List() {
sdkTags = append(sdkTags, &elbv2sdk.Tag{
Key: awssdk.String(key),
Value: awssdk.String(tags[key]),
})
}
return sdkTags
}
// convert AWS SDK tag presentation into tags.
func convertSDKTagsToTags(sdkTags []*elbv2sdk.Tag) map[string]string {
tags := make(map[string]string, len(sdkTags))
for _, sdkTag := range sdkTags {
tags[awssdk.StringValue(sdkTag.Key)] = awssdk.StringValue(sdkTag.Value)
}
return tags
}
// convert tagFilters to RGTTagFilters
func convertTagFiltersToRGTTagFilters(tagFilter tracking.TagFilter) []*resourcegroupstaggingapi.TagFilter {
var RGTTagFilters []*resourcegroupstaggingapi.TagFilter
for k, v := range tagFilter {
RGTTagFilters = append(RGTTagFilters, &resourcegroupstaggingapi.TagFilter{
Key: aws.String(k),
Values: aws.StringSlice(v),
})
}
return RGTTagFilters
}