Merge branch 'stable-2.9' into stable-2.10
[ganeti-local] / lib / network.py
index 31037b9..8059e31 100644 (file)
@@ -1,7 +1,7 @@
 #
 #
 
-# Copyright (C) 2011 Google Inc.
+# Copyright (C) 2011, 2012 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
@@ -19,7 +19,7 @@
 # 02110-1301, USA.
 
 
-"""Ip address pool management functions.
+"""IP address pool management functions.
 
 """
 
@@ -30,15 +30,33 @@ from bitarray import bitarray
 from ganeti import errors
 
 
+def _ComputeIpv4NumHosts(network_size):
+  """Derives the number of hosts in an IPv4 network from the size.
+
+  """
+  return 2 ** (32 - network_size)
+
+
+IPV4_NETWORK_MIN_SIZE = 30
+# FIXME: This limit is for performance reasons. Remove when refactoring
+# for performance tuning was successful.
+IPV4_NETWORK_MAX_SIZE = 16
+IPV4_NETWORK_MIN_NUM_HOSTS = _ComputeIpv4NumHosts(IPV4_NETWORK_MIN_SIZE)
+IPV4_NETWORK_MAX_NUM_HOSTS = _ComputeIpv4NumHosts(IPV4_NETWORK_MAX_SIZE)
+
+
 class AddressPool(object):
-  """Address pool class, wrapping an objects.Network object
+  """Address pool class, wrapping an C{objects.Network} object.
 
   This class provides methods to manipulate address pools, backed by
   L{objects.Network} objects.
 
   """
+  FREE = bitarray("0")
+  RESERVED = bitarray("1")
+
   def __init__(self, network):
-    """Initialize a new IPv4 address pool from an objects.Network object
+    """Initialize a new IPv4 address pool from an L{objects.Network} object.
 
     @type network: L{objects.Network}
     @param network: the network object from which the pool will be generated
@@ -52,6 +70,19 @@ class AddressPool(object):
     self.net = network
 
     self.network = ipaddr.IPNetwork(self.net.network)
+    if self.network.numhosts > IPV4_NETWORK_MAX_NUM_HOSTS:
+      raise errors.AddressPoolError("A big network with %s host(s) is currently"
+                                    " not supported. please specify at most a"
+                                    " /%s network" %
+                                    (str(self.network.numhosts),
+                                     IPV4_NETWORK_MAX_SIZE))
+
+    if self.network.numhosts < IPV4_NETWORK_MIN_NUM_HOSTS:
+      raise errors.AddressPoolError("A network with only %s host(s) is too"
+                                    " small, please specify at least a /%s"
+                                    " network" %
+                                    (str(self.network.numhosts),
+                                     IPV4_NETWORK_MIN_SIZE))
     if self.net.gateway:
       self.gateway = ipaddr.IPAddress(self.net.gateway)
 
@@ -94,7 +125,9 @@ class AddressPool(object):
     return int(addr) - int(self.network.network)
 
   def Update(self):
-    """Write address pools back to the network object"""
+    """Write address pools back to the network object.
+
+    """
     # pylint: disable=E1103
     self.net.ext_reservations = self.ext_reservations.to01()
     self.net.reservations = self.reservations.to01()
@@ -112,58 +145,87 @@ class AddressPool(object):
 
   @property
   def all_reservations(self):
-    """Return a combined map of internal + external reservations."""
+    """Return a combined map of internal and external reservations.
+
+    """
     return (self.reservations | self.ext_reservations)
 
   def Validate(self):
-    assert self.net.family == 4
     assert len(self.reservations) == self._GetSize()
     assert len(self.ext_reservations) == self._GetSize()
-    all_res = self.reservations & self.ext_reservations
-    assert not all_res.any()
 
     if self.gateway is not None:
-      assert self.net.family == self.gateway.version
       assert self.gateway in self.network
 
     if self.network6 and self.gateway6:
-      assert self.gateway6 in self.network6
+      assert self.gateway6 in self.network6 or self.gateway6.is_link_local
 
     return True
 
   def IsFull(self):
-    """Check whether the network is full"""
+    """Check whether the network is full.
+
+    """
     return self.all_reservations.all()
 
   def GetReservedCount(self):
-    """Get the count of reserved addresses"""
+    """Get the count of reserved addresses.
+
+    """
     return self.all_reservations.count(True)
 
   def GetFreeCount(self):
-    """Get the count of unused addresses"""
+    """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 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"""
+  def IsReserved(self, address, external=False):
+    """Checks if the given IP is reserved.
+
+    """
     idx = self._GetAddrIndex(address)
-    return self.all_reservations[idx]
+    if external:
+      return self.ext_reservations[idx]
+    else:
+      return self.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)
+    """Mark an address as used.
+
+    """
+    if self.IsReserved(address, external):
+      if external:
+        msg = "IP %s is already externally reserved" % address
+      else:
+        msg = "IP %s is already used by an instance" % address
+      raise errors.AddressPoolError(msg)
+
     self._Mark(address, external=external)
 
   def Release(self, address, external=False):
-    """Release a given address reservation."""
+    """Release a given address reservation.
+
+    """
+    if not self.IsReserved(address, external):
+      if external:
+        msg = "IP %s is not externally reserved" % address
+      else:
+        msg = "IP %s is not used by an instance" % address
+      raise errors.AddressPoolError(msg)
+
     self._Mark(address, value=False, external=external)
 
   def GetFreeAddress(self):
-    """Returns the first available address."""
+    """Returns the first available address.
+
+    """
     if self.IsFull():
       raise errors.AddressPoolError("%s is full" % self.network)
 
@@ -173,23 +235,30 @@ class AddressPool(object):
     return address
 
   def GenerateFree(self):
-    """A generator for free addresses."""
-    def _iter_free():
-      for idx in self.all_reservations.search("0", 64):
-        yield str(self.network[idx])
-    # pylint: disable=E1101
-    return _iter_free().next
+    """Returns the first free address of the network.
+
+    @raise errors.AddressPoolError: Pool is full
+
+    """
+    idx = self.all_reservations.search(self.FREE, 1)
+    if idx:
+      return str(self.network[idx[0]])
+    else:
+      raise errors.AddressPoolError("%s is full" % self.network)
 
   def GetExternalReservations(self):
-    """Returns a list of all externally reserved addresses"""
-    idxs = self.ext_reservations.search("1")
+    """Returns a list of all externally reserved addresses.
+
+    """
+    # pylint: disable=E1103
+    idxs = self.ext_reservations.search(self.RESERVED)
     return [str(self.network[idx]) for idx in idxs]
 
   @classmethod
   def InitializeNetwork(cls, net):
-    """Initialize an L{objects.Network} object
+    """Initialize an L{objects.Network} object.
 
-    Reserve the network, broadcast and gateway IPs
+    Reserve the network, broadcast and gateway IP addresses.
 
     """
     obj = cls(net)