Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (7.6 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
                                          allowed_methods=['GET', 'POST'])
67

    
68

    
69
def network_demux(request, network_id):
70

    
71
    if request.method == 'GET':
72
        return get_network_details(request, network_id)
73
    elif request.method == 'DELETE':
74
        return delete_network(request, network_id)
75
    elif request.method == 'PUT':
76
        return update_network(request, network_id)
77
    else:
78
        return api.api_method_not_allowed(request,
79
                                          allowed_methods=['GET',
80
                                                           'PUT',
81
                                                           'DELETE'])
82

    
83

    
84
@api.api_method(http_method='GET', user_required=True, logger=log)
85
def list_networks(request, detail=True):
86
    log.debug('list_networks detail=%s', detail)
87

    
88
    user_networks = Network.objects.filter(Q(userid=request.user_uniq) |
89
                                           Q(public=True))\
90
                                   .order_by('id')
91
    if detail:
92
        user_networks = user_networks.prefetch_related("subnets")
93

    
94
    user_networks = api.utils.filter_modified_since(request,
95
                                                    objects=user_networks)
96

    
97
    network_dicts = [network_to_dict(network, detail)
98
                     for network in user_networks]
99

    
100
    if request.serialization == 'xml':
101
        data = render_to_string('list_networks.xml', {
102
            "networks": network_dicts})
103
    else:
104
        data = json.dumps({'networks': network_dicts})
105

    
106
    return HttpResponse(data, status=200)
107

    
108

    
109
@api.api_method(http_method='POST', user_required=True, logger=log)
110
def create_network(request):
111
    userid = request.user_uniq
112
    req = api.utils.get_request_dict(request)
113
    log.info('create_network %s', req)
114

    
115
    network_dict = api.utils.get_attribute(req, "network",
116
                                           attr_type=dict)
117
    flavor = api.utils.get_attribute(network_dict, "type",
118
                                     attr_type=basestring)
119

    
120
    if flavor not in Network.FLAVORS.keys():
121
        raise api.faults.BadRequest("Invalid network type '%s'" % flavor)
122
    if flavor not in settings.API_ENABLED_NETWORK_FLAVORS:
123
        raise api.faults.Forbidden("Cannot create network of type '%s'." %
124
                                   flavor)
125

    
126
    name = api.utils.get_attribute(network_dict, "name", attr_type=basestring,
127
                                   required=False)
128
    if name is None:
129
        name = ""
130

    
131
    network = networks.create(userid=userid, name=name, flavor=flavor,
132
                              public=False)
133
    networkdict = network_to_dict(network, detail=True)
134
    response = render_network(request, networkdict, status=201)
135

    
136
    return response
137

    
138

    
139
@api.api_method(http_method='GET', user_required=True, logger=log)
140
def get_network_details(request, network_id):
141
    log.debug('get_network_details %s', network_id)
142
    network = util.get_network(network_id, request.user_uniq)
143
    return render_network(request, network_to_dict(network, detail=True))
144

    
145

    
146
@api.api_method(http_method='PUT', user_required=True, logger=log)
147
def update_network(request, network_id):
148
    info = api.utils.get_request_dict(request)
149

    
150
    network = api.utils.get_attribute(info, "network", attr_type=dict,
151
                                      required=True)
152
    new_name = api.utils.get_attribute(network, "name", attr_type=basestring)
153

    
154
    network = util.get_network(network_id, request.user_uniq, for_update=True)
155
    if network.public:
156
        raise api.faults.Forbidden("Cannot rename the public network.")
157
    network = networks.rename(network, new_name)
158
    return render_network(request, network_to_dict(network), 200)
159

    
160

    
161
@api.api_method(http_method='DELETE', user_required=True, logger=log)
162
@transaction.commit_on_success
163
def delete_network(request, network_id):
164
    log.info('delete_network %s', network_id)
165
    network = util.get_network(network_id, request.user_uniq, for_update=True)
166
    if network.public:
167
        raise api.faults.Forbidden("Cannot delete the public network.")
168
    networks.delete(network)
169
    return HttpResponse(status=204)
170

    
171

    
172
def network_to_dict(network, detail=True):
173
    d = {'id': str(network.id), 'name': network.name}
174
    d['links'] = util.network_to_links(network.id)
175
    if detail:
176
        # Loop over subnets. Do not perform any extra query because of prefetch
177
        # related!
178
        subnet_ids = []
179
        for subnet in network.subnets.all():
180
            subnet_ids.append(subnet.id)
181

    
182
        state = "SNF:DRAINED" if network.drained else network.state
183
        d['user_id'] = network.userid
184
        d['tenant_id'] = network.userid
185
        d['type'] = network.flavor
186
        d['updated'] = api.utils.isoformat(network.updated)
187
        d['created'] = api.utils.isoformat(network.created)
188
        d['status'] = state
189
        d['public'] = network.public
190
        d['router:external'] = network.external_router
191
        d['admin_state_up'] = True
192
        d['subnets'] = subnet_ids
193
        d['SNF:floating_ip_pool'] = network.floating_ip_pool
194
        d['deleted'] = True
195
    return d
196

    
197

    
198
def render_network(request, networkdict, status=200):
199
    if request.serialization == 'xml':
200
        data = render_to_string('network.xml', {'network': networkdict})
201
    else:
202
        data = json.dumps({'network': networkdict})
203
    return HttpResponse(data, status=status)