4 # Copyright (C) 2011, 2012 Google Inc.
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 """IP address pool management functions.
28 from bitarray import bitarray
30 from ganeti import errors
32 IPV4_NETWORK_MIN_SIZE = 30
33 IPV4_NETWORK_MIN_NUM_HOSTS = 2 ** (32 - IPV4_NETWORK_MIN_SIZE)
36 class AddressPool(object):
37 """Address pool class, wrapping an C{objects.Network} object.
39 This class provides methods to manipulate address pools, backed by
40 L{objects.Network} objects.
44 RESERVED = bitarray("1")
46 def __init__(self, network):
47 """Initialize a new IPv4 address pool from an L{objects.Network} object.
49 @type network: L{objects.Network}
50 @param network: the network object from which the pool will be generated
60 self.network = ipaddr.IPNetwork(self.net.network)
61 if self.network.numhosts < IPV4_NETWORK_MIN_NUM_HOSTS:
62 raise errors.AddressPoolError("A network with only %s host(s) is too"
63 " small, please specify at least a /%s"
65 (str(self.network.numhosts),
66 IPV4_NETWORK_MIN_SIZE))
68 self.gateway = ipaddr.IPAddress(self.net.gateway)
71 self.network6 = ipaddr.IPv6Network(self.net.network6)
73 self.gateway6 = ipaddr.IPv6Address(self.net.gateway6)
75 if self.net.reservations:
76 self.reservations = bitarray(self.net.reservations)
78 self.reservations = bitarray(self.network.numhosts)
79 # pylint: disable=E1103
80 self.reservations.setall(False)
82 if self.net.ext_reservations:
83 self.ext_reservations = bitarray(self.net.ext_reservations)
85 self.ext_reservations = bitarray(self.network.numhosts)
86 # pylint: disable=E1103
87 self.ext_reservations.setall(False)
89 assert len(self.reservations) == self.network.numhosts
90 assert len(self.ext_reservations) == self.network.numhosts
92 def Contains(self, address):
95 addr = ipaddr.IPAddress(address)
97 return addr in self.network
99 def _GetAddrIndex(self, address):
100 addr = ipaddr.IPAddress(address)
102 if not addr in self.network:
103 raise errors.AddressPoolError("%s does not contain %s" %
104 (self.network, addr))
106 return int(addr) - int(self.network.network)
109 """Write address pools back to the network object.
112 # pylint: disable=E1103
113 self.net.ext_reservations = self.ext_reservations.to01()
114 self.net.reservations = self.reservations.to01()
116 def _Mark(self, address, value=True, external=False):
117 idx = self._GetAddrIndex(address)
119 self.ext_reservations[idx] = value
121 self.reservations[idx] = value
125 return 2 ** (32 - self.network.prefixlen)
128 def all_reservations(self):
129 """Return a combined map of internal and external reservations.
132 return (self.reservations | self.ext_reservations)
135 assert len(self.reservations) == self._GetSize()
136 assert len(self.ext_reservations) == self._GetSize()
137 all_res = self.reservations & self.ext_reservations
138 assert not all_res.any()
140 if self.gateway is not None:
141 assert self.gateway in self.network
143 if self.network6 and self.gateway6:
144 assert self.gateway6 in self.network6
149 """Check whether the network is full.
152 return self.all_reservations.all()
154 def GetReservedCount(self):
155 """Get the count of reserved addresses.
158 return self.all_reservations.count(True)
160 def GetFreeCount(self):
161 """Get the count of unused addresses.
164 return self.all_reservations.count(False)
167 """Return a textual representation of the network's occupation status.
170 return self.all_reservations.to01().replace("1", "X").replace("0", ".")
172 def IsReserved(self, address):
173 """Checks if the given IP is reserved.
176 idx = self._GetAddrIndex(address)
177 return self.all_reservations[idx]
179 def Reserve(self, address, external=False):
180 """Mark an address as used.
183 if self.IsReserved(address):
184 raise errors.AddressPoolError("%s is already reserved" % address)
185 self._Mark(address, external=external)
187 def Release(self, address, external=False):
188 """Release a given address reservation.
191 self._Mark(address, value=False, external=external)
193 def GetFreeAddress(self):
194 """Returns the first available address.
198 raise errors.AddressPoolError("%s is full" % self.network)
200 idx = self.all_reservations.index(False)
201 address = str(self.network[idx])
202 self.Reserve(address)
205 def GenerateFree(self):
206 """Returns the first free address of the network.
208 @raise errors.AddressPoolError: Pool is full
211 idx = self.all_reservations.search(self.FREE, 1)
213 return str(self.network[idx[0]])
215 raise errors.AddressPoolError("%s is full" % self.network)
217 def GetExternalReservations(self):
218 """Returns a list of all externally reserved addresses.
221 # pylint: disable=E1103
222 idxs = self.ext_reservations.search(self.RESERVED)
223 return [str(self.network[idx]) for idx in idxs]
226 def InitializeNetwork(cls, net):
227 """Initialize an L{objects.Network} object.
229 Reserve the network, broadcast and gateway IP addresses.
234 for ip in [obj.network[0], obj.network[-1]]:
235 obj.Reserve(ip, external=True)
236 if obj.net.gateway is not None:
237 obj.Reserve(obj.net.gateway, external=True)