Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / quotas.py @ 1e361a6d

History | View | Annotate | Download (9.3 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
import astakos.quotaholder_app.callpoint as qh
38
from astakos.quotaholder_app.exception import QuotaholderError, NoCapacityError
39
from django.db.models import Q
40

    
41

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

    
50

    
51
def limits_only(holding):
52
    limit, usage_min, usage_max = holding
53
    return limit
54

    
55

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

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

    
70

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

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

    
79

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

    
85

    
86
def get_users_quotas_and_limits(users, resources=None, sources=None):
87
    counters = get_counters(users, resources, sources)
88
    quotas = transform_data(counters)
89
    limits = transform_data(counters, limits_only)
90
    return quotas, 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

    
132

    
133
def resolve_pending_serial(serial, accept=True):
134
    return qh.resolve_pending_commission('astakos', serial, accept)
135

    
136

    
137
def register_pending_apps(user, quantity, force=False, dry_run=False):
138
    provision = (user.uuid, SYSTEM, 'astakos.pending_app'), quantity
139
    name = "DRYRUN" if dry_run else ""
140
    try:
141
        s = qh.issue_commission(clientkey='astakos',
142
                                force=force,
143
                                name=name,
144
                                provisions=[provision])
145
    except NoCapacityError as e:
146
        limit = e.data['limit']
147
        return False, limit
148
    except QuotaholderError:
149
        return False, None
150
    accept = not dry_run
151
    qh.resolve_pending_commission('astakos', s, accept)
152
    return True, None
153

    
154

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

    
162
    if not created:
163
        obj.capacity = capacity
164
        obj.save()
165
    qh_sync_user(user.id)
166

    
167

    
168
def remove_base_quota(user, resource):
169
    AstakosUserQuota.objects.filter(
170
        user=user, resource__name=resource).delete()
171
    qh_sync_user(user.id)
172

    
173

    
174
def initial_quotas(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
    if initial is None:
203
        quotas = initial_quotas(users)
204
    else:
205
        quotas = copy.deepcopy(initial)
206

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

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

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

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

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

    
228
        application = project_dict[membership.project]
229

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

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

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

    
244
    return quotas
245

    
246

    
247
def astakos_user_quotas(user):
248
    quotas = astakos_users_quotas([user])
249
    try:
250
        return quotas[user.uuid]
251
    except KeyError:
252
        raise ValueError("could not compute quotas")
253

    
254

    
255
def list_user_quotas(users):
256
    qh_quotas, qh_limits = get_users_quotas_and_limits(users)
257
    astakos_initial = initial_quotas(users)
258
    astakos_quotas = astakos_users_quotas(users)
259

    
260
    diff_quotas = {}
261
    for holder, local in astakos_quotas.iteritems():
262
        registered = qh_limits.get(holder, None)
263
        if local != registered:
264
            diff_quotas[holder] = dict(local)
265

    
266
    return (qh_limits, qh_quotas,
267
            astakos_initial, diff_quotas)
268

    
269

    
270
def qh_add_resource_limit(resource, diff):
271
    objs = AstakosUser.forupdate.filter(Q(email_verified=True) &
272
                                        ~Q(policy=resource))
273
    users = objs.select_for_update()
274
    uuids = [u.uuid for u in users]
275
    qh.add_resource_limit(holders=uuids, sources=[SYSTEM],
276
                          resources=[resource.name], diff=diff)
277

    
278

    
279
def qh_sync_new_resource(resource, limit):
280
    users = AstakosUser.forupdate.filter(
281
        email_verified=True).select_for_update()
282

    
283
    resource_name = resource.name
284
    data = []
285
    for user in users:
286
        uuid = user.uuid
287
        key = uuid, SYSTEM, resource_name
288
        data.append((key, limit))
289

    
290
    qh.set_quota(data)
291

    
292

    
293
def qh_sync_users(user_ids):
294
    users = AstakosUser.forupdate.filter(id__in=user_ids).select_for_update()
295
    astakos_quotas = astakos_users_quotas(list(users))
296
    set_user_quota(astakos_quotas)
297

    
298

    
299
def qh_sync_user(user_id):
300
    qh_sync_users([user_id])