Introduce new module for IP pool management
[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     assert not (self.reservations & self.ext_reservations).any()
119
120     if self.gateway is not None:
121       assert self.net.family == self.gateway.version
122       assert self.gateway in self.network
123
124     if self.network6 and self.gateway6:
125       assert self.gateway6 in self.network6
126
127     return True
128
129   def IsFull(self):
130     """Check whether the network is full"""
131     return self.all_reservations.all()
132
133   def GetReservedCount(self):
134     """Get the count of reserved addresses"""
135     return self.all_reservations.count(True)
136
137   def GetFreeCount(self):
138     """Get the count of unused addresses"""
139     return self.all_reservations.count(False)
140
141   def GetMap(self):
142     """Return a textual representation of the network's occupation status."""
143     return self.all_reservations.to01().replace("1", "X").replace("0", ".")
144
145   def IsReserved(self, address):
146     """Checks if the given IP is reserved"""
147     idx = self._GetAddrIndex(address)
148     return self.all_reservations[idx]
149
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)
155
156   def Release(self, address, external=False):
157     """Release a given address reservation."""
158     self._Mark(address, value=False, external=external)
159
160   def GetFreeAddress(self):
161     """Returns the first available address."""
162     if self.IsFull():
163       raise errors.AddressPoolError("%s is full" % self.network)
164
165     idx = self.all_reservations.index(False)
166     address = str(self.network[idx])
167     self.Reserve(address)
168     return address
169
170   def GenerateFree(self):
171     """A generator for free addresses."""
172     def _iter_free():
173       for idx in self.all_reservations.search("0", 64):
174         yield str(self.network[idx])
175
176     return _iter_free().next
177
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]
182
183   @classmethod
184   def InitializeNetwork(cls, net):
185     """Initialize an L{objects.Network} object
186
187     Reserve the network, broadcast and gateway IPs
188
189     """
190     obj = cls(net)
191     obj._Update()
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)
196     obj.Validate()
197     return obj