Check minimum size of networks on creation
[ganeti-local] / lib / network.py
1 #
2 #
3
4 # Copyright (C) 2011, 2012 Google Inc.
5 #
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.
10 #
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.
15 #
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
19 # 02110-1301, USA.
20
21
22 """IP address pool management functions.
23
24 """
25
26 import ipaddr
27
28 from bitarray import bitarray
29
30 from ganeti import errors
31
32 IPV4_NETWORK_MIN_SIZE = 30
33 IPV4_NETWORK_MIN_NUM_HOSTS = 2 ** (32 - IPV4_NETWORK_MIN_SIZE)
34
35
36 class AddressPool(object):
37   """Address pool class, wrapping an C{objects.Network} object.
38
39   This class provides methods to manipulate address pools, backed by
40   L{objects.Network} objects.
41
42   """
43   FREE = bitarray("0")
44   RESERVED = bitarray("1")
45
46   def __init__(self, network):
47     """Initialize a new IPv4 address pool from an L{objects.Network} object.
48
49     @type network: L{objects.Network}
50     @param network: the network object from which the pool will be generated
51
52     """
53     self.network = None
54     self.gateway = None
55     self.network6 = None
56     self.gateway6 = None
57
58     self.net = network
59
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"
64                                     " network" %
65                                     (str(self.network.numhosts),
66                                      IPV4_NETWORK_MIN_SIZE))
67     if self.net.gateway:
68       self.gateway = ipaddr.IPAddress(self.net.gateway)
69
70     if self.net.network6:
71       self.network6 = ipaddr.IPv6Network(self.net.network6)
72     if self.net.gateway6:
73       self.gateway6 = ipaddr.IPv6Address(self.net.gateway6)
74
75     if self.net.reservations:
76       self.reservations = bitarray(self.net.reservations)
77     else:
78       self.reservations = bitarray(self.network.numhosts)
79       # pylint: disable=E1103
80       self.reservations.setall(False)
81
82     if self.net.ext_reservations:
83       self.ext_reservations = bitarray(self.net.ext_reservations)
84     else:
85       self.ext_reservations = bitarray(self.network.numhosts)
86       # pylint: disable=E1103
87       self.ext_reservations.setall(False)
88
89     assert len(self.reservations) == self.network.numhosts
90     assert len(self.ext_reservations) == self.network.numhosts
91
92   def Contains(self, address):
93     if address is None:
94       return False
95     addr = ipaddr.IPAddress(address)
96
97     return addr in self.network
98
99   def _GetAddrIndex(self, address):
100     addr = ipaddr.IPAddress(address)
101
102     if not addr in self.network:
103       raise errors.AddressPoolError("%s does not contain %s" %
104                                     (self.network, addr))
105
106     return int(addr) - int(self.network.network)
107
108   def Update(self):
109     """Write address pools back to the network object.
110
111     """
112     # pylint: disable=E1103
113     self.net.ext_reservations = self.ext_reservations.to01()
114     self.net.reservations = self.reservations.to01()
115
116   def _Mark(self, address, value=True, external=False):
117     idx = self._GetAddrIndex(address)
118     if external:
119       self.ext_reservations[idx] = value
120     else:
121       self.reservations[idx] = value
122     self.Update()
123
124   def _GetSize(self):
125     return 2 ** (32 - self.network.prefixlen)
126
127   @property
128   def all_reservations(self):
129     """Return a combined map of internal and external reservations.
130
131     """
132     return (self.reservations | self.ext_reservations)
133
134   def Validate(self):
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()
139
140     if self.gateway is not None:
141       assert self.gateway in self.network
142
143     if self.network6 and self.gateway6:
144       assert self.gateway6 in self.network6
145
146     return True
147
148   def IsFull(self):
149     """Check whether the network is full.
150
151     """
152     return self.all_reservations.all()
153
154   def GetReservedCount(self):
155     """Get the count of reserved addresses.
156
157     """
158     return self.all_reservations.count(True)
159
160   def GetFreeCount(self):
161     """Get the count of unused addresses.
162
163     """
164     return self.all_reservations.count(False)
165
166   def GetMap(self):
167     """Return a textual representation of the network's occupation status.
168
169     """
170     return self.all_reservations.to01().replace("1", "X").replace("0", ".")
171
172   def IsReserved(self, address):
173     """Checks if the given IP is reserved.
174
175     """
176     idx = self._GetAddrIndex(address)
177     return self.all_reservations[idx]
178
179   def Reserve(self, address, external=False):
180     """Mark an address as used.
181
182     """
183     if self.IsReserved(address):
184       raise errors.AddressPoolError("%s is already reserved" % address)
185     self._Mark(address, external=external)
186
187   def Release(self, address, external=False):
188     """Release a given address reservation.
189
190     """
191     self._Mark(address, value=False, external=external)
192
193   def GetFreeAddress(self):
194     """Returns the first available address.
195
196     """
197     if self.IsFull():
198       raise errors.AddressPoolError("%s is full" % self.network)
199
200     idx = self.all_reservations.index(False)
201     address = str(self.network[idx])
202     self.Reserve(address)
203     return address
204
205   def GenerateFree(self):
206     """Returns the first free address of the network.
207
208     @raise errors.AddressPoolError: Pool is full
209
210     """
211     idx = self.all_reservations.search(self.FREE, 1)
212     if idx:
213       return str(self.network[idx[0]])
214     else:
215       raise errors.AddressPoolError("%s is full" % self.network)
216
217   def GetExternalReservations(self):
218     """Returns a list of all externally reserved addresses.
219
220     """
221     # pylint: disable=E1103
222     idxs = self.ext_reservations.search(self.RESERVED)
223     return [str(self.network[idx]) for idx in idxs]
224
225   @classmethod
226   def InitializeNetwork(cls, net):
227     """Initialize an L{objects.Network} object.
228
229     Reserve the network, broadcast and gateway IP addresses.
230
231     """
232     obj = cls(net)
233     obj.Update()
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)
238     obj.Validate()
239     return obj