blob: 03dccd469b031f2deb71141c1510e3720c6f58dd [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
JordanP5d29b2c2013-12-18 13:56:03 +000061 self.endpoint_url = None
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
Matthew Treinish684d8992014-01-30 16:27:40 +000066 self.build_interval = CONF.compute.build_interval
67 self.build_timeout = CONF.compute.build_timeout
Attila Fazekas72c7a5f2012-12-03 17:17:23 +010068 self.general_header_lc = set(('cache-control', 'connection',
69 'date', 'pragma', 'trailer',
70 'transfer-encoding', 'via',
71 'warning'))
72 self.response_header_lc = set(('accept-ranges', 'age', 'etag',
73 'location', 'proxy-authenticate',
74 'retry-after', 'server',
75 'vary', 'www-authenticate'))
Matthew Treinish684d8992014-01-30 16:27:40 +000076 dscv = CONF.identity.disable_ssl_certificate_validation
Mate Lakat23a58a32013-08-23 02:06:22 +010077 self.http_obj = http.ClosingHttp(
78 disable_ssl_certificate_validation=dscv)
chris fattarsi5098fa22012-04-17 13:27:00 -070079
vponomaryov67b58fe2014-02-06 19:05:41 +020080 def _get_type(self):
81 return self.TYPE
82
83 def get_headers(self, accept_type=None, send_type=None):
vponomaryov67b58fe2014-02-06 19:05:41 +020084 if accept_type is None:
85 accept_type = self._get_type()
86 if send_type is None:
87 send_type = self._get_type()
88 return {'Content-Type': 'application/%s' % send_type,
89 'Accept': 'application/%s' % accept_type}
90
DennyZhang7be75002013-09-19 06:55:11 -050091 def __str__(self):
92 STRING_LIMIT = 80
Andrea Frittoli8bbdb162014-01-06 11:06:13 +000093 str_format = ("config:%s, service:%s, base_url:%s, "
94 "filters: %s, build_interval:%s, build_timeout:%s"
DennyZhang7be75002013-09-19 06:55:11 -050095 "\ntoken:%s..., \nheaders:%s...")
Andrea Frittoli8bbdb162014-01-06 11:06:13 +000096 return str_format % (CONF, self.service, self.base_url,
97 self.filters, self.build_interval,
98 self.build_timeout,
DennyZhang7be75002013-09-19 06:55:11 -050099 str(self.token)[0:STRING_LIMIT],
vponomaryov67b58fe2014-02-06 19:05:41 +0200100 str(self.get_headers())[0:STRING_LIMIT])
DennyZhang7be75002013-09-19 06:55:11 -0500101
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000102 def _get_region(self, service):
chris fattarsi5098fa22012-04-17 13:27:00 -0700103 """
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000104 Returns the region for a specific service
chris fattarsi5098fa22012-04-17 13:27:00 -0700105 """
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000106 service_region = None
107 for cfgname in dir(CONF._config):
108 # Find all config.FOO.catalog_type and assume FOO is a service.
109 cfg = getattr(CONF, cfgname)
110 catalog_type = getattr(cfg, 'catalog_type', None)
111 if catalog_type == service:
112 service_region = getattr(cfg, 'region', None)
113 if not service_region:
114 service_region = CONF.identity.region
115 return service_region
chris fattarsi5098fa22012-04-17 13:27:00 -0700116
JordanP5d29b2c2013-12-18 13:56:03 +0000117 def _get_endpoint_type(self, service):
118 """
119 Returns the endpoint type for a specific service
120 """
121 # If the client requests a specific endpoint type, then be it
122 if self.endpoint_url:
123 return self.endpoint_url
124 endpoint_type = None
125 for cfgname in dir(CONF._config):
126 # Find all config.FOO.catalog_type and assume FOO is a service.
127 cfg = getattr(CONF, cfgname)
128 catalog_type = getattr(cfg, 'catalog_type', None)
129 if catalog_type == service:
130 endpoint_type = getattr(cfg, 'endpoint_type', 'publicURL')
131 break
132 # Special case for compute v3 service which hasn't its own
133 # configuration group
134 else:
135 if service == CONF.compute.catalog_v3_type:
136 endpoint_type = CONF.compute.endpoint_type
137 return endpoint_type
138
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000139 @property
140 def user(self):
141 return self.auth_provider.credentials.get('username', None)
Li Ma216550f2013-06-12 11:26:08 -0700142
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000143 @property
144 def tenant_name(self):
145 return self.auth_provider.credentials.get('tenant_name', None)
chris fattarsi5098fa22012-04-17 13:27:00 -0700146
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000147 @property
148 def password(self):
149 return self.auth_provider.credentials.get('password', None)
150
151 @property
152 def base_url(self):
153 return self.auth_provider.base_url(filters=self.filters)
154
155 @property
Andrea Frittoli77f9da42014-02-06 11:18:19 +0000156 def token(self):
157 return self.auth_provider.get_token()
158
159 @property
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000160 def filters(self):
161 _filters = dict(
162 service=self.service,
JordanP5d29b2c2013-12-18 13:56:03 +0000163 endpoint_type=self._get_endpoint_type(self.service),
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000164 region=self._get_region(self.service)
165 )
166 if self.api_version is not None:
167 _filters['api_version'] = self.api_version
168 if self._skip_path:
169 _filters['skip_path'] = self._skip_path
170 return _filters
171
172 def skip_path(self):
chris fattarsi5098fa22012-04-17 13:27:00 -0700173 """
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000174 When set, ignore the path part of the base URL from the catalog
chris fattarsi5098fa22012-04-17 13:27:00 -0700175 """
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000176 self._skip_path = True
chris fattarsi5098fa22012-04-17 13:27:00 -0700177
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000178 def reset_path(self):
Attila Fazekasb2902af2013-02-16 16:22:44 +0100179 """
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000180 When reset, use the base URL from the catalog as-is
Daryl Walleck1465d612011-11-02 02:22:15 -0500181 """
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000182 self._skip_path = False
Brant Knudsonc7ca3342013-03-28 21:08:50 -0500183
Attila Fazekas54a42862013-07-28 22:31:06 +0200184 def expected_success(self, expected_code, read_code):
185 assert_msg = ("This function only allowed to use for HTTP status"
186 "codes which explicitly defined in the RFC 2616. {0}"
187 " is not a defined Success Code!").format(expected_code)
188 assert expected_code in HTTP_SUCCESS, assert_msg
189
190 # NOTE(afazekas): the http status code above 400 is processed by
191 # the _error_checker method
192 if read_code < 400 and read_code != expected_code:
193 pattern = """Unexpected http success status code {0},
194 The expected status code is {1}"""
195 details = pattern.format(read_code, expected_code)
196 raise exceptions.InvalidHttpSuccessCode(details)
197
vponomaryov67b58fe2014-02-06 19:05:41 +0200198 def post(self, url, body, headers=None):
Daryl Walleck1465d612011-11-02 02:22:15 -0500199 return self.request('POST', url, headers, body)
200
Attila Fazekasb8aa7592013-01-26 01:25:45 +0100201 def get(self, url, headers=None):
202 return self.request('GET', url, headers)
Daryl Walleck1465d612011-11-02 02:22:15 -0500203
Daisuke Morita499bba32013-11-28 18:44:49 +0900204 def delete(self, url, headers=None, body=None):
205 return self.request('DELETE', url, headers, body)
Daryl Walleck1465d612011-11-02 02:22:15 -0500206
vponomaryov67b58fe2014-02-06 19:05:41 +0200207 def patch(self, url, body, headers=None):
rajalakshmi-ganesanab426722013-02-08 15:49:15 +0530208 return self.request('PATCH', url, headers, body)
209
vponomaryov67b58fe2014-02-06 19:05:41 +0200210 def put(self, url, body, headers=None):
Daryl Walleck1465d612011-11-02 02:22:15 -0500211 return self.request('PUT', url, headers, body)
212
dwalleck5d734432012-10-04 01:11:47 -0500213 def head(self, url, headers=None):
Larisa Ustalov6c3c7802012-11-05 12:25:19 +0200214 return self.request('HEAD', url, headers)
215
216 def copy(self, url, headers=None):
217 return self.request('COPY', url, headers)
dwalleck5d734432012-10-04 01:11:47 -0500218
Matthew Treinishc0f768f2013-03-11 14:24:16 -0400219 def get_versions(self):
220 resp, body = self.get('')
221 body = self._parse_resp(body)
Matthew Treinishc0f768f2013-03-11 14:24:16 -0400222 versions = map(lambda x: x['id'], body)
223 return resp, versions
224
Attila Fazekas11d2a772013-01-29 17:46:52 +0100225 def _log_request(self, method, req_url, headers, body):
226 self.LOG.info('Request: ' + method + ' ' + req_url)
227 if headers:
228 print_headers = headers
229 if 'X-Auth-Token' in headers and headers['X-Auth-Token']:
230 token = headers['X-Auth-Token']
231 if len(token) > 64 and TOKEN_CHARS_RE.match(token):
232 print_headers = headers.copy()
233 print_headers['X-Auth-Token'] = "<Token omitted>"
234 self.LOG.debug('Request Headers: ' + str(print_headers))
235 if body:
236 str_body = str(body)
237 length = len(str_body)
238 self.LOG.debug('Request Body: ' + str_body[:2048])
239 if length >= 2048:
240 self.LOG.debug("Large body (%d) md5 summary: %s", length,
241 hashlib.md5(str_body).hexdigest())
242
243 def _log_response(self, resp, resp_body):
244 status = resp['status']
245 self.LOG.info("Response Status: " + status)
246 headers = resp.copy()
247 del headers['status']
Matthew Treinishe5423912013-08-13 18:07:31 -0400248 if headers.get('x-compute-request-id'):
Matthew Treinishac8dc992014-02-13 19:33:34 -0500249 self.LOG.info("Nova/Cinder request id: %s" %
Matthew Treinishe5423912013-08-13 18:07:31 -0400250 headers.pop('x-compute-request-id'))
251 elif headers.get('x-openstack-request-id'):
Matthew Treinishac8dc992014-02-13 19:33:34 -0500252 self.LOG.info("OpenStack request id %s" %
Matthew Treinishe5423912013-08-13 18:07:31 -0400253 headers.pop('x-openstack-request-id'))
Attila Fazekas11d2a772013-01-29 17:46:52 +0100254 if len(headers):
255 self.LOG.debug('Response Headers: ' + str(headers))
256 if resp_body:
257 str_body = str(resp_body)
258 length = len(str_body)
259 self.LOG.debug('Response Body: ' + str_body[:2048])
260 if length >= 2048:
261 self.LOG.debug("Large body (%d) md5 summary: %s", length,
262 hashlib.md5(str_body).hexdigest())
Daryl Walleck8a707db2012-01-25 00:46:24 -0600263
Dan Smithba6cb162012-08-14 07:22:42 -0700264 def _parse_resp(self, body):
vponomaryov67b58fe2014-02-06 19:05:41 +0200265 if self._get_type() is "json":
266 body = json.loads(body)
267
268 # We assume, that if the first value of the deserialized body's
269 # item set is a dict or a list, that we just return the first value
270 # of deserialized body.
271 # Essentially "cutting out" the first placeholder element in a body
272 # that looks like this:
273 #
274 # {
275 # "users": [
276 # ...
277 # ]
278 # }
279 try:
280 # Ensure there are not more than one top-level keys
281 if len(body.keys()) > 1:
282 return body
283 # Just return the "wrapped" element
284 first_key, first_item = body.items()[0]
285 if isinstance(first_item, (dict, list)):
286 return first_item
287 except (ValueError, IndexError):
288 pass
289 return body
290 elif self._get_type() is "xml":
291 element = etree.fromstring(body)
292 if any(s in element.tag for s in self.dict_tags):
293 # Parse dictionary-like xmls (metadata, etc)
294 dictionary = {}
295 for el in element.getchildren():
296 dictionary[u"%s" % el.get("key")] = u"%s" % el.text
297 return dictionary
298 if any(s in element.tag for s in self.list_tags):
299 # Parse list-like xmls (users, roles, etc)
300 array = []
301 for child in element.getchildren():
302 array.append(xml_to_json(child))
303 return array
304
305 # Parse one-item-like xmls (user, role, etc)
306 return xml_to_json(element)
Dan Smithba6cb162012-08-14 07:22:42 -0700307
Attila Fazekas836e4782013-01-29 15:40:13 +0100308 def response_checker(self, method, url, headers, body, resp, resp_body):
309 if (resp.status in set((204, 205, 304)) or resp.status < 200 or
Pavel Sedláke267eba2013-04-03 15:56:36 +0200310 method.upper() == 'HEAD') and resp_body:
Attila Fazekas836e4782013-01-29 15:40:13 +0100311 raise exceptions.ResponseWithNonEmptyBody(status=resp.status)
Attila Fazekasc3a095b2013-08-17 09:15:44 +0200312 # NOTE(afazekas):
Attila Fazekas836e4782013-01-29 15:40:13 +0100313 # If the HTTP Status Code is 205
314 # 'The response MUST NOT include an entity.'
315 # A HTTP entity has an entity-body and an 'entity-header'.
316 # In the HTTP response specification (Section 6) the 'entity-header'
317 # 'generic-header' and 'response-header' are in OR relation.
318 # All headers not in the above two group are considered as entity
319 # header in every interpretation.
320
321 if (resp.status == 205 and
322 0 != len(set(resp.keys()) - set(('status',)) -
323 self.response_header_lc - self.general_header_lc)):
324 raise exceptions.ResponseWithEntity()
Attila Fazekasc3a095b2013-08-17 09:15:44 +0200325 # NOTE(afazekas)
Attila Fazekas836e4782013-01-29 15:40:13 +0100326 # Now the swift sometimes (delete not empty container)
327 # returns with non json error response, we can create new rest class
328 # for swift.
329 # Usually RFC2616 says error responses SHOULD contain an explanation.
330 # The warning is normal for SHOULD/SHOULD NOT case
331
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100332 # Likely it will cause an error
333 if not resp_body and resp.status >= 400:
Attila Fazekas11d2a772013-01-29 17:46:52 +0100334 self.LOG.warning("status >= 400 response with empty body")
Attila Fazekas836e4782013-01-29 15:40:13 +0100335
vponomaryov67b58fe2014-02-06 19:05:41 +0200336 def _request(self, method, url, headers=None, body=None):
Daryl Wallecke5b83d42011-11-10 14:39:02 -0600337 """A simple HTTP request interface."""
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000338 # Authenticate the request with the auth provider
339 req_url, req_headers, req_body = self.auth_provider.auth_request(
340 method, url, headers, body, self.filters)
341 self._log_request(method, req_url, req_headers, req_body)
342 # Do the actual request
343 resp, resp_body = self.http_obj.request(
344 req_url, method, headers=req_headers, body=req_body)
Attila Fazekas11d2a772013-01-29 17:46:52 +0100345 self._log_response(resp, resp_body)
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000346 # Verify HTTP response codes
347 self.response_checker(method, url, req_headers, req_body, resp,
348 resp_body)
Attila Fazekas72c7a5f2012-12-03 17:17:23 +0100349
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100350 return resp, resp_body
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500351
vponomaryov67b58fe2014-02-06 19:05:41 +0200352 def request(self, method, url, headers=None, body=None):
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100353 retry = 0
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100354
355 if headers is None:
vponomaryov67b58fe2014-02-06 19:05:41 +0200356 # NOTE(vponomaryov): if some client do not need headers,
357 # it should explicitly pass empty dict
358 headers = self.get_headers()
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100359
360 resp, resp_body = self._request(method, url,
361 headers=headers, body=body)
362
363 while (resp.status == 413 and
364 'retry-after' in resp and
365 not self.is_absolute_limit(
366 resp, self._parse_resp(resp_body)) and
367 retry < MAX_RECURSION_DEPTH):
368 retry += 1
369 delay = int(resp['retry-after'])
370 time.sleep(delay)
371 resp, resp_body = self._request(method, url,
372 headers=headers, body=body)
373 self._error_checker(method, url, headers, body,
374 resp, resp_body)
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500375 return resp, resp_body
376
377 def _error_checker(self, method, url,
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100378 headers, body, resp, resp_body):
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500379
380 # NOTE(mtreinish): Check for httplib response from glance_http. The
381 # object can't be used here because importing httplib breaks httplib2.
382 # If another object from a class not imported were passed here as
383 # resp this could possibly fail
384 if str(type(resp)) == "<type 'instance'>":
385 ctype = resp.getheader('content-type')
386 else:
387 try:
388 ctype = resp['content-type']
389 # NOTE(mtreinish): Keystone delete user responses doesn't have a
390 # content-type header. (They don't have a body) So just pretend it
391 # is set.
392 except KeyError:
393 ctype = 'application/json'
394
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100395 # It is not an error response
396 if resp.status < 400:
397 return
398
Sergey Murashovc10cca52014-01-16 12:48:47 +0400399 JSON_ENC = ['application/json', 'application/json; charset=utf-8']
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500400 # NOTE(mtreinish): This is for compatibility with Glance and swift
401 # APIs. These are the return content types that Glance api v1
402 # (and occasionally swift) are using.
Sergey Murashovc10cca52014-01-16 12:48:47 +0400403 TXT_ENC = ['text/plain', 'text/html', 'text/html; charset=utf-8',
404 'text/plain; charset=utf-8']
405 XML_ENC = ['application/xml', 'application/xml; charset=utf-8']
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500406
Sergey Murashovc10cca52014-01-16 12:48:47 +0400407 if ctype.lower() in JSON_ENC or ctype.lower() in XML_ENC:
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500408 parse_resp = True
Sergey Murashovc10cca52014-01-16 12:48:47 +0400409 elif ctype.lower() in TXT_ENC:
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500410 parse_resp = False
411 else:
412 raise exceptions.RestClientException(str(resp.status))
413
Rohit Karajgi6b1e1542012-05-14 05:55:54 -0700414 if resp.status == 401 or resp.status == 403:
Daryl Walleckced8eb82012-03-19 13:52:37 -0500415 raise exceptions.Unauthorized()
Jay Pipes5135bfc2012-01-05 15:46:49 -0500416
417 if resp.status == 404:
Daryl Walleck8a707db2012-01-25 00:46:24 -0600418 raise exceptions.NotFound(resp_body)
Jay Pipes5135bfc2012-01-05 15:46:49 -0500419
Daryl Walleckadea1fa2011-11-15 18:36:39 -0600420 if resp.status == 400:
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500421 if parse_resp:
422 resp_body = self._parse_resp(resp_body)
David Kranz28e35c52012-07-10 10:14:38 -0400423 raise exceptions.BadRequest(resp_body)
Daryl Walleckadea1fa2011-11-15 18:36:39 -0600424
David Kranz5a23d862012-02-14 09:48:55 -0500425 if resp.status == 409:
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500426 if parse_resp:
427 resp_body = self._parse_resp(resp_body)
Anju5c3e510c2013-10-18 06:40:29 +0530428 raise exceptions.Conflict(resp_body)
David Kranz5a23d862012-02-14 09:48:55 -0500429
Daryl Wallecked8bef32011-12-05 23:02:08 -0600430 if resp.status == 413:
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500431 if parse_resp:
432 resp_body = self._parse_resp(resp_body)
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100433 if self.is_absolute_limit(resp, resp_body):
434 raise exceptions.OverLimit(resp_body)
435 else:
436 raise exceptions.RateLimitExceeded(resp_body)
Brian Lamar12d9b292011-12-08 12:41:21 -0500437
Wangpana9b54c62013-02-28 11:04:32 +0800438 if resp.status == 422:
439 if parse_resp:
440 resp_body = self._parse_resp(resp_body)
441 raise exceptions.UnprocessableEntity(resp_body)
442
Daryl Wallecked8bef32011-12-05 23:02:08 -0600443 if resp.status in (500, 501):
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500444 message = resp_body
445 if parse_resp:
Rohan Kanade433994a2013-12-05 22:34:07 +0530446 try:
447 resp_body = self._parse_resp(resp_body)
448 except ValueError:
449 # If response body is a non-json string message.
450 # Use resp_body as is and raise InvalidResponseBody
451 # exception.
452 raise exceptions.InvalidHTTPResponseBody(message)
453 else:
454 # I'm seeing both computeFault
455 # and cloudServersFault come back.
456 # Will file a bug to fix, but leave as is for now.
457 if 'cloudServersFault' in resp_body:
458 message = resp_body['cloudServersFault']['message']
459 elif 'computeFault' in resp_body:
460 message = resp_body['computeFault']['message']
461 elif 'error' in resp_body: # Keystone errors
462 message = resp_body['error']['message']
463 raise exceptions.IdentityError(message)
464 elif 'message' in resp_body:
465 message = resp_body['message']
Dan Princea4b709c2012-10-10 12:27:59 -0400466
Anju5c3e510c2013-10-18 06:40:29 +0530467 raise exceptions.ServerFault(message)
Daryl Wallecked8bef32011-12-05 23:02:08 -0600468
David Kranz5a23d862012-02-14 09:48:55 -0500469 if resp.status >= 400:
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500470 if parse_resp:
471 resp_body = self._parse_resp(resp_body)
Attila Fazekas96524032013-01-29 19:52:49 +0100472 raise exceptions.RestClientException(str(resp.status))
David Kranz5a23d862012-02-14 09:48:55 -0500473
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100474 def is_absolute_limit(self, resp, resp_body):
475 if (not isinstance(resp_body, collections.Mapping) or
Pavel Sedláke267eba2013-04-03 15:56:36 +0200476 'retry-after' not in resp):
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100477 return True
vponomaryov67b58fe2014-02-06 19:05:41 +0200478 if self._get_type() is "json":
479 over_limit = resp_body.get('overLimit', None)
480 if not over_limit:
481 return True
482 return 'exceed' in over_limit.get('message', 'blabla')
483 elif self._get_type() is "xml":
484 return 'exceed' in resp_body.get('message', 'blabla')
rajalakshmi-ganesan0275a0d2013-01-11 18:26:05 +0530485
David Kranz6aceb4a2012-06-05 14:05:45 -0400486 def wait_for_resource_deletion(self, id):
Sean Daguef237ccb2013-01-04 15:19:14 -0500487 """Waits for a resource to be deleted."""
David Kranz6aceb4a2012-06-05 14:05:45 -0400488 start_time = int(time.time())
489 while True:
490 if self.is_resource_deleted(id):
491 return
492 if int(time.time()) - start_time >= self.build_timeout:
493 raise exceptions.TimeoutException
494 time.sleep(self.build_interval)
495
496 def is_resource_deleted(self, id):
497 """
498 Subclasses override with specific deletion detection.
499 """
Attila Fazekasd236b4e2013-01-26 00:44:12 +0100500 message = ('"%s" does not implement is_resource_deleted'
501 % self.__class__.__name__)
502 raise NotImplementedError(message)
Dan Smithba6cb162012-08-14 07:22:42 -0700503
504
Marc Koderer24eb89c2014-01-31 11:23:33 +0100505class NegativeRestClient(RestClient):
506 """
507 Version of RestClient that does not raise exceptions.
508 """
509 def _error_checker(self, method, url,
510 headers, body, resp, resp_body):
511 pass
512
513 def send_request(self, method, url_template, resources, body=None):
514 url = url_template % tuple(resources)
515 if method == "GET":
516 resp, body = self.get(url)
517 elif method == "POST":
vponomaryov67b58fe2014-02-06 19:05:41 +0200518 resp, body = self.post(url, body)
Marc Koderer24eb89c2014-01-31 11:23:33 +0100519 elif method == "PUT":
vponomaryov67b58fe2014-02-06 19:05:41 +0200520 resp, body = self.put(url, body)
Marc Koderer24eb89c2014-01-31 11:23:33 +0100521 elif method == "PATCH":
vponomaryov67b58fe2014-02-06 19:05:41 +0200522 resp, body = self.patch(url, body)
Marc Koderer24eb89c2014-01-31 11:23:33 +0100523 elif method == "HEAD":
524 resp, body = self.head(url)
525 elif method == "DELETE":
526 resp, body = self.delete(url)
527 elif method == "COPY":
528 resp, body = self.copy(url)
529 else:
530 assert False
531
532 return resp, body