Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / connection / kamakicon.py @ 5d16ef46

History | View | Annotate | Download (6.3 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, self.list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, self.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 urlparse import urlparse
35
from objpool.http import get_http_connection
36
from kamaki.clients.connection import KamakiConnection, KamakiResponse
37
from kamaki.clients.connection.errors import KamakiConnectionError
38
from kamaki.clients.connection.errors import KamakiResponseError
39

    
40
from json import loads
41

    
42
from time import sleep
43
from httplib import ResponseNotReady
44

    
45

    
46
class KamakiHTTPResponse(KamakiResponse):
47

    
48
    def _get_response(self):
49
        if self.prefetched:
50
            return
51

    
52
        ready = False
53
        while not ready:
54
            try:
55
                r = self.request.getresponse()
56
            except ResponseNotReady:
57
                sleep(0.001)
58
                continue
59
            break
60
        self.prefetched = True
61
        headers = {}
62
        for k, v in r.getheaders():
63
            headers.update({k: v})
64
        self.headers = headers
65
        self.content = r.read()
66
        self.status_code = r.status
67
        self.status = r.reason
68
        self.request.close()
69

    
70
    @property
71
    def text(self):
72
        """
73
        :returns: (str) content
74
        """
75
        self._get_response()
76
        return unicode(self._content)
77

    
78
    @text.setter
79
    def text(self, v):
80
        pass
81

    
82
    @property
83
    def json(self):
84
        """
85
        :returns: (dict) the json-formated content
86

87
        :raises KamakiResponseError: if content is not json formated
88
        """
89
        self._get_response()
90
        try:
91
            return loads(self._content)
92
        except ValueError as err:
93
            KamakiResponseError('Response not formated in JSON - %s' % err)
94

    
95
    @json.setter
96
    def json(self, v):
97
        pass
98

    
99
    def release(self):
100
        """ Release the connection. Should always be called if the response
101
        content hasn't been used.
102
        """
103
        if not self.prefetched:
104
            self.request.close()
105

    
106

    
107
class KamakiHTTPConnection(KamakiConnection):
108

    
109
    def _retrieve_connection_info(self, extra_params={}):
110
        """
111
        :param extra_params: (dict) key:val for url parameters
112

113
        :returns: (scheme, netloc, url?with&params)
114
        """
115
        if self.url:
116
            url = self.url if self.url[-1] == '/' else (self.url + '/')
117
        else:
118
            url = 'http://127.0.0.1'
119
        if self.path:
120
            url += self.path[1:] if self.path[0] == '/' else self.path
121
        params = dict(self.params)
122
        params.update(extra_params)
123
        for i, (key, val) in enumerate(params.items()):
124
            url += '%s%s%s' % (
125
                '&' if i else '?',
126
                key,
127
                '=%s' % val if val else '')
128

    
129
        parsed = urlparse(url)
130
        self.url = url
131
        self.path = parsed.path or '/'
132
        if parsed.query:
133
            self.path += '?%s' % parsed.query
134
        return (parsed.scheme, parsed.netloc)
135

    
136
    def perform_request(
137
            self,
138
            method=None, data=None, async_headers={}, async_params={}):
139
        """
140
        :param method: (str) http method ('get', 'post', etc.)
141

142
        :param data: (binary object)
143

144
        :param async_headers: (dict) key:val headers that are used only for one
145
            request instance as opposed to self.headers, which remain to be
146
            used by following or parallel requests
147

148
        :param async_params: (dict) key:val url parameters that are used only
149
            for one request instance as opposed to self.params, which remain to
150
            be used by following or parallel requests
151

152
        :returns: (KamakiHTTPResponse) a response object
153

154
        :raises KamakiConnectionError: Connection failures
155
        """
156
        (scheme, netloc) = self._retrieve_connection_info(async_params)
157
        headers = dict(self.headers)
158
        for k, v in async_headers.items():
159
            headers[k] = v
160

    
161
        #de-unicode headers to prepare them for http
162
        http_headers = {}
163
        for k, v in headers.items():
164
            http_headers[str(k)] = str(v)
165

    
166
        #get connection from pool
167
        try:
168
            conn = get_http_connection(netloc=netloc, scheme=scheme)
169
        except ValueError as ve:
170
            raise KamakiConnectionError(
171
                'Cannot establish connection to %s %s' % (self.url, ve),
172
                errno=-1)
173
        try:
174
            #Be carefull, all non-body variables should not be unicode
175
            conn.request(
176
                method=str(method.upper()),
177
                url=str(self.path),
178
                headers=http_headers,
179
                body=data)
180
        except IOError as ioe:
181
            raise KamakiConnectionError(
182
                'Cannot connect to %s: %s' % (self.url, ioe.strerror),
183
                errno=ioe.errno)
184
        except Exception as err:
185
            from traceback import format_stack
186
            from kamaki.clients import recvlog
187
            recvlog.debug('\n'.join(['%s' % type(err)] + format_stack()))
188
            conn.close()
189
            raise
190
        return KamakiHTTPResponse(conn)