Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / quotaholder_app / callpoint.py @ 548938f6

History | View | Annotate | Download (10.3 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, InvalidDataError,
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 _get_holdings_for_update(holding_keys, resource=None, delete=False):
79
    flt = Q(resource=resource) if resource is not None else Q()
80
    holders = set(holder for (holder, source, resource) in holding_keys)
81
    objs = Holding.objects.filter(flt, holder__in=holders).order_by('pk')
82
    hs = objs.select_for_update()
83

    
84
    keys = set(holding_keys)
85
    holdings = {}
86
    put_back = []
87
    for h in hs:
88
        key = h.holder, h.source, h.resource
89
        if key in keys:
90
            holdings[key] = h
91
        else:
92
            put_back.append(h)
93

    
94
    if delete:
95
        objs.delete()
96
        Holding.objects.bulk_create(put_back)
97
    return holdings
98

    
99

    
100
def _mkProvision(key, quantity):
101
    holder, source, resource = key
102
    return {'holder': holder,
103
            'source': source,
104
            'resource': resource,
105
            'quantity': quantity,
106
            }
107

    
108

    
109
def set_quota(quotas, resource=None):
110
    holding_keys = [key for (key, limit) in quotas]
111
    holdings = _get_holdings_for_update(
112
        holding_keys, resource=resource, delete=True)
113

    
114
    new_holdings = {}
115
    for key, limit in quotas:
116
        holder, source, res = key
117
        if resource is not None and resource != res:
118
            continue
119
        h = Holding(holder=holder,
120
                    source=source,
121
                    resource=res,
122
                    limit=limit)
123
        try:
124
            h_old = holdings[key]
125
            h.usage_min = h_old.usage_min
126
            h.usage_max = h_old.usage_max
127
        except KeyError:
128
            pass
129
        new_holdings[key] = h
130

    
131
    Holding.objects.bulk_create(new_holdings.values())
132

    
133

    
134
def issue_commission(clientkey, provisions, name="", force=False):
135
    operations = Operations()
136
    provisions_to_create = []
137

    
138
    keys = [key for (key, value) in provisions]
139
    holdings = _get_holdings_for_update(keys)
140
    try:
141
        checked = []
142
        for key, quantity in provisions:
143
            if not isinstance(quantity, (int, long)):
144
                raise InvalidDataError("Malformed provision")
145

    
146
            if key in checked:
147
                m = "Duplicate provision for %s" % str(key)
148
                provision = _mkProvision(key, quantity)
149
                raise DuplicateError(m,
150
                                     provision=provision)
151
            checked.append(key)
152

    
153
            # Target
154
            try:
155
                th = holdings[key]
156
            except KeyError:
157
                m = ("There is no such holding %s" % str(key))
158
                provision = _mkProvision(key, quantity)
159
                raise NoHoldingError(m,
160
                                     provision=provision)
161

    
162
            if quantity >= 0:
163
                operations.prepare(Import, th, quantity, force)
164

    
165
            else:  # release
166
                abs_quantity = -quantity
167
                operations.prepare(Release, th, abs_quantity, False)
168

    
169
            holdings[key] = th
170
            provisions_to_create.append((key, quantity))
171

    
172
    except QuotaholderError:
173
        operations.revert()
174
        raise
175

    
176
    commission = Commission.objects.create(clientkey=clientkey,
177
                                           name=name,
178
                                           issue_datetime=datetime.now())
179
    for (holder, source, resource), quantity in provisions_to_create:
180
        Provision.objects.create(serial=commission,
181
                                 holder=holder,
182
                                 source=source,
183
                                 resource=resource,
184
                                 quantity=quantity)
185

    
186
    return commission.serial
187

    
188

    
189
def _log_provision(commission, provision, holding, log_datetime, reason):
190

    
191
    kwargs = {
192
        'serial':              commission.serial,
193
        'name':                commission.name,
194
        'holder':              holding.holder,
195
        'source':              holding.source,
196
        'resource':            holding.resource,
197
        'limit':               holding.limit,
198
        'usage_min':           holding.usage_min,
199
        'usage_max':           holding.usage_max,
200
        'delta_quantity':      provision.quantity,
201
        'issue_time':          format_datetime(commission.issue_datetime),
202
        'log_time':            format_datetime(log_datetime),
203
        'reason':              reason,
204
    }
205

    
206
    ProvisionLog.objects.create(**kwargs)
207

    
208

    
209
def _get_commissions_for_update(clientkey, serials):
210
    cs = Commission.objects.filter(
211
        clientkey=clientkey, serial__in=serials).select_for_update()
212

    
213
    commissions = {}
214
    for c in cs:
215
        commissions[c.serial] = c
216
    return commissions
217

    
218

    
219
def _partition_by(f, l):
220
    d = {}
221
    for x in l:
222
        group = f(x)
223
        group_l = d.get(group, [])
224
        group_l.append(x)
225
        d[group] = group_l
226
    return d
227

    
228

    
229
def resolve_pending_commissions(clientkey, accept_set=None, reject_set=None,
230
                                reason=''):
231
    if accept_set is None:
232
        accept_set = []
233
    if reject_set is None:
234
        reject_set = []
235

    
236
    actions = dict.fromkeys(accept_set, True)
237
    conflicting = set()
238
    for serial in reject_set:
239
        if actions.get(serial) is True:
240
            actions.pop(serial)
241
            conflicting.add(serial)
242
        else:
243
            actions[serial] = False
244

    
245
    conflicting = list(conflicting)
246
    serials = actions.keys()
247
    commissions = _get_commissions_for_update(clientkey, serials)
248
    ps = Provision.objects.filter(serial__in=serials).select_for_update()
249
    holding_keys = sorted(p.holding_key() for p in ps)
250
    holdings = _get_holdings_for_update(holding_keys)
251
    provisions = _partition_by(lambda p: p.serial_id, ps)
252

    
253
    log_datetime = datetime.now()
254

    
255
    accepted, rejected, notFound = [], [], []
256
    for serial, accept in actions.iteritems():
257
        commission = commissions.get(serial)
258
        if commission is None:
259
            notFound.append(serial)
260
            continue
261

    
262
        accepted.append(serial) if accept else rejected.append(serial)
263

    
264
        ps = provisions.get(serial, [])
265
        for pv in ps:
266
            key = pv.holding_key()
267
            h = holdings.get(key)
268
            if h is None:
269
                raise CorruptedError("Corrupted provision")
270

    
271
            quantity = pv.quantity
272
            action = finalize if accept else undo
273
            if quantity >= 0:
274
                action(Import, h, quantity)
275
            else:  # release
276
                action(Release, h, -quantity)
277

    
278
            prefix = 'ACCEPT:' if accept else 'REJECT:'
279
            comm_reason = prefix + reason[-121:]
280
            _log_provision(commission, pv, h, log_datetime, comm_reason)
281
            pv.delete()
282
        commission.delete()
283
    return accepted, rejected, notFound, conflicting
284

    
285

    
286
def resolve_pending_commission(clientkey, serial, accept=True):
287
    if accept:
288
        ok, notOk, notF, confl = resolve_pending_commissions(
289
            clientkey=clientkey, accept_set=[serial])
290
    else:
291
        notOk, ok, notF, confl = resolve_pending_commissions(
292
            clientkey=clientkey, reject_set=[serial])
293

    
294
    assert notOk == confl == []
295
    assert ok + notF == [serial]
296
    return bool(ok)
297

    
298

    
299
def get_pending_commissions(clientkey):
300
    pending = Commission.objects.filter(clientkey=clientkey)
301
    pending_list = pending.values_list('serial', flat=True)
302
    return list(pending_list)
303

    
304

    
305
def get_commission(clientkey, serial):
306
    try:
307
        commission = Commission.objects.get(clientkey=clientkey,
308
                                            serial=serial)
309
    except Commission.DoesNotExist:
310
        raise NoCommissionError(serial)
311

    
312
    objs = Provision.objects
313
    provisions = objs.filter(serial=commission)
314

    
315
    ps = [p.todict() for p in provisions]
316

    
317
    response = {'serial':     serial,
318
                'provisions': ps,
319
                'issue_time': commission.issue_datetime,
320
                'name':       commission.name,
321
                }
322
    return response