Statistics
| Branch: | Tag: | Revision:

root / lib / network.py @ 48616625

History | View | Annotate | Download (6.1 kB)

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 len(self.reservations) == self._GetSize()
127
    assert len(self.ext_reservations) == self._GetSize()
128
    all_res = self.reservations & self.ext_reservations
129
    assert not all_res.any()
130

    
131
    if self.gateway is not None:
132
      assert self.gateway in self.network
133

    
134
    if self.network6 and self.gateway6:
135
      assert self.gateway6 in self.network6
136

    
137
    return True
138

    
139
  def IsFull(self):
140
    """Check whether the network is full.
141

142
    """
143
    return self.all_reservations.all()
144

    
145
  def GetReservedCount(self):
146
    """Get the count of reserved addresses.
147

148
    """
149
    return self.all_reservations.count(True)
150

    
151
  def GetFreeCount(self):
152
    """Get the count of unused addresses.
153

154
    """
155
    return self.all_reservations.count(False)
156

    
157
  def GetMap(self):
158
    """Return a textual representation of the network's occupation status.
159

160
    """
161
    return self.all_reservations.to01().replace("1", "X").replace("0", ".")
162

    
163
  def IsReserved(self, address):
164
    """Checks if the given IP is reserved.
165

166
    """
167
    idx = self._GetAddrIndex(address)
168
    return self.all_reservations[idx]
169

    
170
  def Reserve(self, address, external=False):
171
    """Mark an address as used.
172

173
    """
174
    if self.IsReserved(address):
175
      raise errors.AddressPoolError("%s is already reserved" % address)
176
    self._Mark(address, external=external)
177

    
178
  def Release(self, address, external=False):
179
    """Release a given address reservation.
180

181
    """
182
    self._Mark(address, value=False, external=external)
183

    
184
  def GetFreeAddress(self):
185
    """Returns the first available address.
186

187
    """
188
    if self.IsFull():
189
      raise errors.AddressPoolError("%s is full" % self.network)
190

    
191
    idx = self.all_reservations.index(False)
192
    address = str(self.network[idx])
193
    self.Reserve(address)
194
    return address
195

    
196
  def GenerateFree(self):
197
    """Returns the first free address of the network.
198

199
    @raise errors.AddressPoolError: Pool is full
200

201
    """
202
    idx = self.all_reservations.search(self.FREE, 1)
203
    if idx:
204
      return str(self.network[idx[0]])
205
    else:
206
      raise errors.AddressPoolError("%s is full" % self.network)
207

    
208
  def GetExternalReservations(self):
209
    """Returns a list of all externally reserved addresses.
210

211
    """
212
    # pylint: disable=E1103
213
    idxs = self.ext_reservations.search(self.RESERVED)
214
    return [str(self.network[idx]) for idx in idxs]
215

    
216
  @classmethod
217
  def InitializeNetwork(cls, net):
218
    """Initialize an L{objects.Network} object.
219

220
    Reserve the network, broadcast and gateway IP addresses.
221

222
    """
223
    obj = cls(net)
224
    obj.Update()
225
    for ip in [obj.network[0], obj.network[-1]]:
226
      obj.Reserve(ip, external=True)
227
    if obj.net.gateway is not None:
228
      obj.Reserve(obj.net.gateway, external=True)
229
    obj.Validate()
230
    return obj