/
node.go
442 lines (375 loc) · 13.5 KB
/
node.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
// Copyright 2021 Authors of Cilium
//
// 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 eni
import (
"context"
"fmt"
"github.com/cilium/cilium/pkg/alibabacloud/eni/limits"
eniTypes "github.com/cilium/cilium/pkg/alibabacloud/eni/types"
"github.com/cilium/cilium/pkg/alibabacloud/utils"
"github.com/cilium/cilium/pkg/defaults"
"github.com/cilium/cilium/pkg/ipam"
ipamTypes "github.com/cilium/cilium/pkg/ipam/types"
v2 "github.com/cilium/cilium/pkg/k8s/apis/cilium.io/v2"
"github.com/cilium/cilium/pkg/lock"
"github.com/cilium/cilium/pkg/math"
"github.com/sirupsen/logrus"
)
// The following error constants represent the error conditions for
// CreateInterface without additional context embedded in order to make them
// usable for metrics accounting purposes.
const (
errUnableToDetermineLimits = "unable to determine limits"
errUnableToGetSecurityGroups = "unable to get security groups"
errUnableToCreateENI = "unable to create ENI"
errUnableToAttachENI = "unable to attach ENI"
errUnableToFindSubnet = "unable to find matching subnet"
)
const (
maxENIIPCreate = 10
maxENIPerNode = 50
)
type Node struct {
// node contains the general purpose fields of a node
node *ipam.Node
// mutex protects members below this field
mutex lock.RWMutex
// enis is the list of ENIs attached to the node indexed by ENI ID.
// Protected by Node.mutex.
enis map[string]eniTypes.ENI
// k8sObj is the CiliumNode custom resource representing the node
k8sObj *v2.CiliumNode
// manager is the ecs node manager responsible for this node
manager *InstancesManager
// instanceID of the node
instanceID string
}
// UpdatedNode is called when an update to the CiliumNode is received.
func (n *Node) UpdatedNode(obj *v2.CiliumNode) {
n.mutex.Lock()
defer n.mutex.Unlock()
n.k8sObj = obj
}
// PopulateStatusFields fills in the status field of the CiliumNode custom
// resource with ENI specific information
func (n *Node) PopulateStatusFields(resource *v2.CiliumNode) {
resource.Status.AlibabaCloud.ENIs = map[string]eniTypes.ENI{}
n.manager.ForeachInstance(n.node.InstanceID(),
func(instanceID, interfaceID string, rev ipamTypes.InterfaceRevision) error {
e, ok := rev.Resource.(*eniTypes.ENI)
if ok {
resource.Status.AlibabaCloud.ENIs[interfaceID] = *e.DeepCopy()
}
return nil
})
return
}
// CreateInterface creates an additional interface with the instance and
// attaches it to the instance as specified by the CiliumNode. neededAddresses
// of secondary IPs are assigned to the interface up to the maximum number of
// addresses as allowed by the instance.
func (n *Node) CreateInterface(ctx context.Context, allocation *ipam.AllocationAction, scopedLog *logrus.Entry) (int, string, error) {
l, limitsAvailable := n.getLimits()
if !limitsAvailable {
return 0, errUnableToDetermineLimits, fmt.Errorf(errUnableToDetermineLimits)
}
n.mutex.RLock()
resource := *n.k8sObj
n.mutex.RUnlock()
// Must allocate secondary ENI IPs as needed, up to ENI instance limit
toAllocate := math.IntMin(allocation.MaxIPsToAllocate, l.IPv4)
toAllocate = math.IntMin(maxENIIPCreate, toAllocate) // in first alloc no more than 10
// Validate whether request has already been fulfilled in the meantime
if toAllocate == 0 {
return 0, "", nil
}
bestSubnet := n.manager.FindOneVSwitch(resource.Spec.AlibabaCloud.VPCID, resource.Spec.AlibabaCloud.AvailabilityZone,
toAllocate, resource.Spec.AlibabaCloud.VSwitchTags)
if bestSubnet == nil {
return 0,
errUnableToFindSubnet,
fmt.Errorf(
"no matching vSwitch available for interface creation (VPC=%s AZ=%s SubnetTags=%s",
resource.Spec.AlibabaCloud.VPCID,
resource.Spec.AlibabaCloud.AvailabilityZone,
resource.Spec.AlibabaCloud.VSwitchTags,
)
}
securityGroupIDs, err := n.getSecurityGroupIDs(ctx, resource.Spec.AlibabaCloud)
if err != nil {
return 0,
errUnableToGetSecurityGroups,
fmt.Errorf("%s %s", errUnableToGetSecurityGroups, err)
}
scopedLog = scopedLog.WithFields(logrus.Fields{
"securityGroupIDs": securityGroupIDs,
"vSwitchID": bestSubnet.ID,
"toAllocate": toAllocate,
})
scopedLog.Info("No more IPs available, creating new ENI")
instanceID := n.node.InstanceID()
n.mutex.Lock()
defer n.mutex.Unlock()
index, err := n.allocENIIndex()
if err != nil {
scopedLog.WithField("instanceID", instanceID).Error(err)
return 0, "", err
}
eniID, eni, err := n.manager.api.CreateNetworkInterface(ctx, toAllocate-1, bestSubnet.ID, securityGroupIDs,
utils.FillTagWithENIIndex(map[string]string{}, index))
if err != nil {
return 0, errUnableToCreateENI, fmt.Errorf("%s %s", errUnableToCreateENI, err)
}
scopedLog = scopedLog.WithField(fieldENIID, eniID)
scopedLog.Info("Created new ENI")
err = n.manager.api.AttachNetworkInterface(ctx, instanceID, eniID)
if err != nil {
return 0, errUnableToAttachENI, fmt.Errorf("%s %s", errUnableToAttachENI, err)
}
_, err = n.manager.api.WaitENIAttached(ctx, eniID)
if err != nil {
err2 := n.manager.api.DeleteNetworkInterface(ctx, eniID)
if err2 != nil {
scopedLog.Errorf("Failed to release ENI %s", err2.Error())
}
return 0, errUnableToAttachENI, fmt.Errorf("%s %s", errUnableToAttachENI, err)
}
n.enis[eniID] = *eni
scopedLog.Info("Attached ENI to instance")
// Add the information of the created ENI to the instances manager
n.manager.UpdateENI(instanceID, eni)
return toAllocate, "", nil
}
// ResyncInterfacesAndIPs is called to retrieve and ENIs and IPs as known to
// the AlibabaCloud API and return them
func (n *Node) ResyncInterfacesAndIPs(ctx context.Context, scopedLog *logrus.Entry) (ipamTypes.AllocationMap, error) {
instanceID := n.node.InstanceID()
available := ipamTypes.AllocationMap{}
n.mutex.Lock()
defer n.mutex.Unlock()
n.enis = map[string]eniTypes.ENI{}
n.manager.ForeachInstance(instanceID,
func(instanceID, interfaceID string, rev ipamTypes.InterfaceRevision) error {
e, ok := rev.Resource.(*eniTypes.ENI)
if !ok {
return nil
}
n.enis[e.NetworkInterfaceID] = *e
if e.Type == eniTypes.ENITypePrimary {
return nil
}
for _, ip := range e.PrivateIPSets {
available[ip.PrivateIpAddress] = ipamTypes.AllocationIP{Resource: e.NetworkInterfaceID}
}
return nil
})
enis := len(n.enis)
// An ECS instance has at least one ENI attached, no ENI found implies instance not found.
if enis == 0 {
scopedLog.Warning("Instance not found! Please delete corresponding ciliumnode if instance has already been deleted.")
return nil, fmt.Errorf("unable to retrieve ENIs")
}
return available, nil
}
// PrepareIPAllocation returns the number of ENI IPs and interfaces that can be
// allocated/created.
func (n *Node) PrepareIPAllocation(scopedLog *logrus.Entry) (*ipam.AllocationAction, error) {
l, limitsAvailable := n.getLimits()
if !limitsAvailable {
return nil, fmt.Errorf("Unable to determine limits")
}
a := &ipam.AllocationAction{}
n.mutex.RLock()
defer n.mutex.RUnlock()
for key, e := range n.enis {
if e.Type != eniTypes.ENITypeSecondary {
continue
}
scopedLog.WithFields(logrus.Fields{
fieldENIID: e.NetworkInterfaceID,
"ipv4Limit": l.IPv4,
"allocated": len(e.PrivateIPSets),
}).Debug("Considering ENI for allocation")
availableOnENI := math.IntMax(l.IPv4-len(e.PrivateIPSets), 0)
if availableOnENI <= 0 {
continue
} else {
a.AvailableInterfaces++
}
scopedLog.WithFields(logrus.Fields{
fieldENIID: e.NetworkInterfaceID,
"availableOnENI": availableOnENI,
}).Debug("ENI has IPs available")
if subnet := n.manager.GetVSwitch(e.VSwitch.VSwitchID); subnet != nil {
if subnet.AvailableAddresses > 0 && a.InterfaceID == "" {
scopedLog.WithFields(logrus.Fields{
"vSwitchID": e.VSwitch.VSwitchID,
"availableAddresses": subnet.AvailableAddresses,
}).Debug("Subnet has IPs available")
a.InterfaceID = key
a.PoolID = ipamTypes.PoolID(subnet.ID)
a.AvailableForAllocation = math.IntMin(subnet.AvailableAddresses, availableOnENI)
}
}
}
a.AvailableInterfaces = l.Adapters - len(n.enis) + a.AvailableInterfaces
return a, nil
}
// AllocateIPs performs the ENI allocation operation
func (n *Node) AllocateIPs(ctx context.Context, a *ipam.AllocationAction) error {
_, err := n.manager.api.AssignPrivateIPAddresses(ctx, a.InterfaceID, a.AvailableForAllocation)
return err
}
// PrepareIPRelease prepares the release of ENI IPs.
func (n *Node) PrepareIPRelease(excessIPs int, scopedLog *logrus.Entry) *ipam.ReleaseAction {
r := &ipam.ReleaseAction{}
n.mutex.Lock()
defer n.mutex.Unlock()
// Iterate over ENIs on this node, select the ENI with the most
// addresses available for release
for key, e := range n.enis {
if e.Type != eniTypes.ENITypeSecondary {
continue
}
scopedLog.WithFields(logrus.Fields{
fieldENIID: e.NetworkInterfaceID,
"numAddresses": len(e.PrivateIPSets),
}).Debug("Considering ENI for IP release")
// Count free IP addresses on this ENI
ipsOnENI := n.k8sObj.Status.AlibabaCloud.ENIs[e.NetworkInterfaceID].PrivateIPSets
freeIpsOnENI := []string{}
for _, ip := range ipsOnENI {
// exclude primary IPs
if ip.Primary {
continue
}
_, ipUsed := n.k8sObj.Status.IPAM.Used[ip.PrivateIpAddress]
if !ipUsed {
freeIpsOnENI = append(freeIpsOnENI, ip.PrivateIpAddress)
}
}
freeOnENICount := len(freeIpsOnENI)
if freeOnENICount <= 0 {
continue
}
scopedLog.WithFields(logrus.Fields{
fieldENIID: e.NetworkInterfaceID,
"excessIPs": excessIPs,
"freeOnENICount": freeOnENICount,
}).Debug("ENI has unused IPs that can be released")
maxReleaseOnENI := math.IntMin(freeOnENICount, excessIPs)
r.InterfaceID = key
r.PoolID = ipamTypes.PoolID(e.VPC.VPCID)
r.IPsToRelease = freeIpsOnENI[:maxReleaseOnENI]
}
return r
}
// ReleaseIPs performs the ENI IP release operation
func (n *Node) ReleaseIPs(ctx context.Context, r *ipam.ReleaseAction) error {
return n.manager.api.UnassignPrivateIPAddresses(ctx, r.InterfaceID, r.IPsToRelease)
}
// GetMaximumAllocatableIPv4 returns the maximum amount of IPv4 addresses
// that can be allocated to the instance
func (n *Node) GetMaximumAllocatableIPv4() int {
n.mutex.RLock()
defer n.mutex.RUnlock()
// Retrieve l for the instance type
l, limitsAvailable := n.getLimitsLocked()
if !limitsAvailable {
return 0
}
// Return the maximum amount of IP addresses allocatable on the instance
// reserve Primary eni
return (l.Adapters - 1) * l.IPv4
}
// GetMinimumAllocatableIPv4 returns the minimum amount of IPv4 addresses that
// must be allocated to the instance.
func (n *Node) GetMinimumAllocatableIPv4() int {
return defaults.IPAMPreAllocation
}
func (n *Node) loggerLocked() *logrus.Entry {
if n == nil || n.instanceID == "" {
return log
}
return log.WithField("instanceID", n.instanceID)
}
// getLimits returns the interface and IP limits of this node
func (n *Node) getLimits() (ipamTypes.Limits, bool) {
n.mutex.RLock()
l, b := n.getLimitsLocked()
n.mutex.RUnlock()
return l, b
}
// getLimitsLocked is the same function as getLimits, but assumes the n.mutex
// is read locked.
func (n *Node) getLimitsLocked() (ipamTypes.Limits, bool) {
return limits.Get(n.k8sObj.Spec.AlibabaCloud.InstanceType)
}
func (n *Node) getSecurityGroupIDs(ctx context.Context, eniSpec eniTypes.Spec) ([]string, error) {
// ENI must have at least one security group
// 1. use security group defined by user
// 2. use security group used by primary ENI (eth0)
if len(eniSpec.SecurityGroups) > 0 {
return eniSpec.SecurityGroups, nil
}
if len(eniSpec.SecurityGroupTags) > 0 {
securityGroups := n.manager.FindSecurityGroupByTags(eniSpec.VPCID, eniSpec.SecurityGroupTags)
if len(securityGroups) == 0 {
n.loggerLocked().WithFields(logrus.Fields{
"vpcID": eniSpec.VPCID,
"tags": eniSpec.SecurityGroupTags,
}).Warn("No security groups match required VPC ID and tags, using primary ENI's security groups")
} else {
groups := make([]string, 0, len(securityGroups))
for _, secGroup := range securityGroups {
groups = append(groups, secGroup.ID)
}
return groups, nil
}
}
var securityGroups []string
n.manager.ForeachInstance(n.node.InstanceID(),
func(instanceID, interfaceID string, rev ipamTypes.InterfaceRevision) error {
e, ok := rev.Resource.(*eniTypes.ENI)
if ok && e.Type == eniTypes.ENITypePrimary {
securityGroups = append(securityGroups, e.SecurityGroupIDs...)
}
return nil
})
if len(securityGroups) <= 0 {
return nil, fmt.Errorf("failed to get security group ids")
}
return securityGroups, nil
}
// allocENIIndex will alloc an monotonically increased index for each ENI on this instance.
// The index generated the first time this ENI is created, and stored in ENI.Tags.
func (n *Node) allocENIIndex() (int, error) {
// alloc index for each created ENI
used := make([]bool, maxENIPerNode)
for _, v := range n.enis {
index := utils.GetENIIndexFromTags(v.Tags)
if index > maxENIPerNode || index < 0 {
return 0, fmt.Errorf("ENI index(%d) is out of range", index)
}
used[index] = true
}
// ECS has at least 1 ENI, 0 is reserved for eth0
i := 1
for ; i < maxENIPerNode; i++ {
if !used[i] {
break
}
}
return i, nil
}