Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / quotas.py @ 003909e3

History | View | Annotate | Download (7.9 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

    
39
qh = QuotaholderDjangoDBCallpoint()
40

    
41

    
42
def from_holding(holding):
43
    limit, imported_min, imported_max = holding
44
    body = {'limit':       limit,
45
            'used':        imported_min,
46
            'available':   max(0, limit-imported_max),
47
            }
48
    return body
49

    
50

    
51
def limits_only(holding):
52
    limit, imported_min, imported_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_holder_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[user.uuid]
96

    
97

    
98
def get_service_quotas(service):
99
    resources = Resource.objects.filter(service=service.name)
100
    resource_names = [r.name for r in resources]
101
    counters = qh.get_resource_quota(resource_names)
102
    return transform_data(counters)
103

    
104

    
105
def set_user_quota(quotas):
106
    qh.set_holder_quota(quotas)
107

    
108

    
109
def get_resources(resources=None, services=None):
110
    if resources is None:
111
        rs = Resource.objects.all()
112
    else:
113
        rs = Resource.objects.filter(name__in=resources)
114

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

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

    
122
    return resource_dict
123

    
124

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

    
132
    return _DEFAULT_QUOTA
133

    
134

    
135
SYSTEM = 'system'
136

    
137

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

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

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

    
158
    return initial
159

    
160

    
161
def get_grant_source(grant):
162
    return SYSTEM
163

    
164

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

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

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

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

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

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

    
192
        application = project_dict[membership.project]
193

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

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

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

    
208
    return quotas
209

    
210

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

    
218

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

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

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

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

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

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

    
242
    return _sync_users(users, sync)
243

    
244

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

    
249

    
250
def qh_add_resource_limit(resource, diff):
251
    users = AstakosUser.forupdate.all().select_for_update()
252
    qh.add_resource_limit(SYSTEM, resource, diff)
253

    
254

    
255
def qh_sync_new_resource(resource, limit):
256
    users = AstakosUser.forupdate.filter(
257
        email_verified=True).select_for_update()
258

    
259
    data = []
260
    for user in users:
261
        uuid = user.uuid
262
        key = uuid, SYSTEM, resource
263
        data.append((key, limit))
264

    
265
    qh.set_quota(data)