forked from lyft/cni-ipvlan-vpc-k8s
-
Notifications
You must be signed in to change notification settings - Fork 0
/
freeip.go
48 lines (44 loc) · 1.13 KB
/
freeip.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
package cniipvlanvpck8s
import (
"github.com/lyft/cni-ipvlan-vpc-k8s/aws"
"github.com/lyft/cni-ipvlan-vpc-k8s/nl"
)
// FindFreeIPsAtIndex locates free IP addresses by comparing the assigned list
// from the EC2 metadata service and the currently used addresses
// within netlink. This is inherently somewhat racey - for example
// newly provisioned addresses may not show up immediately in metadata
// and are subject to a few seconds of delay.
func FindFreeIPsAtIndex(index int) ([]*aws.AllocationResult, error) {
freeIps := []*aws.AllocationResult{}
interfaces, err := aws.GetInterfaces()
if err != nil {
return nil, err
}
assigned, err := nl.GetIPs()
if err != nil {
return nil, err
}
for _, intf := range interfaces {
if intf.Number < index {
continue
}
for _, intfIP := range intf.IPv4s {
found := false
for _, assignedIP := range assigned {
if assignedIP.IPNet.IP.Equal(intfIP) {
found = true
break
}
}
if !found {
intfIPCopy := intfIP
// No match, record as free
freeIps = append(freeIps, &aws.AllocationResult{
&intfIPCopy,
intf,
})
}
}
}
return freeIps, nil
}