Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / connection / kamakicon.py @ b9d07587

History | View | Annotate | Download (4.6 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 .pool.http import get_http_connection
36
from synnefo.lib.pool.http import get_http_connection
37
from kamaki.clients.connection import HTTPConnection, HTTPResponse, HTTPConnectionError
38
from gevent.dns import DNSError
39

    
40
from json import loads
41

    
42
from time import sleep
43
from httplib import ResponseNotReady
44

    
45
class KamakiHTTPResponse(HTTPResponse):
46

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

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

    
69
    @property 
70
    def text(self):
71
        self._get_response()
72
        return self._content
73
    @text.setter
74
    def test(self, v):
75
        pass
76

    
77
    @property 
78
    def json(self):
79
        self._get_response()
80
        try:
81
            return loads(self._content)
82
        except ValueError as err:
83
            HTTPConnectionError('Response not formated in JSON', details=unicode(err), status=702)
84
    @json.setter
85
    def json(self, v):
86
        pass
87

    
88
    def release(self):
89
        if not self.prefetched:
90
            self.request.close()
91

    
92

    
93
class KamakiHTTPConnection(HTTPConnection):
94

    
95
    def _retrieve_connection_info(self, extra_params={}):
96
        """ return (scheme, netloc, url?with&params) """
97
        url = self.url
98
        params = dict(self.params)
99
        for k,v in extra_params.items():
100
            params[k] = v
101
        for i,(key, val) in enumerate(params.items()):
102
            param_str = ('?' if i == 0 else '&') + unicode(key) 
103
            if val is not None:
104
                param_str+= '='+unicode(val)
105
            url += param_str
106

    
107
        parsed = urlparse(self.url)
108
        self.url = url
109
        return (parsed.scheme, parsed.netloc)
110

    
111
    def perform_request(self, method=None, data=None, async_headers={}, async_params={}):
112
        (scheme, netloc) = self._retrieve_connection_info(extra_params=async_params)
113
        headers = dict(self.headers)
114
        for k,v in async_headers.items():
115
            headers[k] = v
116

    
117
        #de-unicode headers to prepare them for http
118
        http_headers = {}
119
        for k,v in headers.items():
120
            http_headers[str(k)] = str(v)
121

    
122
        #get connection from pool
123
        conn = get_http_connection(netloc=netloc, scheme=scheme)
124
        try:
125
            #Be carefull, all non-body variables should not be unicode
126
            conn.request(method = str(method.upper()),
127
                url=str(self.url),
128
                headers=http_headers,
129
                body=data)
130
        except Exception as err:
131
            conn.close()
132
            if isinstance(err, DNSError):
133
                raise HTTPConnectionError('Cannot connect to %s'%self.url, status=701,
134
                    details='%s: %s'%(type(err),unicode(err)))
135
            raise
136
        return KamakiHTTPResponse(conn)