Debian Codegraph @

glanceclient/common/http.py

raw symbols SCIP
1 # Copyright 2012 OpenStack Foundation
2 # All Rights Reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 import copy
17 import io
18 import json
19 import logging
20 import socket
21
22 from keystoneauth1 import adapter
23 from keystoneauth1 import exceptions as ksa_exc
24 import OpenSSL
25 from oslo_utils import importutils
26 from oslo_utils import netutils
27 import requests
28 import urllib.parse
29
30 from oslo_utils import encodeutils
31
32 from glanceclient.common import utils
33 from glanceclient import exc
34
35 osprofiler_web = importutils.try_import("osprofiler.web")
36
37 LOG = logging.getLogger(__name__)
38 USER_AGENT = 'python-glanceclient'
39 CHUNKSIZE = 1024 * 1024 # 1MiB
40 REQ_ID_HEADER = 'X-OpenStack-Request-ID'
41 TOKEN_HEADERS = ['X-Auth-Token', 'X-Service-Token']
42
43
44 def encode_headers(headers):
45 """Encodes headers.
46
47 Note: This should be used right before
48 sending anything out.
49
50 :param headers: Headers to encode
51 :returns: Dictionary with encoded headers'
52 names and values
53 """
54 # NOTE(rosmaita): This function's rejection of any header name without a
55 # corresponding value is arguably justified by RFC 7230. In any case, that
56 # behavior was already here and there is an existing unit test for it.
57
58 # Bug #1766235: According to RFC 8187, headers must be encoded as ASCII.
59 # So we first %-encode them to get them into range < 128 and then turn
60 # them into ASCII.
61 encoded_dict = {}
62 for h, v in headers.items():
63 if v is not None:
64 # if the item is token, do not quote '+' as well.
65 # NOTE(imacdonn): urllib.parse.quote() is intended for quoting the
66 # path part of a URL, but headers like x-image-meta-location
67 # include an entire URL. We should avoid encoding the colon in
68 # this case (bug #1788942)
69 safe = '=+/' if h in TOKEN_HEADERS else '/:'
70 key = urllib.parse.quote(h, safe)
71 value = urllib.parse.quote(v, safe)
72 encoded_dict[key] = value
73 return dict((encodeutils.safe_encode(h, encoding='ascii'),
74 encodeutils.safe_encode(v, encoding='ascii'))
75 for h, v in encoded_dict.items())
76
77
78 class _BaseHTTPClient(object):
79
80 @staticmethod
81 def _chunk_body(body):
82 chunk = body
83 while chunk:
84 chunk = body.read(CHUNKSIZE)
85 if not chunk:
86 break
87 yield chunk
88
89 def _set_common_request_kwargs(self, headers, kwargs):
90 """Handle the common parameters used to send the request."""
91
92 # Default Content-Type is octet-stream
93 content_type = headers.get('Content-Type', 'application/octet-stream')
94
95 # NOTE(jamielennox): remove this later. Managers should pass json= if
96 # they want to send json data.
97 data = kwargs.pop("data", None)
98 if data is not None and not isinstance(data, str):
99 try:
100 data = json.dumps(data)
101 content_type = 'application/json'
102 except TypeError:
103 # Here we assume it's
104 # a file-like object
105 # and we'll chunk it
106 data = self._chunk_body(data)
107
108 headers['Content-Type'] = content_type
109 kwargs['stream'] = content_type == 'application/octet-stream'
110
111 return data
112
113 def _handle_response(self, resp):
114 if not resp.ok:
115 LOG.debug("Request returned failure status %s.", resp.status_code)
116 raise exc.from_response(resp, resp.content)
117 elif (resp.status_code == requests.codes.MULTIPLE_CHOICES and
118 resp.request.path_url != '/versions'):
119 # NOTE(flaper87): Eventually, we'll remove the check on `versions`
120 # which is a bug (1491350) on the server.
121 raise exc.from_response(resp)
122
123 content_type = resp.headers.get('Content-Type')
124
125 # Read body into string if it isn't obviously image data
126 if content_type == 'application/octet-stream':
127 # Do not read all response in memory when downloading an image.
128 body_iter = _close_after_stream(resp, CHUNKSIZE)
129 else:
130 content = resp.text
131 if content_type and content_type.startswith('application/json'):
132 # Let's use requests json method, it should take care of
133 # response encoding
134 body_iter = resp.json()
135 else:
136 body_iter = io.StringIO(content)
137 try:
138 body_iter = json.loads(''.join([c for c in body_iter]))
139 except ValueError:
140 body_iter = None
141
142 return resp, body_iter
143
144
145 class HTTPClient(_BaseHTTPClient):
146
147 def __init__(self, endpoint, **kwargs):
148 self.endpoint = endpoint
149 self.identity_headers = kwargs.get('identity_headers')
150 self.auth_token = kwargs.get('token')
151 self.language_header = kwargs.get('language_header')
152 self.global_request_id = kwargs.get('global_request_id')
153 if self.identity_headers:
154 self.auth_token = self.identity_headers.pop('X-Auth-Token',
155 self.auth_token)
156
157 self.session = requests.Session()
158 self.session.headers["User-Agent"] = USER_AGENT
159
160 if self.language_header:
161 self.session.headers["Accept-Language"] = self.language_header
162
163 self.timeout = float(kwargs.get('timeout', 600))
164
165 if self.endpoint.startswith("https"):
166
167 if kwargs.get('insecure', False) is True:
168 self.session.verify = False
169 else:
170 if kwargs.get('cacert', None) != '':
171 self.session.verify = kwargs.get('cacert', True)
172
173 self.session.cert = (kwargs.get('cert_file'),
174 kwargs.get('key_file'))
175
176 def __del__(self):
177 if self.session:
178 try:
179 self.session.close()
180 except Exception as e:
181 LOG.exception(e)
182 finally:
183 self.session = None
184
185 @staticmethod
186 def parse_endpoint(endpoint):
187 return netutils.urlsplit(endpoint)
188
189 def log_curl_request(self, method, url, headers, data, kwargs):
190 curl = ['curl -g -i -X %s' % method]
191
192 headers = copy.deepcopy(headers)
193 headers.update(self.session.headers)
194
195 for (key, value) in headers.items():
196 header = '-H \'%s: %s\'' % utils.safe_header(key, value)
197 curl.append(header)
198
199 if not self.session.verify:
200 curl.append('-k')
201 else:
202 if isinstance(self.session.verify, str):
203 curl.append(' --cacert %s' % self.session.verify)
204
205 if self.session.cert:
206 curl.append(' --cert %s --key %s' % self.session.cert)
207
208 if data and isinstance(data, str):
209 curl.append('-d \'%s\'' % data)
210
211 curl.append(url)
212
213 msg = ' '.join([encodeutils.safe_decode(item, errors='ignore')
214 for item in curl])
215 LOG.debug(msg)
216
217 @staticmethod
218 def log_http_response(resp):
219 status = (resp.raw.version / 10.0, resp.status_code, resp.reason)
220 dump = ['\nHTTP/%.1f %s %s' % status]
221 headers = resp.headers.items()
222 dump.extend(['%s: %s' % utils.safe_header(k, v) for k, v in headers])
223 dump.append('')
224 content_type = resp.headers.get('Content-Type')
225
226 if content_type != 'application/octet-stream':
227 dump.extend([resp.text, ''])
228 LOG.debug('\n'.join([encodeutils.safe_decode(x, errors='ignore')
229 for x in dump]))
230
231 def _request(self, method, url, **kwargs):
232 """Send an http request with the specified characteristics.
233
234 Wrapper around httplib.HTTP(S)Connection.request to handle tasks such
235 as setting headers and error handling.
236 """
237 # Copy the kwargs so we can reuse the original in case of redirects
238 headers = copy.deepcopy(kwargs.pop('headers', {}))
239
240 if self.identity_headers:
241 for k, v in self.identity_headers.items():
242 headers.setdefault(k, v)
243
244 data = self._set_common_request_kwargs(headers, kwargs)
245
246 # add identity header to the request
247 if not headers.get('X-Auth-Token'):
248 headers['X-Auth-Token'] = self.auth_token
249
250 if self.global_request_id:
251 headers.setdefault(REQ_ID_HEADER, self.global_request_id)
252
253 if osprofiler_web:
254 headers.update(osprofiler_web.get_trace_id_headers())
255
256 # Note(flaper87): Before letting headers / url fly,
257 # they should be encoded otherwise httplib will
258 # complain.
259 headers = encode_headers(headers)
260
261 if self.endpoint.endswith("/") or url.startswith("/"):
262 conn_url = "%s%s" % (self.endpoint, url)
263 else:
264 conn_url = "%s/%s" % (self.endpoint, url)
265 self.log_curl_request(method, conn_url, headers, data, kwargs)
266
267 try:
268 resp = self.session.request(method,
269 conn_url,
270 data=data,
271 headers=headers,
272 timeout=self.timeout,
273 **kwargs)
274 except requests.exceptions.Timeout as e:
275 message = ("Error communicating with %(url)s: %(e)s" %
276 dict(url=conn_url, e=e))
277 raise exc.InvalidEndpoint(message=message)
278 except requests.exceptions.ConnectionError as e:
279 message = ("Error finding address for %(url)s: %(e)s" %
280 dict(url=conn_url, e=e))
281 raise exc.CommunicationError(message=message)
282 except socket.gaierror as e:
283 message = "Error finding address for %s: %s" % (
284 self.endpoint_hostname, e)
285 raise exc.InvalidEndpoint(message=message)
286 except (socket.error, socket.timeout, IOError) as e:
287 endpoint = self.endpoint
288 message = ("Error communicating with %(endpoint)s %(e)s" %
289 {'endpoint': endpoint, 'e': e})
290 raise exc.CommunicationError(message=message)
291 except OpenSSL.SSL.Error as e:
292 message = ("SSL Error communicating with %(url)s: %(e)s" %
293 {'url': conn_url, 'e': e})
294 raise exc.CommunicationError(message=message)
295
296 # log request-id for each api call
297 request_id = resp.headers.get('x-openstack-request-id')
298 if request_id:
299 LOG.debug('%(method)s call to image for '
300 '%(url)s used request id '
301 '%(response_request_id)s',
302 {'method': resp.request.method,
303 'url': resp.url,
304 'response_request_id': request_id})
305
306 resp, body_iter = self._handle_response(resp)
307 self.log_http_response(resp)
308 return resp, body_iter
309
310 def head(self, url, **kwargs):
311 return self._request('HEAD', url, **kwargs)
312
313 def get(self, url, **kwargs):
314 return self._request('GET', url, **kwargs)
315
316 def post(self, url, **kwargs):
317 return self._request('POST', url, **kwargs)
318
319 def put(self, url, **kwargs):
320 return self._request('PUT', url, **kwargs)
321
322 def patch(self, url, **kwargs):
323 return self._request('PATCH', url, **kwargs)
324
325 def delete(self, url, **kwargs):
326 return self._request('DELETE', url, **kwargs)
327
328
329 def _close_after_stream(response, chunk_size):
330 """Iterate over the content and ensure the response is closed after."""
331 # Yield each chunk in the response body
332 for chunk in response.iter_content(chunk_size=chunk_size):
333 yield chunk
334 # Once we're done streaming the body, ensure everything is closed.
335 # This will return the connection to the HTTPConnectionPool in urllib3
336 # and ideally reduce the number of HTTPConnectionPool full warnings.
337 response.close()
338
339
340 class SessionClient(adapter.Adapter, _BaseHTTPClient):
341
342 def __init__(self, session, **kwargs):
343 kwargs.setdefault('user_agent', USER_AGENT)
344 kwargs.setdefault('service_type', 'image')
345 super(SessionClient, self).__init__(session, **kwargs)
346
347 def request(self, url, method, **kwargs):
348 headers = kwargs.pop('headers', {})
349 if self.global_request_id:
350 headers.setdefault(REQ_ID_HEADER, self.global_request_id)
351
352 kwargs['raise_exc'] = False
353 data = self._set_common_request_kwargs(headers, kwargs)
354 try:
355 # NOTE(pumaranikar): To avoid bug #1641239, no modification of
356 # headers should be allowed after encode_headers() is called.
357 resp = super(SessionClient,
358 self).request(url,
359 method,
360 headers=encode_headers(headers),
361 data=data,
362 **kwargs)
363 except ksa_exc.ConnectTimeout as e:
364 conn_url = self.get_endpoint(auth=kwargs.get('auth'))
365 conn_url = "%s/%s" % (conn_url.rstrip('/'), url.lstrip('/'))
366 message = ("Error communicating with %(url)s %(e)s" %
367 dict(url=conn_url, e=e))
368 raise exc.InvalidEndpoint(message=message)
369 except ksa_exc.ConnectFailure as e:
370 conn_url = self.get_endpoint(auth=kwargs.get('auth'))
371 conn_url = "%s/%s" % (conn_url.rstrip('/'), url.lstrip('/'))
372 message = ("Error finding address for %(url)s: %(e)s" %
373 dict(url=conn_url, e=e))
374 raise exc.CommunicationError(message=message)
375
376 return self._handle_response(resp)
377
378
379 def get_http_client(endpoint=None, session=None, **kwargs):
380 if session:
381 return SessionClient(session, **kwargs)
382 elif endpoint:
383 return HTTPClient(endpoint, **kwargs)
384 else:
385 raise AttributeError('Constructing a client must contain either an '
386 'endpoint or a session')