blob: 212d41d31ab23e04c3e382aef00c8000c25d34ee [file] [log] [blame]
ZhiQiang Fan39f97222013-09-20 04:49:44 +08001# Copyright 2012 OpenStack Foundation
Brant Knudsonc7ca3342013-03-28 21:08:50 -05002# Copyright 2013 IBM Corp.
Jay Pipes3f981df2012-03-27 18:59:44 -04003# All Rights Reserved.
4#
5# Licensed under the Apache License, Version 2.0 (the "License"); you may
6# not use this file except in compliance with the License. You may obtain
7# a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14# License for the specific language governing permissions and limitations
15# under the License.
16
Attila Fazekas55f6d8c2013-03-10 10:32:54 +010017import collections
Attila Fazekas11d2a772013-01-29 17:46:52 +010018import hashlib
Matthew Treinisha83a16e2012-12-07 13:44:02 -050019import json
Dan Smithba6cb162012-08-14 07:22:42 -070020from lxml import etree
Attila Fazekas11d2a772013-01-29 17:46:52 +010021import re
Eoghan Glynna5598972012-03-01 09:27:17 -050022import time
Jay Pipes3f981df2012-03-27 18:59:44 -040023
Mate Lakat23a58a32013-08-23 02:06:22 +010024from tempest.common import http
Matthew Treinish684d8992014-01-30 16:27:40 +000025from tempest import config
Daryl Wallecked8bef32011-12-05 23:02:08 -060026from tempest import exceptions
Matthew Treinishf4a9b0f2013-07-26 16:58:26 -040027from tempest.openstack.common import log as logging
dwallecke62b9f02012-10-10 23:34:42 -050028from tempest.services.compute.xml.common import xml_to_json
Daryl Walleck1465d612011-11-02 02:22:15 -050029
Matthew Treinish684d8992014-01-30 16:27:40 +000030CONF = config.CONF
31
Eoghan Glynna5598972012-03-01 09:27:17 -050032# redrive rate limited calls at most twice
33MAX_RECURSION_DEPTH = 2
Attila Fazekas11d2a772013-01-29 17:46:52 +010034TOKEN_CHARS_RE = re.compile('^[-A-Za-z0-9+/=]*$')
Eoghan Glynna5598972012-03-01 09:27:17 -050035
Attila Fazekas54a42862013-07-28 22:31:06 +020036# All the successful HTTP status codes from RFC 2616
37HTTP_SUCCESS = (200, 201, 202, 203, 204, 205, 206)
38
Eoghan Glynna5598972012-03-01 09:27:17 -050039
Daryl Walleck1465d612011-11-02 02:22:15 -050040class RestClient(object):
vponomaryov67b58fe2014-02-06 19:05:41 +020041
Dan Smithba6cb162012-08-14 07:22:42 -070042 TYPE = "json"
vponomaryov67b58fe2014-02-06 19:05:41 +020043
44 # This is used by _parse_resp method
45 # Redefine it for purposes of your xml service client
46 # List should contain top-xml_tag-names of data, which is like list/array
47 # For example, in keystone it is users, roles, tenants and services
48 # All of it has children with same tag-names
49 list_tags = []
50
51 # This is used by _parse_resp method too
52 # Used for selection of dict-like xmls,
53 # like metadata for Vms in nova, and volumes in cinder
54 dict_tags = ["metadata", ]
55
Attila Fazekas11d2a772013-01-29 17:46:52 +010056 LOG = logging.getLogger(__name__)
Daryl Walleck1465d612011-11-02 02:22:15 -050057
Andrea Frittoli8bbdb162014-01-06 11:06:13 +000058 def __init__(self, auth_provider):
59 self.auth_provider = auth_provider
chris fattarsi5098fa22012-04-17 13:27:00 -070060
chris fattarsi5098fa22012-04-17 13:27:00 -070061 self.endpoint_url = 'publicURL'
Andrea Frittoli8bbdb162014-01-06 11:06:13 +000062 self.service = None
63 # The version of the API this client implements
64 self.api_version = None
65 self._skip_path = False
vponomaryov67b58fe2014-02-06 19:05:41 +020066 # NOTE(vponomaryov): self.headers is deprecated now.
67 # should be removed after excluding it from all use places.
68 # Insted of this should be used 'get_headers' method
Dan Smithba6cb162012-08-14 07:22:42 -070069 self.headers = {'Content-Type': 'application/%s' % self.TYPE,
70 'Accept': 'application/%s' % self.TYPE}
Matthew Treinish684d8992014-01-30 16:27:40 +000071 self.build_interval = CONF.compute.build_interval
72 self.build_timeout = CONF.compute.build_timeout
Attila Fazekas72c7a5f2012-12-03 17:17:23 +010073 self.general_header_lc = set(('cache-control', 'connection',
74 'date', 'pragma', 'trailer',
75 'transfer-encoding', 'via',
76 'warning'))
77 self.response_header_lc = set(('accept-ranges', 'age', 'etag',
78 'location', 'proxy-authenticate',
79 'retry-after', 'server',
80 'vary', 'www-authenticate'))
Matthew Treinish684d8992014-01-30 16:27:40 +000081 dscv = CONF.identity.disable_ssl_certificate_validation
Mate Lakat23a58a32013-08-23 02:06:22 +010082 self.http_obj = http.ClosingHttp(
83 disable_ssl_certificate_validation=dscv)
chris fattarsi5098fa22012-04-17 13:27:00 -070084
vponomaryov67b58fe2014-02-06 19:05:41 +020085 def _get_type(self):
86 return self.TYPE
87
88 def get_headers(self, accept_type=None, send_type=None):
89 # This method should be used instead of
90 # deprecated 'self.headers'
91 if accept_type is None:
92 accept_type = self._get_type()
93 if send_type is None:
94 send_type = self._get_type()
95 return {'Content-Type': 'application/%s' % send_type,
96 'Accept': 'application/%s' % accept_type}
97
DennyZhang7be75002013-09-19 06:55:11 -050098 def __str__(self):
99 STRING_LIMIT = 80
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000100 str_format = ("config:%s, service:%s, base_url:%s, "
101 "filters: %s, build_interval:%s, build_timeout:%s"
DennyZhang7be75002013-09-19 06:55:11 -0500102 "\ntoken:%s..., \nheaders:%s...")
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000103 return str_format % (CONF, self.service, self.base_url,
104 self.filters, self.build_interval,
105 self.build_timeout,
DennyZhang7be75002013-09-19 06:55:11 -0500106 str(self.token)[0:STRING_LIMIT],
vponomaryov67b58fe2014-02-06 19:05:41 +0200107 str(self.get_headers())[0:STRING_LIMIT])
DennyZhang7be75002013-09-19 06:55:11 -0500108
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000109 def _get_region(self, service):
chris fattarsi5098fa22012-04-17 13:27:00 -0700110 """
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000111 Returns the region for a specific service
chris fattarsi5098fa22012-04-17 13:27:00 -0700112 """
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000113 service_region = None
114 for cfgname in dir(CONF._config):
115 # Find all config.FOO.catalog_type and assume FOO is a service.
116 cfg = getattr(CONF, cfgname)
117 catalog_type = getattr(cfg, 'catalog_type', None)
118 if catalog_type == service:
119 service_region = getattr(cfg, 'region', None)
120 if not service_region:
121 service_region = CONF.identity.region
122 return service_region
chris fattarsi5098fa22012-04-17 13:27:00 -0700123
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000124 @property
125 def user(self):
126 return self.auth_provider.credentials.get('username', None)
Li Ma216550f2013-06-12 11:26:08 -0700127
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000128 @property
129 def tenant_name(self):
130 return self.auth_provider.credentials.get('tenant_name', None)
chris fattarsi5098fa22012-04-17 13:27:00 -0700131
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000132 @property
133 def password(self):
134 return self.auth_provider.credentials.get('password', None)
135
136 @property
137 def base_url(self):
138 return self.auth_provider.base_url(filters=self.filters)
139
140 @property
Andrea Frittoli77f9da42014-02-06 11:18:19 +0000141 def token(self):
142 return self.auth_provider.get_token()
143
144 @property
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000145 def filters(self):
146 _filters = dict(
147 service=self.service,
148 endpoint_type=self.endpoint_url,
149 region=self._get_region(self.service)
150 )
151 if self.api_version is not None:
152 _filters['api_version'] = self.api_version
153 if self._skip_path:
154 _filters['skip_path'] = self._skip_path
155 return _filters
156
157 def skip_path(self):
chris fattarsi5098fa22012-04-17 13:27:00 -0700158 """
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000159 When set, ignore the path part of the base URL from the catalog
chris fattarsi5098fa22012-04-17 13:27:00 -0700160 """
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000161 self._skip_path = True
chris fattarsi5098fa22012-04-17 13:27:00 -0700162
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000163 def reset_path(self):
Attila Fazekasb2902af2013-02-16 16:22:44 +0100164 """
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000165 When reset, use the base URL from the catalog as-is
Daryl Walleck1465d612011-11-02 02:22:15 -0500166 """
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000167 self._skip_path = False
Brant Knudsonc7ca3342013-03-28 21:08:50 -0500168
Attila Fazekas54a42862013-07-28 22:31:06 +0200169 def expected_success(self, expected_code, read_code):
170 assert_msg = ("This function only allowed to use for HTTP status"
171 "codes which explicitly defined in the RFC 2616. {0}"
172 " is not a defined Success Code!").format(expected_code)
173 assert expected_code in HTTP_SUCCESS, assert_msg
174
175 # NOTE(afazekas): the http status code above 400 is processed by
176 # the _error_checker method
177 if read_code < 400 and read_code != expected_code:
178 pattern = """Unexpected http success status code {0},
179 The expected status code is {1}"""
180 details = pattern.format(read_code, expected_code)
181 raise exceptions.InvalidHttpSuccessCode(details)
182
vponomaryov67b58fe2014-02-06 19:05:41 +0200183 def post(self, url, body, headers=None):
Daryl Walleck1465d612011-11-02 02:22:15 -0500184 return self.request('POST', url, headers, body)
185
Attila Fazekasb8aa7592013-01-26 01:25:45 +0100186 def get(self, url, headers=None):
187 return self.request('GET', url, headers)
Daryl Walleck1465d612011-11-02 02:22:15 -0500188
Daisuke Morita499bba32013-11-28 18:44:49 +0900189 def delete(self, url, headers=None, body=None):
190 return self.request('DELETE', url, headers, body)
Daryl Walleck1465d612011-11-02 02:22:15 -0500191
vponomaryov67b58fe2014-02-06 19:05:41 +0200192 def patch(self, url, body, headers=None):
rajalakshmi-ganesanab426722013-02-08 15:49:15 +0530193 return self.request('PATCH', url, headers, body)
194
vponomaryov67b58fe2014-02-06 19:05:41 +0200195 def put(self, url, body, headers=None):
Daryl Walleck1465d612011-11-02 02:22:15 -0500196 return self.request('PUT', url, headers, body)
197
dwalleck5d734432012-10-04 01:11:47 -0500198 def head(self, url, headers=None):
Larisa Ustalov6c3c7802012-11-05 12:25:19 +0200199 return self.request('HEAD', url, headers)
200
201 def copy(self, url, headers=None):
202 return self.request('COPY', url, headers)
dwalleck5d734432012-10-04 01:11:47 -0500203
Matthew Treinishc0f768f2013-03-11 14:24:16 -0400204 def get_versions(self):
205 resp, body = self.get('')
206 body = self._parse_resp(body)
207 body = body['versions']
208 versions = map(lambda x: x['id'], body)
209 return resp, versions
210
Attila Fazekas11d2a772013-01-29 17:46:52 +0100211 def _log_request(self, method, req_url, headers, body):
212 self.LOG.info('Request: ' + method + ' ' + req_url)
213 if headers:
214 print_headers = headers
215 if 'X-Auth-Token' in headers and headers['X-Auth-Token']:
216 token = headers['X-Auth-Token']
217 if len(token) > 64 and TOKEN_CHARS_RE.match(token):
218 print_headers = headers.copy()
219 print_headers['X-Auth-Token'] = "<Token omitted>"
220 self.LOG.debug('Request Headers: ' + str(print_headers))
221 if body:
222 str_body = str(body)
223 length = len(str_body)
224 self.LOG.debug('Request Body: ' + str_body[:2048])
225 if length >= 2048:
226 self.LOG.debug("Large body (%d) md5 summary: %s", length,
227 hashlib.md5(str_body).hexdigest())
228
229 def _log_response(self, resp, resp_body):
230 status = resp['status']
231 self.LOG.info("Response Status: " + status)
232 headers = resp.copy()
233 del headers['status']
Matthew Treinishe5423912013-08-13 18:07:31 -0400234 if headers.get('x-compute-request-id'):
235 self.LOG.info("Nova request id: %s" %
236 headers.pop('x-compute-request-id'))
237 elif headers.get('x-openstack-request-id'):
238 self.LOG.info("Glance request id %s" %
239 headers.pop('x-openstack-request-id'))
Attila Fazekas11d2a772013-01-29 17:46:52 +0100240 if len(headers):
241 self.LOG.debug('Response Headers: ' + str(headers))
242 if resp_body:
243 str_body = str(resp_body)
244 length = len(str_body)
245 self.LOG.debug('Response Body: ' + str_body[:2048])
246 if length >= 2048:
247 self.LOG.debug("Large body (%d) md5 summary: %s", length,
248 hashlib.md5(str_body).hexdigest())
Daryl Walleck8a707db2012-01-25 00:46:24 -0600249
Dan Smithba6cb162012-08-14 07:22:42 -0700250 def _parse_resp(self, body):
vponomaryov67b58fe2014-02-06 19:05:41 +0200251 if self._get_type() is "json":
252 body = json.loads(body)
253
254 # We assume, that if the first value of the deserialized body's
255 # item set is a dict or a list, that we just return the first value
256 # of deserialized body.
257 # Essentially "cutting out" the first placeholder element in a body
258 # that looks like this:
259 #
260 # {
261 # "users": [
262 # ...
263 # ]
264 # }
265 try:
266 # Ensure there are not more than one top-level keys
267 if len(body.keys()) > 1:
268 return body
269 # Just return the "wrapped" element
270 first_key, first_item = body.items()[0]
271 if isinstance(first_item, (dict, list)):
272 return first_item
273 except (ValueError, IndexError):
274 pass
275 return body
276 elif self._get_type() is "xml":
277 element = etree.fromstring(body)
278 if any(s in element.tag for s in self.dict_tags):
279 # Parse dictionary-like xmls (metadata, etc)
280 dictionary = {}
281 for el in element.getchildren():
282 dictionary[u"%s" % el.get("key")] = u"%s" % el.text
283 return dictionary
284 if any(s in element.tag for s in self.list_tags):
285 # Parse list-like xmls (users, roles, etc)
286 array = []
287 for child in element.getchildren():
288 array.append(xml_to_json(child))
289 return array
290
291 # Parse one-item-like xmls (user, role, etc)
292 return xml_to_json(element)
Dan Smithba6cb162012-08-14 07:22:42 -0700293
Attila Fazekas836e4782013-01-29 15:40:13 +0100294 def response_checker(self, method, url, headers, body, resp, resp_body):
295 if (resp.status in set((204, 205, 304)) or resp.status < 200 or
Pavel Sedláke267eba2013-04-03 15:56:36 +0200296 method.upper() == 'HEAD') and resp_body:
Attila Fazekas836e4782013-01-29 15:40:13 +0100297 raise exceptions.ResponseWithNonEmptyBody(status=resp.status)
Attila Fazekasc3a095b2013-08-17 09:15:44 +0200298 # NOTE(afazekas):
Attila Fazekas836e4782013-01-29 15:40:13 +0100299 # If the HTTP Status Code is 205
300 # 'The response MUST NOT include an entity.'
301 # A HTTP entity has an entity-body and an 'entity-header'.
302 # In the HTTP response specification (Section 6) the 'entity-header'
303 # 'generic-header' and 'response-header' are in OR relation.
304 # All headers not in the above two group are considered as entity
305 # header in every interpretation.
306
307 if (resp.status == 205 and
308 0 != len(set(resp.keys()) - set(('status',)) -
309 self.response_header_lc - self.general_header_lc)):
310 raise exceptions.ResponseWithEntity()
Attila Fazekasc3a095b2013-08-17 09:15:44 +0200311 # NOTE(afazekas)
Attila Fazekas836e4782013-01-29 15:40:13 +0100312 # Now the swift sometimes (delete not empty container)
313 # returns with non json error response, we can create new rest class
314 # for swift.
315 # Usually RFC2616 says error responses SHOULD contain an explanation.
316 # The warning is normal for SHOULD/SHOULD NOT case
317
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100318 # Likely it will cause an error
319 if not resp_body and resp.status >= 400:
Attila Fazekas11d2a772013-01-29 17:46:52 +0100320 self.LOG.warning("status >= 400 response with empty body")
Attila Fazekas836e4782013-01-29 15:40:13 +0100321
vponomaryov67b58fe2014-02-06 19:05:41 +0200322 def _request(self, method, url, headers=None, body=None):
Daryl Wallecke5b83d42011-11-10 14:39:02 -0600323 """A simple HTTP request interface."""
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000324 # Authenticate the request with the auth provider
325 req_url, req_headers, req_body = self.auth_provider.auth_request(
326 method, url, headers, body, self.filters)
327 self._log_request(method, req_url, req_headers, req_body)
328 # Do the actual request
329 resp, resp_body = self.http_obj.request(
330 req_url, method, headers=req_headers, body=req_body)
Attila Fazekas11d2a772013-01-29 17:46:52 +0100331 self._log_response(resp, resp_body)
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000332 # Verify HTTP response codes
333 self.response_checker(method, url, req_headers, req_body, resp,
334 resp_body)
Attila Fazekas72c7a5f2012-12-03 17:17:23 +0100335
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100336 return resp, resp_body
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500337
vponomaryov67b58fe2014-02-06 19:05:41 +0200338 def request(self, method, url, headers=None, body=None):
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100339 retry = 0
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100340
341 if headers is None:
vponomaryov67b58fe2014-02-06 19:05:41 +0200342 # NOTE(vponomaryov): if some client do not need headers,
343 # it should explicitly pass empty dict
344 headers = self.get_headers()
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100345
346 resp, resp_body = self._request(method, url,
347 headers=headers, body=body)
348
349 while (resp.status == 413 and
350 'retry-after' in resp and
351 not self.is_absolute_limit(
352 resp, self._parse_resp(resp_body)) and
353 retry < MAX_RECURSION_DEPTH):
354 retry += 1
355 delay = int(resp['retry-after'])
356 time.sleep(delay)
357 resp, resp_body = self._request(method, url,
358 headers=headers, body=body)
359 self._error_checker(method, url, headers, body,
360 resp, resp_body)
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500361 return resp, resp_body
362
363 def _error_checker(self, method, url,
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100364 headers, body, resp, resp_body):
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500365
366 # NOTE(mtreinish): Check for httplib response from glance_http. The
367 # object can't be used here because importing httplib breaks httplib2.
368 # If another object from a class not imported were passed here as
369 # resp this could possibly fail
370 if str(type(resp)) == "<type 'instance'>":
371 ctype = resp.getheader('content-type')
372 else:
373 try:
374 ctype = resp['content-type']
375 # NOTE(mtreinish): Keystone delete user responses doesn't have a
376 # content-type header. (They don't have a body) So just pretend it
377 # is set.
378 except KeyError:
379 ctype = 'application/json'
380
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100381 # It is not an error response
382 if resp.status < 400:
383 return
384
Sergey Murashovc10cca52014-01-16 12:48:47 +0400385 JSON_ENC = ['application/json', 'application/json; charset=utf-8']
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500386 # NOTE(mtreinish): This is for compatibility with Glance and swift
387 # APIs. These are the return content types that Glance api v1
388 # (and occasionally swift) are using.
Sergey Murashovc10cca52014-01-16 12:48:47 +0400389 TXT_ENC = ['text/plain', 'text/html', 'text/html; charset=utf-8',
390 'text/plain; charset=utf-8']
391 XML_ENC = ['application/xml', 'application/xml; charset=utf-8']
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500392
Sergey Murashovc10cca52014-01-16 12:48:47 +0400393 if ctype.lower() in JSON_ENC or ctype.lower() in XML_ENC:
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500394 parse_resp = True
Sergey Murashovc10cca52014-01-16 12:48:47 +0400395 elif ctype.lower() in TXT_ENC:
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500396 parse_resp = False
397 else:
398 raise exceptions.RestClientException(str(resp.status))
399
Rohit Karajgi6b1e1542012-05-14 05:55:54 -0700400 if resp.status == 401 or resp.status == 403:
Daryl Walleckced8eb82012-03-19 13:52:37 -0500401 raise exceptions.Unauthorized()
Jay Pipes5135bfc2012-01-05 15:46:49 -0500402
403 if resp.status == 404:
Daryl Walleck8a707db2012-01-25 00:46:24 -0600404 raise exceptions.NotFound(resp_body)
Jay Pipes5135bfc2012-01-05 15:46:49 -0500405
Daryl Walleckadea1fa2011-11-15 18:36:39 -0600406 if resp.status == 400:
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500407 if parse_resp:
408 resp_body = self._parse_resp(resp_body)
David Kranz28e35c52012-07-10 10:14:38 -0400409 raise exceptions.BadRequest(resp_body)
Daryl Walleckadea1fa2011-11-15 18:36:39 -0600410
David Kranz5a23d862012-02-14 09:48:55 -0500411 if resp.status == 409:
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500412 if parse_resp:
413 resp_body = self._parse_resp(resp_body)
Anju5c3e510c2013-10-18 06:40:29 +0530414 raise exceptions.Conflict(resp_body)
David Kranz5a23d862012-02-14 09:48:55 -0500415
Daryl Wallecked8bef32011-12-05 23:02:08 -0600416 if resp.status == 413:
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500417 if parse_resp:
418 resp_body = self._parse_resp(resp_body)
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100419 if self.is_absolute_limit(resp, resp_body):
420 raise exceptions.OverLimit(resp_body)
421 else:
422 raise exceptions.RateLimitExceeded(resp_body)
Brian Lamar12d9b292011-12-08 12:41:21 -0500423
Wangpana9b54c62013-02-28 11:04:32 +0800424 if resp.status == 422:
425 if parse_resp:
426 resp_body = self._parse_resp(resp_body)
427 raise exceptions.UnprocessableEntity(resp_body)
428
Daryl Wallecked8bef32011-12-05 23:02:08 -0600429 if resp.status in (500, 501):
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500430 message = resp_body
431 if parse_resp:
Rohan Kanade433994a2013-12-05 22:34:07 +0530432 try:
433 resp_body = self._parse_resp(resp_body)
434 except ValueError:
435 # If response body is a non-json string message.
436 # Use resp_body as is and raise InvalidResponseBody
437 # exception.
438 raise exceptions.InvalidHTTPResponseBody(message)
439 else:
440 # I'm seeing both computeFault
441 # and cloudServersFault come back.
442 # Will file a bug to fix, but leave as is for now.
443 if 'cloudServersFault' in resp_body:
444 message = resp_body['cloudServersFault']['message']
445 elif 'computeFault' in resp_body:
446 message = resp_body['computeFault']['message']
447 elif 'error' in resp_body: # Keystone errors
448 message = resp_body['error']['message']
449 raise exceptions.IdentityError(message)
450 elif 'message' in resp_body:
451 message = resp_body['message']
Dan Princea4b709c2012-10-10 12:27:59 -0400452
Anju5c3e510c2013-10-18 06:40:29 +0530453 raise exceptions.ServerFault(message)
Daryl Wallecked8bef32011-12-05 23:02:08 -0600454
David Kranz5a23d862012-02-14 09:48:55 -0500455 if resp.status >= 400:
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500456 if parse_resp:
457 resp_body = self._parse_resp(resp_body)
Attila Fazekas96524032013-01-29 19:52:49 +0100458 raise exceptions.RestClientException(str(resp.status))
David Kranz5a23d862012-02-14 09:48:55 -0500459
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100460 def is_absolute_limit(self, resp, resp_body):
461 if (not isinstance(resp_body, collections.Mapping) or
Pavel Sedláke267eba2013-04-03 15:56:36 +0200462 'retry-after' not in resp):
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100463 return True
vponomaryov67b58fe2014-02-06 19:05:41 +0200464 if self._get_type() is "json":
465 over_limit = resp_body.get('overLimit', None)
466 if not over_limit:
467 return True
468 return 'exceed' in over_limit.get('message', 'blabla')
469 elif self._get_type() is "xml":
470 return 'exceed' in resp_body.get('message', 'blabla')
rajalakshmi-ganesan0275a0d2013-01-11 18:26:05 +0530471
David Kranz6aceb4a2012-06-05 14:05:45 -0400472 def wait_for_resource_deletion(self, id):
Sean Daguef237ccb2013-01-04 15:19:14 -0500473 """Waits for a resource to be deleted."""
David Kranz6aceb4a2012-06-05 14:05:45 -0400474 start_time = int(time.time())
475 while True:
476 if self.is_resource_deleted(id):
477 return
478 if int(time.time()) - start_time >= self.build_timeout:
479 raise exceptions.TimeoutException
480 time.sleep(self.build_interval)
481
482 def is_resource_deleted(self, id):
483 """
484 Subclasses override with specific deletion detection.
485 """
Attila Fazekasd236b4e2013-01-26 00:44:12 +0100486 message = ('"%s" does not implement is_resource_deleted'
487 % self.__class__.__name__)
488 raise NotImplementedError(message)
Dan Smithba6cb162012-08-14 07:22:42 -0700489
490
491class RestClientXML(RestClient):
vponomaryov67b58fe2014-02-06 19:05:41 +0200492
493 # NOTE(vponomaryov): This is deprecated class
494 # and should be removed after excluding it
495 # from all service clients
496
Dan Smithba6cb162012-08-14 07:22:42 -0700497 TYPE = "xml"
498
499 def _parse_resp(self, body):
500 return xml_to_json(etree.fromstring(body))
rajalakshmi-ganesan0275a0d2013-01-11 18:26:05 +0530501
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100502 def is_absolute_limit(self, resp, resp_body):
503 if (not isinstance(resp_body, collections.Mapping) or
Pavel Sedláke267eba2013-04-03 15:56:36 +0200504 'retry-after' not in resp):
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100505 return True
506 return 'exceed' in resp_body.get('message', 'blabla')
Marc Koderer24eb89c2014-01-31 11:23:33 +0100507
508
509class NegativeRestClient(RestClient):
510 """
511 Version of RestClient that does not raise exceptions.
512 """
513 def _error_checker(self, method, url,
514 headers, body, resp, resp_body):
515 pass
516
517 def send_request(self, method, url_template, resources, body=None):
518 url = url_template % tuple(resources)
519 if method == "GET":
520 resp, body = self.get(url)
521 elif method == "POST":
vponomaryov67b58fe2014-02-06 19:05:41 +0200522 resp, body = self.post(url, body)
Marc Koderer24eb89c2014-01-31 11:23:33 +0100523 elif method == "PUT":
vponomaryov67b58fe2014-02-06 19:05:41 +0200524 resp, body = self.put(url, body)
Marc Koderer24eb89c2014-01-31 11:23:33 +0100525 elif method == "PATCH":
vponomaryov67b58fe2014-02-06 19:05:41 +0200526 resp, body = self.patch(url, body)
Marc Koderer24eb89c2014-01-31 11:23:33 +0100527 elif method == "HEAD":
528 resp, body = self.head(url)
529 elif method == "DELETE":
530 resp, body = self.delete(url)
531 elif method == "COPY":
532 resp, body = self.copy(url)
533 else:
534 assert False
535
536 return resp, body