root / snf-cyclades-app / synnefo / api / floating_ips.py @ ece5581b
History | View | Annotate | Download (8.9 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.method_not_allowed(request)
|
68 |
|
69 |
|
70 |
def floating_ip_demux(request, floating_ip_id): |
71 |
if request.method == 'GET': |
72 |
return get_floating_ip(request, floating_ip_id)
|
73 |
elif request.method == 'DELETE': |
74 |
return release_floating_ip(request, floating_ip_id)
|
75 |
else:
|
76 |
return api.method_not_allowed(request)
|
77 |
|
78 |
|
79 |
def ip_to_dict(floating_ip): |
80 |
machine_id = floating_ip.machine_id |
81 |
return {"fixed_ip": None, |
82 |
"id": str(floating_ip.id), |
83 |
"instance_id": str(machine_id) if machine_id else None, |
84 |
"ip": floating_ip.ipv4,
|
85 |
"pool": str(floating_ip.network_id)} |
86 |
|
87 |
|
88 |
@api.api_method(http_method="GET", user_required=True, logger=log) |
89 |
def list_floating_ips(request): |
90 |
"""Return user reserved floating IPs"""
|
91 |
log.debug("list_floating_ips")
|
92 |
|
93 |
userid = request.user_uniq |
94 |
floating_ips = FloatingIP.objects.filter(userid=userid, deleted=False)\
|
95 |
.order_by("id")
|
96 |
|
97 |
floating_ips = map(ip_to_dict, floating_ips)
|
98 |
|
99 |
request.serialization = "json"
|
100 |
data = json.dumps({"floating_ips": floating_ips})
|
101 |
|
102 |
return HttpResponse(data, status=200) |
103 |
|
104 |
|
105 |
@api.api_method(http_method="GET", user_required=True, logger=log) |
106 |
def get_floating_ip(request, floating_ip_id): |
107 |
"""Return information for a floating IP."""
|
108 |
userid = request.user_uniq |
109 |
try:
|
110 |
floating_ip = FloatingIP.objects.get(id=floating_ip_id, |
111 |
deleted=False,
|
112 |
userid=userid) |
113 |
except FloatingIP.DoesNotExist:
|
114 |
raise faults.ItemNotFound("Floating IP '%s' does not exist" % |
115 |
floating_ip_id) |
116 |
request.serialization = "json"
|
117 |
data = json.dumps({"floating_ip": ip_to_dict(floating_ip)})
|
118 |
return HttpResponse(data, status=200) |
119 |
|
120 |
|
121 |
@api.api_method(http_method='POST', user_required=True, logger=log) |
122 |
@transaction.commit_manually
|
123 |
def allocate_floating_ip(request): |
124 |
"""Allocate a floating IP."""
|
125 |
req = utils.get_request_dict(request) |
126 |
log.info('allocate_floating_ip %s', req)
|
127 |
|
128 |
userid = request.user_uniq |
129 |
pool = req.get("pool", None) |
130 |
address = req.get("address", None) |
131 |
machine = None
|
132 |
net_objects = Network.objects.select_for_update()\ |
133 |
.filter(public=True, floating_ip_pool=True, |
134 |
deleted=False)
|
135 |
try:
|
136 |
if pool is None: |
137 |
# User did not specified a pool. Choose a random public IP
|
138 |
network, address = util.allocate_public_ip(net_objects) |
139 |
else:
|
140 |
try:
|
141 |
network = Network.objects.select_for_update()\ |
142 |
.get(id=pool, public=True,
|
143 |
deleted=False,
|
144 |
floating_ip_pool=True)
|
145 |
|
146 |
except Network.DoesNotExist:
|
147 |
raise faults.ItemNotFound("Pool '%s' does not exist." % pool) |
148 |
if address is None: |
149 |
# User did not specified an IP address. Choose a random one
|
150 |
# Gets X-Lock on IP pool
|
151 |
address = util.get_network_free_address(network) |
152 |
else:
|
153 |
# User specified an IP address. Check that it is not a used
|
154 |
# floating IP
|
155 |
if FloatingIP.objects.filter(network=network,
|
156 |
deleted=False,
|
157 |
ipv4=address).exists(): |
158 |
msg = "Floating IP '%s' is reserved" % address
|
159 |
raise faults.Conflict(msg)
|
160 |
pool = network.get_pool() # Gets X-Lock
|
161 |
# Check address belongs to pool
|
162 |
if not pool.contains(address): |
163 |
raise faults.BadRequest("Invalid address") |
164 |
if pool.is_available(address):
|
165 |
pool.reserve(address) |
166 |
pool.save() |
167 |
# If address is not available, check that it belongs to the
|
168 |
# same user
|
169 |
elif not network.nics.filter(ipv4=address, |
170 |
machine__userid=userid).exists(): |
171 |
msg = "Address '%s' is already in use" % address
|
172 |
raise faults.Conflict(msg)
|
173 |
floating_ip = FloatingIP.objects.create(ipv4=address, network=network, |
174 |
userid=userid, machine=machine) |
175 |
quotas.issue_and_accept_commission(floating_ip) |
176 |
except:
|
177 |
transaction.rollback() |
178 |
raise
|
179 |
else:
|
180 |
transaction.commit() |
181 |
|
182 |
log.info("User '%s' allocated floating IP '%s", userid, floating_ip)
|
183 |
|
184 |
request.serialization = "json"
|
185 |
data = json.dumps({"floating_ip": ip_to_dict(floating_ip)})
|
186 |
return HttpResponse(data, status=200) |
187 |
|
188 |
|
189 |
@api.api_method(http_method='DELETE', user_required=True, logger=log) |
190 |
@transaction.commit_on_success
|
191 |
def release_floating_ip(request, floating_ip_id): |
192 |
"""Release a floating IP."""
|
193 |
userid = request.user_uniq |
194 |
log.info("release_floating_ip '%s'. User '%s'.", floating_ip_id, userid)
|
195 |
try:
|
196 |
floating_ip = FloatingIP.objects.select_for_update()\ |
197 |
.get(id=floating_ip_id, |
198 |
deleted=False,
|
199 |
userid=userid) |
200 |
except FloatingIP.DoesNotExist:
|
201 |
raise faults.ItemNotFound("Floating IP '%s' does not exist" % |
202 |
floating_ip_id) |
203 |
|
204 |
# Since we have got an exlusively lock in floating IP, and since
|
205 |
# to remove a floating IP you need the same lock, the in_use() query
|
206 |
# is safe
|
207 |
if floating_ip.in_use():
|
208 |
msg = "Floating IP '%s' is used" % floating_ip.id
|
209 |
raise faults.Conflict(message=msg)
|
210 |
|
211 |
try:
|
212 |
floating_ip.network.release_address(floating_ip.ipv4) |
213 |
floating_ip.deleted = True
|
214 |
quotas.issue_and_accept_commission(floating_ip, delete=True)
|
215 |
except:
|
216 |
transaction.rollback() |
217 |
raise
|
218 |
else:
|
219 |
floating_ip.delete() |
220 |
transaction.commit() |
221 |
|
222 |
log.info("User '%s' released IP '%s", userid, floating_ip)
|
223 |
|
224 |
return HttpResponse(status=204) |
225 |
|
226 |
|
227 |
@api.api_method(http_method='GET', user_required=True, logger=log) |
228 |
def list_floating_ip_pools(request): |
229 |
networks = Network.objects.filter(public=True, deleted=False, |
230 |
floating_ip_pool=True)
|
231 |
pools = [{"name": str(net.id)} for net in networks] |
232 |
request.serialization = "json"
|
233 |
data = json.dumps({"floating_ip_pools": pools})
|
234 |
request.serialization = "json"
|
235 |
return HttpResponse(data, status=200) |