-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
Copy pathnatgateway.go
436 lines (363 loc) · 12.1 KB
/
natgateway.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
/*
Copyright 2019 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/service/ec2"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/klog/v2"
raws "k8s.io/kops/pkg/resources/aws"
"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 NatGateway struct {
Name *string
Lifecycle fi.Lifecycle
ElasticIP *ElasticIP
Subnet *Subnet
ID *string
EgressId *string
// Shared is set if this is a shared NatGateway
Shared *bool
// Tags is a map of aws tags that are added to the NatGateway
Tags map[string]string
// We can't tag NatGateways, so we have to find through a surrogate
AssociatedRouteTable *RouteTable
}
var _ fi.CompareWithID = &NatGateway{}
func (e *NatGateway) CompareWithID() *string {
// Match by ID (NAT Gateways don't have tags, so they don't have a name in EC2)
return e.ID
}
func (e *NatGateway) Find(c *fi.Context) (*NatGateway, error) {
cloud := c.Cloud.(awsup.AWSCloud)
var ngw *ec2.NatGateway
actual := &NatGateway{}
if fi.StringValue(e.ID) != "" {
// We have an existing NGW, lets look up the EIP
var ngwIds []*string
ngwIds = append(ngwIds, e.ID)
request := &ec2.DescribeNatGatewaysInput{
NatGatewayIds: ngwIds,
}
response, err := cloud.EC2().DescribeNatGateways(request)
if err != nil {
return nil, fmt.Errorf("error listing Nat Gateways %v", err)
}
if len(response.NatGateways) != 1 {
return nil, fmt.Errorf("found %d Nat Gateways with ID %q, expected 1", len(response.NatGateways), fi.StringValue(e.ID))
}
ngw = response.NatGateways[0]
if len(ngw.NatGatewayAddresses) != 1 {
return nil, fmt.Errorf("found %d EIP Addresses for 1 NATGateway, expected 1", len(ngw.NatGatewayAddresses))
}
} else {
// This is the normal/default path
var err error
ngw, err = e.findNatGateway(c)
if err != nil {
return nil, err
}
if ngw == nil {
return nil, nil
}
}
actual.ID = ngw.NatGatewayId
actual.Subnet = e.Subnet
if len(ngw.NatGatewayAddresses) == 0 {
// Not sure if this ever happens
actual.ElasticIP = nil
} else if len(ngw.NatGatewayAddresses) == 1 {
actual.ElasticIP = &ElasticIP{ID: ngw.NatGatewayAddresses[0].AllocationId}
} else {
return nil, fmt.Errorf("found multiple elastic IPs attached to NatGateway %q", aws.StringValue(ngw.NatGatewayId))
}
// NATGateways now have names and tags so lets pull from there instead.
actual.Name = findNameTag(ngw.Tags)
if e.Tags["Name"] == "" {
// If we're not tagging by name, avoid spurious differences
actual.Name = e.Name
}
actual.Tags = intersectTags(ngw.Tags, e.Tags)
// Avoid spurious changes
actual.Lifecycle = e.Lifecycle
actual.Shared = e.Shared
actual.AssociatedRouteTable = e.AssociatedRouteTable
e.ID = actual.ID
return actual, nil
}
func (e *NatGateway) findNatGateway(c *fi.Context) (*ec2.NatGateway, error) {
cloud := c.Cloud.(awsup.AWSCloud)
id := e.ID
// Find via route on private route table
if id == nil && e.AssociatedRouteTable != nil {
ngw, err := findNatGatewayFromRouteTable(cloud, e.AssociatedRouteTable)
if err != nil {
return nil, err
}
if ngw != nil {
return ngw, nil
}
}
// Find via tag on subnet
// TODO: Obsolete - we can get from the route table instead
if id == nil && e.Subnet != nil {
var filters []*ec2.Filter
filters = append(filters, awsup.NewEC2Filter("key", "AssociatedNatgateway"))
if e.Subnet.ID == nil {
klog.V(2).Infof("Unable to find subnet, bypassing Find() for NatGateway")
return nil, nil
}
filters = append(filters, awsup.NewEC2Filter("resource-id", *e.Subnet.ID))
request := &ec2.DescribeTagsInput{
Filters: filters,
}
response, err := cloud.EC2().DescribeTags(request)
if err != nil {
return nil, fmt.Errorf("error listing tags: %v", err)
}
if response == nil || len(response.Tags) == 0 {
return nil, nil
}
if len(response.Tags) != 1 {
return nil, fmt.Errorf("found multiple tags for: %v", e)
}
t := response.Tags[0]
id = t.Value
klog.V(2).Infof("Found NatGateway via subnet tag: %v", *id)
}
if id != nil {
return findNatGatewayById(cloud, id)
}
return nil, nil
}
func findNatGatewayById(cloud awsup.AWSCloud, id *string) (*ec2.NatGateway, error) {
request := &ec2.DescribeNatGatewaysInput{}
request.NatGatewayIds = []*string{id}
response, err := cloud.EC2().DescribeNatGateways(request)
if err != nil {
return nil, fmt.Errorf("error listing NatGateway %q: %v", aws.StringValue(id), err)
}
if response == nil || len(response.NatGateways) == 0 {
klog.V(2).Infof("Unable to find NatGateway %q", aws.StringValue(id))
return nil, nil
}
if len(response.NatGateways) != 1 {
return nil, fmt.Errorf("found multiple NatGateways with id %q", aws.StringValue(id))
}
return response.NatGateways[0], nil
}
func findNatGatewayFromRouteTable(cloud awsup.AWSCloud, routeTable *RouteTable) (*ec2.NatGateway, error) {
// Find via route on private route table
if routeTable.ID != nil {
klog.V(2).Infof("trying to match NatGateway via RouteTable %s", *routeTable.ID)
rt, err := findRouteTableByID(cloud, *routeTable.ID)
if err != nil {
return nil, fmt.Errorf("error finding associated RouteTable to NatGateway: %v", err)
}
if rt != nil {
var natGatewayIDs []*string
for _, route := range rt.Routes {
if route.NatGatewayId != nil {
natGatewayIDs = append(natGatewayIDs, route.NatGatewayId)
}
}
if len(natGatewayIDs) == 0 {
klog.V(2).Infof("no NatGateway found in route table %s", *rt.RouteTableId)
} else if len(natGatewayIDs) > 1 {
clusterName, ok := routeTable.Tags[awsup.TagClusterName]
if !ok {
return nil, fmt.Errorf("Could not find '%s' tag from route table", awsup.TagClusterName)
}
filteredNatGateways := []*ec2.NatGateway{}
for _, natGatewayID := range natGatewayIDs {
gw, err := findNatGatewayById(cloud, natGatewayID)
if err != nil {
return nil, err
}
if raws.HasOwnedTag(ec2.ResourceTypeNatgateway+":"+fi.StringValue(natGatewayID), gw.Tags, clusterName) {
filteredNatGateways = append(filteredNatGateways, gw)
}
}
if len(filteredNatGateways) == 0 {
klog.V(2).Infof("no kOps NatGateway found in route table %s", *rt.RouteTableId)
} else if len(filteredNatGateways) > 1 {
return nil, fmt.Errorf("found multiple kOps NatGateways in route table %s", *rt.RouteTableId)
} else {
return filteredNatGateways[0], nil
}
} else {
return findNatGatewayById(cloud, natGatewayIDs[0])
}
}
}
return nil, nil
}
func (s *NatGateway) CheckChanges(a, e, changes *NatGateway) error {
// New
if a == nil {
if !fi.BoolValue(e.Shared) {
if e.ElasticIP == nil {
return fi.RequiredField("ElasticIP")
}
if e.Subnet == nil {
return fi.RequiredField("Subnet")
}
}
if e.AssociatedRouteTable == nil {
return fi.RequiredField("AssociatedRouteTable")
}
}
// Delta
if a != nil {
if changes.ElasticIP != nil {
eID := ""
if e.ElasticIP != nil {
eID = fi.StringValue(e.ElasticIP.ID)
}
aID := ""
if a.ElasticIP != nil {
aID = fi.StringValue(a.ElasticIP.ID)
}
return fi.FieldIsImmutable(eID, aID, field.NewPath("ElasticIP"))
}
if changes.Subnet != nil {
return fi.CannotChangeField("Subnet")
}
if changes.ID != nil {
return fi.CannotChangeField("ID")
}
}
return nil
}
func (e *NatGateway) Run(c *fi.Context) error {
return fi.DefaultDeltaRunMethod(e, c)
}
func (_ *NatGateway) RenderAWS(t *awsup.AWSAPITarget, a, e, changes *NatGateway) error {
// New NGW
var id *string
if a == nil {
if fi.BoolValue(e.Shared) {
return fmt.Errorf("NAT gateway %q not found", fi.StringValue(e.ID))
}
klog.V(2).Infof("Creating Nat Gateway")
request := &ec2.CreateNatGatewayInput{
TagSpecifications: awsup.EC2TagSpecification(ec2.ResourceTypeNatgateway, e.Tags),
}
request.AllocationId = e.ElasticIP.ID
request.SubnetId = e.Subnet.ID
response, err := t.Cloud.EC2().CreateNatGateway(request)
if err != nil {
return fmt.Errorf("Error creating Nat Gateway: %v", err)
}
e.ID = response.NatGateway.NatGatewayId
id = e.ID
} else {
id = a.ID
}
err := t.AddAWSTags(*e.ID, e.Tags)
if err != nil {
return fmt.Errorf("unable to tag NatGateway")
}
// Tag the associated subnet
if e.Subnet == nil {
return fmt.Errorf("Subnet not set")
} else if e.Subnet.ID == nil {
return fmt.Errorf("Subnet ID not set")
}
// TODO: AssociatedNatgateway tag is obsolete - we can get from the route table instead
tags := make(map[string]string)
tags["AssociatedNatgateway"] = *id
err = t.AddAWSTags(*e.Subnet.ID, tags)
if err != nil {
return fmt.Errorf("unable to tag subnet %v", err)
}
// If this is a shared NGW, we need to tag it
// The tag that implies "shared" is `AssociatedNatgateway`=> NGW-ID
// This is better than just a tag that's shared because this lets us create a whitelist of these NGWs
// without doing a bunch more work in `kutil/delete_cluster.go`
if fi.BoolValue(e.Shared) {
if e.AssociatedRouteTable == nil {
return fmt.Errorf("AssociatedRouteTable not provided")
}
klog.V(2).Infof("tagging route table %s to track shared NGW", fi.StringValue(e.AssociatedRouteTable.ID))
err = t.AddAWSTags(fi.StringValue(e.AssociatedRouteTable.ID), tags)
if err != nil {
return fmt.Errorf("unable to tag route table %v", err)
}
}
return nil
}
type terraformNATGateway struct {
AllocationID *terraformWriter.Literal `json:"allocation_id,omitempty" cty:"allocation_id"`
SubnetID *terraformWriter.Literal `json:"subnet_id,omitempty" cty:"subnet_id"`
Tag map[string]string `json:"tags,omitempty" cty:"tags"`
}
func (_ *NatGateway) RenderTerraform(t *terraform.TerraformTarget, a, e, changes *NatGateway) error {
if fi.BoolValue(e.Shared) {
if e.ID == nil {
return fmt.Errorf("ID must be set, if NatGateway is shared: %s", e)
}
klog.V(4).Infof("reusing existing NatGateway with id %q", *e.ID)
return nil
}
tf := &terraformNATGateway{
AllocationID: e.ElasticIP.TerraformLink(),
SubnetID: e.Subnet.TerraformLink(),
Tag: e.Tags,
}
return t.RenderResource("aws_nat_gateway", *e.Name, tf)
}
func (e *NatGateway) TerraformLink() *terraformWriter.Literal {
if fi.BoolValue(e.Shared) {
if e.ID == nil {
klog.Fatalf("ID must be set, if NatGateway is shared: %s", e)
}
return terraformWriter.LiteralFromStringValue(*e.ID)
}
return terraformWriter.LiteralProperty("aws_nat_gateway", *e.Name, "id")
}
type cloudformationNATGateway struct {
AllocationID *cloudformation.Literal `json:"AllocationId,omitempty"`
SubnetID *cloudformation.Literal `json:"SubnetId,omitempty"`
Tags []cloudformationTag `json:"Tags,omitempty"`
}
func (_ *NatGateway) RenderCloudformation(t *cloudformation.CloudformationTarget, a, e, changes *NatGateway) error {
if fi.BoolValue(e.Shared) {
if e.ID == nil {
return fmt.Errorf("ID must be set, if NatGateway is shared: %s", e)
}
klog.V(4).Infof("reusing existing NatGateway with id %q", *e.ID)
return nil
}
cf := &cloudformationNATGateway{
AllocationID: e.ElasticIP.CloudformationAllocationID(),
SubnetID: e.Subnet.CloudformationLink(),
Tags: buildCloudformationTags(e.Tags),
}
return t.RenderResource("AWS::EC2::NatGateway", *e.Name, cf)
}
func (e *NatGateway) CloudformationLink() *cloudformation.Literal {
if fi.BoolValue(e.Shared) {
if e.ID == nil {
klog.Fatalf("ID must be set, if NatGateway is shared: %s", e)
}
return cloudformation.LiteralString(*e.ID)
}
return cloudformation.Ref("AWS::EC2::NatGateway", *e.Name)
}