Statistics
| Branch: | Tag: | Revision:

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

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
            h.id = h_old.id
128
        except KeyError:
129
            pass
130
        new_holdings[key] = h
131

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

    
134

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

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

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

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

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

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

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

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

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

    
187
    return commission.serial
188

    
189

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

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

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

    
209

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

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

    
219

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

    
229

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

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

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

    
254
    log_datetime = datetime.now()
255

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

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

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

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

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

    
286

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

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

    
299

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

    
305

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

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

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

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