Commit 1de1cf25 authored by Apollon Oikonomopoulos's avatar Apollon Oikonomopoulos Committed by Iustin Pop
Browse files

Introduce new module for IP pool management

Add new library module lib/
Introduce new class: AddressPool.

AddressPool implements all operations needed for managing IPs inside
the IP pool.

Given a Network config object (nobj), the class:

 * initializes the corresponding IP pool object via
 * obtains the corresponding IP pool object via
 * manipulates IPs inside the pool
Signed-off-by: default avatarApollon Oikonomopoulos <>
Signed-off-by: default avatarDimitris Aragiorgis <>
Reviewed-by: default avatarIustin Pop <>
parent eaa4c57c
......@@ -123,6 +123,12 @@ class ConfigVersionMismatch(ConfigurationError):
class AddressPoolError(GenericError):
"""Errors related to IP address pools.
class ReservationError(GenericError):
"""Errors reserving a resource.
# Copyright (C) 2011 Google Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
"""Ip address pool management functions.
import ipaddr
from bitarray import bitarray
from ganeti import errors
class AddressPool(object):
"""Address pool class, wrapping an objects.Network object
This class provides methods to manipulate address pools, backed by
L{objects.Network} objects.
def __init__(self, network):
"""Initialize a new IPv4 address pool from an objects.Network object
@type network: L{objects.Network}
@param network: the network object from which the pool will be generated
""" = None
self.gateway = None
self.network6 = None
self.gateway6 = None = network = ipaddr.IPNetwork(
self.gateway = ipaddr.IPAddress(
self.network6 = ipaddr.IPv6Network(
self.gateway6 = ipaddr.IPv6Address(
self.reservations = bitarray(
self.reservations = bitarray(
self.ext_reservations = bitarray(
self.ext_reservations = bitarray(
assert len(self.reservations) ==
assert len(self.ext_reservations) ==
def _Contains(self, address):
if address is None:
return False
addr = ipaddr.IPAddress(address)
return addr in
def _GetAddrIndex(self, address):
addr = ipaddr.IPAddress(address)
if not addr in
raise errors.AddressPoolError("%s does not contain %s" %
(, addr))
return int(addr) - int(
def _Update(self):
"""Write address pools back to the network object""" = self.ext_reservations.to01() = self.reservations.to01()
def _Mark(self, address, value=True, external=False):
idx = self._GetAddrIndex(address)
if external:
self.ext_reservations[idx] = value
self.reservations[idx] = value
def _GetSize(self):
return 2**(32 -
def all_reservations(self):
"""Return a combined map of internal + external reservations."""
return (self.reservations | self.ext_reservations)
def Validate(self):
assert == 4
assert len(self.reservations) == self._GetSize()
assert len(self.ext_reservations) == self._GetSize()
assert not (self.reservations & self.ext_reservations).any()
if self.gateway is not None:
assert == self.gateway.version
assert self.gateway in
if self.network6 and self.gateway6:
assert self.gateway6 in self.network6
return True
def IsFull(self):
"""Check whether the network is full"""
return self.all_reservations.all()
def GetReservedCount(self):
"""Get the count of reserved addresses"""
return self.all_reservations.count(True)
def GetFreeCount(self):
"""Get the count of unused addresses"""
return self.all_reservations.count(False)
def GetMap(self):
"""Return a textual representation of the network's occupation status."""
return self.all_reservations.to01().replace("1", "X").replace("0", ".")
def IsReserved(self, address):
"""Checks if the given IP is reserved"""
idx = self._GetAddrIndex(address)
return self.all_reservations[idx]
def Reserve(self, address, external=False):
"""Mark an address as used."""
if self.IsReserved(address):
raise errors.AddressPoolError("%s is already reserved" % address)
self._Mark(address, external=external)
def Release(self, address, external=False):
"""Release a given address reservation."""
self._Mark(address, value=False, external=external)
def GetFreeAddress(self):
"""Returns the first available address."""
if self.IsFull():
raise errors.AddressPoolError("%s is full" %
idx = self.all_reservations.index(False)
address = str([idx])
return address
def GenerateFree(self):
"""A generator for free addresses."""
def _iter_free():
for idx in"0", 64):
yield str([idx])
return _iter_free().next
def GetExternalReservations(self):
"""Returns a list of all externally reserved addresses"""
idxs ="1")
return [str([idx]) for idx in idxs]
def InitializeNetwork(cls, net):
"""Initialize an L{objects.Network} object
Reserve the network, broadcast and gateway IPs
obj = cls(net)
for ip in [[0],[-1]]:
obj.Reserve(ip, external=True)
if is not None:
obj.Reserve(, external=True)
return obj
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment