Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / quotaholder_app / callpoint.py @ fe4000a3

History | View | Annotate | Download (10.4 kB)

1
# Copyright 2012, 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 datetime import datetime
35
from django.db.models import Q
36
from astakos.quotaholder_app.exception import (
37
    QuotaholderError,
38
    NoCommissionError,
39
    CorruptedError,
40
    NoHoldingError,
41
    DuplicateError)
42

    
43
from astakos.quotaholder_app.commission import (
44
    Import, Release, Operations, finalize, undo)
45

    
46
from astakos.quotaholder_app.models import (
47
    Holding, Commission, Provision, ProvisionLog)
48

    
49

    
50
def format_datetime(d):
51
    return d.strftime('%Y-%m-%dT%H:%M:%S.%f')[:24]
52

    
53

    
54
def get_quota(holders=None, sources=None, resources=None, flt=None):
55
    if flt is None:
56
        flt = Q()
57

    
58
    holdings = Holding.objects.filter(flt)
59

    
60
    if holders is not None:
61
        holdings = holdings.filter(holder__in=holders)
62

    
63
    if sources is not None:
64
        holdings = holdings.filter(source__in=sources)
65

    
66
    if resources is not None:
67
        holdings = holdings.filter(resource__in=resources)
68

    
69
    quotas = {}
70
    for holding in holdings:
71
        key = (holding.holder, holding.source, holding.resource)
72
        value = (holding.limit, holding.usage_min, holding.usage_max)
73
        quotas[key] = value
74

    
75
    return quotas
76

    
77

    
78
def delete_quota(keys):
79
    for holder, source, resource in keys:
80
        Holding.objects.filter(holder=holder,
81
                               source=source,
82
                               resource=resource).delete()
83

    
84

    
85
def _get_holdings_for_update(holding_keys, resource=None, delete=False):
86
    flt = Q(resource=resource) if resource is not None else Q()
87
    holders = set(holder for (holder, source, resource) in holding_keys)
88
    objs = Holding.objects.filter(flt, holder__in=holders).order_by('pk')
89
    hs = objs.select_for_update()
90

    
91
    keys = set(holding_keys)
92
    holdings = {}
93
    put_back = []
94
    for h in hs:
95
        key = h.holder, h.source, h.resource
96
        if key in keys:
97
            holdings[key] = h
98
        else:
99
            put_back.append(h)
100

    
101
    if delete:
102
        objs.delete()
103
        Holding.objects.bulk_create(put_back)
104
    return holdings
105

    
106

    
107
def _mkProvision(key, quantity):
108
    holder, source, resource = key
109
    return {'holder': holder,
110
            'source': source,
111
            'resource': resource,
112
            'quantity': quantity,
113
            }
114

    
115

    
116
def set_quota(quotas, resource=None):
117
    holding_keys = [key for (key, limit) in quotas]
118
    holdings = _get_holdings_for_update(
119
        holding_keys, resource=resource, delete=True)
120

    
121
    new_holdings = {}
122
    for key, limit in quotas:
123
        holder, source, res = key
124
        if resource is not None and resource != res:
125
            continue
126
        h = Holding(holder=holder,
127
                    source=source,
128
                    resource=res,
129
                    limit=limit)
130
        try:
131
            h_old = holdings[key]
132
            h.usage_min = h_old.usage_min
133
            h.usage_max = h_old.usage_max
134
            h.id = h_old.id
135
        except KeyError:
136
            pass
137
        new_holdings[key] = h
138

    
139
    Holding.objects.bulk_create(new_holdings.values())
140

    
141

    
142
def issue_commission(clientkey, provisions, name="", force=False):
143
    operations = Operations()
144
    provisions_to_create = []
145

    
146
    keys = [key for (key, value) in provisions]
147
    holdings = _get_holdings_for_update(keys)
148
    try:
149
        checked = []
150
        for key, quantity in provisions:
151
            if key in checked:
152
                m = "Duplicate provision for %s" % str(key)
153
                provision = _mkProvision(key, quantity)
154
                raise DuplicateError(m,
155
                                     provision=provision)
156
            checked.append(key)
157

    
158
            # Target
159
            try:
160
                th = holdings[key]
161
            except KeyError:
162
                m = ("There is no such holding %s" % str(key))
163
                provision = _mkProvision(key, quantity)
164
                raise NoHoldingError(m,
165
                                     provision=provision)
166

    
167
            if quantity >= 0:
168
                operations.prepare(Import, th, quantity, force)
169

    
170
            else:  # release
171
                abs_quantity = -quantity
172
                operations.prepare(Release, th, abs_quantity, False)
173

    
174
            holdings[key] = th
175
            provisions_to_create.append((key, quantity))
176

    
177
    except QuotaholderError:
178
        operations.revert()
179
        raise
180

    
181
    commission = Commission.objects.create(clientkey=clientkey,
182
                                           name=name,
183
                                           issue_datetime=datetime.now())
184
    for (holder, source, resource), quantity in provisions_to_create:
185
        Provision.objects.create(serial=commission,
186
                                 holder=holder,
187
                                 source=source,
188
                                 resource=resource,
189
                                 quantity=quantity)
190

    
191
    return commission.serial
192

    
193

    
194
def _log_provision(commission, provision, holding, log_datetime, reason):
195

    
196
    kwargs = {
197
        'serial':              commission.serial,
198
        'name':                commission.name,
199
        'holder':              holding.holder,
200
        'source':              holding.source,
201
        'resource':            holding.resource,
202
        'limit':               holding.limit,
203
        'usage_min':           holding.usage_min,
204
        'usage_max':           holding.usage_max,
205
        'delta_quantity':      provision.quantity,
206
        'issue_time':          format_datetime(commission.issue_datetime),
207
        'log_time':            format_datetime(log_datetime),
208
        'reason':              reason,
209
    }
210

    
211
    ProvisionLog.objects.create(**kwargs)
212

    
213

    
214
def _get_commissions_for_update(clientkey, serials):
215
    cs = Commission.objects.filter(
216
        clientkey=clientkey, serial__in=serials).select_for_update()
217

    
218
    commissions = {}
219
    for c in cs:
220
        commissions[c.serial] = c
221
    return commissions
222

    
223

    
224
def _partition_by(f, l):
225
    d = {}
226
    for x in l:
227
        group = f(x)
228
        group_l = d.get(group, [])
229
        group_l.append(x)
230
        d[group] = group_l
231
    return d
232

    
233

    
234
def resolve_pending_commissions(clientkey, accept_set=None, reject_set=None,
235
                                reason=''):
236
    if accept_set is None:
237
        accept_set = []
238
    if reject_set is None:
239
        reject_set = []
240

    
241
    actions = dict.fromkeys(accept_set, True)
242
    conflicting = set()
243
    for serial in reject_set:
244
        if actions.get(serial) is True:
245
            actions.pop(serial)
246
            conflicting.add(serial)
247
        else:
248
            actions[serial] = False
249

    
250
    conflicting = list(conflicting)
251
    serials = actions.keys()
252
    commissions = _get_commissions_for_update(clientkey, serials)
253
    ps = Provision.objects.filter(serial__in=serials).select_for_update()
254
    holding_keys = sorted(p.holding_key() for p in ps)
255
    holdings = _get_holdings_for_update(holding_keys)
256
    provisions = _partition_by(lambda p: p.serial_id, ps)
257

    
258
    log_datetime = datetime.now()
259

    
260
    accepted, rejected, notFound = [], [], []
261
    for serial, accept in actions.iteritems():
262
        commission = commissions.get(serial)
263
        if commission is None:
264
            notFound.append(serial)
265
            continue
266

    
267
        accepted.append(serial) if accept else rejected.append(serial)
268

    
269
        ps = provisions.get(serial, [])
270
        for pv in ps:
271
            key = pv.holding_key()
272
            h = holdings.get(key)
273
            if h is None:
274
                raise CorruptedError("Corrupted provision")
275

    
276
            quantity = pv.quantity
277
            action = finalize if accept else undo
278
            if quantity >= 0:
279
                action(Import, h, quantity)
280
            else:  # release
281
                action(Release, h, -quantity)
282

    
283
            prefix = 'ACCEPT:' if accept else 'REJECT:'
284
            comm_reason = prefix + reason[-121:]
285
            _log_provision(commission, pv, h, log_datetime, comm_reason)
286
            pv.delete()
287
        commission.delete()
288
    return accepted, rejected, notFound, conflicting
289

    
290

    
291
def resolve_pending_commission(clientkey, serial, accept=True):
292
    if accept:
293
        ok, notOk, notF, confl = resolve_pending_commissions(
294
            clientkey=clientkey, accept_set=[serial])
295
    else:
296
        notOk, ok, notF, confl = resolve_pending_commissions(
297
            clientkey=clientkey, reject_set=[serial])
298

    
299
    assert notOk == confl == []
300
    assert ok + notF == [serial]
301
    return bool(ok)
302

    
303

    
304
def get_pending_commissions(clientkey):
305
    pending = Commission.objects.filter(clientkey=clientkey)
306
    pending_list = pending.values_list('serial', flat=True)
307
    return list(pending_list)
308

    
309

    
310
def get_commission(clientkey, serial):
311
    try:
312
        commission = Commission.objects.get(clientkey=clientkey,
313
                                            serial=serial)
314
    except Commission.DoesNotExist:
315
        raise NoCommissionError(serial)
316

    
317
    objs = Provision.objects
318
    provisions = objs.filter(serial=commission)
319

    
320
    ps = [p.todict() for p in provisions]
321

    
322
    response = {'serial':     serial,
323
                'provisions': ps,
324
                'issue_time': commission.issue_datetime,
325
                'name':       commission.name,
326
                }
327
    return response