root / snf-cyclades-app / synnefo / api / floating_ips.py @ 381a548c
History | View | Annotate | Download (9.4 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 django.conf.urls.defaults import patterns |
35 |
from django.db import transaction |
36 |
from django.http import HttpResponse |
37 |
from django.utils import simplejson as json |
38 |
|
39 |
from snf_django.lib import api |
40 |
from snf_django.lib.api import faults, utils |
41 |
from synnefo.api import util |
42 |
from synnefo import quotas |
43 |
from synnefo.db.models import Network, FloatingIP |
44 |
|
45 |
|
46 |
from logging import getLogger |
47 |
log = getLogger(__name__) |
48 |
|
49 |
ips_urlpatterns = patterns( |
50 |
'synnefo.api.floating_ips',
|
51 |
(r'^(?:/|.json|.xml)?$', 'demux'), |
52 |
(r'^/(\w+)(?:.json|.xml)?$', 'floating_ip_demux'), |
53 |
) |
54 |
|
55 |
pools_urlpatterns = patterns( |
56 |
"synnefo.api.floating_ips",
|
57 |
(r'^(?:/|.json|.xml)?$', 'list_floating_ip_pools'), |
58 |
) |
59 |
|
60 |
|
61 |
def demux(request): |
62 |
if request.method == 'GET': |
63 |
return list_floating_ips(request)
|
64 |
elif request.method == 'POST': |
65 |
return allocate_floating_ip(request)
|
66 |
else:
|
67 |
return api.api_method_not_allowed(request,
|
68 |
allowed_methods=['GET', 'POST']) |
69 |
|
70 |
|
71 |
def floating_ip_demux(request, floating_ip_id): |
72 |
if request.method == 'GET': |
73 |
return get_floating_ip(request, floating_ip_id)
|
74 |
elif request.method == 'DELETE': |
75 |
return release_floating_ip(request, floating_ip_id)
|
76 |
else:
|
77 |
return api.api_method_not_allowed(request,
|
78 |
allowed_methods=['GET', 'DELETE']) |
79 |
|
80 |
|
81 |
def ip_to_dict(floating_ip): |
82 |
machine_id = floating_ip.machine_id |
83 |
return {"fixed_ip": None, |
84 |
"id": str(floating_ip.id), |
85 |
"instance_id": str(machine_id) if machine_id else None, |
86 |
"ip": floating_ip.ipv4,
|
87 |
"pool": str(floating_ip.network_id)} |
88 |
|
89 |
|
90 |
@api.api_method(http_method="GET", user_required=True, logger=log, |
91 |
serializations=["json"])
|
92 |
def list_floating_ips(request): |
93 |
"""Return user reserved floating IPs"""
|
94 |
log.debug("list_floating_ips")
|
95 |
|
96 |
userid = request.user_uniq |
97 |
floating_ips = FloatingIP.objects.filter(userid=userid).order_by("id")
|
98 |
floating_ips = utils.filter_modified_since(request, objects=floating_ips) |
99 |
|
100 |
floating_ips = map(ip_to_dict, floating_ips)
|
101 |
|
102 |
request.serialization = "json"
|
103 |
data = json.dumps({"floating_ips": floating_ips})
|
104 |
|
105 |
return HttpResponse(data, status=200) |
106 |
|
107 |
|
108 |
@api.api_method(http_method="GET", user_required=True, logger=log, |
109 |
serializations=["json"])
|
110 |
def get_floating_ip(request, floating_ip_id): |
111 |
"""Return information for a floating IP."""
|
112 |
userid = request.user_uniq |
113 |
try:
|
114 |
floating_ip = FloatingIP.objects.get(id=floating_ip_id, |
115 |
deleted=False,
|
116 |
userid=userid) |
117 |
except FloatingIP.DoesNotExist:
|
118 |
raise faults.ItemNotFound("Floating IP '%s' does not exist" % |
119 |
floating_ip_id) |
120 |
request.serialization = "json"
|
121 |
data = json.dumps({"floating_ip": ip_to_dict(floating_ip)})
|
122 |
return HttpResponse(data, status=200) |
123 |
|
124 |
|
125 |
@api.api_method(http_method='POST', user_required=True, logger=log, |
126 |
serializations=["json"])
|
127 |
@transaction.commit_manually
|
128 |
def allocate_floating_ip(request): |
129 |
"""Allocate a floating IP."""
|
130 |
req = utils.get_request_dict(request) |
131 |
log.info('allocate_floating_ip %s', req)
|
132 |
|
133 |
userid = request.user_uniq |
134 |
pool = req.get("pool", None) |
135 |
address = req.get("address", None) |
136 |
machine = None
|
137 |
net_objects = Network.objects.select_for_update()\ |
138 |
.filter(public=True, floating_ip_pool=True, |
139 |
deleted=False)
|
140 |
try:
|
141 |
if pool is None: |
142 |
# User did not specified a pool. Choose a random public IP
|
143 |
network, address = util.get_free_ip(net_objects) |
144 |
else:
|
145 |
try:
|
146 |
network_id = int(pool)
|
147 |
except ValueError: |
148 |
raise faults.BadRequest("Invalid pool ID.") |
149 |
network = next((n for n in net_objects if n.id == network_id), |
150 |
None)
|
151 |
if network is None: |
152 |
raise faults.ItemNotFound("Pool '%s' does not exist." % pool) |
153 |
if address is None: |
154 |
# User did not specified an IP address. Choose a random one
|
155 |
# Gets X-Lock on IP pool
|
156 |
address = util.get_network_free_address(network) |
157 |
else:
|
158 |
# User specified an IP address. Check that it is not a used
|
159 |
# floating IP
|
160 |
if FloatingIP.objects.filter(network=network,
|
161 |
deleted=False,
|
162 |
ipv4=address).exists(): |
163 |
msg = "Floating IP '%s' is reserved" % address
|
164 |
raise faults.Conflict(msg)
|
165 |
pool = network.get_pool() # Gets X-Lock
|
166 |
# Check address belongs to pool
|
167 |
if not pool.contains(address): |
168 |
raise faults.BadRequest("Invalid address") |
169 |
if pool.is_available(address):
|
170 |
pool.reserve(address) |
171 |
pool.save() |
172 |
# If address is not available, check that it belongs to the
|
173 |
# same user
|
174 |
elif not network.nics.filter(ipv4=address, |
175 |
machine__userid=userid).exists(): |
176 |
msg = "Address '%s' is already in use" % address
|
177 |
raise faults.Conflict(msg)
|
178 |
floating_ip = FloatingIP.objects.create(ipv4=address, network=network, |
179 |
userid=userid, machine=machine) |
180 |
quotas.issue_and_accept_commission(floating_ip) |
181 |
except:
|
182 |
transaction.rollback() |
183 |
raise
|
184 |
else:
|
185 |
transaction.commit() |
186 |
|
187 |
log.info("User '%s' allocated floating IP '%s", userid, floating_ip)
|
188 |
|
189 |
request.serialization = "json"
|
190 |
data = json.dumps({"floating_ip": ip_to_dict(floating_ip)})
|
191 |
return HttpResponse(data, status=200) |
192 |
|
193 |
|
194 |
@api.api_method(http_method='DELETE', user_required=True, logger=log, |
195 |
serializations=["json"])
|
196 |
@transaction.commit_on_success
|
197 |
def release_floating_ip(request, floating_ip_id): |
198 |
"""Release a floating IP."""
|
199 |
userid = request.user_uniq |
200 |
log.info("release_floating_ip '%s'. User '%s'.", floating_ip_id, userid)
|
201 |
try:
|
202 |
floating_ip = FloatingIP.objects.select_for_update()\ |
203 |
.get(id=floating_ip_id, |
204 |
deleted=False,
|
205 |
userid=userid) |
206 |
except FloatingIP.DoesNotExist:
|
207 |
raise faults.ItemNotFound("Floating IP '%s' does not exist" % |
208 |
floating_ip_id) |
209 |
|
210 |
# Since we have got an exlusively lock in floating IP, and since
|
211 |
# to remove a floating IP you need the same lock, the in_use() query
|
212 |
# is safe
|
213 |
if floating_ip.in_use():
|
214 |
msg = "Floating IP '%s' is used" % floating_ip.id
|
215 |
raise faults.Conflict(message=msg)
|
216 |
|
217 |
try:
|
218 |
floating_ip.network.release_address(floating_ip.ipv4) |
219 |
floating_ip.deleted = True
|
220 |
quotas.issue_and_accept_commission(floating_ip, delete=True)
|
221 |
except:
|
222 |
transaction.rollback() |
223 |
raise
|
224 |
else:
|
225 |
floating_ip.delete() |
226 |
transaction.commit() |
227 |
|
228 |
log.info("User '%s' released IP '%s", userid, floating_ip)
|
229 |
|
230 |
return HttpResponse(status=204) |
231 |
|
232 |
|
233 |
def network_to_pool(network): |
234 |
pool = network.get_pool(with_lock=False)
|
235 |
return {"name": str(network.id), |
236 |
"size": pool.pool_size,
|
237 |
"free": pool.count_available()}
|
238 |
|
239 |
|
240 |
@api.api_method(http_method='GET', user_required=True, logger=log, |
241 |
serializations=["json"])
|
242 |
def list_floating_ip_pools(request): |
243 |
networks = Network.objects.filter(public=True, floating_ip_pool=True) |
244 |
networks = utils.filter_modified_since(request, objects=networks) |
245 |
pools = map(network_to_pool, networks)
|
246 |
request.serialization = "json"
|
247 |
data = json.dumps({"floating_ip_pools": pools})
|
248 |
request.serialization = "json"
|
249 |
return HttpResponse(data, status=200) |