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
33 def _ComputeIpv4NumHosts(network_size):
34 """Derives the number of hosts in an IPv4 network from the size.
37 return 2 ** (32 - network_size)
40 IPV4_NETWORK_MIN_SIZE = 30
41 # FIXME: This limit is for performance reasons. Remove when refactoring
42 # for performance tuning was successful.
43 IPV4_NETWORK_MAX_SIZE = 16
44 IPV4_NETWORK_MIN_NUM_HOSTS = _ComputeIpv4NumHosts(IPV4_NETWORK_MIN_SIZE)
45 IPV4_NETWORK_MAX_NUM_HOSTS = _ComputeIpv4NumHosts(IPV4_NETWORK_MAX_SIZE)
48 class AddressPool(object):
49 """Address pool class, wrapping an C{objects.Network} object.
51 This class provides methods to manipulate address pools, backed by
52 L{objects.Network} objects.
56 RESERVED = bitarray("1")
58 def __init__(self, network):
59 """Initialize a new IPv4 address pool from an L{objects.Network} object.
61 @type network: L{objects.Network}
62 @param network: the network object from which the pool will be generated
72 self.network = ipaddr.IPNetwork(self.net.network)
73 if self.network.numhosts > IPV4_NETWORK_MAX_NUM_HOSTS:
74 raise errors.AddressPoolError("A big network with %s host(s) is currently"
75 " not supported. please specify at most a"
77 (str(self.network.numhosts),
78 IPV4_NETWORK_MAX_SIZE))
80 if self.network.numhosts < IPV4_NETWORK_MIN_NUM_HOSTS:
81 raise errors.AddressPoolError("A network with only %s host(s) is too"
82 " small, please specify at least a /%s"
84 (str(self.network.numhosts),
85 IPV4_NETWORK_MIN_SIZE))
87 self.gateway = ipaddr.IPAddress(self.net.gateway)
90 self.network6 = ipaddr.IPv6Network(self.net.network6)
92 self.gateway6 = ipaddr.IPv6Address(self.net.gateway6)
94 if self.net.reservations:
95 self.reservations = bitarray(self.net.reservations)
97 self.reservations = bitarray(self.network.numhosts)
98 # pylint: disable=E1103
99 self.reservations.setall(False)
101 if self.net.ext_reservations:
102 self.ext_reservations = bitarray(self.net.ext_reservations)
104 self.ext_reservations = bitarray(self.network.numhosts)
105 # pylint: disable=E1103
106 self.ext_reservations.setall(False)
108 assert len(self.reservations) == self.network.numhosts
109 assert len(self.ext_reservations) == self.network.numhosts
111 def Contains(self, address):
114 addr = ipaddr.IPAddress(address)
116 return addr in self.network
118 def _GetAddrIndex(self, address):
119 addr = ipaddr.IPAddress(address)
121 if not addr in self.network:
122 raise errors.AddressPoolError("%s does not contain %s" %
123 (self.network, addr))
125 return int(addr) - int(self.network.network)
128 """Write address pools back to the network object.
131 # pylint: disable=E1103
132 self.net.ext_reservations = self.ext_reservations.to01()
133 self.net.reservations = self.reservations.to01()
135 def _Mark(self, address, value=True, external=False):
136 idx = self._GetAddrIndex(address)
138 self.ext_reservations[idx] = value
140 self.reservations[idx] = value
144 return 2 ** (32 - self.network.prefixlen)
147 def all_reservations(self):
148 """Return a combined map of internal and external reservations.
151 return (self.reservations | self.ext_reservations)
154 assert len(self.reservations) == self._GetSize()
155 assert len(self.ext_reservations) == self._GetSize()
157 if self.gateway is not None:
158 assert self.gateway in self.network
160 if self.network6 and self.gateway6:
161 assert self.gateway6 in self.network6
166 """Check whether the network is full.
169 return self.all_reservations.all()
171 def GetReservedCount(self):
172 """Get the count of reserved addresses.
175 return self.all_reservations.count(True)
177 def GetFreeCount(self):
178 """Get the count of unused addresses.
181 return self.all_reservations.count(False)
184 """Return a textual representation of the network's occupation status.
187 return self.all_reservations.to01().replace("1", "X").replace("0", ".")
189 def IsReserved(self, address, external=False):
190 """Checks if the given IP is reserved.
193 idx = self._GetAddrIndex(address)
195 return self.ext_reservations[idx]
197 return self.reservations[idx]
199 def Reserve(self, address, external=False):
200 """Mark an address as used.
203 if self.IsReserved(address, external):
205 msg = "IP %s is already externally reserved" % address
207 msg = "IP %s is already used by an instance" % address
208 raise errors.AddressPoolError(msg)
210 self._Mark(address, external=external)
212 def Release(self, address, external=False):
213 """Release a given address reservation.
216 if not self.IsReserved(address, external):
218 msg = "IP %s is not externally reserved" % address
220 msg = "IP %s is not used by an instance" % address
221 raise errors.AddressPoolError(msg)
223 self._Mark(address, value=False, external=external)
225 def GetFreeAddress(self):
226 """Returns the first available address.
230 raise errors.AddressPoolError("%s is full" % self.network)
232 idx = self.all_reservations.index(False)
233 address = str(self.network[idx])
234 self.Reserve(address)
237 def GenerateFree(self):
238 """Returns the first free address of the network.
240 @raise errors.AddressPoolError: Pool is full
243 idx = self.all_reservations.search(self.FREE, 1)
245 return str(self.network[idx[0]])
247 raise errors.AddressPoolError("%s is full" % self.network)
249 def GetExternalReservations(self):
250 """Returns a list of all externally reserved addresses.
253 # pylint: disable=E1103
254 idxs = self.ext_reservations.search(self.RESERVED)
255 return [str(self.network[idx]) for idx in idxs]
258 def InitializeNetwork(cls, net):
259 """Initialize an L{objects.Network} object.
261 Reserve the network, broadcast and gateway IP addresses.
266 for ip in [obj.network[0], obj.network[-1]]:
267 obj.Reserve(ip, external=True)
268 if obj.net.gateway is not None:
269 obj.Reserve(obj.net.gateway, external=True)