Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / endpoints / qh.py @ 6c997921

History | View | Annotate | Download (10.3 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 get_quota(user):
77
    c = get_client()
78
    if not c:
79
        return
80
    payload = []
81
    append = payload.append
82
    for r in user.quota.keys():
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
def register_users(users):
121
    payload = list(CreateEntityPayload(
122
                    entity=u.uuid,
123
                    owner='system',
124
                    key=ENTITY_KEY,
125
                    ownerkey='') for u in users)
126
    rejected = create_entity(payload)
127
    if not rejected:
128
        payload = []
129
        append = payload.append
130
        for u in users:
131
            for resource, capacity in u.quota.iteritems():
132
                append( SetQuotaPayload(
133
                                holder=u.uuid,
134
                                resource=resource,
135
                                key=ENTITY_KEY,
136
                                quantity=0,
137
                                capacity=capacity if capacity != inf else None,
138
                                import_limit=QH_PRACTICALLY_INFINITE,
139
                                export_limit=QH_PRACTICALLY_INFINITE,
140
                                flags=0))
141
        return set_quota(payload)
142

    
143

    
144
def register_resources(resources):
145
    rdata = ((r.service, r) for r in resources)
146
    services = set(r.service for r in resources)
147
    payload = list(CreateEntityPayload(
148
                    entity=service,
149
                    owner='system',
150
                    key=ENTITY_KEY,
151
                    ownerkey='') for service in set(services))
152
    rejected = create_entity(payload)
153
    if not rejected:
154
        payload = list(SetQuotaPayload(
155
                        holder=resource.service,
156
                        resource=resource,
157
                        key=ENTITY_KEY,
158
                        quantity=QH_PRACTICALLY_INFINITE,
159
                        capacity=0,
160
                        import_limit=QH_PRACTICALLY_INFINITE,
161
                        export_limit=QH_PRACTICALLY_INFINITE,
162
                        flags=0) for resource in resources)
163
        return set_quota(payload)
164

    
165
def qh_add_quota(serial, sub_list, add_list):
166
    if not QUOTAHOLDER_URL:
167
        return ()
168

    
169
    context = {}
170
    c = get_client()
171

    
172
    sub_quota = []
173
    sub_append = sub_quota.append
174
    add_quota = []
175
    add_append = add_quota.append
176

    
177
    for ql in sub_list:
178
        args = (ql.holder, ql.resource, ENTITY_KEY,
179
                0, ql.capacity, ql.import_limit, ql.export_limit)
180
        sub_append(args)
181

    
182
    for ql in add_list:
183
        args = (ql.holder, ql.resource, ENTITY_KEY,
184
                0, ql.capacity, ql.import_limit, ql.export_limit)
185
        add_append(args)
186

    
187
    result = c.add_quota(context=context,
188
                         clientkey=clientkey,
189
                         serial=serial,
190
                         sub_quota=sub_quota,
191
                         add_quota=add_quota)
192

    
193
    return result
194

    
195
def qh_query_serials(serials):
196
    if not QUOTAHOLDER_URL:
197
        return ()
198

    
199
    context = {}
200
    c = get_client()
201
    result = c.query_serials(context=context,
202
                             clientkey=clientkey,
203
                             serials=serials)
204
    return result
205

    
206
def qh_ack_serials(serials):
207
    if not QUOTAHOLDER_URL:
208
        return ()
209

    
210
    context = {}
211
    c = get_client()
212
    result = c.ack_serials(context=context,
213
                           clientkey=clientkey,
214
                           serials=serials)
215
    return
216

    
217
from datetime import datetime
218

    
219
strptime = datetime.strptime
220
timefmt = '%Y-%m-%dT%H:%M:%S.%f'
221

    
222
SECOND_RESOLUTION = 1
223

    
224

    
225
def total_seconds(timedelta_object):
226
    return timedelta_object.seconds + timedelta_object.days * 86400
227

    
228

    
229
def iter_timeline(timeline, before):
230
    if not timeline:
231
        return
232

    
233
    for t in timeline:
234
        yield t
235

    
236
    t = dict(t)
237
    t['issue_time'] = before
238
    yield t
239

    
240

    
241
def _usage_units(timeline, after, before, details=0):
242

    
243
    t_total = 0
244
    uu_total = 0
245
    t_after = strptime(after, timefmt)
246
    t_before = strptime(before, timefmt)
247
    t0 = t_after
248
    u0 = 0
249

    
250
    for point in iter_timeline(timeline, before):
251
        issue_time = point['issue_time']
252

    
253
        if issue_time <= after:
254
            u0 = point['target_allocated_through']
255
            continue
256

    
257
        t = strptime(issue_time, timefmt) if issue_time <= before else t_before
258
        t_diff = int(total_seconds(t - t0) * SECOND_RESOLUTION)
259
        t_total += t_diff
260
        uu_cost = u0 * t_diff
261
        uu_total += uu_cost
262
        t0 = t
263
        u0 = point['target_allocated_through']
264

    
265
        target = point['target']
266
        if details:
267
            yield  (target,
268
                    point['resource'],
269
                    point['name'],
270
                    issue_time,
271
                    uu_cost,
272
                    uu_total)
273

    
274
    if not t_total:
275
        return
276

    
277
    yield  (target,
278
            'total',
279
            point['resource'],
280
            issue_time,
281
            uu_total / t_total,
282
            uu_total)
283

    
284

    
285
def usage_units(timeline, after, before, details=0):
286
    return list(_usage_units(timeline, after, before, details=details))
287

    
288

    
289
def traffic_units(timeline, after, before, details=0):
290
    tu_total = 0
291
    target = None
292
    issue_time = None
293

    
294
    for point in timeline:
295
        issue_time = point['issue_time']
296
        if issue_time <= after:
297
            continue
298
        if issue_time > before:
299
            break
300

    
301
        target = point['target']
302
        tu = point['target_allocated_through']
303
        tu_total += tu
304

    
305
        if details:
306
            yield  (target,
307
                    point['resource'],
308
                    point['name'],
309
                    issue_time,
310
                    tu,
311
                    tu_total)
312

    
313
    if not tu_total:
314
        return
315

    
316
    yield  (target,
317
            'total',
318
            point['resource'],
319
            issue_time,
320
            tu_total // len(timeline),
321
            tu_total)
322

    
323

    
324
def timeline_charge(entity, resource, after, before, details, charge_type):
325
    key = '1'
326
    if charge_type == 'charge_usage':
327
        charge_units = usage_units
328
    elif charge_type == 'charge_traffic':
329
        charge_units = traffic_units
330
    else:
331
        m = 'charge type %s not supported' % charge_type
332
        raise ValueError(m)
333

    
334
    quotaholder = QuotaholderClient(QUOTAHOLDER_URL, token=QUOTAHOLDER_TOKEN)
335
    timeline = quotaholder.get_timeline(
336
        context={},
337
        after=after,
338
        before=before,
339
        get_timeline=[[entity, resource, key]])
340
    cu = charge_units(timeline, after, before, details=details)
341
    return cu