Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / endpoints / qh.py @ 0514bcc7

History | View | Annotate | Download (10.7 kB)

1
# Copyright 2011-2012 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 logging
35
import itertools
36

    
37
from functools import wraps
38
from collections import namedtuple
39

    
40
from django.utils.translation import ugettext as _
41

    
42
from astakos.im.settings import (
43
        QUOTAHOLDER_URL, QUOTAHOLDER_TOKEN, LOGGING_LEVEL)
44

    
45
if QUOTAHOLDER_URL:
46
    from kamaki.clients.quotaholder import QuotaholderClient
47
    from kamaki.clients.quotaholder import QH_PRACTICALLY_INFINITE
48

    
49
ENTITY_KEY = '1'
50

    
51

    
52
logger = logging.getLogger(__name__)
53

    
54
inf = float('inf')
55

    
56
clientkey = 'astakos'
57

    
58
_client = None
59
def get_client():
60
    global _client
61
    if _client:
62
        return _client
63
    if not QUOTAHOLDER_URL:
64
        return
65
    _client = QuotaholderClient(QUOTAHOLDER_URL, token=QUOTAHOLDER_TOKEN)
66
    return _client
67

    
68
def set_quota(payload):
69
    c = get_client()
70
    if not c:
71
        return
72
    result = c.set_quota(context={}, clientkey=clientkey, set_quota=payload)
73
    logger.info('set_quota: %s rejected: %s' % (payload, result))
74
    return result
75

    
76
def qh_get_quota(user, resources):
77
    c = get_client()
78
    if not c:
79
        return
80
    payload = []
81
    append = payload.append
82
    for r in resources:
83
        append((user.uuid, r, ENTITY_KEY),)
84
    result = c.get_quota(context={}, clientkey=clientkey, get_quota=payload)
85
    logger.info('get_quota: %s rejected: %s' % (payload, result))
86
    return result
87

    
88
def create_entity(payload):
89
    c = get_client()
90
    if not c:
91
        return
92
    result = c.create_entity(
93
        context={}, clientkey=clientkey, create_entity=payload)
94
    logger.info('create_entity: %s rejected: %s' % (payload, result))
95
    return result
96

    
97
SetQuotaPayload = namedtuple('SetQuotaPayload', ('holder',
98
                                                 'resource',
99
                                                 'key',
100
                                                 'quantity',
101
                                                 'capacity',
102
                                                 'import_limit',
103
                                                 'export_limit',
104
                                                 'flags'))
105

    
106
GetQuotaPayload = namedtuple('GetQuotaPayload', ('holder',
107
                                                 'resource',
108
                                                 'key'))
109

    
110
CreateEntityPayload = namedtuple('CreateEntityPayload', ('entity',
111
                                                         'owner',
112
                                                         'key',
113
                                                         'ownerkey'))
114
QuotaLimits = namedtuple('QuotaLimits', ('holder',
115
                                         'resource',
116
                                         'capacity',
117
                                         'import_limit',
118
                                         'export_limit'))
119

    
120
QuotaValues = namedtuple('QuotaValues', ('quantity',
121
                                         'capacity',
122
                                         'import_limit',
123
                                         'export_limit'))
124

    
125
def add_quota_values(q1, q2):
126
    return QuotaValues(
127
        quantity = q1.quantity + q2.quantity,
128
        capacity = q1.capacity + q2.capacity,
129
        import_limit = q1.import_limit + q2.import_limit,
130
        export_limit = q1.export_limit + q2.export_limit)
131

    
132
def qh_register_user(user):
133
    return register_users([user])
134

    
135
def register_users(users):
136
    rejected = create_users(users)
137
    if not rejected:
138
        register_quotas(users)
139

    
140
def create_users(users):
141
    payload = list(CreateEntityPayload(
142
                    entity=u.uuid,
143
                    owner='system',
144
                    key=ENTITY_KEY,
145
                    ownerkey='') for u in users)
146
    return create_entity(payload)
147

    
148
def register_quotas(users):
149
    payload = []
150
    append = payload.append
151
    for u in users:
152
        for resource, q in u.all_quotas().iteritems():
153
            append( SetQuotaPayload(
154
                    holder=u.uuid,
155
                    resource=resource,
156
                    key=ENTITY_KEY,
157
                    quantity=q.quantity,
158
                    capacity=q.capacity,
159
                    import_limit=q.import_limit,
160
                    export_limit=q.export_limit,
161
                    flags=0))
162
    return set_quota(payload)
163

    
164
def register_services(services):
165
    payload = list(CreateEntityPayload(
166
                    entity=service,
167
                    owner='system',
168
                    key=ENTITY_KEY,
169
                    ownerkey='') for service in set(services))
170
    return create_entity(payload)
171

    
172
def register_resources(resources):
173
    payload = list(SetQuotaPayload(
174
            holder=resource.service,
175
            resource=resource,
176
            key=ENTITY_KEY,
177
            quantity=QH_PRACTICALLY_INFINITE,
178
            capacity=0,
179
            import_limit=QH_PRACTICALLY_INFINITE,
180
            export_limit=QH_PRACTICALLY_INFINITE,
181
            flags=0) for resource in resources)
182
    return set_quota(payload)
183

    
184
def qh_add_quota(serial, sub_list, add_list):
185
    if not QUOTAHOLDER_URL:
186
        return ()
187

    
188
    context = {}
189
    c = get_client()
190

    
191
    sub_quota = []
192
    sub_append = sub_quota.append
193
    add_quota = []
194
    add_append = add_quota.append
195

    
196
    for ql in sub_list:
197
        args = (ql.holder, ql.resource, ENTITY_KEY,
198
                0, ql.capacity, ql.import_limit, ql.export_limit)
199
        sub_append(args)
200

    
201
    for ql in add_list:
202
        args = (ql.holder, ql.resource, ENTITY_KEY,
203
                0, ql.capacity, ql.import_limit, ql.export_limit)
204
        add_append(args)
205

    
206
    result = c.add_quota(context=context,
207
                         clientkey=clientkey,
208
                         serial=serial,
209
                         sub_quota=sub_quota,
210
                         add_quota=add_quota)
211

    
212
    return result
213

    
214
def qh_query_serials(serials):
215
    if not QUOTAHOLDER_URL:
216
        return ()
217

    
218
    context = {}
219
    c = get_client()
220
    result = c.query_serials(context=context,
221
                             clientkey=clientkey,
222
                             serials=serials)
223
    return result
224

    
225
def qh_ack_serials(serials):
226
    if not QUOTAHOLDER_URL:
227
        return ()
228

    
229
    context = {}
230
    c = get_client()
231
    result = c.ack_serials(context=context,
232
                           clientkey=clientkey,
233
                           serials=serials)
234
    return
235

    
236
from datetime import datetime
237

    
238
strptime = datetime.strptime
239
timefmt = '%Y-%m-%dT%H:%M:%S.%f'
240

    
241
SECOND_RESOLUTION = 1
242

    
243

    
244
def total_seconds(timedelta_object):
245
    return timedelta_object.seconds + timedelta_object.days * 86400
246

    
247

    
248
def iter_timeline(timeline, before):
249
    if not timeline:
250
        return
251

    
252
    for t in timeline:
253
        yield t
254

    
255
    t = dict(t)
256
    t['issue_time'] = before
257
    yield t
258

    
259

    
260
def _usage_units(timeline, after, before, details=0):
261

    
262
    t_total = 0
263
    uu_total = 0
264
    t_after = strptime(after, timefmt)
265
    t_before = strptime(before, timefmt)
266
    t0 = t_after
267
    u0 = 0
268

    
269
    for point in iter_timeline(timeline, before):
270
        issue_time = point['issue_time']
271

    
272
        if issue_time <= after:
273
            u0 = point['target_allocated_through']
274
            continue
275

    
276
        t = strptime(issue_time, timefmt) if issue_time <= before else t_before
277
        t_diff = int(total_seconds(t - t0) * SECOND_RESOLUTION)
278
        t_total += t_diff
279
        uu_cost = u0 * t_diff
280
        uu_total += uu_cost
281
        t0 = t
282
        u0 = point['target_allocated_through']
283

    
284
        target = point['target']
285
        if details:
286
            yield  (target,
287
                    point['resource'],
288
                    point['name'],
289
                    issue_time,
290
                    uu_cost,
291
                    uu_total)
292

    
293
    if not t_total:
294
        return
295

    
296
    yield  (target,
297
            'total',
298
            point['resource'],
299
            issue_time,
300
            uu_total / t_total,
301
            uu_total)
302

    
303

    
304
def usage_units(timeline, after, before, details=0):
305
    return list(_usage_units(timeline, after, before, details=details))
306

    
307

    
308
def traffic_units(timeline, after, before, details=0):
309
    tu_total = 0
310
    target = None
311
    issue_time = None
312

    
313
    for point in timeline:
314
        issue_time = point['issue_time']
315
        if issue_time <= after:
316
            continue
317
        if issue_time > before:
318
            break
319

    
320
        target = point['target']
321
        tu = point['target_allocated_through']
322
        tu_total += tu
323

    
324
        if details:
325
            yield  (target,
326
                    point['resource'],
327
                    point['name'],
328
                    issue_time,
329
                    tu,
330
                    tu_total)
331

    
332
    if not tu_total:
333
        return
334

    
335
    yield  (target,
336
            'total',
337
            point['resource'],
338
            issue_time,
339
            tu_total // len(timeline),
340
            tu_total)
341

    
342

    
343
def timeline_charge(entity, resource, after, before, details, charge_type):
344
    key = '1'
345
    if charge_type == 'charge_usage':
346
        charge_units = usage_units
347
    elif charge_type == 'charge_traffic':
348
        charge_units = traffic_units
349
    else:
350
        m = 'charge type %s not supported' % charge_type
351
        raise ValueError(m)
352

    
353
    quotaholder = QuotaholderClient(QUOTAHOLDER_URL, token=QUOTAHOLDER_TOKEN)
354
    timeline = quotaholder.get_timeline(
355
        context={},
356
        after=after,
357
        before=before,
358
        get_timeline=[[entity, resource, key]])
359
    cu = charge_units(timeline, after, before, details=details)
360
    return cu