root / snf-cyclades-app / synnefo / api / networks.py @ cc3f266e
History | View | Annotate | Download (10.1 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, |
48 |
Unauthorized, NetworkInUse) |
49 |
from synnefo.db.models import Network, Pool, BridgePool, MacPrefixPool |
50 |
from synnefo.logic import backend |
51 |
|
52 |
|
53 |
log = getLogger('synnefo.api')
|
54 |
|
55 |
urlpatterns = patterns('synnefo.api.networks',
|
56 |
(r'^(?:/|.json|.xml)?$', 'demux'), |
57 |
(r'^/detail(?:.json|.xml)?$', 'list_networks', {'detail': True}), |
58 |
(r'^/(\w+)(?:.json|.xml)?$', 'network_demux'), |
59 |
(r'^/(\w+)/action(?:.json|.xml)?$', 'network_action'), |
60 |
) |
61 |
|
62 |
|
63 |
def demux(request): |
64 |
if request.method == 'GET': |
65 |
return list_networks(request)
|
66 |
elif request.method == 'POST': |
67 |
return create_network(request)
|
68 |
else:
|
69 |
return method_not_allowed(request)
|
70 |
|
71 |
|
72 |
def network_demux(request, network_id): |
73 |
if request.method == 'GET': |
74 |
return get_network_details(request, network_id)
|
75 |
elif request.method == 'PUT': |
76 |
return update_network_name(request, network_id)
|
77 |
elif request.method == 'DELETE': |
78 |
return delete_network(request, network_id)
|
79 |
else:
|
80 |
return method_not_allowed(request)
|
81 |
|
82 |
|
83 |
def network_to_dict(network, user_id, detail=True): |
84 |
network_id = str(network.id) if not network.public else 'public' |
85 |
d = {'id': network_id, 'name': network.name} |
86 |
if detail:
|
87 |
d['cidr'] = network.subnet
|
88 |
d['cidr6'] = network.subnet6
|
89 |
d['gateway'] = network.gateway
|
90 |
d['gateway6'] = network.gateway6
|
91 |
d['dhcp'] = network.dhcp
|
92 |
d['type'] = network.type
|
93 |
d['updated'] = util.isoformat(network.updated)
|
94 |
d['created'] = util.isoformat(network.created)
|
95 |
d['status'] = network.state
|
96 |
|
97 |
attachments = [util.construct_nic_id(nic) for nic in network.nics.filter(machine__userid= user_id)] |
98 |
d['attachments'] = {'values':attachments} |
99 |
return d
|
100 |
|
101 |
|
102 |
def render_network(request, networkdict, status=200): |
103 |
if request.serialization == 'xml': |
104 |
data = render_to_string('network.xml', {'network': networkdict}) |
105 |
else:
|
106 |
data = json.dumps({'network': networkdict})
|
107 |
return HttpResponse(data, status=status)
|
108 |
|
109 |
|
110 |
@util.api_method('GET') |
111 |
def list_networks(request, detail=False): |
112 |
# Normal Response Codes: 200, 203
|
113 |
# Error Response Codes: computeFault (400, 500),
|
114 |
# serviceUnavailable (503),
|
115 |
# unauthorized (401),
|
116 |
# badRequest (400),
|
117 |
# overLimit (413)
|
118 |
|
119 |
log.debug('list_networks detail=%s', detail)
|
120 |
since = util.isoparse(request.GET.get('changes-since'))
|
121 |
user_networks = Network.objects.filter(Q(userid=request.user_uniq) | |
122 |
Q(public=True),
|
123 |
deleted=False)
|
124 |
|
125 |
if since:
|
126 |
user_networks = user_networks.filter(updated__gte=since) |
127 |
if not user_networks: |
128 |
return HttpResponse(status=304) |
129 |
|
130 |
networks = [network_to_dict(network, request.user_uniq, detail) |
131 |
for network in user_networks] |
132 |
|
133 |
if request.serialization == 'xml': |
134 |
data = render_to_string('list_networks.xml', {
|
135 |
'networks': networks,
|
136 |
'detail': detail})
|
137 |
else:
|
138 |
data = json.dumps({'networks': {'values': networks}}) |
139 |
|
140 |
return HttpResponse(data, status=200) |
141 |
|
142 |
|
143 |
@util.api_method('POST') |
144 |
def create_network(request): |
145 |
# Normal Response Code: 202
|
146 |
# Error Response Codes: computeFault (400, 500),
|
147 |
# serviceUnavailable (503),
|
148 |
# unauthorized (401),
|
149 |
# badMediaType(415),
|
150 |
# badRequest (400),
|
151 |
# overLimit (413)
|
152 |
|
153 |
req = util.get_request_dict(request) |
154 |
log.debug('create_network %s', req)
|
155 |
|
156 |
try:
|
157 |
d = req['network']
|
158 |
name = d['name']
|
159 |
# TODO: Fix this temp values:
|
160 |
subnet = d.get('cidr', '192.168.1.0/24') |
161 |
subnet6 = d.get('cidr6', None) |
162 |
gateway = d.get('gateway', None) |
163 |
gateway6 = d.get('gateway6', None) |
164 |
type = d.get('type', 'PRIVATE_MAC_FILTERED') |
165 |
dhcp = d.get('dhcp', True) |
166 |
except (KeyError, ValueError): |
167 |
raise BadRequest('Malformed request.') |
168 |
|
169 |
if type == 'PUBLIC_ROUTED': |
170 |
raise Unauthorized('Can not create a public network.') |
171 |
|
172 |
mac_prefix = None
|
173 |
try:
|
174 |
if type == 'PRIVATE_MAC_FILTERED': |
175 |
link = settings.PRIVATE_MAC_FILTERED_BRIDGE |
176 |
mac_prefix = MacPrefixPool.get_available().value |
177 |
elif type == 'PRIVATE_PHYSICAL_VLAN': |
178 |
link = BridgePool.get_available().value |
179 |
elif type == 'CUSTOM_ROUTED': |
180 |
link = settings.CUSTOM_ROUTED_ROUTING_TABLE |
181 |
elif type == 'CUSTOM_BRIDGED': |
182 |
link = settings.CUSTOM_BRIDGED_BRIDGE |
183 |
else:
|
184 |
raise BadRequest('Unknown network type') |
185 |
except Pool.PoolExhausted:
|
186 |
raise OverLimit('Network count limit exceeded.') |
187 |
|
188 |
network = Network.objects.create( |
189 |
name=name, |
190 |
userid=request.user_uniq, |
191 |
subnet=subnet, |
192 |
subnet6=subnet6, |
193 |
gateway=gateway, |
194 |
gateway6=gateway6, |
195 |
dhcp=dhcp, |
196 |
type=type,
|
197 |
link=link, |
198 |
mac_prefix=mac_prefix, |
199 |
state='PENDING')
|
200 |
|
201 |
backend.create_network(network) |
202 |
|
203 |
networkdict = network_to_dict(network, request.user_uniq) |
204 |
return render_network(request, networkdict, status=202) |
205 |
|
206 |
|
207 |
@util.api_method('GET') |
208 |
def get_network_details(request, network_id): |
209 |
# Normal Response Codes: 200, 203
|
210 |
# Error Response Codes: computeFault (400, 500),
|
211 |
# serviceUnavailable (503),
|
212 |
# unauthorized (401),
|
213 |
# badRequest (400),
|
214 |
# itemNotFound (404),
|
215 |
# overLimit (413)
|
216 |
|
217 |
log.debug('get_network_details %s', network_id)
|
218 |
net = util.get_network(network_id, request.user_uniq) |
219 |
netdict = network_to_dict(net, request.user_uniq) |
220 |
return render_network(request, netdict)
|
221 |
|
222 |
|
223 |
@util.api_method('PUT') |
224 |
def update_network_name(request, network_id): |
225 |
# Normal Response Code: 204
|
226 |
# Error Response Codes: computeFault (400, 500),
|
227 |
# serviceUnavailable (503),
|
228 |
# unauthorized (401),
|
229 |
# badRequest (400),
|
230 |
# badMediaType(415),
|
231 |
# itemNotFound (404),
|
232 |
# overLimit (413)
|
233 |
|
234 |
req = util.get_request_dict(request) |
235 |
log.debug('update_network_name %s', network_id)
|
236 |
|
237 |
try:
|
238 |
name = req['network']['name'] |
239 |
except (TypeError, KeyError): |
240 |
raise BadRequest('Malformed request.') |
241 |
|
242 |
net = util.get_network(network_id, request.user_uniq) |
243 |
if net.public:
|
244 |
raise Unauthorized('Can not rename the public network.') |
245 |
net.name = name |
246 |
net.save() |
247 |
return HttpResponse(status=204) |
248 |
|
249 |
|
250 |
@util.api_method('DELETE') |
251 |
def delete_network(request, network_id): |
252 |
# Normal Response Code: 204
|
253 |
# Error Response Codes: computeFault (400, 500),
|
254 |
# serviceUnavailable (503),
|
255 |
# unauthorized (401),
|
256 |
# itemNotFound (404),
|
257 |
# unauthorized (401),
|
258 |
# overLimit (413)
|
259 |
|
260 |
log.debug('delete_network %s', network_id)
|
261 |
net = util.get_network(network_id, request.user_uniq) |
262 |
if net.public:
|
263 |
raise Unauthorized('Can not delete the public network.') |
264 |
|
265 |
if net.machines.all(): # Nics attached on network |
266 |
raise NetworkInUse('Machines are connected to network.') |
267 |
|
268 |
net.action = 'DESTROY'
|
269 |
net.save() |
270 |
|
271 |
backend.delete_network(net) |
272 |
return HttpResponse(status=204) |
273 |
|
274 |
|
275 |
@util.api_method('POST') |
276 |
def network_action(request, network_id): |
277 |
req = util.get_request_dict(request) |
278 |
log.debug('network_action %s %s', network_id, req)
|
279 |
if len(req) != 1: |
280 |
raise BadRequest('Malformed request.') |
281 |
|
282 |
net = util.get_network(network_id, request.user_uniq) |
283 |
if net.public:
|
284 |
raise Unauthorized('Can not modify the public network.') |
285 |
|
286 |
key = req.keys()[0]
|
287 |
val = req[key] |
288 |
|
289 |
try:
|
290 |
assert isinstance(val, dict) |
291 |
return network_actions[key](request, net, req[key])
|
292 |
except KeyError: |
293 |
raise BadRequest('Unknown action.') |
294 |
except AssertionError: |
295 |
raise BadRequest('Invalid argument.') |