root / snf-cyclades-app / synnefo / api / networks.py @ ece5581b
History | View | Annotate | Download (10.5 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 |
from django.conf import settings |
34 |
from django.conf.urls.defaults import patterns |
35 |
from django.db.models import Q |
36 |
from django.http import HttpResponse |
37 |
from django.template.loader import render_to_string |
38 |
from django.utils import simplejson as json |
39 |
|
40 |
from snf_django.lib import api |
41 |
from snf_django.lib.api import faults, utils |
42 |
from synnefo.api import util |
43 |
from synnefo.api.servers import network_actions |
44 |
from synnefo.db.models import Network |
45 |
from synnefo.logic import networks |
46 |
|
47 |
|
48 |
from logging import getLogger |
49 |
log = getLogger(__name__) |
50 |
|
51 |
urlpatterns = patterns( |
52 |
'synnefo.api.networks',
|
53 |
(r'^(?:/|.json|.xml)?$', 'demux'), |
54 |
(r'^/detail(?:.json|.xml)?$', 'list_networks', {'detail': True}), |
55 |
(r'^/(\w+)(?:.json|.xml)?$', 'network_demux'), |
56 |
(r'^/(\w+)/action(?:.json|.xml)?$', 'demux_network_action'), |
57 |
) |
58 |
|
59 |
|
60 |
def demux(request): |
61 |
if request.method == 'GET': |
62 |
return list_networks(request)
|
63 |
elif request.method == 'POST': |
64 |
return create_network(request)
|
65 |
else:
|
66 |
return api.api_method_not_allowed(request)
|
67 |
|
68 |
|
69 |
def network_demux(request, network_id): |
70 |
if request.method == 'GET': |
71 |
return get_network_details(request, network_id)
|
72 |
elif request.method == 'PUT': |
73 |
return update_network_name(request, network_id)
|
74 |
elif request.method == 'DELETE': |
75 |
return delete_network(request, network_id)
|
76 |
else:
|
77 |
return api.api_method_not_allowed(request)
|
78 |
|
79 |
|
80 |
def network_to_dict(network, user_id, detail=True): |
81 |
d = {'id': str(network.id), 'name': network.name} |
82 |
d['links'] = util.network_to_links(network.id)
|
83 |
if detail:
|
84 |
d['user_id'] = network.userid
|
85 |
d['tenant_id'] = network.userid
|
86 |
d['cidr'] = network.subnet
|
87 |
d['cidr6'] = network.subnet6
|
88 |
d['gateway'] = network.gateway
|
89 |
d['gateway6'] = network.gateway6
|
90 |
d['dhcp'] = network.dhcp
|
91 |
d['type'] = network.flavor
|
92 |
d['updated'] = utils.isoformat(network.updated)
|
93 |
d['created'] = utils.isoformat(network.created)
|
94 |
d['status'] = network.state
|
95 |
d['public'] = network.public
|
96 |
|
97 |
attachments = [util.construct_nic_id(nic) |
98 |
for nic in network.nics.filter(machine__userid=user_id) |
99 |
.filter(state="ACTIVE")
|
100 |
.order_by('machine')]
|
101 |
d['attachments'] = attachments
|
102 |
return d
|
103 |
|
104 |
|
105 |
def render_network(request, networkdict, status=200): |
106 |
if request.serialization == 'xml': |
107 |
data = render_to_string('network.xml', {'network': networkdict}) |
108 |
else:
|
109 |
data = json.dumps({'network': networkdict})
|
110 |
return HttpResponse(data, status=status)
|
111 |
|
112 |
|
113 |
@api.api_method(http_method='GET', user_required=True, logger=log) |
114 |
def list_networks(request, detail=False): |
115 |
# Normal Response Codes: 200, 203
|
116 |
# Error Response Codes: computeFault (400, 500),
|
117 |
# serviceUnavailable (503),
|
118 |
# unauthorized (401),
|
119 |
# badRequest (400),
|
120 |
# overLimit (413)
|
121 |
|
122 |
log.debug('list_networks detail=%s', detail)
|
123 |
since = utils.isoparse(request.GET.get('changes-since'))
|
124 |
user_networks = Network.objects.filter(Q(userid=request.user_uniq) | |
125 |
Q(public=True))
|
126 |
|
127 |
if since:
|
128 |
user_networks = user_networks.filter(updated__gte=since) |
129 |
if not user_networks: |
130 |
return HttpResponse(status=304) |
131 |
else:
|
132 |
user_networks = user_networks.filter(deleted=False)
|
133 |
|
134 |
networks_dict = [network_to_dict(network, request.user_uniq, detail) |
135 |
for network in user_networks.order_by('id')] |
136 |
|
137 |
if request.serialization == 'xml': |
138 |
data = render_to_string('list_networks.xml', {
|
139 |
'networks': networks_dict,
|
140 |
'detail': detail})
|
141 |
else:
|
142 |
data = json.dumps({'networks': networks_dict})
|
143 |
|
144 |
return HttpResponse(data, status=200) |
145 |
|
146 |
|
147 |
@api.api_method(http_method='POST', user_required=True, logger=log) |
148 |
def create_network(request): |
149 |
# Normal Response Code: 202
|
150 |
# Error Response Codes: computeFault (400, 500),
|
151 |
# serviceUnavailable (503),
|
152 |
# unauthorized (401),
|
153 |
# badMediaType(415),
|
154 |
# badRequest (400),
|
155 |
# forbidden (403)
|
156 |
# overLimit (413)
|
157 |
|
158 |
req = utils.get_request_dict(request) |
159 |
log.info('create_network %s', req)
|
160 |
user_id = request.user_uniq |
161 |
try:
|
162 |
d = req['network']
|
163 |
name = d['name']
|
164 |
except KeyError: |
165 |
raise faults.BadRequest("Malformed request") |
166 |
|
167 |
# Get and validate flavor. Flavors are still exposed as 'type' in the
|
168 |
# API.
|
169 |
flavor = d.get("type", None) |
170 |
if flavor is None: |
171 |
raise faults.BadRequest("Missing request parameter 'type'") |
172 |
elif flavor not in Network.FLAVORS.keys(): |
173 |
raise faults.BadRequest("Invalid network type '%s'" % flavor) |
174 |
elif flavor not in settings.API_ENABLED_NETWORK_FLAVORS: |
175 |
raise faults.Forbidden("Can not create network of type '%s'" % |
176 |
flavor) |
177 |
public = d.get("public", False) |
178 |
if public:
|
179 |
raise faults.Forbidden("Can not create a public network.") |
180 |
|
181 |
dhcp = d.get('dhcp', True) |
182 |
|
183 |
# Get and validate network parameters
|
184 |
subnet = d.get('cidr', '192.168.1.0/24') |
185 |
subnet6 = d.get('cidr6', None) |
186 |
gateway = d.get('gateway', None) |
187 |
gateway6 = d.get('gateway6', None) |
188 |
|
189 |
network = networks.create(user_id=user_id, name=name, flavor=flavor, |
190 |
subnet=subnet, gateway=gateway, subnet6=subnet6, |
191 |
gateway6=gateway6, dhcp=dhcp, public=False)
|
192 |
|
193 |
networkdict = network_to_dict(network, request.user_uniq) |
194 |
response = render_network(request, networkdict, status=202)
|
195 |
|
196 |
return response
|
197 |
|
198 |
|
199 |
@api.api_method(http_method='GET', user_required=True, logger=log) |
200 |
def get_network_details(request, network_id): |
201 |
# Normal Response Codes: 200, 203
|
202 |
# Error Response Codes: computeFault (400, 500),
|
203 |
# serviceUnavailable (503),
|
204 |
# unauthorized (401),
|
205 |
# badRequest (400),
|
206 |
# itemNotFound (404),
|
207 |
# overLimit (413)
|
208 |
|
209 |
log.debug('get_network_details %s', network_id)
|
210 |
net = util.get_network(network_id, request.user_uniq) |
211 |
netdict = network_to_dict(net, request.user_uniq) |
212 |
return render_network(request, netdict)
|
213 |
|
214 |
|
215 |
@api.api_method(http_method='PUT', user_required=True, logger=log) |
216 |
def update_network_name(request, network_id): |
217 |
# Normal Response Code: 204
|
218 |
# Error Response Codes: computeFault (400, 500),
|
219 |
# serviceUnavailable (503),
|
220 |
# unauthorized (401),
|
221 |
# badRequest (400),
|
222 |
# forbidden (403)
|
223 |
# badMediaType(415),
|
224 |
# itemNotFound (404),
|
225 |
# overLimit (413)
|
226 |
|
227 |
req = utils.get_request_dict(request) |
228 |
log.info('update_network_name %s', network_id)
|
229 |
|
230 |
try:
|
231 |
name = req['network']['name'] |
232 |
except (TypeError, KeyError): |
233 |
raise faults.BadRequest('Malformed request.') |
234 |
|
235 |
network = util.get_network(network_id, request.user_uniq) |
236 |
if network.public:
|
237 |
raise faults.Forbidden('Can not rename the public network.') |
238 |
network = networks.rename(network, name) |
239 |
return HttpResponse(status=204) |
240 |
|
241 |
|
242 |
@api.api_method(http_method='DELETE', user_required=True, logger=log) |
243 |
def delete_network(request, network_id): |
244 |
# Normal Response Code: 204
|
245 |
# Error Response Codes: computeFault (400, 500),
|
246 |
# serviceUnavailable (503),
|
247 |
# unauthorized (401),
|
248 |
# forbidden (403)
|
249 |
# itemNotFound (404),
|
250 |
# overLimit (413)
|
251 |
|
252 |
log.info('delete_network %s', network_id)
|
253 |
network = util.get_network(network_id, request.user_uniq, for_update=True)
|
254 |
if network.public:
|
255 |
raise faults.Forbidden('Can not delete the public network.') |
256 |
networks.delete(network) |
257 |
return HttpResponse(status=204) |
258 |
|
259 |
|
260 |
def key_to_action(action): |
261 |
return action.upper()
|
262 |
|
263 |
|
264 |
@api.api_method(http_method='POST', user_required=True, logger=log) |
265 |
def demux_network_action(request, network_id): |
266 |
req = utils.get_request_dict(request) |
267 |
log.debug('network_action %s %s', network_id, req)
|
268 |
if len(req) != 1: |
269 |
raise faults.BadRequest('Malformed request.') |
270 |
|
271 |
net = util.get_network(network_id, request.user_uniq) |
272 |
if net.public:
|
273 |
raise faults.Forbidden('Can not modify the public network.') |
274 |
if net.deleted:
|
275 |
raise faults.BadRequest("Network has been deleted.") |
276 |
|
277 |
action = req.keys()[0]
|
278 |
if key_to_action(action) not in [x[0] for x in Network.ACTIONS]: |
279 |
raise faults.BadRequest("Action %s not supported." % action) |
280 |
action_args = req[action] |
281 |
if not isinstance(action_args, dict): |
282 |
raise faults.BadRequest("Invalid argument.") |
283 |
return network_actions[action](request, net, action_args)
|