subnets.py 14.1 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
34
35
36
37
# 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.

from logging import getLogger
from snf_django.lib import api
from snf_django.lib.api import faults

38
from django.conf.urls import patterns
39
40
41
42
from django.http import HttpResponse
from django.utils import simplejson as json

from snf_django.lib.api import utils
43
from synnefo.db.models import Subnet, Network, IPPoolTable
44
45
from synnefo.logic import networks

46
from ipaddr import IPv4Network, IPv6Network, IPv4Address, IPAddress, IPNetwork
47
48
49
50

log = getLogger(__name__)


51
52
53
54
55
56
urlpatterns = patterns(
    'synnefo.api.subnets',
    (r'^(?:/|.json|.xml)?$', 'demux'),
    (r'^/([-\w]+)(?:/|.json|.xml)?$', 'subnet_demux'))


57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def demux(request):
    if request.method == 'GET':
        return list_subnets(request)
    elif request.method == 'POST':
        return create_subnet(request)
    else:
        return api.api_method_not_allowed(request)


def subnet_demux(request, sub_id):
    if request.method == 'GET':
        return get_subnet(request, sub_id)
    elif request.method == 'DELETE':
        return delete_subnet(request, sub_id)
    elif request.method == 'PUT':
        return update_subnet(request, sub_id)
    else:
        return api.api_method_not_allowed(request)


@api.api_method(http_method='GET', user_required=True, logger=log)
def list_subnets(request):
    """List all subnets of a user"""
    log.debug('list_subnets')

    user_subnets = Subnet.objects.filter(network__userid=request.user_uniq)
    subnets_dict = [subnet_to_dict(sub)
                    for sub in user_subnets.order_by('id')]
    data = json.dumps({'subnets': subnets_dict})

    return HttpResponse(data, status=200)


@api.api_method(http_method='POST', user_required=True, logger=log)
def create_subnet(request):
92
93
94
95
    """
    Create a subnet
    network_id and the desired cidr are mandatory, everything else is optional
    """
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131

    dictionary = utils.get_request_dict(request)
    log.info('create subnet %s', dictionary)
    user_id = request.user_uniq

    try:
        subnet = dictionary['subnet']
        network_id = subnet['network_id']
        cidr = subnet['cidr']
    except KeyError:
        raise api.faults.BadRequest("Malformed request")

    try:
        network = Network.objects.get(id=network_id)
    except Network.DoesNotExist:
        raise api.faults.ItemNotFound("No networks found with that id")

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

    ipversion = subnet.get('ip_version', 4)
    if ipversion not in [4, 6]:
        raise api.faults.BadRequest("Malformed IP version type")

    # Returns the first available IP in the subnet
    if ipversion == 6:
        potential_gateway = str(IPv6Network(cidr).network + 1)
        check_number_of_subnets(network, 6)
    else:
        potential_gateway = str(IPv4Network(cidr).network + 1)
        check_number_of_subnets(network, 4)

    gateway = subnet.get('gateway_ip', potential_gateway)

    if ipversion == 6:
        networks.validate_network_params(None, None, cidr, gateway)
132
        slac = subnet.get('enable_slac', None)
133
        if slac is not None:
134
            dhcp = check_boolean_value(slac, "enable_slac")
135
        else:
136
            dhcp = check_boolean_value(subnet.get('enable_dhcp', True), "dhcp")
137
138
    else:
        networks.validate_network_params(cidr, gateway)
139
        dhcp = check_boolean_value(subnet.get('enable_dhcp', True), "dhcp")
140

141
142
143
144
145
146
147
148
    name = check_name_length(subnet.get('name', None))

    dns = subnet.get('dns_nameservers', None)
    hosts = subnet.get('host_routes', None)

    gateway_ip = IPAddress(gateway)
    cidr_ip = IPNetwork(cidr)

149
150
    allocation_pools = subnet.get('allocation_pools', None)

151
152
153
154
155
156
157
158
    sub = Subnet.objects.create(name=name, network=network, cidr=cidr,
                                ipversion=ipversion, gateway=gateway,
                                dhcp=dhcp, host_routes=hosts,
                                dns_nameservers=dns)

    pool_list = list()
    if allocation_pools is not None:
        # If the user specified IP allocation pools, validate them and use them
159
        if ipversion == 6:
160
161
            raise api.faults.Conflict("Can't allocate an IP Pool in IPv6")
        pools = parse_ip_pools(allocation_pools)
162
163
164
165
166
167
168
169
170
171
172
173
        pool_list = string_to_ipaddr(pools)
        validate_subpools(pool_list, cidr_ip, gateway_ip)
    if allocation_pools is None and ipversion == 4:
        # Check if the gateway is the first IP of the subnet, in this case
        # create a single ip pool
        if int(gateway_ip) - int(cidr_ip) == 1:
            pool_list = [[gateway_ip + 1, cidr_ip.broadcast - 1]]
        else:
            # If the gateway isn't the first available ip, create two different
            # ip pools adjacent to said ip
            pool_list.append([cidr_ip.network + 1, gateway_ip - 1])
            pool_list.append([gateway_ip + 1, cidr_ip.broadcast - 1])
174

175
176
    if pool_list:
        create_ip_pools(pool_list, cidr_ip, sub)
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254

    subnet_dict = subnet_to_dict(sub)
    data = json.dumps({'subnet': subnet_dict})
    return HttpResponse(data, status=200)


@api.api_method(http_method='GET', user_required=True, logger=log)
def get_subnet(request, sub_id):
    """Show info of a specific subnet"""
    log.debug('get_subnet %s', sub_id)
    user_id = request.user_uniq

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

    if subnet.network.userid != user_id:
        raise api.failts.Unauthorized("You're not allowed to view this subnet")

    subnet_dict = subnet_to_dict(subnet)
    data = json.dumps({'subnet': subnet_dict})
    return HttpResponse(data, status=200)


@api.api_method(http_method='DELETE', user_required=True, logger=log)
def delete_subnet(request, sub_id):
    """
    Delete a subnet, raises BadRequest
    A subnet is deleted ONLY when the network that it belongs to is deleted
    """
    raise api.faults.BadRequest("Deletion of a subnet is not supported")


@api.api_method(http_method='PUT', user_required=True, logger=log)
def update_subnet(request, sub_id):
    """
    Update the fields of a subnet
    Only the name can be updated, everything else returns BadRequest
    """

    dictionary = utils.get_request_dict(request)
    log.info('Update subnet %s', dictionary)
    user_id = request.user_uniq

    try:
        subnet = dictionary['subnet']
    except KeyError:
        raise api.faults.BadRequest("Malformed request")

    original_subnet = get_subnet_fromdb(sub_id, user_id)
    original_dict = subnet_to_dict(original_subnet)

    if len(subnet) != 1:
        raise api.faults.BadRequest("Only the name of subnet can be updated")

    name = subnet.get("name", None)

    if not name:
        raise api.faults.BadRequest("Only the name of subnet can be updated")

    check_name_length(name)

    try:
        original_subnet.name = name
        original_subnet.save()
    except:
        #Fix me
        return "Unknown Error"

    subnet_dict = subnet_to_dict(original_subnet)
    data = json.dumps({'subnet': subnet_dict})
    return HttpResponse(data, status=200)


#Utility functions
def subnet_to_dict(subnet):
    """Returns a dictionary containing the info of a subnet"""
255
256
    dns = check_empty_lists(subnet.dns_nameservers)
    hosts = check_empty_lists(subnet.host_routes)
257
258
259
260
261
262
263
264
    allocation_pools = subnet.ip_pools.all()
    pools = list()

    if allocation_pools:
        for pool in allocation_pools:
            cidr = IPNetwork(pool.base)
            start = str(cidr.network + pool.offset)
            end = str(cidr.network + pool.offset + pool.size - 1)
265
            pools.append({"start": start, "end": end})
266
267
268
269
270
271

    dictionary = dict({'id': str(subnet.id),
                       'network_id': str(subnet.network.id),
                       'name': subnet.name if subnet.name is not None else "",
                       'tenant_id': subnet.network.userid,
                       'user_id': subnet.network.userid,
272
                       'gateway_ip': subnet.gateway,
273
274
                       'ip_version': subnet.ipversion,
                       'cidr': subnet.cidr,
275
                       'enable_dhcp': subnet.dhcp,
276
277
                       'dns_nameservers': dns,
                       'host_routes': hosts,
278
                       'allocation_pools': pools if pools is not None else []})
279
280

    if subnet.ipversion == 6:
281
        dictionary['enable_slac'] = subnet.dhcp
282

283
284
285
    return dictionary


286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
def string_to_ipaddr(pools):
    """
    Convert [["192.168.42.1", "192.168.42.15"],
            ["192.168.42.30", "192.168.42.60"]]
    to
            [[IPv4Address('192.168.42.1'), IPv4Address('192.168.42.15')],
            [IPv4Address('192.168.42.30'), IPv4Address('192.168.42.60')]]
    and sort the output
    """
    pool_list = [(map(lambda ip_str: IPAddress(ip_str), pool))
                 for pool in pools]
    pool_list.sort()
    return pool_list


def create_ip_pools(pools, cidr, subnet):
    """Placeholder"""
    for pool in pools:
        size = int(pool[1]) - int(pool[0]) + 1
        base = str(cidr)
        offset = int(pool[0]) - int(cidr.network)
        ip_pool = IPPoolTable.objects.create(size=size, offset=offset,
                                             base=base, subnet=subnet)


311
312
313
314
315
316
317
def check_empty_lists(value):
    """Check if value is Null/None, in which case we return an empty list"""
    if value is None:
        return []
    return value


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


325
def check_boolean_value(value, key):
326
    """Check if dhcp value is in acceptable values"""
327
328
329
330
    if value not in [True, False]:
        raise api.faults.BadRequest("Malformed request, %s must "
                                    "be True or False" % key)
    return value
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363


def check_name_length(name):
    """Check if the length of a name is within acceptable value"""
    if len(str(name)) > Subnet.SUBNET_NAME_LENGTH:
        raise api.faults.BadRequest("Subnet name too long")
    return name


def check_for_hosts_dns(subnet):
    """
    Check if a request contains host_routes or dns_nameservers options
    Expects the request in a dictionary format
    """
    if subnet.get('host_routes', None):
        raise api.faults.BadRequest("Setting host routes isn't supported")
    if subnet.get('dns_nameservers', None):
        raise api.faults.BadRequest("Setting dns nameservers isn't supported")


def get_subnet_fromdb(subnet_id, user_id, for_update=False):
    """
    Return a Subnet instance or raise ItemNotFound.
    This is the same as util.get_network
    """
    try:
        subnet_id = int(subnet_id)
        if for_update:
            return Subnet.objects.select_for_update().get(id=subnet_id,
                                                          network__userid=
                                                          user_id)
        return Subnet.objects.get(id=subnet_id, network__userid=user_id)
    except (ValueError, Subnet.DoesNotExist):
364
        raise api.faults.ItemNotFound('Subnet not found')
365
366
367
368
369
370
371
372
373
374
375
376


def parse_ip_pools(pools):
    """
    Convert [{'start': '192.168.42.1', 'end': '192.168.42.15'},
             {'start': '192.168.42.30', 'end': '192.168.42.60'}]
    to
            [["192.168.42.1", "192.168.42.15"],
             ["192.168.42.30", "192.168.42.60"]]
    """
    pool_list = list()
    for pool in pools:
377
378
        parse = [pool["start"], pool["end"]]
        pool_list.append(parse)
379
380
381
    return pool_list


382
def validate_subpools(pool_list, cidr, gateway):
383
384
385
    """
    Validate the given IP pools are inside the cidr range
    Validate there are no overlaps in the given pools
386
    Finally, validate the gateway isn't in the given ip pools
387
388
389
390
    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')]]
391
392
    """
    if pool_list[0][0] <= cidr.network:
393
        raise api.faults.Conflict("IP Pool out of bounds")
394
    elif pool_list[-1][1] >= cidr.broadcast:
395
        raise api.faults.Conflict("IP Pool out of bounds")
396
397

    for start, end in pool_list:
398
        if start > end:
399
400
401
402
403
404
405
406
            raise api.faults.Conflict("Invalid IP pool range")
        # Raise BadRequest if gateway is inside the pool range
        if not (gateway < start or gateway > end):
            raise api.faults.Conflict("Gateway cannot be in pool range")

    # Check if there is a conflict between the IP Poll ranges
    end = cidr.network
    for pool in pool_list:
407
        if end >= pool[0]:
408
409
            raise api.faults.Conflict("IP Pool range conflict")
        end = pool[1]