Add an IPFamily() method to ipallocator

This commit is contained in:
Tim Hockin 2020-11-17 20:41:55 -08:00
parent 89b633d353
commit 5970c4671c
2 changed files with 22 additions and 3 deletions

View File

@ -35,6 +35,7 @@ type Interface interface {
Release(net.IP) error
ForEach(func(net.IP))
CIDR() net.IPNet
IPFamily() api.IPFamily
// For testing
Has(ip net.IP) bool
@ -76,6 +77,8 @@ type Range struct {
base *big.Int
// max is the maximum size of the usable addresses in the range
max int
// family is the IP family of this range
family api.IPFamily
alloc allocator.Interface
}
@ -85,13 +88,16 @@ func NewAllocatorCIDRRange(cidr *net.IPNet, allocatorFactory allocator.Allocator
max := utilnet.RangeSize(cidr)
base := utilnet.BigForIP(cidr.IP)
rangeSpec := cidr.String()
var family api.IPFamily
if utilnet.IsIPv6CIDR(cidr) {
family = api.IPv6Protocol
// Limit the max size, since the allocator keeps a bitmap of that size.
if max > 65536 {
max = 65536
}
} else {
family = api.IPv4Protocol
// Don't use the IPv4 network's broadcast address.
max--
}
@ -101,9 +107,10 @@ func NewAllocatorCIDRRange(cidr *net.IPNet, allocatorFactory allocator.Allocator
max--
r := Range{
net: cidr,
base: base,
max: maximum(0, int(max)),
net: cidr,
base: base,
max: maximum(0, int(max)),
family: family,
}
var err error
r.alloc, err = allocatorFactory(r.max, rangeSpec)
@ -219,6 +226,11 @@ func (r *Range) Has(ip net.IP) bool {
return r.alloc.Has(offset)
}
// IPFamily returns the IP family of this range.
func (r *Range) IPFamily() api.IPFamily {
return r.family
}
// Snapshot saves the current state of the pool.
func (r *Range) Snapshot(dst *api.RangeAllocation) error {
snapshottable, ok := r.alloc.(allocator.Snapshottable)

View File

@ -28,6 +28,7 @@ func TestAllocate(t *testing.T) {
testCases := []struct {
name string
cidr string
family api.IPFamily
free int
released string
outOfRange []string
@ -36,6 +37,7 @@ func TestAllocate(t *testing.T) {
{
name: "IPv4",
cidr: "192.168.1.0/24",
family: api.IPv4Protocol,
free: 254,
released: "192.168.1.5",
outOfRange: []string{
@ -49,6 +51,7 @@ func TestAllocate(t *testing.T) {
{
name: "IPv6",
cidr: "2001:db8:1::/48",
family: api.IPv6Protocol,
free: 65535,
released: "2001:db8:1::5",
outOfRange: []string{
@ -79,6 +82,10 @@ func TestAllocate(t *testing.T) {
t.Errorf("allocator returned a different cidr")
}
if r.IPFamily() != tc.family {
t.Errorf("allocator returned wrong IP family")
}
if f := r.Used(); f != 0 {
t.Errorf("Test %s unexpected used %d", tc.name, f)
}