callpoint.py 12.3 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
        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_holder_quota(self, quotas):
        q = self._level_quota_dict(quotas)
        self.set_quota(q)
112

113
114
    def _level_quota_dict(self, quotas):
        lst = []
115
116
117
        for holder, holder_quota in quotas.iteritems():
            for source, source_quota in holder_quota.iteritems():
                for resource, limit in source_quota.iteritems():
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
                    key = (holder, source, resource)
                    lst.append((key, limit))
        return lst

    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
137

138
139
140
141
142
143
144
145
146
147
148
149
150
151
    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)
152

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
153
    def issue_commission(self,
154
                         context=None,
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
155
156
                         clientkey=None,
                         name=None,
157
                         force=False,
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
158
                         provisions=()):
159

160
161
        if name is None:
            name = ""
162

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
163
        operations = Operations()
164
        provisions_to_create = []
165

166
167
168
        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
169
170
        try:
            checked = []
171
            for key, quantity in provisions:
172
173
                if not isinstance(quantity, (int, long)):
                    raise InvalidDataError("Malformed provision")
174

175
176
177
                if key in checked:
                    m = "Duplicate provision for %s" % str(key)
                    provision = self._mkProvision(key, quantity)
178
                    raise DuplicateError(m,
179
180
                                         provision=provision)
                checked.append(key)
181

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
182
183
                # Target
                try:
184
185
                    th = holdings[key]
                except KeyError:
186
                    m = ("There is no such holding %s" % str(key))
187
                    provision = self._mkProvision(key, quantity)
188
189
                    raise NoHoldingError(m,
                                         provision=provision)
190

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
191
                if quantity >= 0:
192
                    operations.prepare(Import, th, quantity, force)
193

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
194
195
                else: # release
                    abs_quantity = -quantity
196
                    operations.prepare(Release, th, abs_quantity, force)
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
197

198
                holdings[key] = th
199
                provisions_to_create.append((key, quantity))
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
200
201
202
203

        except QuotaholderError:
            operations.revert()
            raise
204

205
206
207
208
209
210
211
212
213
        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
214

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
215
    def _log_provision(self,
216
                       commission, provision, holding, log_time, reason):
217

Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
218
219
220
        kwargs = {
            'serial':              commission.serial,
            'name':                commission.name,
221
222
223
            'holder':              holding.holder,
            'source':              holding.source,
            'resource':            holding.resource,
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
224
            'limit':               holding.limit,
225
226
            'imported_min':        holding.imported_min,
            'imported_max':        holding.imported_max,
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
227
228
229
230
231
232
233
234
            'delta_quantity':      provision.quantity,
            'issue_time':          commission.issue_time,
            'log_time':            log_time,
            'reason':              reason,
        }

        ProvisionLog.objects.create(**kwargs)

235
236
237
    def _get_commissions_for_update(self, clientkey, serials):
        cs = Commission.objects.filter(
            clientkey=clientkey, serial__in=serials).select_for_update()
238

239
240
241
242
        commissions = {}
        for c in cs:
            commissions[c.serial] = c
        return commissions
Giorgos Korfiatis's avatar
Giorgos Korfiatis committed
243

244
245
246
247
248
249
250
251
    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
252

253
254
255
256
257
258
259
260
261
262
263
264
    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
265

266
267
268
269
270
271
272
        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)
273

274
        log_time = now()
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
305
306
307
308
309
310
311
312
313
314
315
316
317
        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)
318

319
    def get_pending_commissions(self, context=None, clientkey=None):
320
321
        pending = Commission.objects.filter(clientkey=clientkey)
        pending_list = pending.values_list('serial', flat=True)
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
        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

342

343
API_Callpoint = QuotaholderDjangoDBCallpoint