Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (10 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
50
from synnefo.logic import backend
51
from synnefo.settings import MAX_CIDR_BLOCK
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
    network_id = str(network.id) if not network.public else 'public'
86
    d = {'id': network_id, 'name': network.name}
87
    if detail:
88
        d['cidr'] = network.subnet
89
        d['cidr6'] = network.subnet6
90
        d['gateway'] = network.gateway
91
        d['gateway6'] = network.gateway6
92
        d['dhcp'] = network.dhcp
93
        d['type'] = network.type
94
        d['updated'] = util.isoformat(network.updated)
95
        d['created'] = util.isoformat(network.created)
96
        d['status'] = network.state
97

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

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

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

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

    
141
    return HttpResponse(data, status=200)
142

    
143

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

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

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

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

    
174
    cidr_block = int(subnet.split('/')[1])
175
    if cidr_block <= MAX_CIDR_BLOCK:
176
        raise OverLimit("Network size is to big. Please specify a network"
177
                        " smaller than /" + str(MAX_CIDR_BLOCK) + '.')
178

    
179
    link, mac_prefix = util.network_specs_from_type(type)
180
    if not link:
181
        raise Exception("Can not create network. No connectivity link.")
182

    
183
    network = Network.objects.create(
184
            name=name,
185
            userid=request.user_uniq,
186
            subnet=subnet,
187
            subnet6=subnet6,
188
            gateway=gateway,
189
            gateway6=gateway6,
190
            dhcp=dhcp,
191
            type=type,
192
            link=link,
193
            mac_prefix=mac_prefix,
194
            state='PENDING')
195

    
196
    backend.create_network(network)
197

    
198
    networkdict = network_to_dict(network, request.user_uniq)
199
    return render_network(request, networkdict, status=202)
200

    
201

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

    
212
    log.debug('get_network_details %s', network_id)
213
    net = util.get_network(network_id, request.user_uniq)
214
    netdict = network_to_dict(net, request.user_uniq)
215
    return render_network(request, netdict)
216

    
217

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

    
229
    req = util.get_request_dict(request)
230
    log.debug('update_network_name %s', network_id)
231

    
232
    try:
233
        name = req['network']['name']
234
    except (TypeError, KeyError):
235
        raise BadRequest('Malformed request.')
236

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

    
244

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

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

    
261
    if net.machines.all():  # Nics attached on network
262
        raise NetworkInUse('Machines are connected to network.')
263

    
264
    net.action = 'DESTROY'
265
    net.save()
266

    
267
    backend.delete_network(net)
268
    return HttpResponse(status=204)
269

    
270

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

    
278
    net = util.get_network(network_id, request.user_uniq)
279
    if net.public:
280
        raise Unauthorized('Can not modify the public network.')
281

    
282
    key = req.keys()[0]
283
    val = req[key]
284

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