Statistics
| Branch: | Tag: | Revision:

root / snf-common / synnefo / lib / quotaholder / http.py @ 4ab1af1a

History | View | Annotate | Download (3.4 kB)

1
# Copyright 2012 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 synnefo.lib.commissioning import Callpoint, CallError
35
from synnefo.lib.pool.http import PooledHTTPConnection
36
from .api import QuotaholderAPI
37

    
38
from json import loads as json_loads, dumps as json_dumps
39
import logging
40
from urlparse import urlparse
41

    
42
logger = logging.getLogger(__name__)
43

    
44

    
45
class QuotaholderClient(Callpoint):
46

    
47
    api_spec = QuotaholderAPI()
48

    
49
    def __init__(self, base_url, token='', poolsize=1000):
50
        super(QuotaholderClient, self).__init__()
51
        self._url = base_url
52
        parsed = urlparse(base_url)
53
        self._netloc = parsed.netloc
54
        self._scheme = parsed.scheme
55
        basepath = parsed.path
56
        if not basepath.endswith('/'):
57
            basepath += '/'
58
        self._basepath = basepath
59
        self._token = token
60
        self._poolsize = poolsize
61

    
62
    def do_make_call(self, api_call, data):
63

    
64
        gettable = ['list', 'get', 'read']
65
        method = ('GET' if any(api_call.startswith(x) for x in gettable)
66
                  else 'POST')
67

    
68
        path = self._basepath + api_call
69
        json_data = json_dumps(data)
70

    
71
        logger.debug("%s %s\n%s\n<<<\n", method, path, json_data[:128])
72
        headers = {'X-Auth-Token': self._token}
73
        with PooledHTTPConnection(scheme=self._scheme,
74
                                  netloc=self._netloc,
75
                                  size=self._poolsize) as conn:
76
            conn.request(method, path, body=json_data, headers=headers)
77
            resp = conn.getresponse()
78
            body = resp.read()
79

    
80
        logger.debug(">>>\nStatus: %s", resp.status)
81
        logger.debug("\n%s\n<<<\n", body[:128] if body else None)
82

    
83
        status = int(resp.status)
84
        if status == 200:
85
            return json_loads(body)
86
        else:
87
            try:
88
                error = json_loads(body)
89
            except ValueError:
90
                exc = CallError(body, call_error='ValueError')
91
            else:
92
                exc = CallError.from_dict(error)
93
            raise exc