Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / quotas / util.py @ f600b74e

History | View | Annotate | Download (5.4 kB)

1
# Copyright 2012, 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.db.models import Sum, Count, Q
35

    
36
from synnefo.db.models import VirtualMachine, Network, IPAddress
37
from synnefo.quotas import Quotaholder
38

    
39

    
40
def get_db_holdings(user=None):
41
    """Get holdings from Cyclades DB."""
42
    holdings = {}
43

    
44
    vms = VirtualMachine.objects.filter(deleted=False)
45
    networks = Network.objects.filter(deleted=False)
46
    floating_ips = IPAddress.objects.filter(deleted=False, floating_ip=True)
47

    
48
    if user is not None:
49
        vms = vms.filter(userid=user)
50
        networks = networks.filter(userid=user)
51
        floating_ips = floating_ips.filter(userid=user)
52

    
53
    # Get resources related with VMs
54
    vm_resources = vms.values("userid")\
55
                      .annotate(num=Count("id"),
56
                                total_ram=Sum("flavor__ram"),
57
                                total_cpu=Sum("flavor__cpu"),
58
                                disk=Sum("flavor__disk"))
59
    vm_active_resources = \
60
        vms.values("userid")\
61
           .filter(Q(operstate="STARTED") | Q(operstate="BUILD") |
62
                   Q(operstate="ERROR"))\
63
           .annotate(ram=Sum("flavor__ram"),
64
                     cpu=Sum("flavor__cpu"))
65

    
66
    for vm_res in vm_resources.iterator():
67
        user = vm_res['userid']
68
        res = {"cyclades.vm": vm_res["num"],
69
               "cyclades.total_cpu": vm_res["total_cpu"],
70
               "cyclades.disk": 1073741824 * vm_res["disk"],
71
               "cyclades.total_ram": 1048576 * vm_res["total_ram"]}
72
        holdings[user] = res
73

    
74
    for vm_res in vm_active_resources.iterator():
75
        user = vm_res['userid']
76
        holdings[user]["cyclades.cpu"] = vm_res["cpu"]
77
        holdings[user]["cyclades.ram"] = 1048576 * vm_res["ram"]
78

    
79
    # Get resources related with networks
80
    net_resources = networks.values("userid")\
81
                            .annotate(num=Count("id"))
82
    for net_res in net_resources.iterator():
83
        user = net_res['userid']
84
        holdings.setdefault(user, {})
85
        holdings[user]["cyclades.network.private"] = net_res["num"]
86

    
87
    floating_ips_resources = floating_ips.values("userid")\
88
                                         .annotate(num=Count("id"))
89
    for floating_ip_res in floating_ips_resources.iterator():
90
        user = floating_ip_res["userid"]
91
        holdings.setdefault(user, {})
92
        holdings[user]["cyclades.floating_ip"] = floating_ip_res["num"]
93

    
94
    return holdings
95

    
96

    
97
def get_quotaholder_holdings(user=None):
98
    """Get quotas from Quotaholder for all Cyclades resources.
99

100
    Returns quotas for all users, unless a single user is specified.
101
    """
102
    qh = Quotaholder.get()
103
    return qh.service_get_quotas(user)
104

    
105

    
106
def get_qh_users_holdings(users=None):
107
    qh = Quotaholder.get()
108
    if users is None or len(users) != 1:
109
        req = None
110
    else:
111
        req = users[0]
112
    quotas = qh.service_get_quotas(req)
113

    
114
    if users is None:
115
        return quotas
116

    
117
    qs = {}
118
    for user in users:
119
        try:
120
            qs[user] = quotas[user]
121
        except KeyError:
122
            pass
123
    return qs
124

    
125

    
126
def get_qh_project_holdings(projects=None):
127
    qh = Quotaholder.get()
128
    if projects is None or len(projects) != 1:
129
        req = None
130
    else:
131
        req = projects[0]
132
    quotas = qh.service_get_project_quotas(req)
133

    
134
    if projects is None:
135
        return quotas
136

    
137
    qs = {}
138
    for project in projects:
139
        try:
140
            qs[project] = quotas[project]
141
        except KeyError:
142
            pass
143
    return qs
144

    
145

    
146
def transform_quotas(quotas):
147
    d = {}
148
    for resource, counters in quotas.iteritems():
149
        used = counters['usage']
150
        limit = counters['limit']
151
        pending = counters['pending']
152
        d[resource] = (used, limit, pending)
153
    return d
154

    
155

    
156
def transform_project_quotas(quotas):
157
    d = {}
158
    for resource, counters in quotas.iteritems():
159
        used = counters['project_usage']
160
        limit = counters['project_limit']
161
        pending = counters['project_pending']
162
        d[resource] = (used, limit, pending)
163
    return d