Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / quotas.py @ 08043775

History | View | Annotate | Download (7.7 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 astakos.im.models import (
35
    Resource, AstakosUserQuota, AstakosUser,
36
    Project, ProjectMembership, ProjectResourceGrant, ProjectApplication)
37
from astakos.quotaholder.callpoint import QuotaholderDjangoDBCallpoint
38
from django.db.models import Q
39

    
40
qh = QuotaholderDjangoDBCallpoint()
41

    
42

    
43
def from_holding(holding):
44
    limit, imported_min, imported_max = holding
45
    body = {'limit':       limit,
46
            'usage':       imported_max,
47
            'pending':     imported_max-imported_min,
48
            }
49
    return body
50

    
51

    
52
def limits_only(holding):
53
    limit, imported_min, imported_max = holding
54
    return limit
55

    
56

    
57
def transform_data(holdings, func=None):
58
    if func is None:
59
        func = from_holding
60

    
61
    quota = {}
62
    for (holder, source, resource), value in holdings.iteritems():
63
        holder_quota = quota.get(holder, {})
64
        source_quota = holder_quota.get(source, {})
65
        body = func(value)
66
        source_quota[resource] = body
67
        holder_quota[source] = source_quota
68
        quota[holder] = holder_quota
69
    return quota
70

    
71

    
72
def get_counters(users, resources=None, sources=None):
73
    uuids = [user.uuid for user in users]
74

    
75
    counters = qh.get_quota(holders=uuids,
76
                            resources=resources,
77
                            sources=sources)
78
    return counters
79

    
80

    
81
def get_users_quotas(users, resources=None, sources=None):
82
    counters = get_counters(users, resources, sources)
83
    quotas = transform_data(counters)
84
    return quotas
85

    
86

    
87
def get_users_quotas_and_limits(users, resources=None, sources=None):
88
    counters = get_counters(users, resources, sources)
89
    quotas = transform_data(counters)
90
    limits = transform_data(counters, limits_only)
91
    return quotas, limits
92

    
93

    
94
def get_user_quotas(user, resources=None, sources=None):
95
    quotas = get_users_quotas([user], resources, sources)
96
    return quotas[user.uuid]
97

    
98

    
99
def get_service_quotas(service, users=None):
100
    resources = Resource.objects.filter(service=service.name)
101
    resource_names = [r.name for r in resources]
102
    counters = qh.get_quota(holders=users, resources=resource_names)
103
    return transform_data(counters)
104

    
105

    
106
def set_user_quota(quotas):
107
    qh.set_holder_quota(quotas)
108

    
109

    
110
def get_default_quota():
111
    _DEFAULT_QUOTA = {}
112
    resources = Resource.objects.select_related('service').all()
113
    for resource in resources:
114
        capacity = resource.uplimit
115
        _DEFAULT_QUOTA[resource.full_name()] = capacity
116

    
117
    return _DEFAULT_QUOTA
118

    
119

    
120
SYSTEM = 'system'
121

    
122

    
123
def initial_quotas(users):
124
    initial = {}
125
    default_quotas = get_default_quota()
126

    
127
    for user in users:
128
        uuid = user.uuid
129
        source_quota = {SYSTEM: dict(default_quotas)}
130
        initial[uuid] = source_quota
131

    
132
    objs = AstakosUserQuota.objects.select_related()
133
    orig_quotas = objs.filter(user__in=users)
134
    for user_quota in orig_quotas:
135
        uuid = user_quota.user.uuid
136
        user_init = initial.get(uuid, {})
137
        source_quota = user_init.get(SYSTEM, {})
138
        resource = user_quota.resource.full_name()
139
        source_quota[resource] = user_quota.capacity
140
        user_init[SYSTEM] = source_quota
141
        initial[uuid] = user_init
142

    
143
    return initial
144

    
145

    
146
def get_grant_source(grant):
147
    return SYSTEM
148

    
149

    
150
def astakos_users_quotas(users, initial=None):
151
    if initial is None:
152
        quotas = initial_quotas(users)
153
    else:
154
        quotas = copy.deepcopy(initial)
155

    
156
    ACTUALLY_ACCEPTED = ProjectMembership.ACTUALLY_ACCEPTED
157
    objs = ProjectMembership.objects.select_related('project', 'person')
158
    memberships = objs.filter(person__in=users,
159
                              state__in=ACTUALLY_ACCEPTED,
160
                              project__state=Project.APPROVED)
161

    
162
    project_ids = set(m.project_id for m in memberships)
163
    objs = ProjectApplication.objects.select_related('project')
164
    apps = objs.filter(project__in=project_ids)
165

    
166
    project_dict = {}
167
    for app in apps:
168
        project_dict[app.project] = app
169

    
170
    objs = ProjectResourceGrant.objects.select_related()
171
    grants = objs.filter(project_application__in=apps)
172

    
173
    for membership in memberships:
174
        uuid = membership.person.uuid
175
        userquotas = quotas.get(uuid, {})
176

    
177
        application = project_dict[membership.project]
178

    
179
        for grant in grants:
180
            if grant.project_application_id != application.id:
181
                continue
182

    
183
            source = get_grant_source(grant)
184
            source_quotas = userquotas.get(source, {})
185

    
186
            resource = grant.resource.full_name()
187
            prev = source_quotas.get(resource, 0)
188
            new = prev + grant.member_capacity
189
            source_quotas[resource] = new
190
            userquotas[source] = source_quotas
191
        quotas[uuid] = userquotas
192

    
193
    return quotas
194

    
195

    
196
def astakos_user_quotas(user):
197
    quotas = astakos_users_quotas([user])
198
    try:
199
        return quotas[user.uuid]
200
    except KeyError:
201
        raise ValueError("could not compute quotas")
202

    
203

    
204
def list_user_quotas(users):
205
    qh_quotas, qh_limits = get_users_quotas_and_limits(users)
206
    astakos_initial = initial_quotas(users)
207
    astakos_quotas = astakos_users_quotas(users)
208

    
209
    diff_quotas = {}
210
    for holder, local in astakos_quotas.iteritems():
211
        registered = qh_limits.get(holder, None)
212
        if local != registered:
213
            diff_quotas[holder] = dict(local)
214

    
215
    return (qh_limits, qh_quotas,
216
            astakos_initial, diff_quotas)
217

    
218

    
219
def qh_add_resource_limit(resource, diff):
220
    objs = AstakosUser.forupdate.filter(Q(email_verified=True) &
221
                                        ~Q(policy=resource))
222
    users = objs.select_for_update()
223
    uuids = [u.uuid for u in users]
224
    qh.add_resource_limit(holders=uuids, sources=[SYSTEM],
225
                          resources=[resource.name], diff=diff)
226

    
227

    
228
def qh_sync_new_resource(resource, limit):
229
    users = AstakosUser.forupdate.filter(
230
        email_verified=True).select_for_update()
231

    
232
    resource_name = resource.name
233
    data = []
234
    for user in users:
235
        uuid = user.uuid
236
        key = uuid, SYSTEM, resource_name
237
        data.append((key, limit))
238

    
239
    qh.set_quota(data)
240

    
241

    
242
def qh_sync_users(user_ids):
243
    users = AstakosUser.forupdate.filter(id__in=user_ids).select_for_update()
244
    astakos_quotas = astakos_users_quotas(list(users))
245
    set_user_quota(astakos_quotas)
246

    
247

    
248
def qh_sync_user(user_id):
249
    qh_sync_users([user_id])