Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (6.8 kB)

1
# Copyright 2011-2013 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 django.conf import settings
35
from django.conf.urls import patterns
36
from django.http import HttpResponse
37
from django.utils import simplejson as json
38
from django.db import transaction
39
from django.db.models import Q
40
from django.template.loader import render_to_string
41

    
42
from snf_django.lib import api
43

    
44
from synnefo.api import util
45
from synnefo.db.models import Network
46
from synnefo.logic import networks
47

    
48
from logging import getLogger
49

    
50
log = getLogger(__name__)
51

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

    
58

    
59
def demux(request):
60
    if request.method == 'GET':
61
        return list_networks(request)
62
    elif request.method == 'POST':
63
        return create_network(request)
64
    else:
65
        return api.api_method_not_allowed(request)
66

    
67

    
68
def network_demux(request, network_id):
69

    
70
    if request.method == 'GET':
71
        return get_network_details(request, network_id)
72
    elif request.method == 'DELETE':
73
        return delete_network(request, network_id)
74
    elif request.method == 'PUT':
75
        return update_network(request, network_id)
76
    else:
77
        return api.api_method_not_allowed(request)
78

    
79

    
80
@api.api_method(http_method='GET', user_required=True, logger=log)
81
def list_networks(request, detail=False):
82
    log.debug('list_networks detail=%s', detail)
83

    
84
    user_networks = Network.objects.filter(Q(userid=request.user_uniq) |
85
                                           Q(public=True))\
86
                                   .prefetch_related("subnets")
87

    
88
    user_networks = api.utils.filter_modified_since(request,
89
                                                    objects=user_networks)
90

    
91
    network_dicts = [network_to_dict(network, detail)
92
                     for network in user_networks.order_by('id')]
93

    
94
    if request.serialization == 'xml':
95
        data = render_to_string('list_networks.xml', {
96
            "networks": network_dicts})
97
    else:
98
        data = json.dumps({'networks': network_dicts})
99

    
100
    return HttpResponse(data, status=200)
101

    
102

    
103
@api.api_method(http_method='POST', user_required=True, logger=log)
104
def create_network(request):
105
    userid = request.user_uniq
106
    req = api.utils.get_request_dict(request)
107
    log.info('create_network %s', req)
108

    
109
    network_dict = api.utils.get_attribute(req, "network")
110
    flavor = api.utils.get_attribute(network_dict, "type")
111

    
112
    if flavor not in Network.FLAVORS.keys():
113
        raise api.faults.BadRequest("Invalid network type '%s'" % flavor)
114
    if flavor not in settings.API_ENABLED_NETWORK_FLAVORS:
115
        raise api.faults.Forbidden("Can not create network of type '%s'." %
116
                                   flavor)
117

    
118
    name = api.utils.get_attribute(network_dict, "name", required=False)
119
    if name is None:
120
        name = ""
121

    
122
    network = networks.create(userid=userid, name=name, flavor=flavor,
123
                              public=False)
124
    networkdict = network_to_dict(network, detail=True)
125
    response = render_network(request, networkdict, status=201)
126

    
127
    return response
128

    
129

    
130
@api.api_method(http_method='GET', user_required=True, logger=log)
131
def get_network_details(request, network_id):
132
    log.debug('get_network_details %s', network_id)
133
    network = util.get_network(network_id, request.user_uniq)
134
    return render_network(request, network_to_dict(network, detail=True))
135

    
136

    
137
@api.api_method(http_method='PUT', user_required=True, logger=log)
138
def update_network(request, network_id):
139
    info = api.utils.get_request_dict(request)
140

    
141
    network = api.utils.get_attribute(info, "network", required=True)
142
    new_name = api.utils.get_attribute(network, "name")
143

    
144
    network = util.get_network(network_id, request.user_uniq, for_update=True)
145
    if network.public:
146
        raise api.faults.Forbidden("Can not rename the public network.")
147
    network = networks.rename(network, new_name)
148
    return render_network(request, network_to_dict(network), 200)
149

    
150

    
151
@api.api_method(http_method='DELETE', user_required=True, logger=log)
152
@transaction.commit_on_success
153
def delete_network(request, network_id):
154
    log.info('delete_network %s', network_id)
155
    network = util.get_network(network_id, request.user_uniq, for_update=True)
156
    if network.public:
157
        raise api.faults.Forbidden("Can not delete the public network.")
158
    networks.delete(network)
159
    return HttpResponse(status=204)
160

    
161

    
162
def network_to_dict(network, detail=True):
163
    d = {'id': str(network.id), 'name': network.name}
164
    d['links'] = util.network_to_links(network.id)
165
    if detail:
166
        d['user_id'] = network.userid
167
        d['tenant_id'] = network.userid
168
        d['type'] = network.flavor
169
        d['updated'] = api.utils.isoformat(network.updated)
170
        d['created'] = api.utils.isoformat(network.created)
171
        d['status'] = network.state
172
        d['public'] = network.public
173
        d['external_router'] = network.external_router
174
        d['admin_state_up'] = True
175
        d['subnets'] = list(network.subnets.values_list('id', flat=True))
176
        d['SNF:floating_ip_pool'] = network.floating_ip_pool
177
    return d
178

    
179

    
180
def render_network(request, networkdict, status=200):
181
    if request.serialization == 'xml':
182
        data = render_to_string('network.xml', {'network': networkdict})
183
    else:
184
        data = json.dumps({'network': networkdict})
185
    return HttpResponse(data, status=status)