Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / api / quotas.py @ 6609821f

History | View | Annotate | Download (9.8 kB)

1
# Copyright 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 django.utils import simplejson as json
35
from django.views.decorators.csrf import csrf_exempt
36
from django.http import HttpResponse
37

    
38
from snf_django.lib.db.transaction import commit_on_success_strict
39

    
40
from snf_django.lib import api
41
from snf_django.lib.api.faults import BadRequest, ItemNotFound
42

    
43
from astakos.im.resources import get_resources
44
from astakos.im.quotas import get_user_quotas, service_get_quotas
45

    
46
import astakos.quotaholder_app.exception as qh_exception
47
import astakos.quotaholder_app.callpoint as qh
48

    
49
from .util import (json_response, is_integer, are_integer,
50
                   user_from_token, service_from_token)
51

    
52
@api.api_method(http_method='GET', token_required=True, user_required=False)
53
@user_from_token
54
def quotas(request):
55
    result = get_user_quotas(request.user)
56
    return json_response(result)
57

    
58

    
59
@api.api_method(http_method='GET', token_required=True, user_required=False)
60
@service_from_token
61
def service_quotas(request):
62
    user = request.GET.get('user')
63
    users = [user] if user is not None else None
64
    result = service_get_quotas(request.service_instance, users=users)
65

    
66
    if user is not None and result == {}:
67
        raise ItemNotFound("No such user '%s'" % user)
68

    
69
    return json_response(result)
70

    
71

    
72
@api.api_method(http_method='GET', token_required=False, user_required=False)
73
def resources(request):
74
    result = get_resources()
75
    return json_response(result)
76

    
77

    
78
@csrf_exempt
79
def commissions(request):
80
    method = request.method
81
    if method == 'GET':
82
        return get_pending_commissions(request)
83
    elif method == 'POST':
84
        return issue_commission(request)
85
    else:
86
        raise BadRequest('Method not allowed.')
87

    
88

    
89
@api.api_method(http_method='GET', token_required=True, user_required=False)
90
@service_from_token
91
def get_pending_commissions(request):
92
    data = request.GET
93
    client_key = str(request.service_instance)
94

    
95
    result = qh.get_pending_commissions(clientkey=client_key)
96
    return json_response(result)
97

    
98

    
99
def _provisions_to_list(provisions):
100
    lst = []
101
    for provision in provisions:
102
        try:
103
            holder = provision['holder']
104
            source = provision['source']
105
            resource = provision['resource']
106
            quantity = provision['quantity']
107
            key = (holder, source, resource)
108
            lst.append((key, quantity))
109
            if not is_integer(quantity):
110
                raise ValueError()
111
        except (TypeError, KeyError, ValueError):
112
            raise BadRequest("Malformed provision %s" % str(provision))
113
    return lst
114

    
115

    
116
@csrf_exempt
117
@api.api_method(http_method='POST', token_required=True, user_required=False)
118
@service_from_token
119
def issue_commission(request):
120
    data = request.raw_post_data
121
    try:
122
        input_data = json.loads(data)
123
    except json.JSONDecodeError:
124
        raise BadRequest("POST data should be in json format.")
125

    
126
    client_key = str(request.service_instance)
127
    provisions = input_data.get('provisions')
128
    if provisions is None:
129
        raise BadRequest("Provisions are missing.")
130
    if not isinstance(provisions, list):
131
        raise BadRequest("Provisions should be a list.")
132

    
133
    provisions = _provisions_to_list(provisions)
134
    force = input_data.get('force', False)
135
    if not isinstance(force, bool):
136
        raise BadRequest('"force" option should be a boolean.')
137

    
138
    auto_accept = input_data.get('auto_accept', False)
139
    if not isinstance(auto_accept, bool):
140
        raise BadRequest('"auto_accept" option should be a boolean.')
141

    
142
    name = input_data.get('name', "")
143
    if not isinstance(name, basestring):
144
        raise BadRequest("Commission name should be a string.")
145

    
146
    try:
147
        result = _issue_commission(clientkey=client_key,
148
                                   provisions=provisions,
149
                                   name=name,
150
                                   force=force,
151
                                   accept=auto_accept)
152
        data = {"serial": result}
153
        status_code = 201
154
    except (qh_exception.NoCapacityError,
155
            qh_exception.NoQuantityError) as e:
156
        status_code = 413
157
        body = {"message": e.message,
158
                "code": status_code,
159
                "data": e.data,
160
                }
161
        data = {"overLimit": body}
162
    except qh_exception.NoHoldingError as e:
163
        status_code = 404
164
        body = {"message": e.message,
165
                "code": status_code,
166
                "data": e.data,
167
                }
168
        data = {"itemNotFound": body}
169
    except qh_exception.InvalidDataError as e:
170
        status_code = 400
171
        body = {"message": e.message,
172
                "code": status_code,
173
                }
174
        data = {"badRequest": body}
175

    
176
    return json_response(data, status_code=status_code)
177

    
178

    
179
@commit_on_success_strict()
180
def _issue_commission(clientkey, provisions, name, force, accept):
181
    serial = qh.issue_commission(clientkey=clientkey,
182
                                 provisions=provisions,
183
                                 name=name,
184
                                 force=force)
185
    if accept:
186
        done = qh.resolve_pending_commission(clientkey=clientkey,
187
                                             serial=serial)
188

    
189
    return serial
190

    
191

    
192
def notFoundCF(serial):
193
    body = {"code": 404,
194
            "message": "serial %s does not exist" % serial,
195
            }
196
    return {"itemNotFound": body}
197

    
198

    
199
def conflictingCF(serial):
200
    body = {"code": 400,
201
            "message": "cannot both accept and reject serial %s" % serial,
202
            }
203
    return {"badRequest": body}
204

    
205

    
206
@csrf_exempt
207
@api.api_method(http_method='POST', token_required=True, user_required=False)
208
@service_from_token
209
@commit_on_success_strict()
210
def resolve_pending_commissions(request):
211
    data = request.raw_post_data
212
    try:
213
        input_data = json.loads(data)
214
    except json.JSONDecodeError:
215
        raise BadRequest("POST data should be in json format.")
216

    
217
    client_key = str(request.service_instance)
218
    accept = input_data.get('accept', [])
219
    reject = input_data.get('reject', [])
220

    
221
    if not isinstance(accept, list) or not isinstance(reject, list):
222
        m = '"accept" and "reject" should reference lists of serials.'
223
        raise BadRequest(m)
224

    
225
    if not are_integer(accept) or not are_integer(reject):
226
        raise BadRequest("Serials should be integer.")
227

    
228
    result = qh.resolve_pending_commissions(clientkey=client_key,
229
                                            accept_set=accept,
230
                                            reject_set=reject)
231
    accepted, rejected, notFound, conflicting = result
232
    notFound = [(serial, notFoundCF(serial)) for serial in notFound]
233
    conflicting = [(serial, conflictingCF(serial)) for serial in conflicting]
234
    cloudfaults = notFound + conflicting
235
    data = {'accepted': accepted,
236
            'rejected': rejected,
237
            'failed': cloudfaults
238
            }
239

    
240
    return json_response(data)
241

    
242

    
243
@api.api_method(http_method='GET', token_required=True, user_required=False)
244
@service_from_token
245
def get_commission(request, serial):
246
    data = request.GET
247
    client_key = str(request.service_instance)
248
    try:
249
        serial = int(serial)
250
    except ValueError:
251
        raise BadRequest("Serial should be an integer.")
252

    
253
    try:
254
        data = qh.get_commission(clientkey=client_key,
255
                                 serial=serial)
256
        status_code = 200
257
        return json_response(data, status_code)
258
    except qh_exception.NoCommissionError as e:
259
        return HttpResponse(status=404)
260

    
261

    
262
@csrf_exempt
263
@api.api_method(http_method='POST', token_required=True, user_required=False)
264
@service_from_token
265
@commit_on_success_strict()
266
def serial_action(request, serial):
267
    data = request.raw_post_data
268
    try:
269
        input_data = json.loads(data)
270
    except json.JSONDecodeError:
271
        raise BadRequest("POST data should be in json format.")
272

    
273
    try:
274
        serial = int(serial)
275
    except ValueError:
276
        raise BadRequest("Serial should be an integer.")
277

    
278
    client_key = str(request.service_instance)
279

    
280
    accept = 'accept' in input_data
281
    reject = 'reject' in input_data
282

    
283
    if accept == reject:
284
        raise BadRequest('Specify either accept or reject action.')
285

    
286
    result = qh.resolve_pending_commission(clientkey=client_key,
287
                                           serial=serial,
288
                                           accept=accept)
289
    response = HttpResponse()
290
    if not result:
291
        response.status_code = 404
292

    
293
    return response