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