root / logic / credits.py @ 92c53da1
History | View | Annotate | Download (1.7 kB)
1 |
#
|
---|---|
2 |
# Business Logic for all Credit related activity
|
3 |
#
|
4 |
# Copyright 2010 Greek Research and Technology Network
|
5 |
#
|
6 |
|
7 |
from datetime import datetime |
8 |
|
9 |
from db.models import Debit |
10 |
from django.db import transaction |
11 |
|
12 |
@transaction.commit_on_success
|
13 |
def debit_account(user , amount, vm, description): |
14 |
"""Charges the user with the specified amount of credits for a vm (resource)"""
|
15 |
date_now = datetime.now() |
16 |
user.credit = user.credit - amount |
17 |
user.save() |
18 |
|
19 |
# then write the debit entry
|
20 |
debit = Debit() |
21 |
debit.user = user |
22 |
debit.vm = vm |
23 |
debit.when = date_now |
24 |
debit.description = description |
25 |
debit.save() |
26 |
|
27 |
|
28 |
@transaction.commit_on_success
|
29 |
def credit_account(self, amount, creditor, description): |
30 |
"""No clue :)"""
|
31 |
return
|
32 |
|
33 |
|
34 |
@transaction.commit_on_success
|
35 |
def charge(vm): |
36 |
"""Charges the owner of this VM.
|
37 |
|
38 |
Charges the owner of a VM for the period
|
39 |
from vm.charged to datetime.now(), based on the
|
40 |
current operating state.
|
41 |
|
42 |
"""
|
43 |
charged_states = ('STARTED', 'STOPPED') |
44 |
|
45 |
start_datetime = vm.charged |
46 |
vm.charged = datetime.now() |
47 |
|
48 |
# Only charge for a specific set of states
|
49 |
if vm._operstate in charged_states: |
50 |
cost_list = [] |
51 |
|
52 |
# remember, we charge only for Started and Stopped
|
53 |
if vm._operstate == 'STARTED': |
54 |
cost_list = vm.flavor.get_cost_active(start_datetime, vm.charged) |
55 |
elif vm._operstate == 'STOPPED': |
56 |
cost_list = vm.flavor.get_cost_inactive(start_datetime, vm.charged) |
57 |
|
58 |
# find the total vost
|
59 |
total_cost = sum([x[1] for x in cost_list]) |
60 |
|
61 |
# add the debit entry
|
62 |
description = "Server = %s, charge = %d for state: %s" % (vm.name, total_cost, vm._operstate)
|
63 |
debit_account(vm.owner, total_cost, vm, description) |
64 |
|
65 |
vm.save() |