Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (10.4 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 (BadRequest, Unauthorized,
48
                                NetworkInUse, OverLimit)
49
from synnefo.db.models import Network, Pool
50
from synnefo.logic import backend
51

    
52

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

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

    
62

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

    
71

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

    
82

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

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

    
102

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

    
110

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

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

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

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

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

    
142
    return HttpResponse(data, status=200)
143

    
144

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

    
156
    req = util.get_request_dict(request)
157
    log.debug('create_network %s', req)
158

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

    
172
    if typ == 'PUBLIC_ROUTED':
173
        raise Unauthorized('Can not create a public network.')
174

    
175
    user_networks = len(Network.objects.filter(userid=request.user_uniq,
176
                                               deleted=False))
177
    if user_networks == settings.MAX_NETWORKS_PER_USER:
178
        raise OverLimit('Network count limit exceeded for your account.')
179

    
180
    cidr_block = int(subnet.split('/')[1])
181
    if not util.validate_network_size(cidr_block):
182
        raise OverLimit("Unsupported network size.")
183

    
184
    try:
185
        link = util.network_link_from_type(typ)
186
        if not link:
187
            raise Exception("Can not create network. No connectivity link.")
188

    
189
        network = Network.objects.create(
190
                name=name,
191
                userid=request.user_uniq,
192
                subnet=subnet,
193
                subnet6=subnet6,
194
                gateway=gateway,
195
                gateway6=gateway6,
196
                dhcp=dhcp,
197
                type=typ,
198
                link=link,
199
                action='CREATE',
200
                state='PENDING')
201
    except Pool.PoolExhausted:
202
        raise OverLimit('Network count limit exceeded.')
203

    
204
    # Create BackendNetwork entries for each Backend
205
    network.create_backend_network()
206

    
207
    # Create the network in the actual backends
208
    backend.create_network(network)
209

    
210
    networkdict = network_to_dict(network, request.user_uniq)
211
    return render_network(request, networkdict, status=202)
212

    
213

    
214
@util.api_method('GET')
215
def get_network_details(request, network_id):
216
    # Normal Response Codes: 200, 203
217
    # Error Response Codes: computeFault (400, 500),
218
    #                       serviceUnavailable (503),
219
    #                       unauthorized (401),
220
    #                       badRequest (400),
221
    #                       itemNotFound (404),
222
    #                       overLimit (413)
223

    
224
    log.debug('get_network_details %s', network_id)
225
    net = util.get_network(network_id, request.user_uniq)
226
    netdict = network_to_dict(net, request.user_uniq)
227
    return render_network(request, netdict)
228

    
229

    
230
@util.api_method('PUT')
231
def update_network_name(request, network_id):
232
    # Normal Response Code: 204
233
    # Error Response Codes: computeFault (400, 500),
234
    #                       serviceUnavailable (503),
235
    #                       unauthorized (401),
236
    #                       badRequest (400),
237
    #                       badMediaType(415),
238
    #                       itemNotFound (404),
239
    #                       overLimit (413)
240

    
241
    req = util.get_request_dict(request)
242
    log.debug('update_network_name %s', network_id)
243

    
244
    try:
245
        name = req['network']['name']
246
    except (TypeError, KeyError):
247
        raise BadRequest('Malformed request.')
248

    
249
    net = util.get_network(network_id, request.user_uniq)
250
    if net.public:
251
        raise Unauthorized('Can not rename the public network.')
252
    net.name = name
253
    net.save()
254
    return HttpResponse(status=204)
255

    
256

    
257
@util.api_method('DELETE')
258
@transaction.commit_on_success
259
def delete_network(request, network_id):
260
    # Normal Response Code: 204
261
    # Error Response Codes: computeFault (400, 500),
262
    #                       serviceUnavailable (503),
263
    #                       unauthorized (401),
264
    #                       itemNotFound (404),
265
    #                       unauthorized (401),
266
    #                       overLimit (413)
267

    
268
    log.debug('delete_network %s', network_id)
269
    net = util.get_network(network_id, request.user_uniq)
270
    if net.public:
271
        raise Unauthorized('Can not delete the public network.')
272

    
273
    if net.machines.all():  # Nics attached on network
274
        raise NetworkInUse('Machines are connected to network.')
275

    
276
    net.action = 'DESTROY'
277
    net.save()
278

    
279
    backend.delete_network(net)
280
    return HttpResponse(status=204)
281

    
282

    
283
@util.api_method('POST')
284
def network_action(request, network_id):
285
    req = util.get_request_dict(request)
286
    log.debug('network_action %s %s', network_id, req)
287
    if len(req) != 1:
288
        raise BadRequest('Malformed request.')
289

    
290
    net = util.get_network(network_id, request.user_uniq)
291
    if net.public:
292
        raise Unauthorized('Can not modify the public network.')
293

    
294
    key = req.keys()[0]
295
    val = req[key]
296

    
297
    try:
298
        assert isinstance(val, dict)
299
        return network_actions[key](request, net, req[key])
300
    except KeyError:
301
        raise BadRequest('Unknown action.')
302
    except AssertionError:
303
        raise BadRequest('Invalid argument.')