forked from lyft/cni-ipvlan-vpc-k8s
-
Notifications
You must be signed in to change notification settings - Fork 0
/
interface.go
293 lines (243 loc) · 8.35 KB
/
interface.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
package aws
import (
"fmt"
"net"
"os"
"sort"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/lyft/cni-ipvlan-vpc-k8s/nl"
)
var (
interfacePollWaitTime = 1000 * time.Millisecond
interfaceSettleTime = 30 * time.Second
interfaceDetachWaitTime = 1 * time.Second
interfacePostDetachSettleTime = 5 * time.Second
interfaceDetachAttempts = 20 // interfaceDetachAttempts * interfaceDetachWaitTime = total wait time
)
// InterfaceClient provides methods for allocating and deallocating interfaces
type InterfaceClient interface {
NewInterfaceOnSubnetAtIndex(index int, secGrps []string, subnet Subnet) (*Interface, error)
NewInterface(secGrps []string, requiredTags map[string]string) (*Interface, error)
RemoveInterface(interfaceIDs []string) error
}
type interfaceClient struct {
aws *awsclient
subnet SubnetsClient
}
// NewInterfaceOnSubnetAtIndex creates a new Interface with a specified subnet and index
func (c *interfaceClient) NewInterfaceOnSubnetAtIndex(index int, secGrps []string, subnet Subnet) (*Interface, error) {
client, err := c.aws.newEC2()
if err != nil {
return nil, err
}
idDoc, err := c.aws.getIDDoc()
if err != nil {
return nil, err
}
createReq := &ec2.CreateNetworkInterfaceInput{}
createReq.SetDescription(fmt.Sprintf("CNI-ENI %v", idDoc.InstanceID))
secGrpsPtr := []*string{}
for _, grp := range secGrps {
newgrp := grp // Need to copy
secGrpsPtr = append(secGrpsPtr, &newgrp)
}
createReq.SetGroups(secGrpsPtr)
createReq.SetSubnetId(subnet.ID)
resp, err := client.CreateNetworkInterface(createReq)
if err != nil {
return nil, err
}
// resp.NetworkInterface.NetworkInterfaceId
attachReq := &ec2.AttachNetworkInterfaceInput{}
attachReq.SetDeviceIndex(int64(index))
attachReq.SetInstanceId(idDoc.InstanceID)
attachReq.SetNetworkInterfaceId(*resp.NetworkInterface.NetworkInterfaceId)
attachResp, err := client.AttachNetworkInterface(attachReq)
if err != nil {
// We attempt to remove the interface we just made due to attachment failure
delReq := &ec2.DeleteNetworkInterfaceInput{}
delReq.SetNetworkInterfaceId(*resp.NetworkInterface.NetworkInterfaceId)
_, delErr := client.DeleteNetworkInterface(delReq)
if delErr != nil {
return nil, delErr
}
return nil, err
}
// We have an attachment ID from the last API, which lets us mark the
// interface as delete on termination
changes := &ec2.NetworkInterfaceAttachmentChanges{}
changes.SetAttachmentId(*attachResp.AttachmentId)
changes.SetDeleteOnTermination(true)
modifyReq := &ec2.ModifyNetworkInterfaceAttributeInput{}
modifyReq.SetAttachment(changes)
modifyReq.SetNetworkInterfaceId(*resp.NetworkInterface.NetworkInterfaceId)
_, err = client.ModifyNetworkInterfaceAttribute(modifyReq)
if err != nil {
// Continue anyway
fmt.Fprintf(os.Stderr,
"Unable to mark interface for deletion due to %v",
err)
}
for start := time.Now(); time.Since(start) <= interfaceSettleTime; time.Sleep(interfacePollWaitTime) {
newInterfaces, err := c.aws.GetInterfaces()
if err != nil {
// The metadata server is inconsistent - for example, not
// all of the nodes under the interface will populate at once
// and instead return a 404 error. We just swallow this error here and
// continue on.
continue
}
for _, intf := range newInterfaces {
if intf.Mac == *resp.NetworkInterface.MacAddress {
if privateIPAddr := net.ParseIP(*resp.NetworkInterface.PrivateIpAddress); privateIPAddr != nil {
// New IP. Timestamp the addition as a free IP.
registry := &Registry{}
registry.TrackIP(privateIPAddr)
}
configureInterface(&intf)
return &intf, nil
}
}
}
return nil, fmt.Errorf("interface did not attach in time")
}
// Fire and forget method to configure an interface
func configureInterface(intf *Interface) {
// Found a match, going to try to make sure the interface is up
err := nl.UpInterfacePoll(intf.LocalName())
if err != nil {
fmt.Fprintf(os.Stderr,
"Interface %v could not be enabled. Networking will be broken.\n",
intf.LocalName())
return
}
baseMtu, err := nl.GetMtu("eth0")
if err != nil || baseMtu < 1000 || baseMtu > 9001 {
return
}
nl.SetMtu(intf.LocalName(), baseMtu)
}
// NewInterface creates an Interface based on specified parameters
func (c *interfaceClient) NewInterface(secGrps []string, requiredTags map[string]string) (*Interface, error) {
subnets, err := c.subnet.GetSubnetsForInstance()
if err != nil {
return nil, err
}
existingInterfaces, err := c.aws.GetInterfaces()
if err != nil {
return nil, err
}
limits := c.aws.ENILimits()
if len(existingInterfaces) >= limits.Adapters {
return nil, fmt.Errorf("too many adapters on this instance already")
}
var availableSubnets []Subnet
OUTER:
for _, newSubnet := range subnets {
// Match incoming tags
for tagKey, tagValue := range requiredTags {
value, ok := newSubnet.Tags[tagKey]
// Skip untagged subnets and ones not matching
// the required tag
if !ok || (ok && value != tagValue) {
continue OUTER
}
}
availableSubnets = append(availableSubnets, newSubnet)
}
// assign new interfaces to subnets with most available addresses
sort.Sort(SubnetsByAvailableAddressCount(availableSubnets))
if len(availableSubnets) <= 0 {
return nil, fmt.Errorf("No subnets are available which haven't already been used")
}
return c.NewInterfaceOnSubnetAtIndex(len(existingInterfaces), secGrps, availableSubnets[0])
}
// RemoveInterface gracefull shutdown and removal of interfaces
// Simply detach the interface, wait for it to come down and then
// removes.
func (c *awsclient) RemoveInterface(interfaceIDs []string) error {
client, err := c.newEC2()
if err != nil {
return err
}
for _, interfaceID := range interfaceIDs {
// TODO: check if there is any other interface on this namespace?
// We need the interface AttachmentId to detach
interfaceDescription, err := c.describeNetworkInterface(interfaceID)
if err != nil {
return err
}
detachInterfaceInput := &ec2.DetachNetworkInterfaceInput{
AttachmentId: interfaceDescription.Attachment.AttachmentId,
DryRun: aws.Bool(false),
Force: aws.Bool(false),
}
// Detach the networkinterface
_, err = client.DetachNetworkInterface(detachInterfaceInput)
if err != nil {
fmt.Printf("Error occurced when trying to detach %v interface, use --force to override this check", interfaceID)
return err
}
// Wait for the interface to be removed
if err := c.waitUtilInterfaceDetaches(interfaceID); err != nil {
return err
}
// Even after the interface detaches, you cannot delete right away
time.Sleep(interfacePostDetachSettleTime)
// Now we can safely remove the interface
if err := c.deleteInterface(interfaceID); err != nil {
return err
}
}
return nil
}
func (c *awsclient) deleteInterface(interfaceID string) error {
client, err := c.newEC2()
if err != nil {
return err
}
deleteInterfaceInput := &ec2.DeleteNetworkInterfaceInput{
NetworkInterfaceId: aws.String(interfaceID),
}
_, err = client.DeleteNetworkInterface(deleteInterfaceInput)
return err
}
func (c *awsclient) waitUtilInterfaceDetaches(interfaceID string) error {
var interfaceDescription *ec2.NetworkInterface
interfaceDescription, err := c.describeNetworkInterface(interfaceID)
if err != nil {
return err
}
// Once the ENI is in available state, we are ok to delete it
for attempt := 0; *interfaceDescription.Status != "available"; attempt++ {
interfaceDescription, err = c.describeNetworkInterface(interfaceID)
if err != nil {
return err
}
if attempt == interfaceDetachAttempts {
return fmt.Errorf("Interface %v has not detached yet, use --force to override this check", interfaceID)
}
time.Sleep(interfaceDetachWaitTime)
}
return nil
}
func (c *awsclient) describeNetworkInterface(interfaceID string) (*ec2.NetworkInterface, error) {
client, err := c.newEC2()
if err != nil {
return nil, err
}
interfaceIDList := []string{interfaceID}
describeInterfaceInput := &ec2.DescribeNetworkInterfacesInput{
NetworkInterfaceIds: aws.StringSlice(interfaceIDList),
}
interfaceDescribeOutput, err := client.DescribeNetworkInterfaces(describeInterfaceInput)
if err != nil {
return nil, err
}
if len(interfaceDescribeOutput.NetworkInterfaces) <= 0 {
return nil, fmt.Errorf("Cannot describe interface, it might not exist")
}
return interfaceDescribeOutput.NetworkInterfaces[0], nil
}