Statistics
| Branch: | Tag: | Revision:

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

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, Service,
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(component, users=None):
99
    name_values = Service.objects.filter(
100
        component=component).values_list('name')
101
    service_names = [t for (t,) in name_values]
102
    resources = Resource.objects.filter(service_origin__in=service_names)
103
    resource_names = [r.name for r in resources]
104
    counters = qh.get_quota(holders=users, resources=resource_names)
105
    return transform_data(counters)
106

    
107

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

    
117

    
118
def _set_user_quota(quotas):
119
    q = _level_quota_dict(quotas)
120
    qh.set_quota(q)
121

    
122

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

    
130
    return _DEFAULT_QUOTA
131

    
132

    
133
SYSTEM = 'system'
134
PENDING_APP_RESOURCE = 'astakos.pending_app'
135

    
136

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

    
149

    
150
def get_pending_app_quota(user):
151
    quota = get_user_quotas(user)
152
    return quota[SYSTEM][PENDING_APP_RESOURCE]
153

    
154

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

    
163
    if not created:
164
        obj.capacity = capacity
165
        obj.save()
166
    qh_sync_locked_user(user)
167

    
168

    
169
def remove_base_quota(user, resource):
170
    user = get_user_for_update(user.id)
171
    AstakosUserQuota.objects.filter(
172
        user=user, resource__name=resource).delete()
173
    qh_sync_locked_user(user)
174

    
175

    
176
def initial_quotas(users):
177
    users = list(users)
178
    initial = {}
179
    default_quotas = get_default_quota()
180

    
181
    for user in users:
182
        uuid = user.uuid
183
        source_quota = {SYSTEM: dict(default_quotas)}
184
        initial[uuid] = source_quota
185

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

    
197
    return initial
198

    
199

    
200
def get_grant_source(grant):
201
    return SYSTEM
202

    
203

    
204
def astakos_users_quotas(users, initial=None):
205
    users = list(users)
206
    if initial is None:
207
        quotas = initial_quotas(users)
208
    else:
209
        quotas = copy.deepcopy(initial)
210

    
211
    ACTUALLY_ACCEPTED = ProjectMembership.ACTUALLY_ACCEPTED
212
    objs = ProjectMembership.objects.select_related(
213
        'project', 'person', 'project__application')
214
    memberships = objs.filter(
215
        person__in=users,
216
        state__in=ACTUALLY_ACCEPTED,
217
        project__state=Project.NORMAL,
218
        project__application__state=ProjectApplication.APPROVED)
219

    
220
    apps = set(m.project.application_id for m in memberships)
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 = membership.project.application
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.objects
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.objects.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.objects.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)