Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (8.2 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_resources(resources=None, services=None):
111
    if resources is None:
112
        rs = Resource.objects.all()
113
    else:
114
        rs = Resource.objects.filter(name__in=resources)
115

    
116
    if services is not None:
117
        rs = rs.filter(service__in=services)
118

    
119
    resource_dict = {}
120
    for r in rs:
121
        resource_dict[r.full_name()] = r.get_info()
122

    
123
    return resource_dict
124

    
125

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

    
133
    return _DEFAULT_QUOTA
134

    
135

    
136
SYSTEM = 'system'
137

    
138

    
139
def initial_quotas(users):
140
    initial = {}
141
    default_quotas = get_default_quota()
142

    
143
    for user in users:
144
        uuid = user.uuid
145
        source_quota = {SYSTEM: dict(default_quotas)}
146
        initial[uuid] = source_quota
147

    
148
    objs = AstakosUserQuota.objects.select_related()
149
    orig_quotas = objs.filter(user__in=users)
150
    for user_quota in orig_quotas:
151
        uuid = user_quota.user.uuid
152
        user_init = initial.get(uuid, {})
153
        source_quota = user_init.get(SYSTEM, {})
154
        resource = user_quota.resource.full_name()
155
        source_quota[resource] = user_quota.capacity
156
        user_init[SYSTEM] = source_quota
157
        initial[uuid] = user_init
158

    
159
    return initial
160

    
161

    
162
def get_grant_source(grant):
163
    return SYSTEM
164

    
165

    
166
def users_quotas(users, initial=None):
167
    if initial is None:
168
        quotas = initial_quotas(users)
169
    else:
170
        quotas = copy.deepcopy(initial)
171

    
172
    ACTUALLY_ACCEPTED = ProjectMembership.ACTUALLY_ACCEPTED
173
    objs = ProjectMembership.objects.select_related('project', 'person')
174
    memberships = objs.filter(person__in=users,
175
                              state__in=ACTUALLY_ACCEPTED,
176
                              project__state=Project.APPROVED)
177

    
178
    project_ids = set(m.project_id for m in memberships)
179
    objs = ProjectApplication.objects.select_related('project')
180
    apps = objs.filter(project__in=project_ids)
181

    
182
    project_dict = {}
183
    for app in apps:
184
        project_dict[app.project] = app
185

    
186
    objs = ProjectResourceGrant.objects.select_related()
187
    grants = objs.filter(project_application__in=apps)
188

    
189
    for membership in memberships:
190
        uuid = membership.person.uuid
191
        userquotas = quotas.get(uuid, {})
192

    
193
        application = project_dict[membership.project]
194

    
195
        for grant in grants:
196
            if grant.project_application_id != application.id:
197
                continue
198

    
199
            source = get_grant_source(grant)
200
            source_quotas = userquotas.get(source, {})
201

    
202
            resource = grant.resource.full_name()
203
            prev = source_quotas.get(resource, 0)
204
            new = prev + grant.member_capacity
205
            source_quotas[resource] = new
206
            userquotas[source] = source_quotas
207
        quotas[uuid] = userquotas
208

    
209
    return quotas
210

    
211

    
212
def user_quotas(user):
213
    quotas = users_quotas([user])
214
    try:
215
        return quotas[user.uuid]
216
    except KeyError:
217
        raise ValueError("could not compute quotas")
218

    
219

    
220
def sync_users(users, sync=True):
221
    def _sync_users(users, sync):
222

    
223
        info = {}
224
        for user in users:
225
            info[user.uuid] = user.email
226

    
227
        qh_quotas, qh_limits = get_users_quotas_and_limits(users)
228
        astakos_initial = initial_quotas(users)
229
        astakos_quotas = users_quotas(users)
230

    
231
        diff_quotas = {}
232
        for holder, local in astakos_quotas.iteritems():
233
            registered = qh_limits.get(holder, None)
234
            if local != registered:
235
                diff_quotas[holder] = dict(local)
236

    
237
        if sync:
238
            r = set_user_quota(diff_quotas)
239

    
240
        return (qh_limits, qh_quotas,
241
                astakos_initial, diff_quotas, info)
242

    
243
    return _sync_users(users, sync)
244

    
245

    
246
def sync_all_users(sync=True):
247
    users = AstakosUser.objects.verified()
248
    return sync_users(users, sync)
249

    
250

    
251
def qh_add_resource_limit(resource, diff):
252
    objs = AstakosUser.forupdate.filter(Q(email_verified=True) &
253
                                        ~Q(policy=resource))
254
    users = objs.select_for_update()
255
    uuids = [u.uuid for u in users]
256
    qh.add_resource_limit(holders=uuids, sources=[SYSTEM],
257
                          resources=[resource.name], diff=diff)
258

    
259

    
260
def qh_sync_new_resource(resource, limit):
261
    users = AstakosUser.forupdate.filter(
262
        email_verified=True).select_for_update()
263

    
264
    resource_name = resource.name
265
    data = []
266
    for user in users:
267
        uuid = user.uuid
268
        key = uuid, SYSTEM, resource_name
269
        data.append((key, limit))
270

    
271
    qh.set_quota(data)