-
Notifications
You must be signed in to change notification settings - Fork 10
/
eip_controller.go
417 lines (350 loc) · 11.8 KB
/
eip_controller.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
/*
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 controllers
import (
"context"
"errors"
"fmt"
"github.com/go-logr/logr"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/ec2"
awsv1alpha1 "github.com/logmein/k8s-aws-operator/api/v1alpha1"
)
// EIPReconciler reconciles a EIP object
type EIPReconciler struct {
client.Client
Log logr.Logger
EC2 *ec2.EC2
}
// +kubebuilder:rbac:groups=aws.k8s.logmein.com,resources=eips,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=aws.k8s.logmein.com,resources=eips/status,verbs=get;update;patch
func (r *EIPReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
ctx := context.Background()
log := r.Log.WithValues("eip", req.NamespacedName)
var eip awsv1alpha1.EIP
if err := r.Get(ctx, req.NamespacedName, &eip); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
status := &eip.Status
spec := &eip.Spec
if eip.ObjectMeta.DeletionTimestamp.IsZero() {
if !containsString(eip.ObjectMeta.Finalizers, finalizerName) {
// add finalizer, set initial state
eip.ObjectMeta.Finalizers = append(eip.ObjectMeta.Finalizers, finalizerName)
status.State = "allocating"
return ctrl.Result{}, r.Update(ctx, &eip)
}
if status.State == "allocating" {
return ctrl.Result{}, r.allocateEIP(ctx, &eip, log)
}
resp, err := r.EC2.DescribeAddressesWithContext(ctx, &ec2.DescribeAddressesInput{
AllocationIds: []*string{aws.String(status.AllocationId)},
})
if err != nil {
if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "InvalidAllocationID.NotFound" {
log.Info("allocation ID not found; assuming EIP was released; not doing anything", "allocationId", eip.Status.AllocationId)
}
return ctrl.Result{}, err
}
addr := resp.Addresses[0]
if err := r.reconcileTags(ctx, &eip, addr.Tags); err != nil {
return ctrl.Result{}, err
}
if status.State == "allocated" {
if spec.Assignment != nil {
if spec.Assignment.PodName != "" || spec.Assignment.ENI != "" || spec.Assignment.PrivateIPAddress != "" {
status.State = "assigning"
return ctrl.Result{}, r.Update(ctx, &eip)
}
}
}
if status.State == "assigned" {
changed := false
switch {
case spec.Assignment == nil:
// assignment was removed
status.State = "unassigning"
changed = true
case *(spec.Assignment) != *(status.Assignment) || addr.AssociationId == nil:
// assignment was changed (in spec or in EC2)
status.State = "reassigning"
changed = true
case status.Assignment.PodName != "":
privateIP, podUID, err := r.getPodInfo(ctx, eip.Namespace, spec.Assignment.PodName)
if err != nil {
return ctrl.Result{}, err
}
if status.Assignment.PrivateIPAddress != privateIP || status.PodUID != podUID {
// pod was replaced
// (even if only the pod UID has changed, we can't be sure if the private IP is still attached to the same ENI)
status.State = "reassigning"
changed = true
}
}
if changed {
return ctrl.Result{}, r.Update(ctx, &eip)
}
}
if status.State == "assigning" {
if spec.Assignment == nil {
// assignment was removed before EIP was actually assigned
status.State = "allocated"
return ctrl.Result{}, r.Update(ctx, &eip)
}
}
if status.State == "assigning" || status.State == "reassigning" {
if spec.Assignment != nil {
if spec.Assignment.PodName != "" || spec.Assignment.ENI != "" || spec.Assignment.PrivateIPAddress != "" {
return ctrl.Result{}, r.assignEIP(ctx, &eip, log)
}
}
}
if status.State == "unassigning" {
return ctrl.Result{}, r.unassignEIP(ctx, &eip, log)
}
} else {
// EIP object is being deleted
if containsString(eip.ObjectMeta.Finalizers, finalizerName) {
if status.State == "assigned" || status.State == "reassigning" {
status.State = "unassigning"
return ctrl.Result{}, r.Update(ctx, &eip)
}
if status.State == "unassigning" {
return ctrl.Result{}, r.unassignEIP(ctx, &eip, log)
}
if status.State == "allocated" {
status.State = "releasing"
return ctrl.Result{}, r.Update(ctx, &eip)
}
if status.State == "releasing" {
if err := r.releaseEIP(ctx, &eip, log); err != nil {
return ctrl.Result{}, err
}
}
// remove finalizer, allow k8s to remove the resource
eip.ObjectMeta.Finalizers = removeString(eip.ObjectMeta.Finalizers, finalizerName)
return ctrl.Result{}, r.Update(ctx, &eip)
}
}
return ctrl.Result{}, nil
}
func (r *EIPReconciler) allocateEIP(ctx context.Context, eip *awsv1alpha1.EIP, log logr.Logger) error {
log.Info("allocating")
input := &ec2.AllocateAddressInput{
Domain: aws.String("vpc"),
}
if eip.Spec.PublicIPAddress != "" {
input.Address = aws.String(eip.Spec.PublicIPAddress)
} else if eip.Spec.PublicIPv4Pool != "" {
input.PublicIpv4Pool = aws.String(eip.Spec.PublicIPv4Pool)
}
if resp, err := r.EC2.AllocateAddressWithContext(ctx, input); err != nil {
return err
} else {
eip.Status.State = "allocated"
eip.Status.AllocationId = aws.StringValue(resp.AllocationId)
eip.Status.PublicIPAddress = aws.StringValue(resp.PublicIp)
r.Log.Info("allocated", "allocationId", eip.Status.AllocationId)
if err := r.Update(ctx, eip); err != nil {
return err
}
}
return r.reconcileTags(ctx, eip, []*ec2.Tag{})
}
func (r *EIPReconciler) reconcileTags(ctx context.Context, eip *awsv1alpha1.EIP, existingTags []*ec2.Tag) error {
if eip.Spec.Tags == nil {
return nil
}
resources := []*string{aws.String(eip.Status.AllocationId)}
var tagsToCreate []*ec2.Tag
for k, v := range *eip.Spec.Tags {
create := true
for _, tag := range existingTags {
if aws.StringValue(tag.Key) == k && aws.StringValue(tag.Value) == v {
create = false
break
}
}
if create {
tagsToCreate = append(tagsToCreate, &ec2.Tag{Key: aws.String(k), Value: aws.String(v)})
}
}
if len(tagsToCreate) > 0 {
if _, err := r.EC2.CreateTagsWithContext(ctx, &ec2.CreateTagsInput{
Resources: resources,
Tags: tagsToCreate,
}); err != nil {
return err
}
}
var tagsToRemove []*ec2.Tag
for _, tag := range existingTags {
if _, ok := (*eip.Spec.Tags)[aws.StringValue(tag.Key)]; !ok {
tagsToRemove = append(tagsToRemove, tag)
}
}
if len(tagsToRemove) > 0 {
_, err := r.EC2.DeleteTagsWithContext(ctx, &ec2.DeleteTagsInput{
Resources: resources,
Tags: tagsToRemove,
})
return err
}
return nil
}
func (r *EIPReconciler) releaseEIP(ctx context.Context, eip *awsv1alpha1.EIP, log logr.Logger) error {
log.Info("releasing")
if _, err := r.EC2.ReleaseAddressWithContext(ctx, &ec2.ReleaseAddressInput{
AllocationId: aws.String(eip.Status.AllocationId),
}); err != nil {
if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "InvalidAllocationID.NotFound" {
log.Info("allocation ID not found; assuming EIP already released", "allocationId", eip.Status.AllocationId)
} else {
return err
}
}
log.Info("released")
return nil
}
func (r *EIPReconciler) getPodInfo(ctx context.Context, namespace, podName string) (string, types.UID, error) {
pod := &corev1.Pod{}
if err := r.Client.Get(ctx, client.ObjectKey{
Namespace: namespace,
Name: podName,
}, pod); err != nil {
return "", types.UID(""), err
}
return pod.Status.PodIP, pod.UID, nil
}
func (r *EIPReconciler) findENI(ctx context.Context, privateIP string) (string, error) {
if resp, err := r.EC2.DescribeNetworkInterfacesWithContext(ctx, &ec2.DescribeNetworkInterfacesInput{
Filters: []*ec2.Filter{
&ec2.Filter{
Name: aws.String("addresses.private-ip-address"),
Values: []*string{
aws.String(privateIP),
},
},
},
}); err != nil {
return "", err
} else {
if len(resp.NetworkInterfaces) == 0 {
return "", errors.New("No ENI with private IP of pod found")
}
return aws.StringValue(resp.NetworkInterfaces[0].NetworkInterfaceId), nil
}
}
func (r *EIPReconciler) getAssignmentTarget(ctx context.Context, eip *awsv1alpha1.EIP) (string, string, types.UID, error) {
modes := 0
if eip.Spec.Assignment.PodName != "" {
modes++
}
if eip.Spec.Assignment.ENI != "" {
modes++
}
if eip.Spec.Assignment.PrivateIPAddress != "" {
modes++
}
if modes != 1 {
return "", "", types.UID(""), fmt.Errorf("exactly one of podName, eni or privateIPAddress needs to be given in assignment")
}
if eip.Spec.Assignment.ENI != "" {
var eni awsv1alpha1.ENI
if err := r.Get(ctx, types.NamespacedName{
Namespace: eip.Namespace,
Name: eip.Spec.Assignment.ENI,
}, &eni); err != nil {
return "", "", types.UID(""), err
}
index := eip.Spec.Assignment.ENIPrivateIPAddressIndex
if index >= len(eni.Status.PrivateIPAddresses) {
return "", "", types.UID(""), fmt.Errorf("eniPrivateIPAddressIndex %d is out of range (ENI has %d addresses)", index, len(eni.Status.PrivateIPAddresses))
}
return eni.Status.NetworkInterfaceID, eni.Status.PrivateIPAddresses[index], "", nil
}
privateIP := eip.Spec.Assignment.PrivateIPAddress
podUID := types.UID("")
if privateIP == "" {
ip, uid, err := r.getPodInfo(ctx, eip.Namespace, eip.Spec.Assignment.PodName)
if err != nil {
return "", "", types.UID(""), err
}
if ip == "" {
return "", "", types.UID(""), errors.New("Pod has no IP")
}
privateIP = ip
podUID = uid
}
eni, err := r.findENI(ctx, privateIP)
if err != nil {
return "", "", types.UID(""), err
}
return eni, privateIP, podUID, nil
}
func (r *EIPReconciler) assignEIP(ctx context.Context, eip *awsv1alpha1.EIP, log logr.Logger) error {
eni, privateIP, podUID, err := r.getAssignmentTarget(ctx, eip)
if err != nil {
return err
}
log.Info("assigning", "podName", eip.Spec.Assignment.PodName, "privateIP", privateIP, "eni", eni)
resp, err := r.EC2.AssociateAddressWithContext(ctx, &ec2.AssociateAddressInput{
AllowReassociation: aws.Bool(eip.Status.State == "reassigning"),
AllocationId: aws.String(eip.Status.AllocationId),
NetworkInterfaceId: aws.String(eni),
PrivateIpAddress: aws.String(privateIP),
})
if err != nil {
return err
}
log.Info("assigned")
eip.Status.State = "assigned"
eip.Status.AssociationId = aws.StringValue(resp.AssociationId)
eip.Status.Assignment = eip.Spec.Assignment
eip.Status.Assignment.PrivateIPAddress = privateIP
eip.Status.PodUID = podUID
if err := r.Update(ctx, eip); err != nil {
return err
}
return nil
}
func (r *EIPReconciler) unassignEIP(ctx context.Context, eip *awsv1alpha1.EIP, log logr.Logger) error {
log.Info("unassigning")
_, err := r.EC2.DisassociateAddressWithContext(ctx, &ec2.DisassociateAddressInput{
AssociationId: aws.String(eip.Status.AssociationId),
})
if err != nil {
if awsErr, ok := err.(awserr.Error); ok && (awsErr.Code() == "InvalidAssociationID.NotFound" || awsErr.Code() == "InvalidNetworkInterfaceID.NotFound") {
log.Info("association ID or network interface ID not found; assuming EIP already disassociated", "associationnId", eip.Status.AssociationId)
} else {
log.Info(awsErr.Code())
return err
}
}
log.Info("unassigned")
eip.Status.State = "allocated"
eip.Status.Assignment = nil
if err := r.Update(ctx, eip); err != nil {
return err
}
return nil
}
func (r *EIPReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&awsv1alpha1.EIP{}).
Complete(r)
}