Statistics
| Branch: | Tag: | Revision:

root / lib / network.py @ 861a92b4

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 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 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
    # pylint: disable=E1103
102
    self.net.ext_reservations = self.ext_reservations.to01()
103
    self.net.reservations = self.reservations.to01()
104

    
105
  def _Mark(self, address, value=True, external=False):
106
    idx = self._GetAddrIndex(address)
107
    if external:
108
      self.ext_reservations[idx] = value
109
    else:
110
      self.reservations[idx] = value
111
    self.Update()
112

    
113
  def _GetSize(self):
114
    return 2 ** (32 - self.network.prefixlen)
115

    
116
  @property
117
  def all_reservations(self):
118
    """Return a combined map of internal + external reservations."""
119
    return (self.reservations | self.ext_reservations)
120

    
121
  def Validate(self):
122
    assert self.net.family == 4
123
    assert len(self.reservations) == self._GetSize()
124
    assert len(self.ext_reservations) == self._GetSize()
125
    all_res = self.reservations & self.ext_reservations
126
    assert not all_res.any()
127

    
128
    if self.gateway is not None:
129
      assert self.net.family == self.gateway.version
130
      assert self.gateway in self.network
131

    
132
    if self.network6 and self.gateway6:
133
      assert self.gateway6 in self.network6
134

    
135
    return True
136

    
137
  def IsFull(self):
138
    """Check whether the network is full"""
139
    return self.all_reservations.all()
140

    
141
  def GetReservedCount(self):
142
    """Get the count of reserved addresses"""
143
    return self.all_reservations.count(True)
144

    
145
  def GetFreeCount(self):
146
    """Get the count of unused addresses"""
147
    return self.all_reservations.count(False)
148

    
149
  def GetMap(self):
150
    """Return a textual representation of the network's occupation status."""
151
    return self.all_reservations.to01().replace("1", "X").replace("0", ".")
152

    
153
  def IsReserved(self, address):
154
    """Checks if the given IP is reserved"""
155
    idx = self._GetAddrIndex(address)
156
    return self.all_reservations[idx]
157

    
158
  def Reserve(self, address, external=False):
159
    """Mark an address as used."""
160
    if self.IsReserved(address):
161
      raise errors.AddressPoolError("%s is already reserved" % address)
162
    self._Mark(address, external=external)
163

    
164
  def Release(self, address, external=False):
165
    """Release a given address reservation."""
166
    self._Mark(address, value=False, external=external)
167

    
168
  def GetFreeAddress(self):
169
    """Returns the first available address."""
170
    if self.IsFull():
171
      raise errors.AddressPoolError("%s is full" % self.network)
172

    
173
    idx = self.all_reservations.index(False)
174
    address = str(self.network[idx])
175
    self.Reserve(address)
176
    return address
177

    
178
  def GenerateFree(self):
179
    """Returns the first free address of the network if any or
180
       raises an error if it is full.
181

182
    """
183
    if self.IsFull():
184
      raise errors.AddressPoolError("%s is full" % self.network)
185
    idx = self.all_reservations.search(self.FREE, 1)
186
    return str(self.network[idx])
187

    
188
  def GetExternalReservations(self):
189
    """Returns a list of all externally reserved addresses"""
190
    # pylint: disable=E1103
191
    idxs = self.ext_reservations.search(self.RESERVED)
192
    return [str(self.network[idx]) for idx in idxs]
193

    
194
  @classmethod
195
  def InitializeNetwork(cls, net):
196
    """Initialize an L{objects.Network} object
197

198
    Reserve the network, broadcast and gateway IPs
199

200
    """
201
    obj = cls(net)
202
    obj.Update()
203
    for ip in [obj.network[0], obj.network[-1]]:
204
      obj.Reserve(ip, external=True)
205
    if obj.net.gateway is not None:
206
      obj.Reserve(obj.net.gateway, external=True)
207
    obj.Validate()
208
    return obj