Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / quotas.py @ 67cf14bf

History | View | Annotate | Download (10 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
import copy
35
from astakos.im.models import (
36
    Resource, AstakosUserQuota, AstakosUser,
37
    Project, ProjectMembership, ProjectResourceGrant, ProjectApplication)
38
import astakos.quotaholder_app.callpoint as qh
39
from astakos.quotaholder_app.exception import NoCapacityError
40
from django.db.models import Q
41

    
42

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

    
51

    
52
def limits_only(holding):
53
    limit, usage_min, usage_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_quota_limits(users, resources=None, sources=None):
88
    counters = get_counters(users, resources, sources)
89
    limits = transform_data(counters, limits_only)
90
    return limits
91

    
92

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

    
97

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

    
104

    
105
def _level_quota_dict(quotas):
106
    lst = []
107
    for holder, holder_quota in quotas.iteritems():
108
        for source, source_quota in holder_quota.iteritems():
109
            for resource, limit in source_quota.iteritems():
110
                key = (holder, source, resource)
111
                lst.append((key, limit))
112
    return lst
113

    
114

    
115
def _set_user_quota(quotas):
116
    q = _level_quota_dict(quotas)
117
    qh.set_quota(q)
118

    
119

    
120
def get_default_quota():
121
    _DEFAULT_QUOTA = {}
122
    resources = Resource.objects.select_related('service').all()
123
    for resource in resources:
124
        capacity = resource.uplimit
125
        _DEFAULT_QUOTA[resource.full_name()] = capacity
126

    
127
    return _DEFAULT_QUOTA
128

    
129

    
130
SYSTEM = 'system'
131
PENDING_APP_RESOURCE = 'astakos.pending_app'
132

    
133

    
134
def register_pending_apps(user, quantity, force=False):
135
    provision = (user.uuid, SYSTEM, PENDING_APP_RESOURCE), quantity
136
    try:
137
        s = qh.issue_commission(clientkey='astakos',
138
                                force=force,
139
                                provisions=[provision])
140
    except NoCapacityError as e:
141
        limit = e.data['limit']
142
        return False, limit
143
    qh.resolve_pending_commission('astakos', s)
144
    return True, None
145

    
146

    
147
def get_pending_app_quota(user):
148
    quota = get_user_quotas(user)
149
    return quota[SYSTEM][PENDING_APP_RESOURCE]
150

    
151

    
152
def add_base_quota(user, resource, capacity):
153
    resource = Resource.objects.get(name=resource)
154
    user = get_user_for_update(user.id)
155
    obj, created = AstakosUserQuota.objects.get_or_create(
156
        user=user, resource=resource, defaults={
157
            'capacity': capacity,
158
        })
159

    
160
    if not created:
161
        obj.capacity = capacity
162
        obj.save()
163
    qh_sync_locked_user(user)
164

    
165

    
166
def remove_base_quota(user, resource):
167
    user = get_user_for_update(user.id)
168
    AstakosUserQuota.objects.filter(
169
        user=user, resource__name=resource).delete()
170
    qh_sync_locked_user(user)
171

    
172

    
173
def initial_quotas(users):
174
    users = list(users)
175
    initial = {}
176
    default_quotas = get_default_quota()
177

    
178
    for user in users:
179
        uuid = user.uuid
180
        source_quota = {SYSTEM: dict(default_quotas)}
181
        initial[uuid] = source_quota
182

    
183
    objs = AstakosUserQuota.objects.select_related()
184
    orig_quotas = objs.filter(user__in=users)
185
    for user_quota in orig_quotas:
186
        uuid = user_quota.user.uuid
187
        user_init = initial.get(uuid, {})
188
        source_quota = user_init.get(SYSTEM, {})
189
        resource = user_quota.resource.full_name()
190
        source_quota[resource] = user_quota.capacity
191
        user_init[SYSTEM] = source_quota
192
        initial[uuid] = user_init
193

    
194
    return initial
195

    
196

    
197
def get_grant_source(grant):
198
    return SYSTEM
199

    
200

    
201
def astakos_users_quotas(users, initial=None):
202
    users = list(users)
203
    if initial is None:
204
        quotas = initial_quotas(users)
205
    else:
206
        quotas = copy.deepcopy(initial)
207

    
208
    ACTUALLY_ACCEPTED = ProjectMembership.ACTUALLY_ACCEPTED
209
    objs = ProjectMembership.objects.select_related('project', 'person')
210
    memberships = objs.filter(person__in=users,
211
                              state__in=ACTUALLY_ACCEPTED,
212
                              project__state=Project.APPROVED)
213

    
214
    project_ids = set(m.project_id for m in memberships)
215
    objs = ProjectApplication.objects.select_related('project')
216
    apps = objs.filter(project__in=project_ids)
217

    
218
    project_dict = {}
219
    for app in apps:
220
        project_dict[app.project] = app
221

    
222
    objs = ProjectResourceGrant.objects.select_related()
223
    grants = objs.filter(project_application__in=apps)
224

    
225
    for membership in memberships:
226
        uuid = membership.person.uuid
227
        userquotas = quotas.get(uuid, {})
228

    
229
        application = project_dict[membership.project]
230

    
231
        for grant in grants:
232
            if grant.project_application_id != application.id:
233
                continue
234

    
235
            source = get_grant_source(grant)
236
            source_quotas = userquotas.get(source, {})
237

    
238
            resource = grant.resource.full_name()
239
            prev = source_quotas.get(resource, 0)
240
            new = prev + grant.member_capacity
241
            source_quotas[resource] = new
242
            userquotas[source] = source_quotas
243
        quotas[uuid] = userquotas
244

    
245
    return quotas
246

    
247

    
248
def list_user_quotas(users):
249
    qh_quotas = get_users_quotas(users)
250
    astakos_initial = initial_quotas(users)
251
    return qh_quotas, astakos_initial
252

    
253

    
254
# Syncing to quotaholder
255

    
256
def get_users_for_update(user_ids):
257
    uids = sorted(user_ids)
258
    objs = AstakosUser.forupdate
259
    return list(objs.filter(id__in=uids).order_by('id').select_for_update())
260

    
261

    
262
def get_user_for_update(user_id):
263
    return get_users_for_update([user_id])[0]
264

    
265

    
266
def qh_sync_locked_users(users):
267
    astakos_quotas = astakos_users_quotas(users)
268
    _set_user_quota(astakos_quotas)
269

    
270

    
271
def qh_sync_users(users):
272
    uids = [user.id for user in users]
273
    users = get_users_for_update(uids)
274
    qh_sync_locked_users(users)
275

    
276

    
277
def qh_sync_users_diffs(users, sync=True):
278
    uids = [user.id for user in users]
279
    if sync:
280
        users = get_users_for_update(uids)
281

    
282
    astakos_quotas = astakos_users_quotas(users)
283
    qh_limits = get_users_quota_limits(users)
284
    diff_quotas = {}
285
    for holder, local in astakos_quotas.iteritems():
286
        registered = qh_limits.get(holder, None)
287
        if local != registered:
288
            diff_quotas[holder] = dict(local)
289

    
290
    if sync:
291
        _set_user_quota(diff_quotas)
292
    return qh_limits, diff_quotas
293

    
294

    
295
def qh_sync_locked_user(user):
296
    qh_sync_locked_users([user])
297

    
298

    
299
def qh_sync_user(user):
300
    qh_sync_users([user])
301

    
302

    
303
def members_to_sync(project):
304
    objs = ProjectMembership.objects.select_related('person')
305
    memberships = objs.filter(project=project,
306
                              state__in=ProjectMembership.ACTUALLY_ACCEPTED)
307
    return set(m.person for m in memberships)
308

    
309

    
310
def qh_sync_project(project):
311
    users = members_to_sync(project)
312
    qh_sync_users(users)
313

    
314

    
315
def qh_add_resource_limit(resource, diff):
316
    objs = AstakosUser.forupdate.filter(Q(email_verified=True) &
317
                                        ~Q(policy=resource))
318
    users = objs.order_by('id').select_for_update()
319
    uuids = [u.uuid for u in users]
320
    qh.add_resource_limit(holders=uuids, sources=[SYSTEM],
321
                          resources=[resource.name], diff=diff)
322

    
323

    
324
def qh_sync_new_resource(resource, limit):
325
    users = AstakosUser.forupdate.filter(
326
        email_verified=True).order_by('id').select_for_update()
327

    
328
    resource_name = resource.name
329
    data = []
330
    for user in users:
331
        uuid = user.uuid
332
        key = uuid, SYSTEM, resource_name
333
        data.append((key, limit))
334

    
335
    qh.set_quota(data)