Fixes to pass unittests (make check)
[ganeti-local] / lib / network.py
1 #
2 #
3
4 # Copyright (C) 2011 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 class AddressPool(object):
33   """Address pool class, wrapping an objects.Network object
34
35   This class provides methods to manipulate address pools, backed by
36   L{objects.Network} objects.
37
38   """
39   def __init__(self, network):
40     """Initialize a new IPv4 address pool from an objects.Network object
41
42     @type network: L{objects.Network}
43     @param network: the network object from which the pool will be generated
44
45     """
46     self.network = None
47     self.gateway = None
48     self.network6 = None
49     self.gateway6 = None
50
51     self.net = network
52
53     self.network = ipaddr.IPNetwork(self.net.network)
54     if self.net.gateway:
55       self.gateway = ipaddr.IPAddress(self.net.gateway)
56
57     if self.net.network6:
58       self.network6 = ipaddr.IPv6Network(self.net.network6)
59     if self.net.gateway6:
60       self.gateway6 = ipaddr.IPv6Address(self.net.gateway6)
61
62     if self.net.reservations:
63       self.reservations = bitarray(self.net.reservations)
64     else:
65       self.reservations = bitarray(self.network.numhosts)
66       self.reservations.setall(False)
67
68     if self.net.ext_reservations:
69       self.ext_reservations = bitarray(self.net.ext_reservations)
70     else:
71       self.ext_reservations = bitarray(self.network.numhosts)
72       self.ext_reservations.setall(False)
73
74     assert len(self.reservations) == self.network.numhosts
75     assert len(self.ext_reservations) == self.network.numhosts
76
77   def _Contains(self, address):
78     if address is None:
79       return False
80     addr = ipaddr.IPAddress(address)
81
82     return addr in self.network
83
84   def _GetAddrIndex(self, address):
85     addr = ipaddr.IPAddress(address)
86
87     if not addr in self.network:
88       raise errors.AddressPoolError("%s does not contain %s" %
89                                     (self.network, addr))
90
91     return int(addr) - int(self.network.network)
92
93   def _Update(self):
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()
97
98   def _Mark(self, address, value=True, external=False):
99     idx = self._GetAddrIndex(address)
100     if external:
101       self.ext_reservations[idx] = value
102     else:
103       self.reservations[idx] = value
104     self._Update()
105
106   def _GetSize(self):
107     return 2**(32 - self.network.prefixlen)
108
109   @property
110   def all_reservations(self):
111     """Return a combined map of internal + external reservations."""
112     return (self.reservations | self.ext_reservations)
113
114   def Validate(self):
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()
120
121     if self.gateway is not None:
122       assert self.net.family == self.gateway.version
123       assert self.gateway in self.network
124
125     if self.network6 and self.gateway6:
126       assert self.gateway6 in self.network6
127
128     return True
129
130   def IsFull(self):
131     """Check whether the network is full"""
132     return self.all_reservations.all()
133
134   def GetReservedCount(self):
135     """Get the count of reserved addresses"""
136     return self.all_reservations.count(True)
137
138   def GetFreeCount(self):
139     """Get the count of unused addresses"""
140     return self.all_reservations.count(False)
141
142   def GetMap(self):
143     """Return a textual representation of the network's occupation status."""
144     return self.all_reservations.to01().replace("1", "X").replace("0", ".")
145
146   def IsReserved(self, address):
147     """Checks if the given IP is reserved"""
148     idx = self._GetAddrIndex(address)
149     return self.all_reservations[idx]
150
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)
156
157   def Release(self, address, external=False):
158     """Release a given address reservation."""
159     self._Mark(address, value=False, external=external)
160
161   def GetFreeAddress(self):
162     """Returns the first available address."""
163     if self.IsFull():
164       raise errors.AddressPoolError("%s is full" % self.network)
165
166     idx = self.all_reservations.index(False)
167     address = str(self.network[idx])
168     self.Reserve(address)
169     return address
170
171   def GenerateFree(self):
172     """A generator for free addresses."""
173     def _iter_free():
174       for idx in self.all_reservations.search("0", 64):
175         yield str(self.network[idx])
176
177     return _iter_free().next
178
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]
183
184   @classmethod
185   def InitializeNetwork(cls, net):
186     """Initialize an L{objects.Network} object
187
188     Reserve the network, broadcast and gateway IPs
189
190     """
191     obj = cls(net)
192     obj._Update()
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)
197     obj.Validate()
198     return obj