root / snf-cyclades-app / synnefo / api / subnets.py @ 16f7d0d9
History | View | Annotate | Download (11.1 kB)
1 |
# Copyright 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 logging import getLogger |
35 |
from snf_django.lib import api |
36 |
from snf_django.lib.api import faults |
37 |
|
38 |
from django.http import HttpResponse |
39 |
from django.utils import simplejson as json |
40 |
|
41 |
from snf_django.lib.api import utils |
42 |
from models import Subnet, Network |
43 |
from synnefo.logic import networks |
44 |
|
45 |
from ipaddr import IPv4Network, IPv6Network, IPv4Address |
46 |
|
47 |
log = getLogger(__name__) |
48 |
|
49 |
|
50 |
def demux(request): |
51 |
if request.method == 'GET': |
52 |
return list_subnets(request)
|
53 |
elif request.method == 'POST': |
54 |
return create_subnet(request)
|
55 |
else:
|
56 |
return api.api_method_not_allowed(request)
|
57 |
|
58 |
|
59 |
def subnet_demux(request, sub_id): |
60 |
if request.method == 'GET': |
61 |
return get_subnet(request, sub_id)
|
62 |
elif request.method == 'DELETE': |
63 |
return delete_subnet(request, sub_id)
|
64 |
elif request.method == 'PUT': |
65 |
return update_subnet(request, sub_id)
|
66 |
else:
|
67 |
return api.api_method_not_allowed(request)
|
68 |
|
69 |
|
70 |
@api.api_method(http_method='GET', user_required=True, logger=log) |
71 |
def list_subnets(request): |
72 |
"""List all subnets of a user"""
|
73 |
log.debug('list_subnets')
|
74 |
|
75 |
user_subnets = Subnet.objects.filter(network__userid=request.user_uniq) |
76 |
subnets_dict = [subnet_to_dict(sub) |
77 |
for sub in user_subnets.order_by('id')] |
78 |
data = json.dumps({'subnets': subnets_dict})
|
79 |
|
80 |
return HttpResponse(data, status=200) |
81 |
|
82 |
|
83 |
@api.api_method(http_method='POST', user_required=True, logger=log) |
84 |
def create_subnet(request): |
85 |
"""Create a subnet"""
|
86 |
|
87 |
dictionary = utils.get_request_dict(request) |
88 |
log.info('create subnet %s', dictionary)
|
89 |
user_id = request.user_uniq |
90 |
|
91 |
try:
|
92 |
subnet = dictionary['subnet']
|
93 |
network_id = subnet['network_id']
|
94 |
cidr = subnet['cidr']
|
95 |
except KeyError: |
96 |
raise api.faults.BadRequest("Malformed request") |
97 |
|
98 |
try:
|
99 |
network = Network.objects.get(id=network_id) |
100 |
except Network.DoesNotExist:
|
101 |
raise api.faults.ItemNotFound("No networks found with that id") |
102 |
|
103 |
if user_id != network.userid:
|
104 |
raise api.faults.Unauthorized("Unauthorized operation") |
105 |
|
106 |
ipversion = subnet.get('ip_version', 4) |
107 |
if ipversion not in [4, 6]: |
108 |
raise api.faults.BadRequest("Malformed IP version type") |
109 |
|
110 |
# Returns the first available IP in the subnet
|
111 |
if ipversion == 6: |
112 |
potential_gateway = str(IPv6Network(cidr).network + 1) |
113 |
check_number_of_subnets(network, 6)
|
114 |
else:
|
115 |
potential_gateway = str(IPv4Network(cidr).network + 1) |
116 |
check_number_of_subnets(network, 4)
|
117 |
|
118 |
gateway = subnet.get('gateway_ip', potential_gateway)
|
119 |
|
120 |
if ipversion == 6: |
121 |
networks.validate_network_params(None, None, cidr, gateway) |
122 |
else:
|
123 |
networks.validate_network_params(cidr, gateway) |
124 |
|
125 |
allocation_pools = subnet.get('allocation_pools', None) |
126 |
|
127 |
if allocation_pools:
|
128 |
if ipversion == 6: |
129 |
raise api.faults.BadRequest("Can't allocate an IP Pool in IPv6") |
130 |
for pool in allocation_pools: |
131 |
start = pool['start']
|
132 |
end = pool['end']
|
133 |
networks.validate_network_params(cidr, start) |
134 |
networks.validate_network_params(cidr, end) |
135 |
start = IPv4Address(start) |
136 |
end = IPv4Address(end) |
137 |
if start >= end:
|
138 |
raise api.faults.BadRequest("Invalid IP pool range") |
139 |
else:
|
140 |
# FIX ME
|
141 |
pass
|
142 |
|
143 |
dhcp = check_dhcp_value(subnet.get('enable_dhcp', True)) |
144 |
name = check_name_length(subnet.get('name', None)) |
145 |
|
146 |
dns = subnet.get('dns_nameservers', None) |
147 |
hosts = subnet.get('host_routes', None) |
148 |
|
149 |
# FIX ME
|
150 |
try:
|
151 |
sub = Subnet.objects.create(name=name, network=network, cidr=cidr, |
152 |
ipversion=ipversion, gateway=gateway, |
153 |
dhcp=dhcp, host_routes=hosts, |
154 |
dns_nameservers=dns) |
155 |
except:
|
156 |
raise
|
157 |
return "Error" |
158 |
|
159 |
subnet_dict = subnet_to_dict(sub) |
160 |
data = json.dumps({'subnet': subnet_dict})
|
161 |
return HttpResponse(data, status=200) |
162 |
|
163 |
|
164 |
@api.api_method(http_method='GET', user_required=True, logger=log) |
165 |
def get_subnet(request, sub_id): |
166 |
"""Show info of a specific subnet"""
|
167 |
log.debug('get_subnet %s', sub_id)
|
168 |
user_id = request.user_uniq |
169 |
|
170 |
try:
|
171 |
subnet = Subnet.objects.get(id=sub_id) |
172 |
except Subnet.DoesNotExist:
|
173 |
raise api.faults.ItemNotFound("Subnet not found") |
174 |
|
175 |
if subnet.network.userid != user_id:
|
176 |
raise api.failts.Unauthorized("You're not allowed to view this subnet") |
177 |
|
178 |
subnet_dict = subnet_to_dict(subnet) |
179 |
data = json.dumps({'subnet': subnet_dict})
|
180 |
return HttpResponse(data, status=200) |
181 |
|
182 |
|
183 |
@api.api_method(http_method='DELETE', user_required=True, logger=log) |
184 |
def delete_subnet(request, sub_id): |
185 |
"""
|
186 |
Delete a subnet, raises BadRequest
|
187 |
A subnet is deleted ONLY when the network that it belongs to is deleted
|
188 |
"""
|
189 |
raise api.faults.BadRequest("Deletion of a subnet is not supported") |
190 |
|
191 |
|
192 |
@api.api_method(http_method='PUT', user_required=True, logger=log) |
193 |
def update_subnet(request, sub_id): |
194 |
"""
|
195 |
Update the fields of a subnet
|
196 |
Only the name can be updated, everything else returns BadRequest
|
197 |
"""
|
198 |
|
199 |
dictionary = utils.get_request_dict(request) |
200 |
log.info('Update subnet %s', dictionary)
|
201 |
user_id = request.user_uniq |
202 |
|
203 |
try:
|
204 |
subnet = dictionary['subnet']
|
205 |
except KeyError: |
206 |
raise api.faults.BadRequest("Malformed request") |
207 |
|
208 |
original_subnet = get_subnet_fromdb(sub_id, user_id) |
209 |
original_dict = subnet_to_dict(original_subnet) |
210 |
|
211 |
if len(subnet) != 1: |
212 |
raise api.faults.BadRequest("Only the name of subnet can be updated") |
213 |
|
214 |
name = subnet.get("name", None) |
215 |
|
216 |
if not name: |
217 |
raise api.faults.BadRequest("Only the name of subnet can be updated") |
218 |
|
219 |
#if subnet.get('ip_version', None):
|
220 |
# raise api.faults.BadRequest("Malformed request, ip_version cannot be "
|
221 |
# "updated")
|
222 |
#if subnet.get('cidr', None):
|
223 |
# raise api.faults.BadRequest("Malformed request, cidr cannot be "
|
224 |
# "updated")
|
225 |
#if subnet.get('allocation_pools', None):
|
226 |
# raise api.faults.BadRequest("Malformed request, allocation pools "
|
227 |
# "cannot be updated")
|
228 |
#
|
229 |
# Check if request contained host/dns information
|
230 |
#check_for_hosts_dns(subnet)
|
231 |
#
|
232 |
#name = subnet.get('name', original_dict['name'])
|
233 |
check_name_length(name) |
234 |
|
235 |
#dhcp = subnet.get('enable_dhcp', original_dict['enable_dhcp'])
|
236 |
#check_dhcp_value(dhcp)
|
237 |
#
|
238 |
#gateway = subnet.get('gateway_ip', original_dict['gateway_ip'])
|
239 |
#FIX ME, check if IP is in use
|
240 |
#if original_dict['ip_version'] == 6:
|
241 |
# networks.validate_network_params(None, None, original_dict['cidr'],
|
242 |
# gateway)
|
243 |
#else:
|
244 |
# networks.validate_network_params(original_dict['cidr'], gateway)
|
245 |
#
|
246 |
try:
|
247 |
#original_subnet.gateway = gateway
|
248 |
original_subnet.name = name |
249 |
#original_subnet.dhcp = dhcp
|
250 |
original_subnet.save() |
251 |
except:
|
252 |
#Fix me
|
253 |
return "Unknown Error" |
254 |
|
255 |
subnet_dict = subnet_to_dict(original_subnet) |
256 |
data = json.dumps({'subnet': subnet_dict})
|
257 |
return HttpResponse(data, status=200) |
258 |
|
259 |
|
260 |
#Utility functions
|
261 |
def subnet_to_dict(subnet): |
262 |
"""Returns a dictionary containing the info of a subnet"""
|
263 |
# FIX ME, allocation pools
|
264 |
dictionary = dict({'id': subnet.id, 'network_id': subnet.network.id, |
265 |
'name': subnet.name, 'tenant_id': subnet.network.userid, |
266 |
'gateway_ip': subnet.gateway,
|
267 |
'ip_version': subnet.ipversion, 'cidr': subnet.cidr, |
268 |
'enable_dhcp': subnet.dhcp,
|
269 |
'dns_nameservers': subnet.dns_nameservers,
|
270 |
'host_routes': subnet.host_routes,
|
271 |
'allocation_pools': []})
|
272 |
return dictionary
|
273 |
|
274 |
|
275 |
def check_number_of_subnets(network, version): |
276 |
"""Check if a user can add a subnet in a network"""
|
277 |
if network.subnet_set.filter(ipversion=version):
|
278 |
raise api.faults.BadRequest("Only one subnet of IPv4/IPv6 per " |
279 |
"network is allowed")
|
280 |
|
281 |
|
282 |
def check_dhcp_value(dhcp): |
283 |
"""Check if dhcp value is in acceptable values"""
|
284 |
if dhcp not in [True, False]: |
285 |
raise api.faults.BadRequest("Malformed request, enable_dhcp must be " |
286 |
"True or False")
|
287 |
return dhcp
|
288 |
|
289 |
|
290 |
def check_name_length(name): |
291 |
"""Check if the length of a name is within acceptable value"""
|
292 |
if len(str(name)) > Subnet.SUBNET_NAME_LENGTH: |
293 |
raise api.faults.BadRequest("Subnet name too long") |
294 |
return name
|
295 |
|
296 |
|
297 |
def check_for_hosts_dns(subnet): |
298 |
"""
|
299 |
Check if a request contains host_routes or dns_nameservers options
|
300 |
Expects the request in a dictionary format
|
301 |
"""
|
302 |
if subnet.get('host_routes', None): |
303 |
raise api.faults.BadRequest("Setting host routes isn't supported") |
304 |
if subnet.get('dns_nameservers', None): |
305 |
raise api.faults.BadRequest("Setting dns nameservers isn't supported") |
306 |
|
307 |
|
308 |
def get_subnet_fromdb(subnet_id, user_id, for_update=False): |
309 |
"""
|
310 |
Return a Subnet instance or raise ItemNotFound.
|
311 |
This is the same as util.get_network
|
312 |
"""
|
313 |
try:
|
314 |
subnet_id = int(subnet_id)
|
315 |
if for_update:
|
316 |
return Subnet.objects.select_for_update().get(id=subnet_id,
|
317 |
network__userid= |
318 |
user_id) |
319 |
return Subnet.objects.get(id=subnet_id, network__userid=user_id)
|
320 |
except (ValueError, Subnet.DoesNotExist): |
321 |
raise api.faults.ItemNotFound('Subnet not found.') |