subnets.py 11.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Copyright 2013 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

34
import ipaddr
35
from logging import getLogger
36
37
38
39
from functools import wraps

from django.conf import settings
from django.db import transaction
40
41
from django.db.models import Q

42
43
from snf_django.lib import api
from snf_django.lib.api import faults
44
from synnefo.logic import utils
45
from synnefo.api import util
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

from synnefo.db.models import Subnet, Network, IPPoolTable

log = getLogger(__name__)


def subnet_command(action):
    def decorator(func):
        @wraps(func)
        @transaction.commit_on_success()
        def wrapper(subnet, *args, **kwargs):
            return func(subnet, *args, **kwargs)
        return wrapper
    return decorator


def list_subnets(user_id):
    """List all subnets of a user"""
64
    log.debug('list_subnets %s', user_id)
65

66
67
68
    query = (((Q(network__userid=user_id) & Q(network__public=False)) |
              Q(network__public=True)) & Q(deleted=False))
    user_subnets = Subnet.objects.filter(query)
69
    return user_subnets
70
71
72


@transaction.commit_on_success
73
74
75
76
77
def create_subnet(*args, **kwargs):
    return _create_subnet(*args, **kwargs)


def _create_subnet(network_id, user_id, cidr, name, ipversion=4, gateway=None,
78
                   dhcp=True, slaac=True, dns_nameservers=None,
79
                   allocation_pools=None, host_routes=None):
80
    """Create a subnet
81

82
    network_id and the desired cidr are mandatory, everything else is optional
83

84
85
86
87
    """
    try:
        network = Network.objects.get(id=network_id)
    except Network.DoesNotExist:
88
        raise api.faults.ItemNotFound("No network found with that id")
89

90
91
92
    if network.deleted:
        raise api.faults.BadRequest("Network has been deleted")

93
94
95
    if user_id != network.userid:
        raise api.faults.Unauthorized("Unauthorized operation")

96
97
98
    if ipversion not in [4, 6]:
        raise api.faults.BadRequest("Malformed IP version type")

99
100
    check_number_of_subnets(network, ipversion)

101
102
103
104
105
    if network.backend_networks.exists():
        raise api.faults.BadRequest("Cannot create subnet in network %s, VMs"
                                    " are already connected to this network" %
                                    network_id)

106
    try:
107
        cidr_ip = ipaddr.IPNetwork(cidr)
108
109
    except ValueError:
        raise api.faults.BadRequest("Malformed CIDR")
110

111
    if ipversion == 6:
112
        validate_subnet_params(subnet6=cidr, gateway6=gateway)
113
    else:
114
        validate_subnet_params(subnet=cidr, gateway=gateway)
115

116
117
    name = utils.check_name_length(name, Subnet.SUBNET_NAME_LENGTH, "Subnet "
                                   "name is too long")
118
119
    sub = Subnet.objects.create(name=name, network=network, cidr=cidr,
                                ipversion=ipversion, gateway=gateway,
120
121
                                dhcp=dhcp, host_routes=host_routes,
                                dns_nameservers=dns_nameservers)
122

123
124
    gateway_ip = ipaddr.IPAddress(gateway) if gateway else None

125
126
127
    if allocation_pools is not None:
        if ipversion == 6:
            raise api.faults.Conflict("Can't allocate an IP Pool in IPv6")
128
    elif ipversion == 4:
129
130
        # Check if the gateway is the first IP of the subnet, or the last. In
        # that case create a single ip pool.
131
132
        if gateway_ip:
            if int(gateway_ip) - int(cidr_ip) == 1:
133
                allocation_pools = [(gateway_ip + 1, cidr_ip.broadcast - 1)]
134
135
            elif int(cidr_ip.broadcast) - int(gateway_ip) == 1:
                allocation_pools = [(cidr_ip.network + 1, gateway_ip - 1)]
136
137
138
            else:
                # If the gateway isn't the first available ip, create two
                # different ip pools adjacent to said ip
139
140
                allocation_pools = [(cidr_ip.network + 1, gateway_ip - 1),
                                    (gateway_ip + 1, cidr_ip.broadcast - 1)]
141
        else:
142
            allocation_pools = [(cidr_ip.network + 1, cidr_ip.broadcast - 1)]
143

144
    if allocation_pools:
145
146
        # Validate the allocation pools
        validate_pools(allocation_pools, cidr_ip, gateway_ip)
147
        create_ip_pools(allocation_pools, cidr_ip, sub)
148
149
150
151

    return sub


152
153
154
def get_subnet(subnet_id, user_id, for_update=False):
    """Return a Subnet instance or raise ItemNotFound."""

155
    try:
156
157
158
159
160
161
162
163
164
165
        objects = Subnet.objects
        subnet_id = int(subnet_id)
        subnet = objects.get(id=subnet_id)
        if (subnet.network.userid != user_id) and (subnet.network.public is
                                                   False):
            raise api.faults.Unauthorized("You're not allowed to view this "
                                          "subnet")
        return subnet
    except (ValueError, TypeError):
        raise faults.BadRequest("Invalid subnet ID '%s'" % subnet_id)
166
    except Subnet.DoesNotExist:
167
        raise faults.ItemNotFound("Subnet '%s' not found." % subnet_id)
168
169
170


def delete_subnet():
171
    """Delete a subnet, raises BadRequest
172
    A subnet is deleted ONLY when the network that it belongs to is deleted
173

174
175
176
177
178
    """
    raise api.faults.BadRequest("Deletion of a subnet is not supported")


@transaction.commit_on_success
179
def update_subnet(sub_id, name, user_id):
180
    """Update the fields of a subnet
181
    Only the name can be updated
182

183
    """
184
    log.info('Update subnet %s, name %s' % (sub_id, name))
185
186
187
188
189
190

    try:
        subnet = Subnet.objects.get(id=sub_id)
    except:
        raise api.faults.ItemNotFound("Subnet not found")

191
192
193
    if user_id != subnet.network.userid:
        raise api.faults.Unauthorized("Unauthorized operation")

194
195
    utils.check_name_length(name, Subnet.SUBNET_NAME_LENGTH, "Subnet name is "
                            " too long")
196
197
198
199
200
201
202
203
204
205

    subnet.name = name
    subnet.save()

    return subnet


#Utility functions
def create_ip_pools(pools, cidr, subnet):
    """Create IP Pools in the database"""
206
207
208
209
210
211
212
213
214
    return [_create_ip_pool(pool, cidr, subnet) for pool in pools]


def _create_ip_pool(pool, cidr, subnet):
    size = int(pool[1]) - int(pool[0]) + 1
    base = str(cidr)
    offset = int(pool[0]) - int(cidr.network)
    return IPPoolTable.objects.create(size=size, offset=offset,
                                      base=base, subnet=subnet)
215
216
217
218
219
220
221
222
223


def check_number_of_subnets(network, version):
    """Check if a user can add a subnet in a network"""
    if network.subnets.filter(ipversion=version):
        raise api.faults.BadRequest("Only one subnet of IPv4/IPv6 per "
                                    "network is allowed")


224
def validate_pools(pool_list, cidr, gateway):
225
226
    """Validate IP Pools

227
228
229
230
231
232
233
    Validate the given IP pools are inside the cidr range
    Validate there are no overlaps in the given pools
    Finally, validate the gateway isn't in the given ip pools
    Input must be a list containing a sublist with start/end ranges as
    ipaddr.IPAddress items eg.,
    [[IPv4Address('192.168.42.11'), IPv4Address('192.168.42.15')],
     [IPv4Address('192.168.42.30'), IPv4Address('192.168.42.60')]]
234

235
236
237
238
239
240
241
242
243
244
    """
    if pool_list[0][0] <= cidr.network:
        raise api.faults.Conflict("IP Pool out of bounds")
    elif pool_list[-1][1] >= cidr.broadcast:
        raise api.faults.Conflict("IP Pool out of bounds")

    for start, end in pool_list:
        if start > end:
            raise api.faults.Conflict("Invalid IP pool range")
        # Raise BadRequest if gateway is inside the pool range
245
246
247
        if gateway:
            if not (gateway < start or gateway > end):
                raise api.faults.Conflict("Gateway cannot be in pool range")
248

249
    # Check if there is a conflict between the IP Pool ranges
250
251
252
253
254
    end = cidr.network
    for pool in pool_list:
        if end >= pool[0]:
            raise api.faults.Conflict("IP Pool range conflict")
        end = pool[1]
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299


def validate_subnet_params(subnet=None, gateway=None, subnet6=None,
                           gateway6=None):
    if subnet:
        try:
            # Use strict option to not all subnets with host bits set
            network = ipaddr.IPv4Network(subnet, strict=True)
        except ValueError:
            raise faults.BadRequest("Invalid network IPv4 subnet")

        # Check that network size is allowed!
        prefixlen = network.prefixlen
        if prefixlen > 29 or prefixlen <= settings.MAX_CIDR_BLOCK:
            raise faults.OverLimit(
                message="Unsupported network size",
                details="Netmask must be in range: (%s, 29]" %
                settings.MAX_CIDR_BLOCK)
        if gateway:  # Check that gateway belongs to network
            try:
                gateway = ipaddr.IPv4Address(gateway)
            except ValueError:
                raise faults.BadRequest("Invalid network IPv4 gateway")
            if not gateway in network:
                raise faults.BadRequest("Invalid network IPv4 gateway")

    if subnet6:
        try:
            # Use strict option to not all subnets with host bits set
            network6 = ipaddr.IPv6Network(subnet6, strict=True)
        except ValueError:
            raise faults.BadRequest("Invalid network IPv6 subnet")
        # Check that network6 is an /64 subnet, because this is imposed by
        # 'mac2eui64' utiity.
        if network6.prefixlen != 64:
            msg = ("Unsupported IPv6 subnet size. Network netmask must be"
                   " /64")
            raise faults.BadRequest(msg)
        if gateway6:
            try:
                gateway6 = ipaddr.IPv6Address(gateway6)
            except ValueError:
                raise faults.BadRequest("Invalid network IPv6 gateway")
            if not gateway6 in network6:
                raise faults.BadRequest("Invalid network IPv6 gateway")
300
301
302
303
304
305
306
307
308
309


def parse_allocation_pools(allocation_pools):
    alloc = list()
    for pool in allocation_pools:
        try:
            start, end = pool.split(',')
            alloc.append([ipaddr.IPv4Address(start),
                          ipaddr.IPv4Address(end)])
        except ValueError:
310
            raise faults.BadRequest("Malformed IPv4 address")
311
312

    return alloc