subnets.py 9.36 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
# 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

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

from snf_django.lib.api import utils
43
from synnefo.db.models import Subnet
44
from synnefo.logic import subnets
45
from synnefo.api import util
46

47
import ipaddr
48
49
50
51

log = getLogger(__name__)


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


58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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"""
81
82
83
84
85
86
87
88
89
90
91
    userid = request.user_uniq
    subnets_list = Subnet.objects.filter(Q(network__public=True) |
                                         (Q(network__userid=userid) &
                                          Q(network__public=False)))\
                                 .order_by("id")
    subnets_list = subnets_list.prefetch_related("ip_pools")\
                               .select_related("network")
    subnets_list = api.utils.filter_modified_since(request,
                                                   objects=subnets_list)

    subnets_dict = [subnet_to_dict(sub) for sub in subnets_list]
92

93
94
95
96
97
98
99
    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):
100
    """Create a subnet
101
    network_id and the desired cidr are mandatory, everything else is optional
102

103
    """
104
105
106
107
108
109
110
111
112
113
    dictionary = utils.get_request_dict(request)
    log.info('create subnet %s', dictionary)

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

114
115
    name = subnet.get('name', None)
    ipversion = subnet.get('ip_version', 4)
116

117
118
119
120
    allocation_pools = subnet.get('allocation_pools', None)
    if allocation_pools is not None:
        allocation_pools = parse_ip_pools(allocation_pools)

121
122
123
    try:
        cidr_ip = ipaddr.IPNetwork(cidr)
    except ValueError:
124
        raise api.faults.BadRequest("Malformed CIDR '%s'" % cidr)
125

126
127
128
    # If no gateway is specified, send an empty string, because None is used
    # if the user wants no gateway at all
    gateway = subnet.get('gateway_ip', "")
129
    if gateway is "":
130
        gateway = str(cidr_ip.network + 1)
131

132
    dhcp = subnet.get('enable_dhcp', True)
133
134
135
136
137
138
139
140
141
142
    slaac = subnet.get('enable_slaac', None)

    if ipversion == 6:
        if slaac is not None:
            dhcp = check_boolean_value(slaac, "enable_slaac")
        else:
            dhcp = check_boolean_value(dhcp, "dhcp")
    else:
        dhcp = check_boolean_value(dhcp, "dhcp")

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

146
147
148
149
150
151
    sub = subnets.create_subnet(network_id=network_id,
                                cidr=cidr,
                                name=name,
                                ipversion=ipversion,
                                gateway=gateway,
                                dhcp=dhcp,
152
                                slaac=slaac,
153
154
155
156
                                dns_nameservers=dns,
                                allocation_pools=allocation_pools,
                                host_routes=hosts,
                                user_id=request.user_uniq)
157
158
159

    subnet_dict = subnet_to_dict(sub)
    data = json.dumps({'subnet': subnet_dict})
160
    return HttpResponse(data, status=201)
161
162
163
164
165
166


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

169
    if (subnet.network.userid != user_id) and (subnet.network.public is False):
170
        raise api.faults.Unauthorized("You're not allowed to view this subnet")
171

172
    subnet_dict = subnet_to_dict(subnet)
173
174
175
176
177
178
    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):
179
    """Delete a subnet, raises BadRequest
180
    A subnet is deleted ONLY when the network that it belongs to is deleted
181

182
183
184
185
186
187
    """
    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):
188
    """Update the fields of a subnet
189
    Only the name can be updated, everything else returns BadRequest
190

191
192
193
194
195
196
197
198
199
200
    """

    dictionary = utils.get_request_dict(request)
    user_id = request.user_uniq

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

201
    if len(subnet) != 1 or "name" not in subnet:
202
203
204
205
        raise api.faults.BadRequest("Only the name of subnet can be updated")

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

206
    subnet_dict = subnet_to_dict(subnets.update_subnet(sub_id, name, user_id))
207
208
209
210
211
212
213
    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"""
214
215
    dns = check_empty_lists(subnet.dns_nameservers)
    hosts = check_empty_lists(subnet.host_routes)
216
217
218
219
220
221

    allocation_pools = [render_ip_pool(pool)
                        for pool in subnet.ip_pools.all()]

    network = subnet.network
    d = {'id': str(subnet.id),
222
         'network_id': str(subnet.network_id),
223
224
225
226
227
228
229
230
231
232
         'name': subnet.name if subnet.name is not None else "",
         'tenant_id': network.userid,
         'user_id': network.userid,
         'gateway_ip': subnet.gateway,
         'ip_version': subnet.ipversion,
         'cidr': subnet.cidr,
         'enable_dhcp': subnet.dhcp,
         'dns_nameservers': dns,
         'host_routes': hosts,
         'allocation_pools': allocation_pools}
233
234

    if subnet.ipversion == 6:
235
236
237
        d['enable_slaac'] = subnet.dhcp

    d['links'] = util.subnet_to_links(subnet.id)
238

239
    return d
240
241


242
243
244
245
246
247
248
249
250
251
def render_ip_pool(pool):
    network = ipaddr.IPNetwork(pool.base).network
    start = str(network + pool.offset)
    end = str(network + pool.offset + pool.size - 1)
    return {"start": start, "end": end}


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'}]
252
    to
253
254
            [(IPv4Address("192.168.42.1"), IPv4Address("192.168.42.15")),
             (IPv4Address("192.168.42.30"), IPv4Address("192.168.42.60"))]
255

256
    """
257
258
259
260
261
262
263
264
    try:
        return sorted([(ipaddr.IPv4Address(p["start"]),
                        ipaddr.IPv4Address(p["end"])) for p in pools])
    except KeyError:
        raise api.faults.BadRequest("Malformed allocation pool.")
    except ipaddr.AddressValueError:
        raise api.faults.BadRequest("Allocation pools contain invalid IPv4"
                                    " address")
265
266


267
268
269
270
271
272
273
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


274
275
276
277
278
279
def check_boolean_value(value, key):
    """Check if dhcp value is in acceptable values"""
    if value not in [True, False]:
        raise api.faults.BadRequest("Malformed request, %s must "
                                    "be True or False" % key)
    return value