root / snf-cyclades-app / synnefo / quotas / __init__.py @ 13f1e2ff
History | View | Annotate | Download (14.6 kB)
1 |
# Copyright 2012, 2013 GRNET S.A. All rights reserved.
|
---|---|
2 |
#
|
3 |
# Redistribution and use in source and binary forms, with or without
|
4 |
# modification, are permitted provided that the following conditions
|
5 |
# are met:
|
6 |
#
|
7 |
# 1. Redistributions of source code must retain the above copyright
|
8 |
# notice, this list of conditions and the following disclaimer.
|
9 |
#
|
10 |
# 2. Redistributions in binary form must reproduce the above copyright
|
11 |
# notice, this list of conditions and the following disclaimer in the
|
12 |
# documentation and/or other materials provided with the distribution.
|
13 |
#
|
14 |
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
|
15 |
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
16 |
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
17 |
# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
|
18 |
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
19 |
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
|
20 |
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
21 |
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
22 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
23 |
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
24 |
# SUCH DAMAGE.
|
25 |
#
|
26 |
# The views and conclusions contained in the software and documentation are
|
27 |
# those of the authors and should not be interpreted as representing official
|
28 |
# policies, either expressed or implied, of GRNET S.A.
|
29 |
|
30 |
from django.utils import simplejson as json |
31 |
from django.db import transaction |
32 |
|
33 |
from snf_django.lib.api import faults |
34 |
from synnefo.db.models import (QuotaHolderSerial, VirtualMachine, Network, |
35 |
IPAddress) |
36 |
|
37 |
from synnefo.settings import (CYCLADES_SERVICE_TOKEN as ASTAKOS_TOKEN, |
38 |
ASTAKOS_AUTH_URL) |
39 |
from astakosclient import AstakosClient |
40 |
from astakosclient import errors |
41 |
|
42 |
import logging |
43 |
log = logging.getLogger(__name__) |
44 |
|
45 |
|
46 |
QUOTABLE_RESOURCES = [VirtualMachine, Network, IPAddress] |
47 |
|
48 |
|
49 |
RESOURCES = [ |
50 |
"cyclades.vm",
|
51 |
"cyclades.total_cpu",
|
52 |
"cyclades.cpu",
|
53 |
"cyclades.disk",
|
54 |
"cyclades.total_ram",
|
55 |
"cyclades.ram",
|
56 |
"cyclades.network.private",
|
57 |
"cyclades.floating_ip",
|
58 |
] |
59 |
|
60 |
|
61 |
class Quotaholder(object): |
62 |
_object = None
|
63 |
|
64 |
@classmethod
|
65 |
def get(cls): |
66 |
if cls._object is None: |
67 |
cls._object = AstakosClient(ASTAKOS_TOKEN, |
68 |
ASTAKOS_AUTH_URL, |
69 |
use_pool=True,
|
70 |
retry=3,
|
71 |
logger=log) |
72 |
return cls._object
|
73 |
|
74 |
|
75 |
class AstakosClientExceptionHandler(object): |
76 |
def __init__(self, *args, **kwargs): |
77 |
self.user = kwargs.get("user") |
78 |
self.projects = kwargs.get("projects") |
79 |
|
80 |
def __enter__(self): |
81 |
pass
|
82 |
|
83 |
def check_notFound(self): |
84 |
if not self.user or not self.projects: |
85 |
return
|
86 |
try:
|
87 |
qh = Quotaholder.get() |
88 |
user_quota = qh.service_get_quotas(self.user)
|
89 |
except errors.AstakosClientException as e: |
90 |
log.exception("Unexpected error %s" % e.message)
|
91 |
raise faults.InternalServerError("Unexpected error") |
92 |
|
93 |
user_quota = user_quota[self.user]
|
94 |
for project in self.projects: |
95 |
try:
|
96 |
user_quota[project] |
97 |
except KeyError: |
98 |
m = "User %s not in project %s" % (self.user, project) |
99 |
raise faults.BadRequest(m)
|
100 |
|
101 |
def __exit__(self, exc_type, value, traceback): |
102 |
if value is not None: # exception |
103 |
if not isinstance(value, errors.AstakosClientException): |
104 |
return False # reraise |
105 |
if exc_type is errors.QuotaLimit: |
106 |
msg, details = render_overlimit_exception(value) |
107 |
raise faults.OverLimit(msg, details=details)
|
108 |
if exc_type is errors.NotFound: |
109 |
self.check_notFound()
|
110 |
|
111 |
log.exception("Unexpected error %s" % value.message)
|
112 |
raise faults.InternalServerError("Unexpected error") |
113 |
|
114 |
|
115 |
def issue_commission(resource, action, name="", force=False, auto_accept=False, |
116 |
action_fields=None):
|
117 |
"""Issue a new commission to the quotaholder.
|
118 |
|
119 |
Issue a new commission to the quotaholder, and create the
|
120 |
corresponing QuotaHolderSerial object in DB.
|
121 |
|
122 |
"""
|
123 |
|
124 |
provisions = get_commission_info(resource=resource, action=action, |
125 |
action_fields=action_fields) |
126 |
|
127 |
if provisions is None: |
128 |
return None |
129 |
|
130 |
user = resource.userid |
131 |
source = resource.project |
132 |
|
133 |
qh = Quotaholder.get() |
134 |
if True: # placeholder |
135 |
with AstakosClientExceptionHandler(user=user, projects=[source]):
|
136 |
serial = qh.issue_one_commission(user, source, |
137 |
provisions, name=name, |
138 |
force=force, |
139 |
auto_accept=auto_accept) |
140 |
|
141 |
if not serial: |
142 |
raise Exception("No serial") |
143 |
|
144 |
serial_info = {"serial": serial}
|
145 |
if auto_accept:
|
146 |
serial_info["pending"] = False |
147 |
serial_info["accept"] = True |
148 |
serial_info["resolved"] = True |
149 |
|
150 |
serial = QuotaHolderSerial.objects.create(**serial_info) |
151 |
|
152 |
# Correlate the serial with the resource. Resolved serials are not
|
153 |
# attached to resources
|
154 |
if not auto_accept: |
155 |
resource.serial = serial |
156 |
resource.save() |
157 |
|
158 |
return serial
|
159 |
|
160 |
|
161 |
def accept_resource_serial(resource, strict=True): |
162 |
serial = resource.serial |
163 |
assert serial.pending or serial.accept, "%s can't be accepted" % serial |
164 |
log.debug("Accepting serial %s of resource %s", serial, resource)
|
165 |
_resolve_commissions(accept=[serial.serial], strict=strict) |
166 |
resource.serial = None
|
167 |
resource.save() |
168 |
return resource
|
169 |
|
170 |
|
171 |
def reject_resource_serial(resource, strict=True): |
172 |
serial = resource.serial |
173 |
assert serial.pending or not serial.accept, "%s can't be rejected" % serial |
174 |
log.debug("Rejecting serial %s of resource %s", serial, resource)
|
175 |
_resolve_commissions(reject=[serial.serial], strict=strict) |
176 |
resource.serial = None
|
177 |
resource.save() |
178 |
return resource
|
179 |
|
180 |
|
181 |
def _resolve_commissions(accept=None, reject=None, strict=True): |
182 |
if accept is None: |
183 |
accept = [] |
184 |
if reject is None: |
185 |
reject = [] |
186 |
|
187 |
qh = Quotaholder.get() |
188 |
with AstakosClientExceptionHandler():
|
189 |
response = qh.resolve_commissions(accept, reject) |
190 |
|
191 |
accepted = response.get("accepted", [])
|
192 |
rejected = response.get("rejected", [])
|
193 |
|
194 |
if accepted:
|
195 |
QuotaHolderSerial.objects.filter(serial__in=accepted).update( |
196 |
accept=True, pending=False, resolved=True) |
197 |
if rejected:
|
198 |
QuotaHolderSerial.objects.filter(serial__in=rejected).update( |
199 |
accept=False, pending=False, resolved=True) |
200 |
|
201 |
if strict:
|
202 |
failed = response["failed"]
|
203 |
if failed:
|
204 |
log.error("Unexpected error while resolving commissions: %s",
|
205 |
failed) |
206 |
|
207 |
return response
|
208 |
|
209 |
|
210 |
def reconcile_resolve_commissions(accept=None, reject=None, strict=True): |
211 |
response = _resolve_commissions(accept=accept, |
212 |
reject=reject, |
213 |
strict=strict) |
214 |
affected = response.get("accepted", []) + response.get("rejected", []) |
215 |
for resource in QUOTABLE_RESOURCES: |
216 |
resource.objects.filter(serial__in=affected).update(serial=None)
|
217 |
|
218 |
|
219 |
def resolve_pending_commissions(): |
220 |
"""Resolve quotaholder pending commissions.
|
221 |
|
222 |
Get pending commissions from the quotaholder and resolve them
|
223 |
to accepted and rejected, according to the state of the
|
224 |
QuotaHolderSerial DB table. A pending commission in the quotaholder
|
225 |
can exist in the QuotaHolderSerial table and be either accepted or
|
226 |
rejected, or cannot exist in this table, so it is rejected.
|
227 |
|
228 |
"""
|
229 |
|
230 |
qh_pending = get_quotaholder_pending() |
231 |
if not qh_pending: |
232 |
return ([], [])
|
233 |
|
234 |
qh_pending.sort() |
235 |
min_ = qh_pending[0]
|
236 |
|
237 |
serials = QuotaHolderSerial.objects.filter(serial__gte=min_, pending=False)
|
238 |
accepted = serials.filter(accept=True).values_list('serial', flat=True) |
239 |
accepted = filter(lambda x: x in qh_pending, accepted) |
240 |
|
241 |
rejected = list(set(qh_pending) - set(accepted)) |
242 |
|
243 |
return (accepted, rejected)
|
244 |
|
245 |
|
246 |
def get_quotaholder_pending(): |
247 |
qh = Quotaholder.get() |
248 |
pending_serials = qh.get_pending_commissions() |
249 |
return pending_serials
|
250 |
|
251 |
|
252 |
def render_overlimit_exception(e): |
253 |
resource_name = {"vm": "Virtual Machine", |
254 |
"cpu": "CPU", |
255 |
"ram": "RAM", |
256 |
"network.private": "Private Network", |
257 |
"floating_ip": "Floating IP address"} |
258 |
details = json.loads(e.details) |
259 |
data = details['overLimit']['data'] |
260 |
usage = data["usage"]
|
261 |
limit = data["limit"]
|
262 |
available = limit - usage |
263 |
provision = data['provision']
|
264 |
requested = provision['quantity']
|
265 |
resource = provision['resource']
|
266 |
res = resource.replace("cyclades.", "", 1) |
267 |
try:
|
268 |
resource = resource_name[res] |
269 |
except KeyError: |
270 |
resource = res |
271 |
|
272 |
msg = "Resource Limit Exceeded for your account."
|
273 |
details = "Limit for resource '%s' exceeded for your account."\
|
274 |
" Available: %s, Requested: %s"\
|
275 |
% (resource, available, requested) |
276 |
return msg, details
|
277 |
|
278 |
|
279 |
@transaction.commit_on_success
|
280 |
def issue_and_accept_commission(resource, action="BUILD", action_fields=None): |
281 |
"""Issue and accept a commission to Quotaholder.
|
282 |
|
283 |
This function implements the Commission workflow, and must be called
|
284 |
exactly after and in the same transaction that created/updated the
|
285 |
resource. The workflow that implements is the following:
|
286 |
0) Resolve previous unresolved commission if exists
|
287 |
1) Issue commission, get a serial and correlate it with the resource
|
288 |
2) Store the serial in DB as a serial to accept
|
289 |
3) COMMIT!
|
290 |
4) Accept commission to QH
|
291 |
|
292 |
"""
|
293 |
commission_reason = ("client: api, resource: %s, action: %s"
|
294 |
% (resource, action)) |
295 |
serial = handle_resource_commission(resource=resource, action=action, |
296 |
action_fields=action_fields, |
297 |
commission_name=commission_reason) |
298 |
|
299 |
if serial is None: |
300 |
return
|
301 |
|
302 |
# Mark the serial as one to accept and associate it with the resource
|
303 |
serial.pending = False
|
304 |
serial.accept = True
|
305 |
serial.save() |
306 |
transaction.commit() |
307 |
|
308 |
try:
|
309 |
# Accept the commission to quotaholder
|
310 |
accept_resource_serial(resource) |
311 |
except:
|
312 |
# Do not crash if we can not accept commission to Quotaholder. Quotas
|
313 |
# have already been reserved and the resource already exists in DB.
|
314 |
# Just log the error
|
315 |
log.exception("Failed to accept commission: %s", resource.serial)
|
316 |
|
317 |
|
318 |
def get_commission_info(resource, action, action_fields=None): |
319 |
if isinstance(resource, VirtualMachine): |
320 |
flavor = resource.flavor |
321 |
resources = {"cyclades.vm": 1, |
322 |
"cyclades.total_cpu": flavor.cpu,
|
323 |
"cyclades.disk": 1073741824 * flavor.disk, |
324 |
"cyclades.total_ram": 1048576 * flavor.ram} |
325 |
online_resources = {"cyclades.cpu": flavor.cpu,
|
326 |
"cyclades.ram": 1048576 * flavor.ram} |
327 |
if action == "BUILD": |
328 |
resources.update(online_resources) |
329 |
return resources
|
330 |
if action == "START": |
331 |
if resource.operstate == "STOPPED": |
332 |
return online_resources
|
333 |
else:
|
334 |
return None |
335 |
elif action == "STOP": |
336 |
if resource.operstate in ["STARTED", "BUILD", "ERROR"]: |
337 |
return reverse_quantities(online_resources)
|
338 |
else:
|
339 |
return None |
340 |
elif action == "REBOOT": |
341 |
if resource.operstate == "STOPPED": |
342 |
return online_resources
|
343 |
else:
|
344 |
return None |
345 |
elif action == "DESTROY": |
346 |
if resource.operstate in ["STARTED", "BUILD", "ERROR"]: |
347 |
resources.update(online_resources) |
348 |
return reverse_quantities(resources)
|
349 |
elif action == "RESIZE" and action_fields: |
350 |
beparams = action_fields.get("beparams")
|
351 |
cpu = beparams.get("vcpus", flavor.cpu)
|
352 |
ram = beparams.get("maxmem", flavor.ram)
|
353 |
return {"cyclades.total_cpu": cpu - flavor.cpu, |
354 |
"cyclades.total_ram": 1048576 * (ram - flavor.ram)} |
355 |
else:
|
356 |
#["CONNECT", "DISCONNECT", "SET_FIREWALL_PROFILE"]:
|
357 |
return None |
358 |
elif isinstance(resource, Network): |
359 |
resources = {"cyclades.network.private": 1} |
360 |
if action == "BUILD": |
361 |
return resources
|
362 |
elif action == "DESTROY": |
363 |
return reverse_quantities(resources)
|
364 |
elif isinstance(resource, IPAddress): |
365 |
if resource.floating_ip:
|
366 |
resources = {"cyclades.floating_ip": 1} |
367 |
if action == "BUILD": |
368 |
return resources
|
369 |
elif action == "DESTROY": |
370 |
return reverse_quantities(resources)
|
371 |
else:
|
372 |
return None |
373 |
|
374 |
|
375 |
def reverse_quantities(resources): |
376 |
return dict((r, -s) for r, s in resources.items()) |
377 |
|
378 |
|
379 |
def handle_resource_commission(resource, action, commission_name, |
380 |
force=False, auto_accept=False, |
381 |
action_fields=None):
|
382 |
"""Handle a issuing of a commission for a resource.
|
383 |
|
384 |
Create a new commission for a resource based on the action that
|
385 |
is performed. If the resource has a previous pending commission,
|
386 |
resolved it before issuing the new one.
|
387 |
|
388 |
"""
|
389 |
# Try to resolve previous serial:
|
390 |
# If action is DESTROY, we must always reject the previous commission,
|
391 |
# since multiple DESTROY actions are allowed in the same resource (e.g. VM)
|
392 |
# The one who succeeds will be finally accepted, and all other will be
|
393 |
# rejected
|
394 |
force = force or (action == "DESTROY") |
395 |
resolve_resource_commission(resource, force=force) |
396 |
|
397 |
serial = issue_commission(resource, action, name=commission_name, |
398 |
force=force, auto_accept=auto_accept, |
399 |
action_fields=action_fields) |
400 |
return serial
|
401 |
|
402 |
|
403 |
class ResolveError(Exception): |
404 |
pass
|
405 |
|
406 |
|
407 |
def resolve_resource_commission(resource, force=False): |
408 |
serial = resource.serial |
409 |
if serial is None or serial.resolved: |
410 |
return
|
411 |
if serial.pending and not force: |
412 |
m = "Could not resolve commission: serial %s is undecided" % serial
|
413 |
raise ResolveError(m)
|
414 |
log.warning("Resolving pending commission: %s", serial)
|
415 |
if not serial.pending and serial.accept: |
416 |
accept_resource_serial(resource) |
417 |
else:
|
418 |
reject_resource_serial(resource) |