blob: e864ae3b173d60ed9795e0d8e21e979617360d0c [file] [log] [blame]
Jay Pipes3f981df2012-03-27 18:59:44 -04001# vim: tabstop=4 shiftwidth=4 softtabstop=4
2
ZhiQiang Fan39f97222013-09-20 04:49:44 +08003# Copyright 2012 OpenStack Foundation
Brant Knudsonc7ca3342013-03-28 21:08:50 -05004# Copyright 2013 IBM Corp.
Jay Pipes3f981df2012-03-27 18:59:44 -04005# All Rights Reserved.
6#
7# Licensed under the Apache License, Version 2.0 (the "License"); you may
8# not use this file except in compliance with the License. You may obtain
9# a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16# License for the specific language governing permissions and limitations
17# under the License.
18
Attila Fazekas55f6d8c2013-03-10 10:32:54 +010019import collections
Attila Fazekas11d2a772013-01-29 17:46:52 +010020import hashlib
Matthew Treinisha83a16e2012-12-07 13:44:02 -050021import json
Dan Smithba6cb162012-08-14 07:22:42 -070022from lxml import etree
Attila Fazekas11d2a772013-01-29 17:46:52 +010023import re
Eoghan Glynna5598972012-03-01 09:27:17 -050024import time
Jay Pipes3f981df2012-03-27 18:59:44 -040025
Mate Lakat23a58a32013-08-23 02:06:22 +010026from tempest.common import http
Daryl Wallecked8bef32011-12-05 23:02:08 -060027from tempest import exceptions
Matthew Treinishf4a9b0f2013-07-26 16:58:26 -040028from tempest.openstack.common import log as logging
dwallecke62b9f02012-10-10 23:34:42 -050029from tempest.services.compute.xml.common import xml_to_json
Daryl Walleck1465d612011-11-02 02:22:15 -050030
Eoghan Glynna5598972012-03-01 09:27:17 -050031# redrive rate limited calls at most twice
32MAX_RECURSION_DEPTH = 2
Attila Fazekas11d2a772013-01-29 17:46:52 +010033TOKEN_CHARS_RE = re.compile('^[-A-Za-z0-9+/=]*$')
Eoghan Glynna5598972012-03-01 09:27:17 -050034
Attila Fazekas54a42862013-07-28 22:31:06 +020035# All the successful HTTP status codes from RFC 2616
36HTTP_SUCCESS = (200, 201, 202, 203, 204, 205, 206)
37
Eoghan Glynna5598972012-03-01 09:27:17 -050038
Daryl Walleck1465d612011-11-02 02:22:15 -050039class RestClient(object):
Dan Smithba6cb162012-08-14 07:22:42 -070040 TYPE = "json"
Attila Fazekas11d2a772013-01-29 17:46:52 +010041 LOG = logging.getLogger(__name__)
Daryl Walleck1465d612011-11-02 02:22:15 -050042
Brant Knudsonc7ca3342013-03-28 21:08:50 -050043 def __init__(self, config, user, password, auth_url, tenant_name=None,
44 auth_version='v2'):
Jay Pipes7f757632011-12-02 15:53:32 -050045 self.config = config
chris fattarsi5098fa22012-04-17 13:27:00 -070046 self.user = user
47 self.password = password
48 self.auth_url = auth_url
49 self.tenant_name = tenant_name
Brant Knudsonc7ca3342013-03-28 21:08:50 -050050 self.auth_version = auth_version
chris fattarsi5098fa22012-04-17 13:27:00 -070051
52 self.service = None
53 self.token = None
54 self.base_url = None
Arata Notsu8f440392013-09-13 16:14:20 +090055 self.region = {}
56 for cfgname in dir(self.config):
57 # Find all config.FOO.catalog_type and assume FOO is a service.
58 cfg = getattr(self.config, cfgname)
59 catalog_type = getattr(cfg, 'catalog_type', None)
60 if not catalog_type:
61 continue
62 service_region = getattr(cfg, 'region', None)
63 if not service_region:
64 service_region = self.config.identity.region
65 self.region[catalog_type] = service_region
chris fattarsi5098fa22012-04-17 13:27:00 -070066 self.endpoint_url = 'publicURL'
Dan Smithba6cb162012-08-14 07:22:42 -070067 self.headers = {'Content-Type': 'application/%s' % self.TYPE,
68 'Accept': 'application/%s' % self.TYPE}
David Kranz6aceb4a2012-06-05 14:05:45 -040069 self.build_interval = config.compute.build_interval
70 self.build_timeout = config.compute.build_timeout
Attila Fazekas72c7a5f2012-12-03 17:17:23 +010071 self.general_header_lc = set(('cache-control', 'connection',
72 'date', 'pragma', 'trailer',
73 'transfer-encoding', 'via',
74 'warning'))
75 self.response_header_lc = set(('accept-ranges', 'age', 'etag',
76 'location', 'proxy-authenticate',
77 'retry-after', 'server',
78 'vary', 'www-authenticate'))
Attila Fazekas55f6d8c2013-03-10 10:32:54 +010079 dscv = self.config.identity.disable_ssl_certificate_validation
Mate Lakat23a58a32013-08-23 02:06:22 +010080 self.http_obj = http.ClosingHttp(
81 disable_ssl_certificate_validation=dscv)
chris fattarsi5098fa22012-04-17 13:27:00 -070082
83 def _set_auth(self):
84 """
85 Sets the token and base_url used in requests based on the strategy type
86 """
87
Li Ma216550f2013-06-12 11:26:08 -070088 if self.auth_version == 'v3':
89 auth_func = self.identity_auth_v3
Daryl Walleck1465d612011-11-02 02:22:15 -050090 else:
Li Ma216550f2013-06-12 11:26:08 -070091 auth_func = self.keystone_auth
92
93 self.token, self.base_url = (
94 auth_func(self.user, self.password, self.auth_url,
95 self.service, self.tenant_name))
chris fattarsi5098fa22012-04-17 13:27:00 -070096
97 def clear_auth(self):
98 """
99 Can be called to clear the token and base_url so that the next request
Attila Fazekasb2902af2013-02-16 16:22:44 +0100100 will fetch a new token and base_url.
chris fattarsi5098fa22012-04-17 13:27:00 -0700101 """
102
103 self.token = None
104 self.base_url = None
Daryl Walleck1465d612011-11-02 02:22:15 -0500105
Rohit Karajgi6b1e1542012-05-14 05:55:54 -0700106 def get_auth(self):
107 """Returns the token of the current request or sets the token if
Attila Fazekasb2902af2013-02-16 16:22:44 +0100108 none.
109 """
Rohit Karajgi6b1e1542012-05-14 05:55:54 -0700110
111 if not self.token:
112 self._set_auth()
113
114 return self.token
115
Daryl Walleck587385b2012-03-03 13:00:26 -0600116 def basic_auth(self, user, password, auth_url):
Daryl Walleck1465d612011-11-02 02:22:15 -0500117 """
Attila Fazekasb2902af2013-02-16 16:22:44 +0100118 Provides authentication for the target API.
Daryl Walleck1465d612011-11-02 02:22:15 -0500119 """
120
121 params = {}
122 params['headers'] = {'User-Agent': 'Test-Client', 'X-Auth-User': user,
Daryl Walleck587385b2012-03-03 13:00:26 -0600123 'X-Auth-Key': password}
Daryl Walleck1465d612011-11-02 02:22:15 -0500124
Daryl Walleck1465d612011-11-02 02:22:15 -0500125 resp, body = self.http_obj.request(auth_url, 'GET', **params)
126 try:
127 return resp['x-auth-token'], resp['x-server-management-url']
Matthew Treinish05d9fb92012-12-07 16:14:05 -0500128 except Exception:
Daryl Walleck1465d612011-11-02 02:22:15 -0500129 raise
130
Daryl Walleck587385b2012-03-03 13:00:26 -0600131 def keystone_auth(self, user, password, auth_url, service, tenant_name):
Daryl Walleck1465d612011-11-02 02:22:15 -0500132 """
Brant Knudsonc7ca3342013-03-28 21:08:50 -0500133 Provides authentication via Keystone using v2 identity API.
Daryl Walleck1465d612011-11-02 02:22:15 -0500134 """
135
Jay Pipes7c88eb22013-01-16 21:32:43 -0500136 # Normalize URI to ensure /tokens is in it.
137 if 'tokens' not in auth_url:
138 auth_url = auth_url.rstrip('/') + '/tokens'
139
Zhongyue Luo30a563f2012-09-30 23:43:50 +0900140 creds = {
141 'auth': {
Daryl Walleck1465d612011-11-02 02:22:15 -0500142 'passwordCredentials': {
143 'username': user,
Daryl Walleck587385b2012-03-03 13:00:26 -0600144 'password': password,
Daryl Walleck1465d612011-11-02 02:22:15 -0500145 },
Zhongyue Luo30a563f2012-09-30 23:43:50 +0900146 'tenantName': tenant_name,
Daryl Walleck1465d612011-11-02 02:22:15 -0500147 }
148 }
149
Daryl Walleck1465d612011-11-02 02:22:15 -0500150 headers = {'Content-Type': 'application/json'}
151 body = json.dumps(creds)
Pavel Sedláke267eba2013-04-03 15:56:36 +0200152 self._log_request('POST', auth_url, headers, body)
153 resp, resp_body = self.http_obj.request(auth_url, 'POST',
154 headers=headers, body=body)
155 self._log_response(resp, resp_body)
Daryl Walleck1465d612011-11-02 02:22:15 -0500156
Jay Pipes7f757632011-12-02 15:53:32 -0500157 if resp.status == 200:
158 try:
Pavel Sedláke267eba2013-04-03 15:56:36 +0200159 auth_data = json.loads(resp_body)['access']
Jay Pipes7f757632011-12-02 15:53:32 -0500160 token = auth_data['token']['id']
Dirk Mueller1db5db22013-06-23 20:21:32 +0200161 except Exception as e:
162 print("Failed to obtain token for user: %s" % e)
Jay Pipes7f757632011-12-02 15:53:32 -0500163 raise
Adam Gandelmane2d46b42012-01-03 17:40:44 -0800164
165 mgmt_url = None
166 for ep in auth_data['serviceCatalog']:
Dan Prince8527c8a2012-12-14 14:00:31 -0500167 if ep["type"] == service:
K Jonathan Harkerd6ba4b42012-12-18 13:50:47 -0800168 for _ep in ep['endpoints']:
169 if service in self.region and \
170 _ep['region'] == self.region[service]:
171 mgmt_url = _ep[self.endpoint_url]
172 if not mgmt_url:
173 mgmt_url = ep['endpoints'][0][self.endpoint_url]
Adam Gandelmane2d46b42012-01-03 17:40:44 -0800174 break
175
Zhongyue Luoe471d6e2012-09-17 17:02:43 +0800176 if mgmt_url is None:
Adam Gandelmane2d46b42012-01-03 17:40:44 -0800177 raise exceptions.EndpointNotFound(service)
178
Rohit Karajgid2a28af2012-05-23 03:44:59 -0700179 return token, mgmt_url
180
Jay Pipes7f757632011-12-02 15:53:32 -0500181 elif resp.status == 401:
Daryl Wallecka22f57b2012-03-20 16:52:07 -0500182 raise exceptions.AuthenticationFailure(user=user,
Matthew Treinishb86cda92013-07-29 11:22:23 -0400183 password=password,
184 tenant=tenant_name)
Pavel Sedláke267eba2013-04-03 15:56:36 +0200185 raise exceptions.IdentityError('Unexpected status code {0}'.format(
186 resp.status))
Daryl Walleck1465d612011-11-02 02:22:15 -0500187
Brant Knudsonc7ca3342013-03-28 21:08:50 -0500188 def identity_auth_v3(self, user, password, auth_url, service,
189 project_name, domain_id='default'):
190 """Provides authentication using Identity API v3."""
191
192 req_url = auth_url.rstrip('/') + '/auth/tokens'
193
194 creds = {
195 "auth": {
196 "identity": {
197 "methods": ["password"],
198 "password": {
199 "user": {
200 "name": user, "password": password,
201 "domain": {"id": domain_id}
202 }
203 }
204 },
205 "scope": {
206 "project": {
207 "domain": {"id": domain_id},
208 "name": project_name
209 }
210 }
211 }
212 }
213
214 headers = {'Content-Type': 'application/json'}
215 body = json.dumps(creds)
216 resp, body = self.http_obj.request(req_url, 'POST',
217 headers=headers, body=body)
218
219 if resp.status == 201:
220 try:
221 token = resp['x-subject-token']
222 except Exception:
223 self.LOG.exception("Failed to obtain token using V3"
224 " authentication (auth URL is '%s')" %
225 req_url)
226 raise
227
228 catalog = json.loads(body)['token']['catalog']
229
230 mgmt_url = None
231 for service_info in catalog:
232 if service_info['type'] != service:
233 continue # this isn't the entry for us.
234
235 endpoints = service_info['endpoints']
236
237 # Look for an endpoint in the region if configured.
238 if service in self.region:
239 region = self.region[service]
240
241 for ep in endpoints:
242 if ep['region'] != region:
243 continue
244
245 mgmt_url = ep['url']
246 # FIXME(blk-u): this isn't handling endpoint type
247 # (public, internal, admin).
248 break
249
250 if not mgmt_url:
251 # Didn't find endpoint for region, use the first.
252
253 ep = endpoints[0]
254 mgmt_url = ep['url']
255 # FIXME(blk-u): this isn't handling endpoint type
256 # (public, internal, admin).
257
258 break
259
260 return token, mgmt_url
261
262 elif resp.status == 401:
263 raise exceptions.AuthenticationFailure(user=user,
264 password=password)
265 else:
266 self.LOG.error("Failed to obtain token using V3 authentication"
267 " (auth URL is '%s'), the response status is %s" %
268 (req_url, resp.status))
269 raise exceptions.AuthenticationFailure(user=user,
270 password=password)
271
Attila Fazekas54a42862013-07-28 22:31:06 +0200272 def expected_success(self, expected_code, read_code):
273 assert_msg = ("This function only allowed to use for HTTP status"
274 "codes which explicitly defined in the RFC 2616. {0}"
275 " is not a defined Success Code!").format(expected_code)
276 assert expected_code in HTTP_SUCCESS, assert_msg
277
278 # NOTE(afazekas): the http status code above 400 is processed by
279 # the _error_checker method
280 if read_code < 400 and read_code != expected_code:
281 pattern = """Unexpected http success status code {0},
282 The expected status code is {1}"""
283 details = pattern.format(read_code, expected_code)
284 raise exceptions.InvalidHttpSuccessCode(details)
285
Daryl Walleck1465d612011-11-02 02:22:15 -0500286 def post(self, url, body, headers):
287 return self.request('POST', url, headers, body)
288
Attila Fazekasb8aa7592013-01-26 01:25:45 +0100289 def get(self, url, headers=None):
290 return self.request('GET', url, headers)
Daryl Walleck1465d612011-11-02 02:22:15 -0500291
Dan Smithba6cb162012-08-14 07:22:42 -0700292 def delete(self, url, headers=None):
293 return self.request('DELETE', url, headers)
Daryl Walleck1465d612011-11-02 02:22:15 -0500294
rajalakshmi-ganesanab426722013-02-08 15:49:15 +0530295 def patch(self, url, body, headers):
296 return self.request('PATCH', url, headers, body)
297
Daryl Walleck1465d612011-11-02 02:22:15 -0500298 def put(self, url, body, headers):
299 return self.request('PUT', url, headers, body)
300
dwalleck5d734432012-10-04 01:11:47 -0500301 def head(self, url, headers=None):
Larisa Ustalov6c3c7802012-11-05 12:25:19 +0200302 return self.request('HEAD', url, headers)
303
304 def copy(self, url, headers=None):
305 return self.request('COPY', url, headers)
dwalleck5d734432012-10-04 01:11:47 -0500306
Matthew Treinishc0f768f2013-03-11 14:24:16 -0400307 def get_versions(self):
308 resp, body = self.get('')
309 body = self._parse_resp(body)
310 body = body['versions']
311 versions = map(lambda x: x['id'], body)
312 return resp, versions
313
Attila Fazekas11d2a772013-01-29 17:46:52 +0100314 def _log_request(self, method, req_url, headers, body):
315 self.LOG.info('Request: ' + method + ' ' + req_url)
316 if headers:
317 print_headers = headers
318 if 'X-Auth-Token' in headers and headers['X-Auth-Token']:
319 token = headers['X-Auth-Token']
320 if len(token) > 64 and TOKEN_CHARS_RE.match(token):
321 print_headers = headers.copy()
322 print_headers['X-Auth-Token'] = "<Token omitted>"
323 self.LOG.debug('Request Headers: ' + str(print_headers))
324 if body:
325 str_body = str(body)
326 length = len(str_body)
327 self.LOG.debug('Request Body: ' + str_body[:2048])
328 if length >= 2048:
329 self.LOG.debug("Large body (%d) md5 summary: %s", length,
330 hashlib.md5(str_body).hexdigest())
331
332 def _log_response(self, resp, resp_body):
333 status = resp['status']
334 self.LOG.info("Response Status: " + status)
335 headers = resp.copy()
336 del headers['status']
Matthew Treinishe5423912013-08-13 18:07:31 -0400337 if headers.get('x-compute-request-id'):
338 self.LOG.info("Nova request id: %s" %
339 headers.pop('x-compute-request-id'))
340 elif headers.get('x-openstack-request-id'):
341 self.LOG.info("Glance request id %s" %
342 headers.pop('x-openstack-request-id'))
Attila Fazekas11d2a772013-01-29 17:46:52 +0100343 if len(headers):
344 self.LOG.debug('Response Headers: ' + str(headers))
345 if resp_body:
346 str_body = str(resp_body)
347 length = len(str_body)
348 self.LOG.debug('Response Body: ' + str_body[:2048])
349 if length >= 2048:
350 self.LOG.debug("Large body (%d) md5 summary: %s", length,
351 hashlib.md5(str_body).hexdigest())
Daryl Walleck8a707db2012-01-25 00:46:24 -0600352
Dan Smithba6cb162012-08-14 07:22:42 -0700353 def _parse_resp(self, body):
354 return json.loads(body)
355
Attila Fazekas836e4782013-01-29 15:40:13 +0100356 def response_checker(self, method, url, headers, body, resp, resp_body):
357 if (resp.status in set((204, 205, 304)) or resp.status < 200 or
Pavel Sedláke267eba2013-04-03 15:56:36 +0200358 method.upper() == 'HEAD') and resp_body:
Attila Fazekas836e4782013-01-29 15:40:13 +0100359 raise exceptions.ResponseWithNonEmptyBody(status=resp.status)
Attila Fazekasc3a095b2013-08-17 09:15:44 +0200360 # NOTE(afazekas):
Attila Fazekas836e4782013-01-29 15:40:13 +0100361 # If the HTTP Status Code is 205
362 # 'The response MUST NOT include an entity.'
363 # A HTTP entity has an entity-body and an 'entity-header'.
364 # In the HTTP response specification (Section 6) the 'entity-header'
365 # 'generic-header' and 'response-header' are in OR relation.
366 # All headers not in the above two group are considered as entity
367 # header in every interpretation.
368
369 if (resp.status == 205 and
370 0 != len(set(resp.keys()) - set(('status',)) -
371 self.response_header_lc - self.general_header_lc)):
372 raise exceptions.ResponseWithEntity()
Attila Fazekasc3a095b2013-08-17 09:15:44 +0200373 # NOTE(afazekas)
Attila Fazekas836e4782013-01-29 15:40:13 +0100374 # Now the swift sometimes (delete not empty container)
375 # returns with non json error response, we can create new rest class
376 # for swift.
377 # Usually RFC2616 says error responses SHOULD contain an explanation.
378 # The warning is normal for SHOULD/SHOULD NOT case
379
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100380 # Likely it will cause an error
381 if not resp_body and resp.status >= 400:
Attila Fazekas11d2a772013-01-29 17:46:52 +0100382 self.LOG.warning("status >= 400 response with empty body")
Attila Fazekas836e4782013-01-29 15:40:13 +0100383
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100384 def _request(self, method, url,
385 headers=None, body=None):
Daryl Wallecke5b83d42011-11-10 14:39:02 -0600386 """A simple HTTP request interface."""
Daryl Walleck1465d612011-11-02 02:22:15 -0500387
Daryl Walleck1465d612011-11-02 02:22:15 -0500388 req_url = "%s/%s" % (self.base_url, url)
Attila Fazekas11d2a772013-01-29 17:46:52 +0100389 self._log_request(method, req_url, headers, body)
Daryl Walleck8a707db2012-01-25 00:46:24 -0600390 resp, resp_body = self.http_obj.request(req_url, method,
Zhongyue Luo79d8d362012-09-25 13:49:27 +0800391 headers=headers, body=body)
Attila Fazekas11d2a772013-01-29 17:46:52 +0100392 self._log_response(resp, resp_body)
Attila Fazekas836e4782013-01-29 15:40:13 +0100393 self.response_checker(method, url, headers, body, resp, resp_body)
Attila Fazekas72c7a5f2012-12-03 17:17:23 +0100394
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100395 return resp, resp_body
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500396
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100397 def request(self, method, url,
398 headers=None, body=None):
399 retry = 0
400 if (self.token is None) or (self.base_url is None):
401 self._set_auth()
402
403 if headers is None:
404 headers = {}
405 headers['X-Auth-Token'] = self.token
406
407 resp, resp_body = self._request(method, url,
408 headers=headers, body=body)
409
410 while (resp.status == 413 and
411 'retry-after' in resp and
412 not self.is_absolute_limit(
413 resp, self._parse_resp(resp_body)) and
414 retry < MAX_RECURSION_DEPTH):
415 retry += 1
416 delay = int(resp['retry-after'])
417 time.sleep(delay)
418 resp, resp_body = self._request(method, url,
419 headers=headers, body=body)
420 self._error_checker(method, url, headers, body,
421 resp, resp_body)
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500422 return resp, resp_body
423
424 def _error_checker(self, method, url,
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100425 headers, body, resp, resp_body):
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500426
427 # NOTE(mtreinish): Check for httplib response from glance_http. The
428 # object can't be used here because importing httplib breaks httplib2.
429 # If another object from a class not imported were passed here as
430 # resp this could possibly fail
431 if str(type(resp)) == "<type 'instance'>":
432 ctype = resp.getheader('content-type')
433 else:
434 try:
435 ctype = resp['content-type']
436 # NOTE(mtreinish): Keystone delete user responses doesn't have a
437 # content-type header. (They don't have a body) So just pretend it
438 # is set.
439 except KeyError:
440 ctype = 'application/json'
441
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100442 # It is not an error response
443 if resp.status < 400:
444 return
445
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500446 JSON_ENC = ['application/json; charset=UTF-8', 'application/json',
447 'application/json; charset=utf-8']
448 # NOTE(mtreinish): This is for compatibility with Glance and swift
449 # APIs. These are the return content types that Glance api v1
450 # (and occasionally swift) are using.
Joe H. Rahme2eccc332013-08-29 15:50:35 +0200451 TXT_ENC = ['text/plain', 'text/plain; charset=UTF-8',
452 'text/html; charset=UTF-8', 'text/plain; charset=utf-8']
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500453 XML_ENC = ['application/xml', 'application/xml; charset=UTF-8']
454
455 if ctype in JSON_ENC or ctype in XML_ENC:
456 parse_resp = True
457 elif ctype in TXT_ENC:
458 parse_resp = False
459 else:
460 raise exceptions.RestClientException(str(resp.status))
461
Rohit Karajgi6b1e1542012-05-14 05:55:54 -0700462 if resp.status == 401 or resp.status == 403:
Daryl Walleckced8eb82012-03-19 13:52:37 -0500463 raise exceptions.Unauthorized()
Jay Pipes5135bfc2012-01-05 15:46:49 -0500464
465 if resp.status == 404:
Daryl Walleck8a707db2012-01-25 00:46:24 -0600466 raise exceptions.NotFound(resp_body)
Jay Pipes5135bfc2012-01-05 15:46:49 -0500467
Daryl Walleckadea1fa2011-11-15 18:36:39 -0600468 if resp.status == 400:
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500469 if parse_resp:
470 resp_body = self._parse_resp(resp_body)
David Kranz28e35c52012-07-10 10:14:38 -0400471 raise exceptions.BadRequest(resp_body)
Daryl Walleckadea1fa2011-11-15 18:36:39 -0600472
David Kranz5a23d862012-02-14 09:48:55 -0500473 if resp.status == 409:
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500474 if parse_resp:
475 resp_body = self._parse_resp(resp_body)
David Kranz5a23d862012-02-14 09:48:55 -0500476 raise exceptions.Duplicate(resp_body)
477
Daryl Wallecked8bef32011-12-05 23:02:08 -0600478 if resp.status == 413:
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500479 if parse_resp:
480 resp_body = self._parse_resp(resp_body)
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100481 if self.is_absolute_limit(resp, resp_body):
482 raise exceptions.OverLimit(resp_body)
483 else:
484 raise exceptions.RateLimitExceeded(resp_body)
Brian Lamar12d9b292011-12-08 12:41:21 -0500485
Wangpana9b54c62013-02-28 11:04:32 +0800486 if resp.status == 422:
487 if parse_resp:
488 resp_body = self._parse_resp(resp_body)
489 raise exceptions.UnprocessableEntity(resp_body)
490
Daryl Wallecked8bef32011-12-05 23:02:08 -0600491 if resp.status in (500, 501):
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500492 message = resp_body
493 if parse_resp:
494 resp_body = self._parse_resp(resp_body)
Attila Fazekasc3a095b2013-08-17 09:15:44 +0200495 # I'm seeing both computeFault and cloudServersFault come back.
496 # Will file a bug to fix, but leave as is for now.
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500497 if 'cloudServersFault' in resp_body:
498 message = resp_body['cloudServersFault']['message']
499 elif 'computeFault' in resp_body:
500 message = resp_body['computeFault']['message']
501 elif 'error' in resp_body: # Keystone errors
502 message = resp_body['error']['message']
503 raise exceptions.IdentityError(message)
504 elif 'message' in resp_body:
505 message = resp_body['message']
Dan Princea4b709c2012-10-10 12:27:59 -0400506
Daryl Walleckf0087032011-12-18 13:37:05 -0600507 raise exceptions.ComputeFault(message)
Daryl Wallecked8bef32011-12-05 23:02:08 -0600508
David Kranz5a23d862012-02-14 09:48:55 -0500509 if resp.status >= 400:
Matthew Treinish7e5a3ec2013-02-08 13:53:58 -0500510 if parse_resp:
511 resp_body = self._parse_resp(resp_body)
Attila Fazekas96524032013-01-29 19:52:49 +0100512 raise exceptions.RestClientException(str(resp.status))
David Kranz5a23d862012-02-14 09:48:55 -0500513
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100514 def is_absolute_limit(self, resp, resp_body):
515 if (not isinstance(resp_body, collections.Mapping) or
Pavel Sedláke267eba2013-04-03 15:56:36 +0200516 'retry-after' not in resp):
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100517 return True
518 over_limit = resp_body.get('overLimit', None)
519 if not over_limit:
520 return True
521 return 'exceed' in over_limit.get('message', 'blabla')
rajalakshmi-ganesan0275a0d2013-01-11 18:26:05 +0530522
David Kranz6aceb4a2012-06-05 14:05:45 -0400523 def wait_for_resource_deletion(self, id):
Sean Daguef237ccb2013-01-04 15:19:14 -0500524 """Waits for a resource to be deleted."""
David Kranz6aceb4a2012-06-05 14:05:45 -0400525 start_time = int(time.time())
526 while True:
527 if self.is_resource_deleted(id):
528 return
529 if int(time.time()) - start_time >= self.build_timeout:
530 raise exceptions.TimeoutException
531 time.sleep(self.build_interval)
532
533 def is_resource_deleted(self, id):
534 """
535 Subclasses override with specific deletion detection.
536 """
Attila Fazekasd236b4e2013-01-26 00:44:12 +0100537 message = ('"%s" does not implement is_resource_deleted'
538 % self.__class__.__name__)
539 raise NotImplementedError(message)
Dan Smithba6cb162012-08-14 07:22:42 -0700540
541
542class RestClientXML(RestClient):
543 TYPE = "xml"
544
545 def _parse_resp(self, body):
546 return xml_to_json(etree.fromstring(body))
rajalakshmi-ganesan0275a0d2013-01-11 18:26:05 +0530547
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100548 def is_absolute_limit(self, resp, resp_body):
549 if (not isinstance(resp_body, collections.Mapping) or
Pavel Sedláke267eba2013-04-03 15:56:36 +0200550 'retry-after' not in resp):
Attila Fazekas55f6d8c2013-03-10 10:32:54 +0100551 return True
552 return 'exceed' in resp_body.get('message', 'blabla')