4 # Copyright (C) 2011 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 class AddressPool(object):
33 """Address pool class, wrapping an objects.Network object
35 This class provides methods to manipulate address pools, backed by
36 L{objects.Network} objects.
39 def __init__(self, network):
40 """Initialize a new IPv4 address pool from an objects.Network object
42 @type network: L{objects.Network}
43 @param network: the network object from which the pool will be generated
53 self.network = ipaddr.IPNetwork(self.net.network)
55 self.gateway = ipaddr.IPAddress(self.net.gateway)
58 self.network6 = ipaddr.IPv6Network(self.net.network6)
60 self.gateway6 = ipaddr.IPv6Address(self.net.gateway6)
62 if self.net.reservations:
63 self.reservations = bitarray(self.net.reservations)
65 self.reservations = bitarray(self.network.numhosts)
66 self.reservations.setall(False)
68 if self.net.ext_reservations:
69 self.ext_reservations = bitarray(self.net.ext_reservations)
71 self.ext_reservations = bitarray(self.network.numhosts)
72 self.ext_reservations.setall(False)
74 assert len(self.reservations) == self.network.numhosts
75 assert len(self.ext_reservations) == self.network.numhosts
77 def _Contains(self, address):
80 addr = ipaddr.IPAddress(address)
82 return addr in self.network
84 def _GetAddrIndex(self, address):
85 addr = ipaddr.IPAddress(address)
87 if not addr in self.network:
88 raise errors.AddressPoolError("%s does not contain %s" %
91 return int(addr) - int(self.network.network)
94 """Write address pools back to the network object"""
95 self.net.ext_reservations = self.ext_reservations.to01()
96 self.net.reservations = self.reservations.to01()
98 def _Mark(self, address, value=True, external=False):
99 idx = self._GetAddrIndex(address)
101 self.ext_reservations[idx] = value
103 self.reservations[idx] = value
107 return 2**(32 - self.network.prefixlen)
110 def all_reservations(self):
111 """Return a combined map of internal + external reservations."""
112 return (self.reservations | self.ext_reservations)
115 assert self.net.family == 4
116 assert len(self.reservations) == self._GetSize()
117 assert len(self.ext_reservations) == self._GetSize()
118 assert not (self.reservations & self.ext_reservations).any()
120 if self.gateway is not None:
121 assert self.net.family == self.gateway.version
122 assert self.gateway in self.network
124 if self.network6 and self.gateway6:
125 assert self.gateway6 in self.network6
130 """Check whether the network is full"""
131 return self.all_reservations.all()
133 def GetReservedCount(self):
134 """Get the count of reserved addresses"""
135 return self.all_reservations.count(True)
137 def GetFreeCount(self):
138 """Get the count of unused addresses"""
139 return self.all_reservations.count(False)
142 """Return a textual representation of the network's occupation status."""
143 return self.all_reservations.to01().replace("1", "X").replace("0", ".")
145 def IsReserved(self, address):
146 """Checks if the given IP is reserved"""
147 idx = self._GetAddrIndex(address)
148 return self.all_reservations[idx]
150 def Reserve(self, address, external=False):
151 """Mark an address as used."""
152 if self.IsReserved(address):
153 raise errors.AddressPoolError("%s is already reserved" % address)
154 self._Mark(address, external=external)
156 def Release(self, address, external=False):
157 """Release a given address reservation."""
158 self._Mark(address, value=False, external=external)
160 def GetFreeAddress(self):
161 """Returns the first available address."""
163 raise errors.AddressPoolError("%s is full" % self.network)
165 idx = self.all_reservations.index(False)
166 address = str(self.network[idx])
167 self.Reserve(address)
170 def GenerateFree(self):
171 """A generator for free addresses."""
173 for idx in self.all_reservations.search("0", 64):
174 yield str(self.network[idx])
176 return _iter_free().next
178 def GetExternalReservations(self):
179 """Returns a list of all externally reserved addresses"""
180 idxs = self.ext_reservations.search("1")
181 return [str(self.network[idx]) for idx in idxs]
184 def InitializeNetwork(cls, net):
185 """Initialize an L{objects.Network} object
187 Reserve the network, broadcast and gateway IPs
192 for ip in [obj.network[0], obj.network[-1]]:
193 obj.Reserve(ip, external=True)
194 if obj.net.gateway is not None:
195 obj.Reserve(obj.net.gateway, external=True)