Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (9.6 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.http import HttpResponse
40
from django.template.loader import render_to_string
41
from django.utils import simplejson as json
42

    
43
from synnefo import settings
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, OverLimit, Unauthorized
48
from synnefo.db.models import Network, BridgePool, MacPrefixPool
49
from synnefo.logic import backend
50

    
51

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

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

    
61

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

    
70

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

    
81

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

    
94
        attachments = [util.construct_nic_id(nic) for nic in network.nics.filter(machine__userid= user_id)]
95
        d['attachments'] = {'values':attachments}
96
    return d
97

    
98

    
99
def render_network(request, networkdict, status=200):
100
    if request.serialization == 'xml':
101
        data = render_to_string('network.xml', {'network': networkdict})
102
    else:
103
        data = json.dumps({'network': networkdict})
104
    return HttpResponse(data, status=status)
105

    
106

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

    
116
    log.debug('list_networks detail=%s', detail)
117
    since = util.isoparse(request.GET.get('changes-since'))
118
    user_networks = Network.objects.filter(
119
                                Q(userid=request.user_uniq) | Q(public=True))
120

    
121
    if since:
122
        user_networks = user_networks.filter(updated__gte=since)
123
        if not user_networks:
124
            return HttpResponse(status=304)
125
    else:
126
        user_networks = user_networks.filter(deleted=False)
127

    
128
    networks = [network_to_dict(network, request.user_uniq, detail)
129
                for network in user_networks]
130

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

    
138
    return HttpResponse(data, status=200)
139

    
140

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

    
151
    req = util.get_request_dict(request)
152
    log.debug('create_network %s', req)
153

    
154
    try:
155
        d = req['network']
156
        name = d['name']
157
        # TODO: Fix this temp values:
158
        subnet = d.get('cidr', '192.168.1.0/24')
159
        gateway = d.get('gateway', None)
160
        type = d.get('type', 'PRIVATE_VLAN')
161
        dhcp = d.get('dhcp', True)
162
    except (KeyError, ValueError):
163
        raise BadRequest('Malformed request.')
164

    
165
    link = None
166
    mac_prefix = None
167
    if type == 'PUBLIC_ROUTED':
168
        pass
169
        # raise Exception (user can not create public)
170
    if type == 'PRIVATE_FILTERED':
171
        link = settings.GANETI_PRIVATE_BRIDGE
172
        mac_prefix = MacPrefixPool.get_available().value
173
        state = 'PENDING'
174
    else: # PRIVATE_VLAN
175
        link = BridgePool.get_available().value
176
        # Physical-Vlans are pre-provisioned
177
        state = 'ACTIVE'
178

    
179
    network = Network.objects.create(
180
            name=name,
181
            userid=request.user_uniq,
182
            subnet=subnet,
183
            gateway=gateway,
184
            dhcp=dhcp,
185
            type=type,
186
            link=link,
187
            mac_prefix=mac_prefix,
188
            state=state)
189

    
190
    network = backend.create_network(network)
191
    if not network:
192
        raise OverLimit('Network count limit exceeded for your account.')
193

    
194
    networkdict = network_to_dict(network, request.user_uniq)
195
    return render_network(request, networkdict, status=202)
196

    
197

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

    
208
    log.debug('get_network_details %s', network_id)
209
    net = util.get_network(network_id, request.user_uniq)
210
    netdict = network_to_dict(net, request.user_uniq)
211
    return render_network(request, netdict)
212

    
213

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

    
225
    req = util.get_request_dict(request)
226
    log.debug('update_network_name %s', network_id)
227

    
228
    try:
229
        name = req['network']['name']
230
    except (TypeError, KeyError):
231
        raise BadRequest('Malformed request.')
232

    
233
    net = util.get_network(network_id, request.user_uniq)
234
    if net.public:
235
        raise Unauthorized('Can not rename the public network.')
236
    net.name = name
237
    net.save()
238
    return HttpResponse(status=204)
239

    
240

    
241
@util.api_method('DELETE')
242
def delete_network(request, network_id):
243
    # Normal Response Code: 204
244
    # Error Response Codes: computeFault (400, 500),
245
    #                       serviceUnavailable (503),
246
    #                       unauthorized (401),
247
    #                       itemNotFound (404),
248
    #                       unauthorized (401),
249
    #                       overLimit (413)
250

    
251
    log.debug('delete_network %s', network_id)
252
    net = util.get_network(network_id, request.user_uniq)
253
    if net.public:
254
        raise Unauthorized('Can not delete the public network.')
255

    
256
    net.action = 'DESTROY'
257
    net.save()
258

    
259
    backend.delete_network(net)
260
    return HttpResponse(status=204)
261

    
262

    
263
@util.api_method('POST')
264
def network_action(request, network_id):
265
    req = util.get_request_dict(request)
266
    log.debug('network_action %s %s', network_id, req)
267
    if len(req) != 1:
268
        raise BadRequest('Malformed request.')
269

    
270
    net = util.get_network(network_id, request.user_uniq)
271
    if net.public:
272
        raise Unauthorized('Can not modify the public network.')
273

    
274
    key = req.keys()[0]
275
    val = req[key]
276

    
277
    try:
278
        assert isinstance(val, dict)
279
        return network_actions[key](request, net, req[key])
280
    except KeyError:
281
        raise BadRequest('Unknown action.')
282
    except AssertionError:
283
        raise BadRequest('Invalid argument.')