Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / quotas.py @ 103086a4

History | View | Annotate | Download (9.5 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_quota_limits(users, resources=None, sources=None):
87
    counters = get_counters(users, resources, sources)
88
    limits = transform_data(counters, limits_only)
89
    return limits
90

    
91

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

    
96

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

    
103

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

    
113

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

    
118

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

    
126
    return _DEFAULT_QUOTA
127

    
128

    
129
SYSTEM = 'system'
130

    
131

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

    
147

    
148
def add_base_quota(user, resource, capacity):
149
    resource = Resource.objects.get(name=resource)
150
    obj, created = AstakosUserQuota.objects.get_or_create(
151
        user=user, resource=resource, defaults={
152
            'capacity': capacity,
153
        })
154

    
155
    if not created:
156
        obj.capacity = capacity
157
        obj.save()
158
    qh_sync_user(user)
159

    
160

    
161
def remove_base_quota(user, resource):
162
    AstakosUserQuota.objects.filter(
163
        user=user, resource__name=resource).delete()
164
    qh_sync_user(user)
165

    
166

    
167
def initial_quotas(users):
168
    users = list(users)
169
    initial = {}
170
    default_quotas = get_default_quota()
171

    
172
    for user in users:
173
        uuid = user.uuid
174
        source_quota = {SYSTEM: dict(default_quotas)}
175
        initial[uuid] = source_quota
176

    
177
    objs = AstakosUserQuota.objects.select_related()
178
    orig_quotas = objs.filter(user__in=users)
179
    for user_quota in orig_quotas:
180
        uuid = user_quota.user.uuid
181
        user_init = initial.get(uuid, {})
182
        source_quota = user_init.get(SYSTEM, {})
183
        resource = user_quota.resource.full_name()
184
        source_quota[resource] = user_quota.capacity
185
        user_init[SYSTEM] = source_quota
186
        initial[uuid] = user_init
187

    
188
    return initial
189

    
190

    
191
def get_grant_source(grant):
192
    return SYSTEM
193

    
194

    
195
def astakos_users_quotas(users, initial=None):
196
    users = list(users)
197
    if initial is None:
198
        quotas = initial_quotas(users)
199
    else:
200
        quotas = copy.deepcopy(initial)
201

    
202
    ACTUALLY_ACCEPTED = ProjectMembership.ACTUALLY_ACCEPTED
203
    objs = ProjectMembership.objects.select_related('project', 'person')
204
    memberships = objs.filter(person__in=users,
205
                              state__in=ACTUALLY_ACCEPTED,
206
                              project__state=Project.APPROVED)
207

    
208
    project_ids = set(m.project_id for m in memberships)
209
    objs = ProjectApplication.objects.select_related('project')
210
    apps = objs.filter(project__in=project_ids)
211

    
212
    project_dict = {}
213
    for app in apps:
214
        project_dict[app.project] = app
215

    
216
    objs = ProjectResourceGrant.objects.select_related()
217
    grants = objs.filter(project_application__in=apps)
218

    
219
    for membership in memberships:
220
        uuid = membership.person.uuid
221
        userquotas = quotas.get(uuid, {})
222

    
223
        application = project_dict[membership.project]
224

    
225
        for grant in grants:
226
            if grant.project_application_id != application.id:
227
                continue
228

    
229
            source = get_grant_source(grant)
230
            source_quotas = userquotas.get(source, {})
231

    
232
            resource = grant.resource.full_name()
233
            prev = source_quotas.get(resource, 0)
234
            new = prev + grant.member_capacity
235
            source_quotas[resource] = new
236
            userquotas[source] = source_quotas
237
        quotas[uuid] = userquotas
238

    
239
    return quotas
240

    
241

    
242
def list_user_quotas(users):
243
    qh_quotas = get_users_quotas(users)
244
    astakos_initial = initial_quotas(users)
245
    return qh_quotas, astakos_initial
246

    
247

    
248
# Syncing to quotaholder
249

    
250
def qh_sync_users(users, sync=True, diff_only=False):
251
    uids = [user.id for user in users]
252
    if sync:
253
        users = AstakosUser.forupdate.filter(id__in=uids).select_for_update()
254

    
255
    astakos_quotas = astakos_users_quotas(users)
256

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

    
265
        if sync:
266
            _set_user_quota(diff_quotas)
267
        return qh_limits, diff_quotas
268
    else:
269
        if sync:
270
            _set_user_quota(astakos_quotas)
271
        return None
272

    
273

    
274
def qh_sync_user(user):
275
    qh_sync_users([user])
276

    
277

    
278
def qh_sync_projects(projects):
279
    projects = list(projects)
280
    memberships = ProjectMembership.objects.filter(
281
        project__in=projects, state__in=ProjectMembership.ACTUALLY_ACCEPTED)
282
    users = set(m.person for m in memberships)
283

    
284
    qh_sync_users(users)
285

    
286

    
287
def qh_sync_project(project):
288
    qh_sync_projects([project])
289

    
290

    
291
def qh_add_resource_limit(resource, diff):
292
    objs = AstakosUser.forupdate.filter(Q(email_verified=True) &
293
                                        ~Q(policy=resource))
294
    users = objs.select_for_update()
295
    uuids = [u.uuid for u in users]
296
    qh.add_resource_limit(holders=uuids, sources=[SYSTEM],
297
                          resources=[resource.name], diff=diff)
298

    
299

    
300
def qh_sync_new_resource(resource, limit):
301
    users = AstakosUser.forupdate.filter(
302
        email_verified=True).select_for_update()
303

    
304
    resource_name = resource.name
305
    data = []
306
    for user in users:
307
        uuid = user.uuid
308
        key = uuid, SYSTEM, resource_name
309
        data.append((key, limit))
310

    
311
    qh.set_quota(data)