Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / api / networks.py @ 17600d55

History | View | Annotate | Download (11.2 kB)

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

    
34
from logging import getLogger
35

    
36
from django.conf.urls.defaults import patterns
37
from django.conf import settings
38
from django.db.models import Q
39
from django.db import transaction
40
from django.http import HttpResponse
41
from django.template.loader import render_to_string
42
from django.utils import simplejson as json
43

    
44
from synnefo.api import util
45
from synnefo.api.actions import network_actions
46
from synnefo.api.common import method_not_allowed
47
from synnefo.api.faults import (ServiceUnavailable, BadRequest, Forbidden,
48
                                NetworkInUse, OverLimit)
49
from synnefo.db.models import Network
50
from synnefo.db.pools import EmptyPool
51
from synnefo.logic import backend
52

    
53

    
54
log = getLogger('synnefo.api')
55

    
56
urlpatterns = patterns('synnefo.api.networks',
57
    (r'^(?:/|.json|.xml)?$', 'demux'),
58
    (r'^/detail(?:.json|.xml)?$', 'list_networks', {'detail': True}),
59
    (r'^/(\w+)(?:.json|.xml)?$', 'network_demux'),
60
    (r'^/(\w+)/action(?:.json|.xml)?$', 'network_action'),
61
)
62

    
63

    
64
def demux(request):
65
    if request.method == 'GET':
66
        return list_networks(request)
67
    elif request.method == 'POST':
68
        return create_network(request)
69
    else:
70
        return method_not_allowed(request)
71

    
72

    
73
def network_demux(request, network_id):
74
    if request.method == 'GET':
75
        return get_network_details(request, network_id)
76
    elif request.method == 'PUT':
77
        return update_network_name(request, network_id)
78
    elif request.method == 'DELETE':
79
        return delete_network(request, network_id)
80
    else:
81
        return method_not_allowed(request)
82

    
83

    
84
def network_to_dict(network, user_id, detail=True):
85
    d = {'id': str(network.id), 'name': network.name}
86
    if detail:
87
        d['cidr'] = network.subnet
88
        d['cidr6'] = network.subnet6
89
        d['gateway'] = network.gateway
90
        d['gateway6'] = network.gateway6
91
        d['dhcp'] = network.dhcp
92
        d['type'] = network.type
93
        d['updated'] = util.isoformat(network.updated)
94
        d['created'] = util.isoformat(network.created)
95
        d['status'] = network.state
96
        d['public'] = network.public
97

    
98
        attachments = [util.construct_nic_id(nic)
99
                       for nic in network.nics.filter(machine__userid=user_id)]
100
        d['attachments'] = {'values': attachments}
101
    return d
102

    
103

    
104
def render_network(request, networkdict, status=200):
105
    if request.serialization == 'xml':
106
        data = render_to_string('network.xml', {'network': networkdict})
107
    else:
108
        data = json.dumps({'network': networkdict})
109
    return HttpResponse(data, status=status)
110

    
111

    
112
@util.api_method('GET')
113
def list_networks(request, detail=False):
114
    # Normal Response Codes: 200, 203
115
    # Error Response Codes: computeFault (400, 500),
116
    #                       serviceUnavailable (503),
117
    #                       unauthorized (401),
118
    #                       badRequest (400),
119
    #                       overLimit (413)
120

    
121
    log.debug('list_networks detail=%s', detail)
122
    since = util.isoparse(request.GET.get('changes-since'))
123
    user_networks = Network.objects.filter(Q(userid=request.user_uniq) |
124
                                           Q(public=True))
125

    
126
    if since:
127
        user_networks = user_networks.filter(updated__gte=since)
128
        if not user_networks:
129
            return HttpResponse(status=304)
130
    else:
131
        user_networks = user_networks.filter(deleted=False)
132

    
133
    networks = [network_to_dict(network, request.user_uniq, detail)
134
                for network in user_networks]
135

    
136
    if request.serialization == 'xml':
137
        data = render_to_string('list_networks.xml', {
138
            'networks': networks,
139
            'detail': detail})
140
    else:
141
        data = json.dumps({'networks': {'values': networks}})
142

    
143
    return HttpResponse(data, status=200)
144

    
145

    
146
@util.api_method('POST')
147
@transaction.commit_on_success
148
def create_network(request):
149
    # Normal Response Code: 202
150
    # Error Response Codes: computeFault (400, 500),
151
    #                       serviceUnavailable (503),
152
    #                       unauthorized (401),
153
    #                       badMediaType(415),
154
    #                       badRequest (400),
155
    #                       forbidden (403)
156
    #                       overLimit (413)
157

    
158
    req = util.get_request_dict(request)
159
    log.info('create_network %s', req)
160

    
161
    try:
162
        d = req['network']
163
        name = d['name']
164
        # TODO: Fix this temp values:
165
        subnet = d.get('cidr', '192.168.1.0/24')
166
        subnet6 = d.get('cidr6', None)
167
        gateway = d.get('gateway', None)
168
        gateway6 = d.get('gateway6', None)
169
        net_type = d.get('type', 'PRIVATE_MAC_FILTERED')
170
        dhcp = d.get('dhcp', True)
171
    except (KeyError, ValueError):
172
        raise BadRequest('Malformed request.')
173

    
174
    if net_type == 'PUBLIC_ROUTED':
175
        raise Forbidden('Can not create a public network.')
176

    
177
    if net_type not in ['PUBLIC_ROUTED', 'PRIVATE_MAC_FILTERED',
178
                        'PRIVATE_PHYSICAL_VLAN', 'CUSTOM_ROUTED',
179
                        'CUSTOM_BRIDGED']:
180
        raise BadRequest("Invalid network type: %s", net_type)
181
    if net_type not in settings.ENABLED_NETWORKS:
182
        raise Forbidden("Can not create %s network" % net_type)
183

    
184
    user_networks = len(Network.objects.filter(userid=request.user_uniq,
185
                                               deleted=False))
186

    
187
    if user_networks >= settings.MAX_NETWORKS_PER_USER:
188
        raise OverLimit('Network count limit exceeded for your account.')
189

    
190
    cidr_block = int(subnet.split('/')[1])
191
    if not util.validate_network_size(cidr_block):
192
        raise OverLimit("Unsupported network size.")
193

    
194
    try:
195
        link, mac_prefix = util.net_resources(net_type)
196
        if not link:
197
            raise Exception("Can not create network. No connectivity link.")
198

    
199
        network = Network.objects.create(
200
                name=name,
201
                userid=request.user_uniq,
202
                subnet=subnet,
203
                subnet6=subnet6,
204
                gateway=gateway,
205
                gateway6=gateway6,
206
                dhcp=dhcp,
207
                type=net_type,
208
                link=link,
209
                mac_prefix=mac_prefix,
210
                action='CREATE',
211
                state='PENDING')
212
    except EmptyPool:
213
        log.error("Failed to allocate resources for network of type: %s",
214
                  net_type)
215
        raise ServiceUnavailable("Failed to allocate resources for network")
216

    
217
    # Create BackendNetwork entries for each Backend
218
    network.create_backend_network()
219

    
220
    # Create the network in the actual backends
221
    backend.create_network(network)
222

    
223
    networkdict = network_to_dict(network, request.user_uniq)
224
    return render_network(request, networkdict, status=202)
225

    
226

    
227
@util.api_method('GET')
228
def get_network_details(request, network_id):
229
    # Normal Response Codes: 200, 203
230
    # Error Response Codes: computeFault (400, 500),
231
    #                       serviceUnavailable (503),
232
    #                       unauthorized (401),
233
    #                       badRequest (400),
234
    #                       itemNotFound (404),
235
    #                       overLimit (413)
236

    
237
    log.debug('get_network_details %s', network_id)
238
    net = util.get_network(network_id, request.user_uniq)
239
    netdict = network_to_dict(net, request.user_uniq)
240
    return render_network(request, netdict)
241

    
242

    
243
@util.api_method('PUT')
244
def update_network_name(request, network_id):
245
    # Normal Response Code: 204
246
    # Error Response Codes: computeFault (400, 500),
247
    #                       serviceUnavailable (503),
248
    #                       unauthorized (401),
249
    #                       badRequest (400),
250
    #                       forbidden (403)
251
    #                       badMediaType(415),
252
    #                       itemNotFound (404),
253
    #                       overLimit (413)
254

    
255
    req = util.get_request_dict(request)
256
    log.info('update_network_name %s', network_id)
257

    
258
    try:
259
        name = req['network']['name']
260
    except (TypeError, KeyError):
261
        raise BadRequest('Malformed request.')
262

    
263
    net = util.get_network(network_id, request.user_uniq)
264
    if net.public:
265
        raise Forbidden('Can not rename the public network.')
266
    if net.deleted:
267
        raise Network.DeletedError
268
    net.name = name
269
    net.save()
270
    return HttpResponse(status=204)
271

    
272

    
273
@util.api_method('DELETE')
274
@transaction.commit_on_success
275
def delete_network(request, network_id):
276
    # Normal Response Code: 204
277
    # Error Response Codes: computeFault (400, 500),
278
    #                       serviceUnavailable (503),
279
    #                       unauthorized (401),
280
    #                       forbidden (403)
281
    #                       itemNotFound (404),
282
    #                       overLimit (413)
283

    
284
    log.info('delete_network %s', network_id)
285
    net = util.get_network(network_id, request.user_uniq, for_update=True)
286
    if net.public:
287
        raise Forbidden('Can not delete the public network.')
288

    
289
    if net.deleted:
290
        raise Network.DeletedError
291

    
292
    if net.machines.all():  # Nics attached on network
293
        raise NetworkInUse('Machines are connected to network.')
294

    
295

    
296
    net.action = 'DESTROY'
297
    net.save()
298

    
299
    backend.delete_network(net)
300
    return HttpResponse(status=204)
301

    
302

    
303
@util.api_method('POST')
304
def network_action(request, network_id):
305
    req = util.get_request_dict(request)
306
    log.debug('network_action %s %s', network_id, req)
307
    if len(req) != 1:
308
        raise BadRequest('Malformed request.')
309

    
310
    net = util.get_network(network_id, request.user_uniq)
311
    if net.public:
312
        raise Forbidden('Can not modify the public network.')
313
    if net.deleted:
314
        raise Network.DeletedError
315

    
316
    try:
317
        key = req.keys()[0]
318
        val = req[key]
319
        assert isinstance(val, dict)
320
        return network_actions[key](request, net, req[key])
321
    except KeyError:
322
        raise BadRequest('Unknown action.')
323
    except AssertionError:
324
        raise BadRequest('Invalid argument.')