Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (10.1 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

    
51
from synnefo.logic import backend
52
from synnefo.settings import MAX_CIDR_BLOCK
53

    
54

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

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

    
64

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

    
73

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

    
84

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

    
99
        attachments = [util.construct_nic_id(nic) 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
                                           deleted=False)
126

    
127
    if since:
128
        user_networks = user_networks.filter(updated__gte=since)
129
        if not user_networks:
130
            return HttpResponse(status=304)
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
    cidr_block = int(subnet.split('/')[1])
176
    if cidr_block <= MAX_CIDR_BLOCK:
177
        raise OverLimit("Network size is to big. Please specify a network"
178
                        " smaller than /" + str(MAX_CIDR_BLOCK) + '.')
179

    
180
    try:
181
        link = util.network_link_from_type(typ)
182
        if not link:
183
            raise Exception("Can not create network. No connectivity link.")
184

    
185
        network = Network.objects.create(
186
                name=name,
187
                userid=request.user_uniq,
188
                subnet=subnet,
189
                subnet6=subnet6,
190
                gateway=gateway,
191
                gateway6=gateway6,
192
                dhcp=dhcp,
193
                type=typ,
194
                link=link,
195
                state='PENDING')
196
    except Pool.PoolExhausted:
197
        raise OverLimit('Network count limit exceeded.')
198

    
199
    backend.create_network(network)
200

    
201
    networkdict = network_to_dict(network, request.user_uniq)
202
    return render_network(request, networkdict, status=202)
203

    
204

    
205
@util.api_method('GET')
206
def get_network_details(request, network_id):
207
    # Normal Response Codes: 200, 203
208
    # Error Response Codes: computeFault (400, 500),
209
    #                       serviceUnavailable (503),
210
    #                       unauthorized (401),
211
    #                       badRequest (400),
212
    #                       itemNotFound (404),
213
    #                       overLimit (413)
214

    
215
    log.debug('get_network_details %s', network_id)
216
    net = util.get_network(network_id, request.user_uniq)
217
    netdict = network_to_dict(net, request.user_uniq)
218
    return render_network(request, netdict)
219

    
220

    
221
@util.api_method('PUT')
222
def update_network_name(request, network_id):
223
    # Normal Response Code: 204
224
    # Error Response Codes: computeFault (400, 500),
225
    #                       serviceUnavailable (503),
226
    #                       unauthorized (401),
227
    #                       badRequest (400),
228
    #                       badMediaType(415),
229
    #                       itemNotFound (404),
230
    #                       overLimit (413)
231

    
232
    req = util.get_request_dict(request)
233
    log.debug('update_network_name %s', network_id)
234

    
235
    try:
236
        name = req['network']['name']
237
    except (TypeError, KeyError):
238
        raise BadRequest('Malformed request.')
239

    
240
    net = util.get_network(network_id, request.user_uniq)
241
    if net.public:
242
        raise Unauthorized('Can not rename the public network.')
243
    net.name = name
244
    net.save()
245
    return HttpResponse(status=204)
246

    
247

    
248
@util.api_method('DELETE')
249
@transaction.commit_on_success
250
def delete_network(request, network_id):
251
    # Normal Response Code: 204
252
    # Error Response Codes: computeFault (400, 500),
253
    #                       serviceUnavailable (503),
254
    #                       unauthorized (401),
255
    #                       itemNotFound (404),
256
    #                       unauthorized (401),
257
    #                       overLimit (413)
258

    
259
    log.debug('delete_network %s', network_id)
260
    net = util.get_network(network_id, request.user_uniq)
261
    if net.public:
262
        raise Unauthorized('Can not delete the public network.')
263

    
264
    if net.machines.all():  # Nics attached on network
265
        raise NetworkInUse('Machines are connected to network.')
266

    
267
    net.action = 'DESTROY'
268
    net.save()
269

    
270
    backend.delete_network(net)
271
    return HttpResponse(status=204)
272

    
273

    
274
@util.api_method('POST')
275
def network_action(request, network_id):
276
    req = util.get_request_dict(request)
277
    log.debug('network_action %s %s', network_id, req)
278
    if len(req) != 1:
279
        raise BadRequest('Malformed request.')
280

    
281
    net = util.get_network(network_id, request.user_uniq)
282
    if net.public:
283
        raise Unauthorized('Can not modify the public network.')
284

    
285
    key = req.keys()[0]
286
    val = req[key]
287

    
288
    try:
289
        assert isinstance(val, dict)
290
        return network_actions[key](request, net, req[key])
291
    except KeyError:
292
        raise BadRequest('Unknown action.')
293
    except AssertionError:
294
        raise BadRequest('Invalid argument.')