root / kamaki / clients / __init__.py @ 2b74ab4a
History | View | Annotate | Download (8.4 kB)
1 |
# Copyright 2011-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 threading import Thread |
35 |
from json import dumps, loads |
36 |
from time import time |
37 |
import logging |
38 |
from kamaki.clients.connection.kamakicon import KamakiHTTPConnection |
39 |
|
40 |
sendlog = logging.getLogger('clients.send')
|
41 |
recvlog = logging.getLogger('clients.recv')
|
42 |
|
43 |
|
44 |
class ClientError(Exception): |
45 |
def __init__(self, message, status=0, details=[]): |
46 |
try:
|
47 |
serv_stat, sep, new_msg = message.partition('{')
|
48 |
new_msg = sep + new_msg |
49 |
json_msg = loads(new_msg) |
50 |
key = json_msg.keys()[0]
|
51 |
|
52 |
json_msg = json_msg[key] |
53 |
message = '%s %s (%s)\n' % (serv_stat, key, json_msg['message'])\ |
54 |
if 'message' in json_msg else '%s %s' % (serv_stat, key) |
55 |
if 'code' in json_msg: |
56 |
status = json_msg['code']
|
57 |
if 'details' in json_msg: |
58 |
if not details: |
59 |
details = [] |
60 |
elif not isinstance(details, list): |
61 |
details = [details] |
62 |
if json_msg['details']: |
63 |
details.append(json_msg['details'])
|
64 |
except:
|
65 |
pass
|
66 |
|
67 |
super(ClientError, self).__init__(message) |
68 |
self.status = status
|
69 |
self.details = details
|
70 |
|
71 |
|
72 |
class SilentEvent(Thread): |
73 |
""" Thread-run method(*args, **kwargs)
|
74 |
put exception in exception_bucket
|
75 |
"""
|
76 |
def __init__(self, method, *args, **kwargs): |
77 |
super(self.__class__, self).__init__() |
78 |
self.method = method
|
79 |
self.args = args
|
80 |
self.kwargs = kwargs
|
81 |
|
82 |
@property
|
83 |
def exception(self): |
84 |
return getattr(self, '_exception', False) |
85 |
|
86 |
@property
|
87 |
def value(self): |
88 |
return getattr(self, '_value', None) |
89 |
|
90 |
def run(self): |
91 |
try:
|
92 |
self._value = self.method(*(self.args), **(self.kwargs)) |
93 |
except Exception as e: |
94 |
print('______\n%s\n_______' % e)
|
95 |
self._exception = e
|
96 |
|
97 |
class Client(object): |
98 |
POOL_SIZE = 7
|
99 |
|
100 |
def __init__(self, base_url, token, http_client=KamakiHTTPConnection()): |
101 |
self.base_url = base_url
|
102 |
self.token = token
|
103 |
self.headers = {}
|
104 |
self.DATE_FORMATS = ["%a %b %d %H:%M:%S %Y", |
105 |
"%A, %d-%b-%y %H:%M:%S GMT",
|
106 |
"%a, %d %b %Y %H:%M:%S GMT"]
|
107 |
self.http_client = http_client
|
108 |
|
109 |
def _init_thread_limit(self, limit=1): |
110 |
self._thread_limit = limit
|
111 |
self._elapsed_old = 0.0 |
112 |
self._elapsed_new = 0.0 |
113 |
|
114 |
def _watch_thread_limit(self, threadlist): |
115 |
if self._elapsed_old > self._elapsed_new\ |
116 |
and self._thread_limit < self.POOL_SIZE: |
117 |
self._thread_limit += 1 |
118 |
elif self._elapsed_old < self._elapsed_new and self._thread_limit > 1: |
119 |
self._thread_limit -= 1 |
120 |
|
121 |
self._elapsed_old = self._elapsed_new |
122 |
if len(threadlist) >= self._thread_limit: |
123 |
self._elapsed_new = 0.0 |
124 |
for thread in threadlist: |
125 |
begin_time = time() |
126 |
thread.join() |
127 |
self._elapsed_new += time() - begin_time
|
128 |
self._elapsed_new = self._elapsed_new / len(threadlist) |
129 |
return []
|
130 |
return threadlist
|
131 |
|
132 |
def _raise_for_status(self, r): |
133 |
status_msg = getattr(r, 'status', '') |
134 |
try:
|
135 |
message = '%s %s\n' % (status_msg, r.text)
|
136 |
except:
|
137 |
message = '%s %s\n' % (status_msg, r)
|
138 |
status = getattr(r, 'status_code', getattr(r, 'status', 0)) |
139 |
raise ClientError(message, status=status)
|
140 |
|
141 |
def set_header(self, name, value, iff=True): |
142 |
"""Set a header 'name':'value'"""
|
143 |
if value is not None and iff: |
144 |
self.http_client.set_header(name, value)
|
145 |
|
146 |
def set_param(self, name, value=None, iff=True): |
147 |
if iff:
|
148 |
self.http_client.set_param(name, value)
|
149 |
|
150 |
def set_default_header(self, name, value): |
151 |
self.http_client.headers.setdefault(name, value)
|
152 |
|
153 |
def request(self, |
154 |
method, |
155 |
path, |
156 |
async_headers={}, |
157 |
async_params={}, |
158 |
**kwargs): |
159 |
"""In threaded/asynchronous requests, headers and params are not safe
|
160 |
Therefore, the standard self.set_header/param system can be used only
|
161 |
for headers and params that are common for all requests. All other
|
162 |
params and headers should passes as
|
163 |
@param async_headers
|
164 |
@async_params
|
165 |
E.g. in most queries the 'X-Auth-Token' header might be the same for
|
166 |
all, but the 'Range' header might be different from request to request.
|
167 |
"""
|
168 |
|
169 |
try:
|
170 |
success = kwargs.pop('success', 200) |
171 |
|
172 |
data = kwargs.pop('data', None) |
173 |
self.set_default_header('X-Auth-Token', self.token) |
174 |
|
175 |
if 'json' in kwargs: |
176 |
data = dumps(kwargs.pop('json'))
|
177 |
self.set_default_header('Content-Type', 'application/json') |
178 |
if data:
|
179 |
self.set_default_header('Content-Length', unicode(len(data))) |
180 |
|
181 |
self.http_client.url = self.base_url |
182 |
self.http_client.path = path
|
183 |
r = self.http_client.perform_request(method,
|
184 |
data, |
185 |
async_headers, |
186 |
async_params) |
187 |
|
188 |
req = self.http_client
|
189 |
sendlog.info('%s %s', method, req.url)
|
190 |
headers = dict(req.headers)
|
191 |
headers.update(async_headers) |
192 |
|
193 |
for key, val in headers.items(): |
194 |
sendlog.info('\t%s: %s', key, val)
|
195 |
sendlog.info('')
|
196 |
if data:
|
197 |
sendlog.info('%s', data)
|
198 |
|
199 |
recvlog.info('%d %s', r.status_code, r.status)
|
200 |
for key, val in r.headers.items(): |
201 |
recvlog.info('%s: %s', key, val)
|
202 |
if r.content:
|
203 |
recvlog.debug(r.content) |
204 |
|
205 |
except Exception as err: |
206 |
from traceback import print_stack |
207 |
recvlog.debug(print_stack) |
208 |
self.http_client.reset_headers()
|
209 |
self.http_client.reset_params()
|
210 |
raise ClientError('%s' % err, status=getattr(err, 'status', 0)) |
211 |
|
212 |
self.http_client.reset_headers()
|
213 |
self.http_client.reset_params()
|
214 |
|
215 |
if success is not None: |
216 |
# Success can either be an in or a collection
|
217 |
success = (success,) if isinstance(success, int) else success |
218 |
if r.status_code not in success: |
219 |
r.release() |
220 |
self._raise_for_status(r)
|
221 |
return r
|
222 |
|
223 |
def delete(self, path, **kwargs): |
224 |
return self.request('delete', path, **kwargs) |
225 |
|
226 |
def get(self, path, **kwargs): |
227 |
return self.request('get', path, **kwargs) |
228 |
|
229 |
def head(self, path, **kwargs): |
230 |
return self.request('head', path, **kwargs) |
231 |
|
232 |
def post(self, path, **kwargs): |
233 |
return self.request('post', path, **kwargs) |
234 |
|
235 |
def put(self, path, **kwargs): |
236 |
return self.request('put', path, **kwargs) |
237 |
|
238 |
def copy(self, path, **kwargs): |
239 |
return self.request('copy', path, **kwargs) |
240 |
|
241 |
def move(self, path, **kwargs): |
242 |
return self.request('move', path, **kwargs) |