-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
Copy pathtargetgroup.go
305 lines (254 loc) · 9.05 KB
/
targetgroup.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
/*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package awstasks
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/elbv2"
"k8s.io/klog/v2"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/cloudup/awsup"
"k8s.io/kops/upup/pkg/fi/cloudup/cloudformation"
"k8s.io/kops/upup/pkg/fi/cloudup/terraform"
"k8s.io/kops/upup/pkg/fi/cloudup/terraformWriter"
)
// +kops:fitask
type TargetGroup struct {
Name *string
Lifecycle fi.Lifecycle
VPC *VPC
Tags map[string]string
Port *int64
Protocol *string
// ARN is the Amazon Resource Name for the Target Group
ARN *string
// Shared is set if this is an external LB (one we don't create or own)
Shared *bool
HealthyThreshold *int64
UnhealthyThreshold *int64
}
var _ fi.CompareWithID = &TargetGroup{}
func (e *TargetGroup) CompareWithID() *string {
return e.ARN
}
func (e *TargetGroup) Find(c *fi.Context) (*TargetGroup, error) {
cloud := c.Cloud.(awsup.AWSCloud)
request := &elbv2.DescribeTargetGroupsInput{}
if e.ARN != nil {
request.TargetGroupArns = []*string{e.ARN}
} else if e.Name != nil {
request.Names = []*string{e.Name}
}
response, err := cloud.ELBV2().DescribeTargetGroups(request)
if err != nil {
if aerr, ok := err.(awserr.Error); ok && aerr.Code() == elbv2.ErrCodeTargetGroupNotFoundException {
if !fi.BoolValue(e.Shared) {
return nil, nil
}
}
return nil, fmt.Errorf("error describing targetgroup %s: %v", *e.Name, err)
}
if len(response.TargetGroups) > 1 {
return nil, fmt.Errorf("found %d TargetGroups with ID %q, expected 1", len(response.TargetGroups), fi.StringValue(e.Name))
} else if len(response.TargetGroups) == 0 {
return nil, nil
}
tg := response.TargetGroups[0]
actual := &TargetGroup{
Name: tg.TargetGroupName,
Port: tg.Port,
Protocol: tg.Protocol,
ARN: tg.TargetGroupArn,
HealthyThreshold: tg.HealthyThresholdCount,
UnhealthyThreshold: tg.UnhealthyThresholdCount,
VPC: &VPC{ID: tg.VpcId},
}
e.ARN = tg.TargetGroupArn
tagsResp, err := cloud.ELBV2().DescribeTags(&elbv2.DescribeTagsInput{
ResourceArns: []*string{tg.TargetGroupArn},
})
if err != nil {
return nil, err
}
tags := make(map[string]string)
for _, tagDesc := range tagsResp.TagDescriptions {
for _, tag := range tagDesc.Tags {
tags[fi.StringValue(tag.Key)] = fi.StringValue(tag.Value)
}
}
actual.Tags = tags
// Prevent spurious changes
actual.Lifecycle = e.Lifecycle
actual.Shared = e.Shared
return actual, nil
}
func FindTargetGroupByName(cloud awsup.AWSCloud, findName string) (*elbv2.TargetGroup, error) {
klog.V(2).Infof("Listing all TargetGroups for FindTargetGroupByName")
request := &elbv2.DescribeTargetGroupsInput{
Names: []*string{aws.String(findName)},
}
// ELB DescribeTags has a limit of 20 names, so we set the page size here to 20 also
request.PageSize = aws.Int64(20)
resp, err := cloud.ELBV2().DescribeTargetGroups(request)
if err != nil {
if aerr, ok := err.(awserr.Error); ok && aerr.Code() == elbv2.ErrCodeTargetGroupNotFoundException {
return nil, nil
}
return nil, fmt.Errorf("error describing TargetGroups: %v", err)
}
if len(resp.TargetGroups) == 0 {
return nil, nil
}
if len(resp.TargetGroups) != 1 {
return nil, fmt.Errorf("Found multiple TargetGroups with Name %q", findName)
}
return resp.TargetGroups[0], nil
}
func (e *TargetGroup) Run(c *fi.Context) error {
return fi.DefaultDeltaRunMethod(e, c)
}
func (_ *TargetGroup) ShouldCreate(a, e, changes *TargetGroup) (bool, error) {
if fi.BoolValue(e.Shared) {
return false, nil
}
return true, nil
}
func (s *TargetGroup) CheckChanges(a, e, changes *TargetGroup) error {
return nil
}
func (_ *TargetGroup) RenderAWS(t *awsup.AWSAPITarget, a, e, changes *TargetGroup) error {
shared := fi.BoolValue(e.Shared)
if shared {
return nil
}
//You register targets for your Network Load Balancer with a target group. By default, the load balancer sends requests
//to registered targets using the port and protocol that you specified for the target group. You can override this port
//when you register each target with the target group.
if a == nil {
request := &elbv2.CreateTargetGroupInput{
Name: e.Name,
Port: e.Port,
Protocol: e.Protocol,
VpcId: e.VPC.ID,
HealthyThresholdCount: e.HealthyThreshold,
UnhealthyThresholdCount: e.UnhealthyThreshold,
Tags: awsup.ELBv2Tags(e.Tags),
}
klog.V(2).Infof("Creating Target Group for NLB")
response, err := t.Cloud.ELBV2().CreateTargetGroup(request)
if err != nil {
return fmt.Errorf("Error creating target group for NLB : %v", err)
}
targetGroupArn := *response.TargetGroups[0].TargetGroupArn
e.ARN = fi.String(targetGroupArn)
} else {
if a.ARN != nil {
if err := t.AddELBV2Tags(fi.StringValue(a.ARN), e.Tags); err != nil {
return err
}
}
}
return nil
}
// OrderTargetGroupsByName implements sort.Interface for []OrderTargetGroupsByName, based on port number
type OrderTargetGroupsByName []*TargetGroup
func (a OrderTargetGroupsByName) Len() int { return len(a) }
func (a OrderTargetGroupsByName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a OrderTargetGroupsByName) Less(i, j int) bool {
return fi.StringValue(a[i].Name) < fi.StringValue(a[j].Name)
}
type terraformTargetGroup struct {
Name string `json:"name" cty:"name"`
Port int64 `json:"port" cty:"port"`
Protocol string `json:"protocol" cty:"protocol"`
VPCID terraformWriter.Literal `json:"vpc_id" cty:"vpc_id"`
Tags map[string]string `json:"tags,omitempty" cty:"tags"`
HealthCheck terraformTargetGroupHealthCheck `json:"health_check" cty:"health_check"`
}
type terraformTargetGroupHealthCheck struct {
HealthyThreshold int64 `json:"healthy_threshold" cty:"healthy_threshold"`
UnhealthyThreshold int64 `json:"unhealthy_threshold" cty:"unhealthy_threshold"`
Protocol string `json:"protocol" cty:"protocol"`
}
func (_ *TargetGroup) RenderTerraform(t *terraform.TerraformTarget, a, e, changes *TargetGroup) error {
shared := fi.BoolValue(e.Shared)
if shared {
return nil
}
if e.VPC == nil {
return fmt.Errorf("Missing VPC task from target group:\n%v\n%v", e, e.VPC)
}
tf := &terraformTargetGroup{
Name: *e.Name,
Port: *e.Port,
Protocol: *e.Protocol,
VPCID: *e.VPC.TerraformLink(),
Tags: e.Tags,
HealthCheck: terraformTargetGroupHealthCheck{
HealthyThreshold: *e.HealthyThreshold,
UnhealthyThreshold: *e.UnhealthyThreshold,
Protocol: elbv2.ProtocolEnumTcp,
},
}
return t.RenderResource("aws_lb_target_group", *e.Name, tf)
}
func (e *TargetGroup) TerraformLink(params ...string) *terraformWriter.Literal {
shared := fi.BoolValue(e.Shared)
if shared {
if e.ARN != nil {
return terraformWriter.LiteralFromStringValue(*e.ARN)
} else {
klog.Warningf("ID not set on shared Target Group %v", e)
}
}
return terraformWriter.LiteralProperty("aws_lb_target_group", *e.Name, "id")
}
type cloudformationTargetGroup struct {
Name string `json:"Name"`
Port int64 `json:"Port"`
Protocol string `json:"Protocol"`
VPCID *cloudformation.Literal `json:"VpcId"`
Tags []cloudformationTag `json:"Tags"`
HealthCheckProtocol string `json:"HealthCheckProtocol"`
HealthyThreshold int64 `json:"HealthyThresholdCount"`
UnhealthyThreshold int64 `json:"UnhealthyThresholdCount"`
}
func (_ *TargetGroup) RenderCloudformation(t *cloudformation.CloudformationTarget, a, e, changes *TargetGroup) error {
shared := fi.BoolValue(e.Shared)
if shared {
return nil
}
cf := &cloudformationTargetGroup{
Name: *e.Name,
Port: *e.Port,
Protocol: *e.Protocol,
VPCID: e.VPC.CloudformationLink(),
Tags: buildCloudformationTags(e.Tags),
HealthCheckProtocol: *e.Protocol,
HealthyThreshold: *e.HealthyThreshold,
UnhealthyThreshold: *e.UnhealthyThreshold,
}
return t.RenderResource("AWS::ElasticLoadBalancingV2::TargetGroup", *e.Name, cf)
}
func (e *TargetGroup) CloudformationLink() *cloudformation.Literal {
shared := fi.BoolValue(e.Shared)
if shared {
if e.ARN != nil {
return cloudformation.LiteralString(*e.ARN)
} else {
klog.Warningf("ID not set on shared Target Group: %v", e)
}
}
return cloudformation.Ref("AWS::ElasticLoadBalancingV2::TargetGroup", *e.Name)
}