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 all_res = self.reservations & self.ext_reservations
119 assert not all_res.any()
121 if self.gateway is not None:
122 assert self.net.family == self.gateway.version
123 assert self.gateway in self.network
125 if self.network6 and self.gateway6:
126 assert self.gateway6 in self.network6
131 """Check whether the network is full"""
132 return self.all_reservations.all()
134 def GetReservedCount(self):
135 """Get the count of reserved addresses"""
136 return self.all_reservations.count(True)
138 def GetFreeCount(self):
139 """Get the count of unused addresses"""
140 return self.all_reservations.count(False)
143 """Return a textual representation of the network's occupation status."""
144 return self.all_reservations.to01().replace("1", "X").replace("0", ".")
146 def IsReserved(self, address):
147 """Checks if the given IP is reserved"""
148 idx = self._GetAddrIndex(address)
149 return self.all_reservations[idx]
151 def Reserve(self, address, external=False):
152 """Mark an address as used."""
153 if self.IsReserved(address):
154 raise errors.AddressPoolError("%s is already reserved" % address)
155 self._Mark(address, external=external)
157 def Release(self, address, external=False):
158 """Release a given address reservation."""
159 self._Mark(address, value=False, external=external)
161 def GetFreeAddress(self):
162 """Returns the first available address."""
164 raise errors.AddressPoolError("%s is full" % self.network)
166 idx = self.all_reservations.index(False)
167 address = str(self.network[idx])
168 self.Reserve(address)
171 def GenerateFree(self):
172 """A generator for free addresses."""
174 for idx in self.all_reservations.search("0", 64):
175 yield str(self.network[idx])
177 return _iter_free().next
179 def GetExternalReservations(self):
180 """Returns a list of all externally reserved addresses"""
181 idxs = self.ext_reservations.search("1")
182 return [str(self.network[idx]) for idx in idxs]
185 def InitializeNetwork(cls, net):
186 """Initialize an L{objects.Network} object
188 Reserve the network, broadcast and gateway IPs
193 for ip in [obj.network[0], obj.network[-1]]:
194 obj.Reserve(ip, external=True)
195 if obj.net.gateway is not None:
196 obj.Reserve(obj.net.gateway, external=True)