Statistics
| Branch: | Tag: | Revision:

root / lib / network.py @ beb81ea5

History | View | Annotate | Download (5.9 kB)

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
      # pylint: disable=E1103
67
      self.reservations.setall(False)
68

    
69
    if self.net.ext_reservations:
70
      self.ext_reservations = bitarray(self.net.ext_reservations)
71
    else:
72
      self.ext_reservations = bitarray(self.network.numhosts)
73
      # pylint: disable=E1103
74
      self.ext_reservations.setall(False)
75

    
76
    assert len(self.reservations) == self.network.numhosts
77
    assert len(self.ext_reservations) == self.network.numhosts
78

    
79
  def Contains(self, address):
80
    if address is None:
81
      return False
82
    addr = ipaddr.IPAddress(address)
83

    
84
    return addr in self.network
85

    
86
  def _GetAddrIndex(self, address):
87
    addr = ipaddr.IPAddress(address)
88

    
89
    if not addr in self.network:
90
      raise errors.AddressPoolError("%s does not contain %s" %
91
                                    (self.network, addr))
92

    
93
    return int(addr) - int(self.network.network)
94

    
95
  def Update(self):
96
    """Write address pools back to the network object"""
97
    # pylint: disable=E1103
98
    self.net.ext_reservations = self.ext_reservations.to01()
99
    self.net.reservations = self.reservations.to01()
100

    
101
  def _Mark(self, address, value=True, external=False):
102
    idx = self._GetAddrIndex(address)
103
    if external:
104
      self.ext_reservations[idx] = value
105
    else:
106
      self.reservations[idx] = value
107
    self.Update()
108

    
109
  def _GetSize(self):
110
    return 2**(32 - self.network.prefixlen)
111

    
112
  @property
113
  def all_reservations(self):
114
    """Return a combined map of internal + external reservations."""
115
    return (self.reservations | self.ext_reservations)
116

    
117
  def Validate(self):
118
    assert self.net.family == 4
119
    assert len(self.reservations) == self._GetSize()
120
    assert len(self.ext_reservations) == self._GetSize()
121
    all_res = self.reservations & self.ext_reservations
122
    assert not all_res.any()
123

    
124
    if self.gateway is not None:
125
      assert self.net.family == self.gateway.version
126
      assert self.gateway in self.network
127

    
128
    if self.network6 and self.gateway6:
129
      assert self.gateway6 in self.network6
130

    
131
    return True
132

    
133
  def IsFull(self):
134
    """Check whether the network is full"""
135
    return self.all_reservations.all()
136

    
137
  def GetReservedCount(self):
138
    """Get the count of reserved addresses"""
139
    return self.all_reservations.count(True)
140

    
141
  def GetFreeCount(self):
142
    """Get the count of unused addresses"""
143
    return self.all_reservations.count(False)
144

    
145
  def GetMap(self):
146
    """Return a textual representation of the network's occupation status."""
147
    return self.all_reservations.to01().replace("1", "X").replace("0", ".")
148

    
149
  def IsReserved(self, address):
150
    """Checks if the given IP is reserved"""
151
    idx = self._GetAddrIndex(address)
152
    return self.all_reservations[idx]
153

    
154
  def Reserve(self, address, external=False):
155
    """Mark an address as used."""
156
    if self.IsReserved(address):
157
      raise errors.AddressPoolError("%s is already reserved" % address)
158
    self._Mark(address, external=external)
159

    
160
  def Release(self, address, external=False):
161
    """Release a given address reservation."""
162
    self._Mark(address, value=False, external=external)
163

    
164
  def GetFreeAddress(self):
165
    """Returns the first available address."""
166
    if self.IsFull():
167
      raise errors.AddressPoolError("%s is full" % self.network)
168

    
169
    idx = self.all_reservations.index(False)
170
    address = str(self.network[idx])
171
    self.Reserve(address)
172
    return address
173

    
174
  def GenerateFree(self):
175
    """A generator for free addresses."""
176
    def _iter_free():
177
      for idx in self.all_reservations.search("0", 64):
178
        yield str(self.network[idx])
179
    # pylint: disable=E1101
180
    return _iter_free().next
181

    
182
  def GetExternalReservations(self):
183
    """Returns a list of all externally reserved addresses"""
184
    idxs = self.ext_reservations.search("1")
185
    return [str(self.network[idx]) for idx in idxs]
186

    
187
  @classmethod
188
  def InitializeNetwork(cls, net):
189
    """Initialize an L{objects.Network} object
190

191
    Reserve the network, broadcast and gateway IPs
192

193
    """
194
    obj = cls(net)
195
    obj.Update()
196
    for ip in [obj.network[0], obj.network[-1]]:
197
      obj.Reserve(ip, external=True)
198
    if obj.net.gateway is not None:
199
      obj.Reserve(obj.net.gateway, external=True)
200
    obj.Validate()
201
    return obj