callpoint.py 11.8 KB
Newer Older
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
1
# Copyright 2012, 2013 GRNET S.A. All rights reserved.
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

34
from django.db.models import F
35
36
from astakos.quotaholder.exception import (
    QuotaholderError,
37
    NoCommissionError,
38
    CorruptedError, InvalidDataError,
39
    NoHoldingError,
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
40
    DuplicateError)
41

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
42
from astakos.quotaholder.commission import (
43
    Import, Release, Operations, finalize, undo)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
44

45
46
from astakos.quotaholder.utils.newname import newname
from astakos.quotaholder.api import QH_PRACTICALLY_INFINITE
47

48
from .models import (Holding,
49
                     Commission, Provision, ProvisionLog,
50
                     now)
51

52

53
class QuotaholderDjangoDBCallpoint(object):
54

55
56
57
58
59
    def get_quota(self, holders=None, sources=None, resources=None):
        holdings = Holding.objects.all()

        if holders is not None:
            holdings = holdings.filter(holder__in=holders)
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

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

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

        quotas = {}
        for holding in holdings:
            key = (holding.holder, holding.source, holding.resource)
            value = (holding.limit, holding.imported_min, holding.imported_max)
            quotas[key] = value

        return quotas

75
76
    def _get_holdings_for_update(self, holding_keys):
        holding_keys = sorted(holding_keys)
77
        holdings = {}
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
        for (holder, source, resource) in holding_keys:
            try:
                h = Holding.objects.get_for_update(
                    holder=holder, source=source, resource=resource)
                holdings[(holder, source, resource)] = h
            except Holding.DoesNotExist:
                pass
        return holdings

    def _provisions_to_list(self, provisions):
        lst = []
        for provision in provisions:
            try:
                holder = provision['holder']
                source = provision['source']
                resource = provision['resource']
                quantity = provision['quantity']
                key = (holder, source, resource)
                lst.append((key, quantity))
            except KeyError:
                raise InvalidDataError("Malformed provision")
        return lst

    def _mkProvision(self, key, quantity):
        holder, source, resource = key
        return {'holder': holder,
                'source': source,
                'resource': resource,
                'quantity': quantity,
                }

    def set_quota(self, quotas):
        holding_keys = [key for (key, limit) in quotas]
        holdings = self._get_holdings_for_update(holding_keys)

        for key, limit in quotas:
            try:
                h = holdings[key]
            except KeyError:
                holder, source, resource = key
                h = Holding(holder=holder,
                            source=source,
                            resource=resource)
            h.limit = limit
            h.save()
            holdings[key] = h
124

125
126
127
128
129
130
131
132
133
134
135
136
137
138
    def add_resource_limit(self, holders=None, sources=None, resources=None,
                           diff=0):
        holdings = Holding.objects.all()

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

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

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

        holdings.update(limit=F('limit')+diff)
139

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
140
    def issue_commission(self,
141
                         context=None,
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
142
143
                         clientkey=None,
                         name=None,
144
                         force=False,
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
145
                         provisions=()):
146

147
148
        if name is None:
            name = ""
149

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
150
        operations = Operations()
151
        provisions_to_create = []
152

153
154
155
        provisions = self._provisions_to_list(provisions)
        keys = [key for (key, value) in provisions]
        holdings = self._get_holdings_for_update(keys)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
156
157
        try:
            checked = []
158
            for key, quantity in provisions:
159
160
                if not isinstance(quantity, (int, long)):
                    raise InvalidDataError("Malformed provision")
161

162
163
164
                if key in checked:
                    m = "Duplicate provision for %s" % str(key)
                    provision = self._mkProvision(key, quantity)
165
                    raise DuplicateError(m,
166
167
                                         provision=provision)
                checked.append(key)
168

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
169
170
                # Target
                try:
171
172
                    th = holdings[key]
                except KeyError:
173
                    m = ("There is no such holding %s" % str(key))
174
                    provision = self._mkProvision(key, quantity)
175
176
                    raise NoHoldingError(m,
                                         provision=provision)
177

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
178
                if quantity >= 0:
179
                    operations.prepare(Import, th, quantity, force)
180

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
181
182
                else: # release
                    abs_quantity = -quantity
183
                    operations.prepare(Release, th, abs_quantity, force)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
184

185
                holdings[key] = th
186
                provisions_to_create.append((key, quantity))
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
187
188
189
190

        except QuotaholderError:
            operations.revert()
            raise
191

192
193
194
195
196
197
198
199
200
        commission = Commission.objects.create(clientkey=clientkey, name=name)
        for (holder, source, resource), quantity in provisions_to_create:
            Provision.objects.create(serial=commission,
                                     holder=holder,
                                     source=source,
                                     resource=resource,
                                     quantity=quantity)

        return commission.serial
201

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
202
    def _log_provision(self,
203
                       commission, provision, holding, log_time, reason):
204

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
205
206
207
        kwargs = {
            'serial':              commission.serial,
            'name':                commission.name,
208
209
210
            'holder':              holding.holder,
            'source':              holding.source,
            'resource':            holding.resource,
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
211
            'limit':               holding.limit,
212
213
            'imported_min':        holding.imported_min,
            'imported_max':        holding.imported_max,
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
214
215
216
217
218
219
220
221
            'delta_quantity':      provision.quantity,
            'issue_time':          commission.issue_time,
            'log_time':            log_time,
            'reason':              reason,
        }

        ProvisionLog.objects.create(**kwargs)

222
223
224
    def _get_commissions_for_update(self, clientkey, serials):
        cs = Commission.objects.filter(
            clientkey=clientkey, serial__in=serials).select_for_update()
225

226
227
228
229
        commissions = {}
        for c in cs:
            commissions[c.serial] = c
        return commissions
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
230

231
232
233
234
235
236
237
238
    def _partition_by(self, f, l):
        d = {}
        for x in l:
            group = f(x)
            group_l = d.get(group, [])
            group_l.append(x)
            d[group] = group_l
        return d
239

240
241
242
243
244
245
246
247
248
249
250
251
    def resolve_pending_commissions(self,
                                    context=None, clientkey=None,
                                    accept_set=[], reject_set=[],
                                    reason=''):
        actions = dict.fromkeys(accept_set, True)
        conflicting = set()
        for serial in reject_set:
            if actions.get(serial) is True:
                actions.pop(serial)
                conflicting.add(serial)
            else:
                actions[serial] = False
Georgios D. Tsoukalas's avatar
Georgios D. Tsoukalas committed
252

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

261
        log_time = now()
262

263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
        accepted, rejected, notFound = [], [], []
        for serial, accept in actions.iteritems():
            commission = commissions.get(serial)
            if commission is None:
                notFound.append(serial)
                continue

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

            ps = provisions.get(serial)
            assert ps is not None
            for pv in ps:
                key = pv.holding_key()
                h = holdings.get(key)
                if h is None:
                    raise CorruptedError("Corrupted provision")

                quantity = pv.quantity
                action = finalize if accept else undo
                if quantity >= 0:
                    action(Import, h, quantity)
                else:  # release
                    action(Release, h, -quantity)

                prefix = 'ACCEPT:' if accept else 'REJECT:'
                comm_reason = prefix + reason[-121:]
                self._log_provision(commission, pv, h, log_time, comm_reason)
                pv.delete()
            commission.delete()
        return accepted, rejected, notFound, conflicting

    def resolve_pending_commission(self, clientkey, serial, accept=True):
        if accept:
            ok, notOk, notF, confl = self.resolve_pending_commissions(
                clientkey=clientkey, accept_set=[serial])
        else:
            notOk, ok, notF, confl = self.resolve_pending_commissions(
                clientkey=clientkey, reject_set=[serial])

        assert notOk == confl == []
        assert ok + notF == [serial]
        return bool(ok)
305

306
    def get_pending_commissions(self, context=None, clientkey=None):
307
308
        pending = Commission.objects.filter(clientkey=clientkey)
        pending_list = pending.values_list('serial', flat=True)
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
        return list(pending_list)

    def get_commission(self, clientkey=None, serial=None):
        try:
            commission = Commission.objects.get(clientkey=clientkey,
                                                serial=serial)
        except Commission.DoesNotExist:
            raise NoCommissionError(serial)

        objs = Provision.objects.select_related('holding')
        provisions = objs.filter(serial=commission)

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

        response = {'serial':     serial,
                    'provisions': ps,
                    'issue_time': commission.issue_time,
                    }
        return response

329

330
API_Callpoint = QuotaholderDjangoDBCallpoint